]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/iD/iD/mapillary-js/mapillary.js
Update to iD v2.2.0
[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 && 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":158}],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, error) {
5273         this.kind = kind;
5274         this.value = value;
5275         this.error = error;
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.error);
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.error);
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.error);
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` error.
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     Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5421         var operator = this.operator;
5422         var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5423         if (operator) {
5424             operator.call(sink, this.source);
5425         }
5426         else {
5427             sink.add(this._trySubscribe(sink));
5428         }
5429         if (sink.syncErrorThrowable) {
5430             sink.syncErrorThrowable = false;
5431             if (sink.syncErrorThrown) {
5432                 throw sink.syncErrorValue;
5433             }
5434         }
5435         return sink;
5436     };
5437     Observable.prototype._trySubscribe = function (sink) {
5438         try {
5439             return this._subscribe(sink);
5440         }
5441         catch (err) {
5442             sink.syncErrorThrown = true;
5443             sink.syncErrorValue = err;
5444             sink.error(err);
5445         }
5446     };
5447     /**
5448      * @method forEach
5449      * @param {Function} next a handler for each value emitted by the observable
5450      * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5451      * @return {Promise} a promise that either resolves on observable completion or
5452      *  rejects with the handled error
5453      */
5454     Observable.prototype.forEach = function (next, PromiseCtor) {
5455         var _this = this;
5456         if (!PromiseCtor) {
5457             if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5458                 PromiseCtor = root_1.root.Rx.config.Promise;
5459             }
5460             else if (root_1.root.Promise) {
5461                 PromiseCtor = root_1.root.Promise;
5462             }
5463         }
5464         if (!PromiseCtor) {
5465             throw new Error('no Promise impl found');
5466         }
5467         return new PromiseCtor(function (resolve, reject) {
5468             var subscription = _this.subscribe(function (value) {
5469                 if (subscription) {
5470                     // if there is a subscription, then we can surmise
5471                     // the next handling is asynchronous. Any errors thrown
5472                     // need to be rejected explicitly and unsubscribe must be
5473                     // called manually
5474                     try {
5475                         next(value);
5476                     }
5477                     catch (err) {
5478                         reject(err);
5479                         subscription.unsubscribe();
5480                     }
5481                 }
5482                 else {
5483                     // if there is NO subscription, then we're getting a nexted
5484                     // value synchronously during subscription. We can just call it.
5485                     // If it errors, Observable's `subscribe` will ensure the
5486                     // unsubscription logic is called, then synchronously rethrow the error.
5487                     // After that, Promise will trap the error and send it
5488                     // down the rejection path.
5489                     next(value);
5490                 }
5491             }, reject, resolve);
5492         });
5493     };
5494     Observable.prototype._subscribe = function (subscriber) {
5495         return this.source.subscribe(subscriber);
5496     };
5497     /**
5498      * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5499      * @method Symbol.observable
5500      * @return {Observable} this instance of the observable
5501      */
5502     Observable.prototype[observable_1.$$observable] = function () {
5503         return this;
5504     };
5505     // HACK: Since TypeScript inherits static properties too, we have to
5506     // fight against TypeScript here so Subject can have a different static create signature
5507     /**
5508      * Creates a new cold Observable by calling the Observable constructor
5509      * @static true
5510      * @owner Observable
5511      * @method create
5512      * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5513      * @return {Observable} a new cold observable
5514      */
5515     Observable.create = function (subscribe) {
5516         return new Observable(subscribe);
5517     };
5518     return Observable;
5519 }());
5520 exports.Observable = Observable;
5521
5522 },{"./symbol/observable":153,"./util/root":170,"./util/toSubscriber":172}],29:[function(require,module,exports){
5523 "use strict";
5524 exports.empty = {
5525     closed: true,
5526     next: function (value) { },
5527     error: function (err) { throw err; },
5528     complete: function () { }
5529 };
5530
5531 },{}],30:[function(require,module,exports){
5532 "use strict";
5533 var __extends = (this && this.__extends) || function (d, b) {
5534     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5535     function __() { this.constructor = d; }
5536     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5537 };
5538 var Subscriber_1 = require('./Subscriber');
5539 /**
5540  * We need this JSDoc comment for affecting ESDoc.
5541  * @ignore
5542  * @extends {Ignored}
5543  */
5544 var OuterSubscriber = (function (_super) {
5545     __extends(OuterSubscriber, _super);
5546     function OuterSubscriber() {
5547         _super.apply(this, arguments);
5548     }
5549     OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5550         this.destination.next(innerValue);
5551     };
5552     OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5553         this.destination.error(error);
5554     };
5555     OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5556         this.destination.complete();
5557     };
5558     return OuterSubscriber;
5559 }(Subscriber_1.Subscriber));
5560 exports.OuterSubscriber = OuterSubscriber;
5561
5562 },{"./Subscriber":35}],31:[function(require,module,exports){
5563 "use strict";
5564 var __extends = (this && this.__extends) || function (d, b) {
5565     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5566     function __() { this.constructor = d; }
5567     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5568 };
5569 var Subject_1 = require('./Subject');
5570 var queue_1 = require('./scheduler/queue');
5571 var Subscription_1 = require('./Subscription');
5572 var observeOn_1 = require('./operator/observeOn');
5573 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5574 var SubjectSubscription_1 = require('./SubjectSubscription');
5575 /**
5576  * @class ReplaySubject<T>
5577  */
5578 var ReplaySubject = (function (_super) {
5579     __extends(ReplaySubject, _super);
5580     function ReplaySubject(bufferSize, windowTime, scheduler) {
5581         if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5582         if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5583         _super.call(this);
5584         this.scheduler = scheduler;
5585         this._events = [];
5586         this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5587         this._windowTime = windowTime < 1 ? 1 : windowTime;
5588     }
5589     ReplaySubject.prototype.next = function (value) {
5590         var now = this._getNow();
5591         this._events.push(new ReplayEvent(now, value));
5592         this._trimBufferThenGetEvents();
5593         _super.prototype.next.call(this, value);
5594     };
5595     ReplaySubject.prototype._subscribe = function (subscriber) {
5596         var _events = this._trimBufferThenGetEvents();
5597         var scheduler = this.scheduler;
5598         var subscription;
5599         if (this.closed) {
5600             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5601         }
5602         else if (this.hasError) {
5603             subscription = Subscription_1.Subscription.EMPTY;
5604         }
5605         else if (this.isStopped) {
5606             subscription = Subscription_1.Subscription.EMPTY;
5607         }
5608         else {
5609             this.observers.push(subscriber);
5610             subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5611         }
5612         if (scheduler) {
5613             subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5614         }
5615         var len = _events.length;
5616         for (var i = 0; i < len && !subscriber.closed; i++) {
5617             subscriber.next(_events[i].value);
5618         }
5619         if (this.hasError) {
5620             subscriber.error(this.thrownError);
5621         }
5622         else if (this.isStopped) {
5623             subscriber.complete();
5624         }
5625         return subscription;
5626     };
5627     ReplaySubject.prototype._getNow = function () {
5628         return (this.scheduler || queue_1.queue).now();
5629     };
5630     ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5631         var now = this._getNow();
5632         var _bufferSize = this._bufferSize;
5633         var _windowTime = this._windowTime;
5634         var _events = this._events;
5635         var eventsCount = _events.length;
5636         var spliceCount = 0;
5637         // Trim events that fall out of the time window.
5638         // Start at the front of the list. Break early once
5639         // we encounter an event that falls within the window.
5640         while (spliceCount < eventsCount) {
5641             if ((now - _events[spliceCount].time) < _windowTime) {
5642                 break;
5643             }
5644             spliceCount++;
5645         }
5646         if (eventsCount > _bufferSize) {
5647             spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5648         }
5649         if (spliceCount > 0) {
5650             _events.splice(0, spliceCount);
5651         }
5652         return _events;
5653     };
5654     return ReplaySubject;
5655 }(Subject_1.Subject));
5656 exports.ReplaySubject = ReplaySubject;
5657 var ReplayEvent = (function () {
5658     function ReplayEvent(time, value) {
5659         this.time = time;
5660         this.value = value;
5661     }
5662     return ReplayEvent;
5663 }());
5664
5665 },{"./Subject":33,"./SubjectSubscription":34,"./Subscription":36,"./operator/observeOn":128,"./scheduler/queue":151,"./util/ObjectUnsubscribedError":158}],32:[function(require,module,exports){
5666 "use strict";
5667 /**
5668  * An execution context and a data structure to order tasks and schedule their
5669  * execution. Provides a notion of (potentially virtual) time, through the
5670  * `now()` getter method.
5671  *
5672  * Each unit of work in a Scheduler is called an {@link Action}.
5673  *
5674  * ```ts
5675  * class Scheduler {
5676  *   now(): number;
5677  *   schedule(work, delay?, state?): Subscription;
5678  * }
5679  * ```
5680  *
5681  * @class Scheduler
5682  */
5683 var Scheduler = (function () {
5684     function Scheduler(SchedulerAction, now) {
5685         if (now === void 0) { now = Scheduler.now; }
5686         this.SchedulerAction = SchedulerAction;
5687         this.now = now;
5688     }
5689     /**
5690      * Schedules a function, `work`, for execution. May happen at some point in
5691      * the future, according to the `delay` parameter, if specified. May be passed
5692      * some context object, `state`, which will be passed to the `work` function.
5693      *
5694      * The given arguments will be processed an stored as an Action object in a
5695      * queue of actions.
5696      *
5697      * @param {function(state: ?T): ?Subscription} work A function representing a
5698      * task, or some unit of work to be executed by the Scheduler.
5699      * @param {number} [delay] Time to wait before executing the work, where the
5700      * time unit is implicit and defined by the Scheduler itself.
5701      * @param {T} [state] Some contextual data that the `work` function uses when
5702      * called by the Scheduler.
5703      * @return {Subscription} A subscription in order to be able to unsubscribe
5704      * the scheduled work.
5705      */
5706     Scheduler.prototype.schedule = function (work, delay, state) {
5707         if (delay === void 0) { delay = 0; }
5708         return new this.SchedulerAction(this, work).schedule(state, delay);
5709     };
5710     Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
5711     return Scheduler;
5712 }());
5713 exports.Scheduler = Scheduler;
5714
5715 },{}],33:[function(require,module,exports){
5716 "use strict";
5717 var __extends = (this && this.__extends) || function (d, b) {
5718     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5719     function __() { this.constructor = d; }
5720     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5721 };
5722 var Observable_1 = require('./Observable');
5723 var Subscriber_1 = require('./Subscriber');
5724 var Subscription_1 = require('./Subscription');
5725 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5726 var SubjectSubscription_1 = require('./SubjectSubscription');
5727 var rxSubscriber_1 = require('./symbol/rxSubscriber');
5728 /**
5729  * @class SubjectSubscriber<T>
5730  */
5731 var SubjectSubscriber = (function (_super) {
5732     __extends(SubjectSubscriber, _super);
5733     function SubjectSubscriber(destination) {
5734         _super.call(this, destination);
5735         this.destination = destination;
5736     }
5737     return SubjectSubscriber;
5738 }(Subscriber_1.Subscriber));
5739 exports.SubjectSubscriber = SubjectSubscriber;
5740 /**
5741  * @class Subject<T>
5742  */
5743 var Subject = (function (_super) {
5744     __extends(Subject, _super);
5745     function Subject() {
5746         _super.call(this);
5747         this.observers = [];
5748         this.closed = false;
5749         this.isStopped = false;
5750         this.hasError = false;
5751         this.thrownError = null;
5752     }
5753     Subject.prototype[rxSubscriber_1.$$rxSubscriber] = function () {
5754         return new SubjectSubscriber(this);
5755     };
5756     Subject.prototype.lift = function (operator) {
5757         var subject = new AnonymousSubject(this, this);
5758         subject.operator = operator;
5759         return subject;
5760     };
5761     Subject.prototype.next = function (value) {
5762         if (this.closed) {
5763             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5764         }
5765         if (!this.isStopped) {
5766             var observers = this.observers;
5767             var len = observers.length;
5768             var copy = observers.slice();
5769             for (var i = 0; i < len; i++) {
5770                 copy[i].next(value);
5771             }
5772         }
5773     };
5774     Subject.prototype.error = function (err) {
5775         if (this.closed) {
5776             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5777         }
5778         this.hasError = true;
5779         this.thrownError = err;
5780         this.isStopped = true;
5781         var observers = this.observers;
5782         var len = observers.length;
5783         var copy = observers.slice();
5784         for (var i = 0; i < len; i++) {
5785             copy[i].error(err);
5786         }
5787         this.observers.length = 0;
5788     };
5789     Subject.prototype.complete = function () {
5790         if (this.closed) {
5791             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5792         }
5793         this.isStopped = true;
5794         var observers = this.observers;
5795         var len = observers.length;
5796         var copy = observers.slice();
5797         for (var i = 0; i < len; i++) {
5798             copy[i].complete();
5799         }
5800         this.observers.length = 0;
5801     };
5802     Subject.prototype.unsubscribe = function () {
5803         this.isStopped = true;
5804         this.closed = true;
5805         this.observers = null;
5806     };
5807     Subject.prototype._trySubscribe = function (subscriber) {
5808         if (this.closed) {
5809             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5810         }
5811         else {
5812             return _super.prototype._trySubscribe.call(this, subscriber);
5813         }
5814     };
5815     Subject.prototype._subscribe = function (subscriber) {
5816         if (this.closed) {
5817             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5818         }
5819         else if (this.hasError) {
5820             subscriber.error(this.thrownError);
5821             return Subscription_1.Subscription.EMPTY;
5822         }
5823         else if (this.isStopped) {
5824             subscriber.complete();
5825             return Subscription_1.Subscription.EMPTY;
5826         }
5827         else {
5828             this.observers.push(subscriber);
5829             return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5830         }
5831     };
5832     Subject.prototype.asObservable = function () {
5833         var observable = new Observable_1.Observable();
5834         observable.source = this;
5835         return observable;
5836     };
5837     Subject.create = function (destination, source) {
5838         return new AnonymousSubject(destination, source);
5839     };
5840     return Subject;
5841 }(Observable_1.Observable));
5842 exports.Subject = Subject;
5843 /**
5844  * @class AnonymousSubject<T>
5845  */
5846 var AnonymousSubject = (function (_super) {
5847     __extends(AnonymousSubject, _super);
5848     function AnonymousSubject(destination, source) {
5849         _super.call(this);
5850         this.destination = destination;
5851         this.source = source;
5852     }
5853     AnonymousSubject.prototype.next = function (value) {
5854         var destination = this.destination;
5855         if (destination && destination.next) {
5856             destination.next(value);
5857         }
5858     };
5859     AnonymousSubject.prototype.error = function (err) {
5860         var destination = this.destination;
5861         if (destination && destination.error) {
5862             this.destination.error(err);
5863         }
5864     };
5865     AnonymousSubject.prototype.complete = function () {
5866         var destination = this.destination;
5867         if (destination && destination.complete) {
5868             this.destination.complete();
5869         }
5870     };
5871     AnonymousSubject.prototype._subscribe = function (subscriber) {
5872         var source = this.source;
5873         if (source) {
5874             return this.source.subscribe(subscriber);
5875         }
5876         else {
5877             return Subscription_1.Subscription.EMPTY;
5878         }
5879     };
5880     return AnonymousSubject;
5881 }(Subject));
5882 exports.AnonymousSubject = AnonymousSubject;
5883
5884 },{"./Observable":28,"./SubjectSubscription":34,"./Subscriber":35,"./Subscription":36,"./symbol/rxSubscriber":154,"./util/ObjectUnsubscribedError":158}],34:[function(require,module,exports){
5885 "use strict";
5886 var __extends = (this && this.__extends) || function (d, b) {
5887     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5888     function __() { this.constructor = d; }
5889     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5890 };
5891 var Subscription_1 = require('./Subscription');
5892 /**
5893  * We need this JSDoc comment for affecting ESDoc.
5894  * @ignore
5895  * @extends {Ignored}
5896  */
5897 var SubjectSubscription = (function (_super) {
5898     __extends(SubjectSubscription, _super);
5899     function SubjectSubscription(subject, subscriber) {
5900         _super.call(this);
5901         this.subject = subject;
5902         this.subscriber = subscriber;
5903         this.closed = false;
5904     }
5905     SubjectSubscription.prototype.unsubscribe = function () {
5906         if (this.closed) {
5907             return;
5908         }
5909         this.closed = true;
5910         var subject = this.subject;
5911         var observers = subject.observers;
5912         this.subject = null;
5913         if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
5914             return;
5915         }
5916         var subscriberIndex = observers.indexOf(this.subscriber);
5917         if (subscriberIndex !== -1) {
5918             observers.splice(subscriberIndex, 1);
5919         }
5920     };
5921     return SubjectSubscription;
5922 }(Subscription_1.Subscription));
5923 exports.SubjectSubscription = SubjectSubscription;
5924
5925 },{"./Subscription":36}],35:[function(require,module,exports){
5926 "use strict";
5927 var __extends = (this && this.__extends) || function (d, b) {
5928     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5929     function __() { this.constructor = d; }
5930     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5931 };
5932 var isFunction_1 = require('./util/isFunction');
5933 var Subscription_1 = require('./Subscription');
5934 var Observer_1 = require('./Observer');
5935 var rxSubscriber_1 = require('./symbol/rxSubscriber');
5936 /**
5937  * Implements the {@link Observer} interface and extends the
5938  * {@link Subscription} class. While the {@link Observer} is the public API for
5939  * consuming the values of an {@link Observable}, all Observers get converted to
5940  * a Subscriber, in order to provide Subscription-like capabilities such as
5941  * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
5942  * implementing operators, but it is rarely used as a public API.
5943  *
5944  * @class Subscriber<T>
5945  */
5946 var Subscriber = (function (_super) {
5947     __extends(Subscriber, _super);
5948     /**
5949      * @param {Observer|function(value: T): void} [destinationOrNext] A partially
5950      * defined Observer or a `next` callback function.
5951      * @param {function(e: ?any): void} [error] The `error` callback of an
5952      * Observer.
5953      * @param {function(): void} [complete] The `complete` callback of an
5954      * Observer.
5955      */
5956     function Subscriber(destinationOrNext, error, complete) {
5957         _super.call(this);
5958         this.syncErrorValue = null;
5959         this.syncErrorThrown = false;
5960         this.syncErrorThrowable = false;
5961         this.isStopped = false;
5962         switch (arguments.length) {
5963             case 0:
5964                 this.destination = Observer_1.empty;
5965                 break;
5966             case 1:
5967                 if (!destinationOrNext) {
5968                     this.destination = Observer_1.empty;
5969                     break;
5970                 }
5971                 if (typeof destinationOrNext === 'object') {
5972                     if (destinationOrNext instanceof Subscriber) {
5973                         this.destination = destinationOrNext;
5974                         this.destination.add(this);
5975                     }
5976                     else {
5977                         this.syncErrorThrowable = true;
5978                         this.destination = new SafeSubscriber(this, destinationOrNext);
5979                     }
5980                     break;
5981                 }
5982             default:
5983                 this.syncErrorThrowable = true;
5984                 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
5985                 break;
5986         }
5987     }
5988     Subscriber.prototype[rxSubscriber_1.$$rxSubscriber] = function () { return this; };
5989     /**
5990      * A static factory for a Subscriber, given a (potentially partial) definition
5991      * of an Observer.
5992      * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
5993      * @param {function(e: ?any): void} [error] The `error` callback of an
5994      * Observer.
5995      * @param {function(): void} [complete] The `complete` callback of an
5996      * Observer.
5997      * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
5998      * Observer represented by the given arguments.
5999      */
6000     Subscriber.create = function (next, error, complete) {
6001         var subscriber = new Subscriber(next, error, complete);
6002         subscriber.syncErrorThrowable = false;
6003         return subscriber;
6004     };
6005     /**
6006      * The {@link Observer} callback to receive notifications of type `next` from
6007      * the Observable, with a value. The Observable may call this method 0 or more
6008      * times.
6009      * @param {T} [value] The `next` value.
6010      * @return {void}
6011      */
6012     Subscriber.prototype.next = function (value) {
6013         if (!this.isStopped) {
6014             this._next(value);
6015         }
6016     };
6017     /**
6018      * The {@link Observer} callback to receive notifications of type `error` from
6019      * the Observable, with an attached {@link Error}. Notifies the Observer that
6020      * the Observable has experienced an error condition.
6021      * @param {any} [err] The `error` exception.
6022      * @return {void}
6023      */
6024     Subscriber.prototype.error = function (err) {
6025         if (!this.isStopped) {
6026             this.isStopped = true;
6027             this._error(err);
6028         }
6029     };
6030     /**
6031      * The {@link Observer} callback to receive a valueless notification of type
6032      * `complete` from the Observable. Notifies the Observer that the Observable
6033      * has finished sending push-based notifications.
6034      * @return {void}
6035      */
6036     Subscriber.prototype.complete = function () {
6037         if (!this.isStopped) {
6038             this.isStopped = true;
6039             this._complete();
6040         }
6041     };
6042     Subscriber.prototype.unsubscribe = function () {
6043         if (this.closed) {
6044             return;
6045         }
6046         this.isStopped = true;
6047         _super.prototype.unsubscribe.call(this);
6048     };
6049     Subscriber.prototype._next = function (value) {
6050         this.destination.next(value);
6051     };
6052     Subscriber.prototype._error = function (err) {
6053         this.destination.error(err);
6054         this.unsubscribe();
6055     };
6056     Subscriber.prototype._complete = function () {
6057         this.destination.complete();
6058         this.unsubscribe();
6059     };
6060     Subscriber.prototype._unsubscribeAndRecycle = function () {
6061         var _a = this, _parent = _a._parent, _parents = _a._parents;
6062         this._parent = null;
6063         this._parents = null;
6064         this.unsubscribe();
6065         this.closed = false;
6066         this.isStopped = false;
6067         this._parent = _parent;
6068         this._parents = _parents;
6069         return this;
6070     };
6071     return Subscriber;
6072 }(Subscription_1.Subscription));
6073 exports.Subscriber = Subscriber;
6074 /**
6075  * We need this JSDoc comment for affecting ESDoc.
6076  * @ignore
6077  * @extends {Ignored}
6078  */
6079 var SafeSubscriber = (function (_super) {
6080     __extends(SafeSubscriber, _super);
6081     function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6082         _super.call(this);
6083         this._parentSubscriber = _parentSubscriber;
6084         var next;
6085         var context = this;
6086         if (isFunction_1.isFunction(observerOrNext)) {
6087             next = observerOrNext;
6088         }
6089         else if (observerOrNext) {
6090             context = observerOrNext;
6091             next = observerOrNext.next;
6092             error = observerOrNext.error;
6093             complete = observerOrNext.complete;
6094             if (isFunction_1.isFunction(context.unsubscribe)) {
6095                 this.add(context.unsubscribe.bind(context));
6096             }
6097             context.unsubscribe = this.unsubscribe.bind(this);
6098         }
6099         this._context = context;
6100         this._next = next;
6101         this._error = error;
6102         this._complete = complete;
6103     }
6104     SafeSubscriber.prototype.next = function (value) {
6105         if (!this.isStopped && this._next) {
6106             var _parentSubscriber = this._parentSubscriber;
6107             if (!_parentSubscriber.syncErrorThrowable) {
6108                 this.__tryOrUnsub(this._next, value);
6109             }
6110             else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6111                 this.unsubscribe();
6112             }
6113         }
6114     };
6115     SafeSubscriber.prototype.error = function (err) {
6116         if (!this.isStopped) {
6117             var _parentSubscriber = this._parentSubscriber;
6118             if (this._error) {
6119                 if (!_parentSubscriber.syncErrorThrowable) {
6120                     this.__tryOrUnsub(this._error, err);
6121                     this.unsubscribe();
6122                 }
6123                 else {
6124                     this.__tryOrSetError(_parentSubscriber, this._error, err);
6125                     this.unsubscribe();
6126                 }
6127             }
6128             else if (!_parentSubscriber.syncErrorThrowable) {
6129                 this.unsubscribe();
6130                 throw err;
6131             }
6132             else {
6133                 _parentSubscriber.syncErrorValue = err;
6134                 _parentSubscriber.syncErrorThrown = true;
6135                 this.unsubscribe();
6136             }
6137         }
6138     };
6139     SafeSubscriber.prototype.complete = function () {
6140         if (!this.isStopped) {
6141             var _parentSubscriber = this._parentSubscriber;
6142             if (this._complete) {
6143                 if (!_parentSubscriber.syncErrorThrowable) {
6144                     this.__tryOrUnsub(this._complete);
6145                     this.unsubscribe();
6146                 }
6147                 else {
6148                     this.__tryOrSetError(_parentSubscriber, this._complete);
6149                     this.unsubscribe();
6150                 }
6151             }
6152             else {
6153                 this.unsubscribe();
6154             }
6155         }
6156     };
6157     SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6158         try {
6159             fn.call(this._context, value);
6160         }
6161         catch (err) {
6162             this.unsubscribe();
6163             throw err;
6164         }
6165     };
6166     SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6167         try {
6168             fn.call(this._context, value);
6169         }
6170         catch (err) {
6171             parent.syncErrorValue = err;
6172             parent.syncErrorThrown = true;
6173             return true;
6174         }
6175         return false;
6176     };
6177     SafeSubscriber.prototype._unsubscribe = function () {
6178         var _parentSubscriber = this._parentSubscriber;
6179         this._context = null;
6180         this._parentSubscriber = null;
6181         _parentSubscriber.unsubscribe();
6182     };
6183     return SafeSubscriber;
6184 }(Subscriber));
6185
6186 },{"./Observer":29,"./Subscription":36,"./symbol/rxSubscriber":154,"./util/isFunction":165}],36:[function(require,module,exports){
6187 "use strict";
6188 var isArray_1 = require('./util/isArray');
6189 var isObject_1 = require('./util/isObject');
6190 var isFunction_1 = require('./util/isFunction');
6191 var tryCatch_1 = require('./util/tryCatch');
6192 var errorObject_1 = require('./util/errorObject');
6193 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6194 /**
6195  * Represents a disposable resource, such as the execution of an Observable. A
6196  * Subscription has one important method, `unsubscribe`, that takes no argument
6197  * and just disposes the resource held by the subscription.
6198  *
6199  * Additionally, subscriptions may be grouped together through the `add()`
6200  * method, which will attach a child Subscription to the current Subscription.
6201  * When a Subscription is unsubscribed, all its children (and its grandchildren)
6202  * will be unsubscribed as well.
6203  *
6204  * @class Subscription
6205  */
6206 var Subscription = (function () {
6207     /**
6208      * @param {function(): void} [unsubscribe] A function describing how to
6209      * perform the disposal of resources when the `unsubscribe` method is called.
6210      */
6211     function Subscription(unsubscribe) {
6212         /**
6213          * A flag to indicate whether this Subscription has already been unsubscribed.
6214          * @type {boolean}
6215          */
6216         this.closed = false;
6217         this._parent = null;
6218         this._parents = null;
6219         this._subscriptions = null;
6220         if (unsubscribe) {
6221             this._unsubscribe = unsubscribe;
6222         }
6223     }
6224     /**
6225      * Disposes the resources held by the subscription. May, for instance, cancel
6226      * an ongoing Observable execution or cancel any other type of work that
6227      * started when the Subscription was created.
6228      * @return {void}
6229      */
6230     Subscription.prototype.unsubscribe = function () {
6231         var hasErrors = false;
6232         var errors;
6233         if (this.closed) {
6234             return;
6235         }
6236         var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6237         this.closed = true;
6238         this._parent = null;
6239         this._parents = null;
6240         // null out _subscriptions first so any child subscriptions that attempt
6241         // to remove themselves from this subscription will noop
6242         this._subscriptions = null;
6243         var index = -1;
6244         var len = _parents ? _parents.length : 0;
6245         // if this._parent is null, then so is this._parents, and we
6246         // don't have to remove ourselves from any parent subscriptions.
6247         while (_parent) {
6248             _parent.remove(this);
6249             // if this._parents is null or index >= len,
6250             // then _parent is set to null, and the loop exits
6251             _parent = ++index < len && _parents[index] || null;
6252         }
6253         if (isFunction_1.isFunction(_unsubscribe)) {
6254             var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6255             if (trial === errorObject_1.errorObject) {
6256                 hasErrors = true;
6257                 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6258                     flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6259             }
6260         }
6261         if (isArray_1.isArray(_subscriptions)) {
6262             index = -1;
6263             len = _subscriptions.length;
6264             while (++index < len) {
6265                 var sub = _subscriptions[index];
6266                 if (isObject_1.isObject(sub)) {
6267                     var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6268                     if (trial === errorObject_1.errorObject) {
6269                         hasErrors = true;
6270                         errors = errors || [];
6271                         var err = errorObject_1.errorObject.e;
6272                         if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6273                             errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6274                         }
6275                         else {
6276                             errors.push(err);
6277                         }
6278                     }
6279                 }
6280             }
6281         }
6282         if (hasErrors) {
6283             throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6284         }
6285     };
6286     /**
6287      * Adds a tear down to be called during the unsubscribe() of this
6288      * Subscription.
6289      *
6290      * If the tear down being added is a subscription that is already
6291      * unsubscribed, is the same reference `add` is being called on, or is
6292      * `Subscription.EMPTY`, it will not be added.
6293      *
6294      * If this subscription is already in an `closed` state, the passed
6295      * tear down logic will be executed immediately.
6296      *
6297      * @param {TeardownLogic} teardown The additional logic to execute on
6298      * teardown.
6299      * @return {Subscription} Returns the Subscription used or created to be
6300      * added to the inner subscriptions list. This Subscription can be used with
6301      * `remove()` to remove the passed teardown logic from the inner subscriptions
6302      * list.
6303      */
6304     Subscription.prototype.add = function (teardown) {
6305         if (!teardown || (teardown === Subscription.EMPTY)) {
6306             return Subscription.EMPTY;
6307         }
6308         if (teardown === this) {
6309             return this;
6310         }
6311         var subscription = teardown;
6312         switch (typeof teardown) {
6313             case 'function':
6314                 subscription = new Subscription(teardown);
6315             case 'object':
6316                 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6317                     return subscription;
6318                 }
6319                 else if (this.closed) {
6320                     subscription.unsubscribe();
6321                     return subscription;
6322                 }
6323                 else if (typeof subscription._addParent !== 'function' /* quack quack */) {
6324                     var tmp = subscription;
6325                     subscription = new Subscription();
6326                     subscription._subscriptions = [tmp];
6327                 }
6328                 break;
6329             default:
6330                 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6331         }
6332         var subscriptions = this._subscriptions || (this._subscriptions = []);
6333         subscriptions.push(subscription);
6334         subscription._addParent(this);
6335         return subscription;
6336     };
6337     /**
6338      * Removes a Subscription from the internal list of subscriptions that will
6339      * unsubscribe during the unsubscribe process of this Subscription.
6340      * @param {Subscription} subscription The subscription to remove.
6341      * @return {void}
6342      */
6343     Subscription.prototype.remove = function (subscription) {
6344         var subscriptions = this._subscriptions;
6345         if (subscriptions) {
6346             var subscriptionIndex = subscriptions.indexOf(subscription);
6347             if (subscriptionIndex !== -1) {
6348                 subscriptions.splice(subscriptionIndex, 1);
6349             }
6350         }
6351     };
6352     Subscription.prototype._addParent = function (parent) {
6353         var _a = this, _parent = _a._parent, _parents = _a._parents;
6354         if (!_parent || _parent === parent) {
6355             // If we don't have a parent, or the new parent is the same as the
6356             // current parent, then set this._parent to the new parent.
6357             this._parent = parent;
6358         }
6359         else if (!_parents) {
6360             // If there's already one parent, but not multiple, allocate an Array to
6361             // store the rest of the parent Subscriptions.
6362             this._parents = [parent];
6363         }
6364         else if (_parents.indexOf(parent) === -1) {
6365             // Only add the new parent to the _parents list if it's not already there.
6366             _parents.push(parent);
6367         }
6368     };
6369     Subscription.EMPTY = (function (empty) {
6370         empty.closed = true;
6371         return empty;
6372     }(new Subscription()));
6373     return Subscription;
6374 }());
6375 exports.Subscription = Subscription;
6376 function flattenUnsubscriptionErrors(errors) {
6377     return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6378 }
6379
6380 },{"./util/UnsubscriptionError":160,"./util/errorObject":161,"./util/isArray":162,"./util/isFunction":165,"./util/isObject":167,"./util/tryCatch":173}],37:[function(require,module,exports){
6381 "use strict";
6382 var Observable_1 = require('../../Observable');
6383 var combineLatest_1 = require('../../observable/combineLatest');
6384 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6385
6386 },{"../../Observable":28,"../../observable/combineLatest":96}],38:[function(require,module,exports){
6387 "use strict";
6388 var Observable_1 = require('../../Observable');
6389 var defer_1 = require('../../observable/defer');
6390 Observable_1.Observable.defer = defer_1.defer;
6391
6392 },{"../../Observable":28,"../../observable/defer":97}],39:[function(require,module,exports){
6393 "use strict";
6394 var Observable_1 = require('../../Observable');
6395 var empty_1 = require('../../observable/empty');
6396 Observable_1.Observable.empty = empty_1.empty;
6397
6398 },{"../../Observable":28,"../../observable/empty":98}],40:[function(require,module,exports){
6399 "use strict";
6400 var Observable_1 = require('../../Observable');
6401 var from_1 = require('../../observable/from');
6402 Observable_1.Observable.from = from_1.from;
6403
6404 },{"../../Observable":28,"../../observable/from":99}],41:[function(require,module,exports){
6405 "use strict";
6406 var Observable_1 = require('../../Observable');
6407 var fromEvent_1 = require('../../observable/fromEvent');
6408 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6409
6410 },{"../../Observable":28,"../../observable/fromEvent":100}],42:[function(require,module,exports){
6411 "use strict";
6412 var Observable_1 = require('../../Observable');
6413 var fromPromise_1 = require('../../observable/fromPromise');
6414 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6415
6416 },{"../../Observable":28,"../../observable/fromPromise":101}],43:[function(require,module,exports){
6417 "use strict";
6418 var Observable_1 = require('../../Observable');
6419 var merge_1 = require('../../observable/merge');
6420 Observable_1.Observable.merge = merge_1.merge;
6421
6422 },{"../../Observable":28,"../../observable/merge":102}],44:[function(require,module,exports){
6423 "use strict";
6424 var Observable_1 = require('../../Observable');
6425 var of_1 = require('../../observable/of');
6426 Observable_1.Observable.of = of_1.of;
6427
6428 },{"../../Observable":28,"../../observable/of":103}],45:[function(require,module,exports){
6429 "use strict";
6430 var Observable_1 = require('../../Observable');
6431 var throw_1 = require('../../observable/throw');
6432 Observable_1.Observable.throw = throw_1._throw;
6433
6434 },{"../../Observable":28,"../../observable/throw":104}],46:[function(require,module,exports){
6435 "use strict";
6436 var Observable_1 = require('../../Observable');
6437 var timer_1 = require('../../observable/timer');
6438 Observable_1.Observable.timer = timer_1.timer;
6439
6440 },{"../../Observable":28,"../../observable/timer":105}],47:[function(require,module,exports){
6441 "use strict";
6442 var Observable_1 = require('../../Observable');
6443 var zip_1 = require('../../observable/zip');
6444 Observable_1.Observable.zip = zip_1.zip;
6445
6446 },{"../../Observable":28,"../../observable/zip":106}],48:[function(require,module,exports){
6447 "use strict";
6448 var Observable_1 = require('../../Observable');
6449 var buffer_1 = require('../../operator/buffer');
6450 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6451
6452 },{"../../Observable":28,"../../operator/buffer":107}],49:[function(require,module,exports){
6453 "use strict";
6454 var Observable_1 = require('../../Observable');
6455 var bufferCount_1 = require('../../operator/bufferCount');
6456 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6457
6458 },{"../../Observable":28,"../../operator/bufferCount":108}],50:[function(require,module,exports){
6459 "use strict";
6460 var Observable_1 = require('../../Observable');
6461 var bufferWhen_1 = require('../../operator/bufferWhen');
6462 Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen;
6463
6464 },{"../../Observable":28,"../../operator/bufferWhen":109}],51:[function(require,module,exports){
6465 "use strict";
6466 var Observable_1 = require('../../Observable');
6467 var catch_1 = require('../../operator/catch');
6468 Observable_1.Observable.prototype.catch = catch_1._catch;
6469 Observable_1.Observable.prototype._catch = catch_1._catch;
6470
6471 },{"../../Observable":28,"../../operator/catch":110}],52:[function(require,module,exports){
6472 "use strict";
6473 var Observable_1 = require('../../Observable');
6474 var combineLatest_1 = require('../../operator/combineLatest');
6475 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6476
6477 },{"../../Observable":28,"../../operator/combineLatest":111}],53:[function(require,module,exports){
6478 "use strict";
6479 var Observable_1 = require('../../Observable');
6480 var concat_1 = require('../../operator/concat');
6481 Observable_1.Observable.prototype.concat = concat_1.concat;
6482
6483 },{"../../Observable":28,"../../operator/concat":112}],54:[function(require,module,exports){
6484 "use strict";
6485 var Observable_1 = require('../../Observable');
6486 var debounceTime_1 = require('../../operator/debounceTime');
6487 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6488
6489 },{"../../Observable":28,"../../operator/debounceTime":113}],55:[function(require,module,exports){
6490 "use strict";
6491 var Observable_1 = require('../../Observable');
6492 var delay_1 = require('../../operator/delay');
6493 Observable_1.Observable.prototype.delay = delay_1.delay;
6494
6495 },{"../../Observable":28,"../../operator/delay":114}],56:[function(require,module,exports){
6496 "use strict";
6497 var Observable_1 = require('../../Observable');
6498 var distinct_1 = require('../../operator/distinct');
6499 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6500
6501 },{"../../Observable":28,"../../operator/distinct":115}],57:[function(require,module,exports){
6502 "use strict";
6503 var Observable_1 = require('../../Observable');
6504 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6505 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6506
6507 },{"../../Observable":28,"../../operator/distinctUntilChanged":116}],58:[function(require,module,exports){
6508 "use strict";
6509 var Observable_1 = require('../../Observable');
6510 var do_1 = require('../../operator/do');
6511 Observable_1.Observable.prototype.do = do_1._do;
6512 Observable_1.Observable.prototype._do = do_1._do;
6513
6514 },{"../../Observable":28,"../../operator/do":117}],59:[function(require,module,exports){
6515 "use strict";
6516 var Observable_1 = require('../../Observable');
6517 var expand_1 = require('../../operator/expand');
6518 Observable_1.Observable.prototype.expand = expand_1.expand;
6519
6520 },{"../../Observable":28,"../../operator/expand":118}],60:[function(require,module,exports){
6521 "use strict";
6522 var Observable_1 = require('../../Observable');
6523 var filter_1 = require('../../operator/filter');
6524 Observable_1.Observable.prototype.filter = filter_1.filter;
6525
6526 },{"../../Observable":28,"../../operator/filter":119}],61:[function(require,module,exports){
6527 "use strict";
6528 var Observable_1 = require('../../Observable');
6529 var finally_1 = require('../../operator/finally');
6530 Observable_1.Observable.prototype.finally = finally_1._finally;
6531 Observable_1.Observable.prototype._finally = finally_1._finally;
6532
6533 },{"../../Observable":28,"../../operator/finally":120}],62:[function(require,module,exports){
6534 "use strict";
6535 var Observable_1 = require('../../Observable');
6536 var first_1 = require('../../operator/first');
6537 Observable_1.Observable.prototype.first = first_1.first;
6538
6539 },{"../../Observable":28,"../../operator/first":121}],63:[function(require,module,exports){
6540 "use strict";
6541 var Observable_1 = require('../../Observable');
6542 var last_1 = require('../../operator/last');
6543 Observable_1.Observable.prototype.last = last_1.last;
6544
6545 },{"../../Observable":28,"../../operator/last":122}],64:[function(require,module,exports){
6546 "use strict";
6547 var Observable_1 = require('../../Observable');
6548 var map_1 = require('../../operator/map');
6549 Observable_1.Observable.prototype.map = map_1.map;
6550
6551 },{"../../Observable":28,"../../operator/map":123}],65:[function(require,module,exports){
6552 "use strict";
6553 var Observable_1 = require('../../Observable');
6554 var merge_1 = require('../../operator/merge');
6555 Observable_1.Observable.prototype.merge = merge_1.merge;
6556
6557 },{"../../Observable":28,"../../operator/merge":124}],66:[function(require,module,exports){
6558 "use strict";
6559 var Observable_1 = require('../../Observable');
6560 var mergeAll_1 = require('../../operator/mergeAll');
6561 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6562
6563 },{"../../Observable":28,"../../operator/mergeAll":125}],67:[function(require,module,exports){
6564 "use strict";
6565 var Observable_1 = require('../../Observable');
6566 var mergeMap_1 = require('../../operator/mergeMap');
6567 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6568 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6569
6570 },{"../../Observable":28,"../../operator/mergeMap":126}],68:[function(require,module,exports){
6571 "use strict";
6572 var Observable_1 = require('../../Observable');
6573 var pairwise_1 = require('../../operator/pairwise');
6574 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6575
6576 },{"../../Observable":28,"../../operator/pairwise":129}],69:[function(require,module,exports){
6577 "use strict";
6578 var Observable_1 = require('../../Observable');
6579 var pluck_1 = require('../../operator/pluck');
6580 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6581
6582 },{"../../Observable":28,"../../operator/pluck":130}],70:[function(require,module,exports){
6583 "use strict";
6584 var Observable_1 = require('../../Observable');
6585 var publish_1 = require('../../operator/publish');
6586 Observable_1.Observable.prototype.publish = publish_1.publish;
6587
6588 },{"../../Observable":28,"../../operator/publish":131}],71:[function(require,module,exports){
6589 "use strict";
6590 var Observable_1 = require('../../Observable');
6591 var publishReplay_1 = require('../../operator/publishReplay');
6592 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6593
6594 },{"../../Observable":28,"../../operator/publishReplay":132}],72:[function(require,module,exports){
6595 "use strict";
6596 var Observable_1 = require('../../Observable');
6597 var scan_1 = require('../../operator/scan');
6598 Observable_1.Observable.prototype.scan = scan_1.scan;
6599
6600 },{"../../Observable":28,"../../operator/scan":133}],73:[function(require,module,exports){
6601 "use strict";
6602 var Observable_1 = require('../../Observable');
6603 var share_1 = require('../../operator/share');
6604 Observable_1.Observable.prototype.share = share_1.share;
6605
6606 },{"../../Observable":28,"../../operator/share":134}],74:[function(require,module,exports){
6607 "use strict";
6608 var Observable_1 = require('../../Observable');
6609 var skip_1 = require('../../operator/skip');
6610 Observable_1.Observable.prototype.skip = skip_1.skip;
6611
6612 },{"../../Observable":28,"../../operator/skip":135}],75:[function(require,module,exports){
6613 "use strict";
6614 var Observable_1 = require('../../Observable');
6615 var skipUntil_1 = require('../../operator/skipUntil');
6616 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6617
6618 },{"../../Observable":28,"../../operator/skipUntil":136}],76:[function(require,module,exports){
6619 "use strict";
6620 var Observable_1 = require('../../Observable');
6621 var skipWhile_1 = require('../../operator/skipWhile');
6622 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
6623
6624 },{"../../Observable":28,"../../operator/skipWhile":137}],77:[function(require,module,exports){
6625 "use strict";
6626 var Observable_1 = require('../../Observable');
6627 var startWith_1 = require('../../operator/startWith');
6628 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
6629
6630 },{"../../Observable":28,"../../operator/startWith":138}],78:[function(require,module,exports){
6631 "use strict";
6632 var Observable_1 = require('../../Observable');
6633 var switchMap_1 = require('../../operator/switchMap');
6634 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
6635
6636 },{"../../Observable":28,"../../operator/switchMap":139}],79:[function(require,module,exports){
6637 "use strict";
6638 var Observable_1 = require('../../Observable');
6639 var take_1 = require('../../operator/take');
6640 Observable_1.Observable.prototype.take = take_1.take;
6641
6642 },{"../../Observable":28,"../../operator/take":140}],80:[function(require,module,exports){
6643 "use strict";
6644 var Observable_1 = require('../../Observable');
6645 var takeUntil_1 = require('../../operator/takeUntil');
6646 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
6647
6648 },{"../../Observable":28,"../../operator/takeUntil":141}],81:[function(require,module,exports){
6649 "use strict";
6650 var Observable_1 = require('../../Observable');
6651 var throttleTime_1 = require('../../operator/throttleTime');
6652 Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime;
6653
6654 },{"../../Observable":28,"../../operator/throttleTime":142}],82:[function(require,module,exports){
6655 "use strict";
6656 var Observable_1 = require('../../Observable');
6657 var withLatestFrom_1 = require('../../operator/withLatestFrom');
6658 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
6659
6660 },{"../../Observable":28,"../../operator/withLatestFrom":143}],83:[function(require,module,exports){
6661 "use strict";
6662 var Observable_1 = require('../../Observable');
6663 var zip_1 = require('../../operator/zip');
6664 Observable_1.Observable.prototype.zip = zip_1.zipProto;
6665
6666 },{"../../Observable":28,"../../operator/zip":144}],84:[function(require,module,exports){
6667 "use strict";
6668 var __extends = (this && this.__extends) || function (d, b) {
6669     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6670     function __() { this.constructor = d; }
6671     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6672 };
6673 var Observable_1 = require('../Observable');
6674 var ScalarObservable_1 = require('./ScalarObservable');
6675 var EmptyObservable_1 = require('./EmptyObservable');
6676 /**
6677  * We need this JSDoc comment for affecting ESDoc.
6678  * @extends {Ignored}
6679  * @hide true
6680  */
6681 var ArrayLikeObservable = (function (_super) {
6682     __extends(ArrayLikeObservable, _super);
6683     function ArrayLikeObservable(arrayLike, scheduler) {
6684         _super.call(this);
6685         this.arrayLike = arrayLike;
6686         this.scheduler = scheduler;
6687         if (!scheduler && arrayLike.length === 1) {
6688             this._isScalar = true;
6689             this.value = arrayLike[0];
6690         }
6691     }
6692     ArrayLikeObservable.create = function (arrayLike, scheduler) {
6693         var length = arrayLike.length;
6694         if (length === 0) {
6695             return new EmptyObservable_1.EmptyObservable();
6696         }
6697         else if (length === 1) {
6698             return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
6699         }
6700         else {
6701             return new ArrayLikeObservable(arrayLike, scheduler);
6702         }
6703     };
6704     ArrayLikeObservable.dispatch = function (state) {
6705         var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
6706         if (subscriber.closed) {
6707             return;
6708         }
6709         if (index >= length) {
6710             subscriber.complete();
6711             return;
6712         }
6713         subscriber.next(arrayLike[index]);
6714         state.index = index + 1;
6715         this.schedule(state);
6716     };
6717     ArrayLikeObservable.prototype._subscribe = function (subscriber) {
6718         var index = 0;
6719         var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
6720         var length = arrayLike.length;
6721         if (scheduler) {
6722             return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
6723                 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
6724             });
6725         }
6726         else {
6727             for (var i = 0; i < length && !subscriber.closed; i++) {
6728                 subscriber.next(arrayLike[i]);
6729             }
6730             subscriber.complete();
6731         }
6732     };
6733     return ArrayLikeObservable;
6734 }(Observable_1.Observable));
6735 exports.ArrayLikeObservable = ArrayLikeObservable;
6736
6737 },{"../Observable":28,"./EmptyObservable":88,"./ScalarObservable":94}],85:[function(require,module,exports){
6738 "use strict";
6739 var __extends = (this && this.__extends) || function (d, b) {
6740     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6741     function __() { this.constructor = d; }
6742     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6743 };
6744 var Observable_1 = require('../Observable');
6745 var ScalarObservable_1 = require('./ScalarObservable');
6746 var EmptyObservable_1 = require('./EmptyObservable');
6747 var isScheduler_1 = require('../util/isScheduler');
6748 /**
6749  * We need this JSDoc comment for affecting ESDoc.
6750  * @extends {Ignored}
6751  * @hide true
6752  */
6753 var ArrayObservable = (function (_super) {
6754     __extends(ArrayObservable, _super);
6755     function ArrayObservable(array, scheduler) {
6756         _super.call(this);
6757         this.array = array;
6758         this.scheduler = scheduler;
6759         if (!scheduler && array.length === 1) {
6760             this._isScalar = true;
6761             this.value = array[0];
6762         }
6763     }
6764     ArrayObservable.create = function (array, scheduler) {
6765         return new ArrayObservable(array, scheduler);
6766     };
6767     /**
6768      * Creates an Observable that emits some values you specify as arguments,
6769      * immediately one after the other, and then emits a complete notification.
6770      *
6771      * <span class="informal">Emits the arguments you provide, then completes.
6772      * </span>
6773      *
6774      * <img src="./img/of.png" width="100%">
6775      *
6776      * This static operator is useful for creating a simple Observable that only
6777      * emits the arguments given, and the complete notification thereafter. It can
6778      * be used for composing with other Observables, such as with {@link concat}.
6779      * By default, it uses a `null` IScheduler, which means the `next`
6780      * notifications are sent synchronously, although with a different IScheduler
6781      * it is possible to determine when those notifications will be delivered.
6782      *
6783      * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
6784      * var numbers = Rx.Observable.of(10, 20, 30);
6785      * var letters = Rx.Observable.of('a', 'b', 'c');
6786      * var interval = Rx.Observable.interval(1000);
6787      * var result = numbers.concat(letters).concat(interval);
6788      * result.subscribe(x => console.log(x));
6789      *
6790      * @see {@link create}
6791      * @see {@link empty}
6792      * @see {@link never}
6793      * @see {@link throw}
6794      *
6795      * @param {...T} values Arguments that represent `next` values to be emitted.
6796      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
6797      * the emissions of the `next` notifications.
6798      * @return {Observable<T>} An Observable that emits each given input value.
6799      * @static true
6800      * @name of
6801      * @owner Observable
6802      */
6803     ArrayObservable.of = function () {
6804         var array = [];
6805         for (var _i = 0; _i < arguments.length; _i++) {
6806             array[_i - 0] = arguments[_i];
6807         }
6808         var scheduler = array[array.length - 1];
6809         if (isScheduler_1.isScheduler(scheduler)) {
6810             array.pop();
6811         }
6812         else {
6813             scheduler = null;
6814         }
6815         var len = array.length;
6816         if (len > 1) {
6817             return new ArrayObservable(array, scheduler);
6818         }
6819         else if (len === 1) {
6820             return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
6821         }
6822         else {
6823             return new EmptyObservable_1.EmptyObservable(scheduler);
6824         }
6825     };
6826     ArrayObservable.dispatch = function (state) {
6827         var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
6828         if (index >= count) {
6829             subscriber.complete();
6830             return;
6831         }
6832         subscriber.next(array[index]);
6833         if (subscriber.closed) {
6834             return;
6835         }
6836         state.index = index + 1;
6837         this.schedule(state);
6838     };
6839     ArrayObservable.prototype._subscribe = function (subscriber) {
6840         var index = 0;
6841         var array = this.array;
6842         var count = array.length;
6843         var scheduler = this.scheduler;
6844         if (scheduler) {
6845             return scheduler.schedule(ArrayObservable.dispatch, 0, {
6846                 array: array, index: index, count: count, subscriber: subscriber
6847             });
6848         }
6849         else {
6850             for (var i = 0; i < count && !subscriber.closed; i++) {
6851                 subscriber.next(array[i]);
6852             }
6853             subscriber.complete();
6854         }
6855     };
6856     return ArrayObservable;
6857 }(Observable_1.Observable));
6858 exports.ArrayObservable = ArrayObservable;
6859
6860 },{"../Observable":28,"../util/isScheduler":169,"./EmptyObservable":88,"./ScalarObservable":94}],86:[function(require,module,exports){
6861 "use strict";
6862 var __extends = (this && this.__extends) || function (d, b) {
6863     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6864     function __() { this.constructor = d; }
6865     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6866 };
6867 var Subject_1 = require('../Subject');
6868 var Observable_1 = require('../Observable');
6869 var Subscriber_1 = require('../Subscriber');
6870 var Subscription_1 = require('../Subscription');
6871 /**
6872  * @class ConnectableObservable<T>
6873  */
6874 var ConnectableObservable = (function (_super) {
6875     __extends(ConnectableObservable, _super);
6876     function ConnectableObservable(source, subjectFactory) {
6877         _super.call(this);
6878         this.source = source;
6879         this.subjectFactory = subjectFactory;
6880         this._refCount = 0;
6881     }
6882     ConnectableObservable.prototype._subscribe = function (subscriber) {
6883         return this.getSubject().subscribe(subscriber);
6884     };
6885     ConnectableObservable.prototype.getSubject = function () {
6886         var subject = this._subject;
6887         if (!subject || subject.isStopped) {
6888             this._subject = this.subjectFactory();
6889         }
6890         return this._subject;
6891     };
6892     ConnectableObservable.prototype.connect = function () {
6893         var connection = this._connection;
6894         if (!connection) {
6895             connection = this._connection = new Subscription_1.Subscription();
6896             connection.add(this.source
6897                 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
6898             if (connection.closed) {
6899                 this._connection = null;
6900                 connection = Subscription_1.Subscription.EMPTY;
6901             }
6902             else {
6903                 this._connection = connection;
6904             }
6905         }
6906         return connection;
6907     };
6908     ConnectableObservable.prototype.refCount = function () {
6909         return this.lift(new RefCountOperator(this));
6910     };
6911     return ConnectableObservable;
6912 }(Observable_1.Observable));
6913 exports.ConnectableObservable = ConnectableObservable;
6914 exports.connectableObservableDescriptor = {
6915     operator: { value: null },
6916     _refCount: { value: 0, writable: true },
6917     _subscribe: { value: ConnectableObservable.prototype._subscribe },
6918     getSubject: { value: ConnectableObservable.prototype.getSubject },
6919     connect: { value: ConnectableObservable.prototype.connect },
6920     refCount: { value: ConnectableObservable.prototype.refCount }
6921 };
6922 var ConnectableSubscriber = (function (_super) {
6923     __extends(ConnectableSubscriber, _super);
6924     function ConnectableSubscriber(destination, connectable) {
6925         _super.call(this, destination);
6926         this.connectable = connectable;
6927     }
6928     ConnectableSubscriber.prototype._error = function (err) {
6929         this._unsubscribe();
6930         _super.prototype._error.call(this, err);
6931     };
6932     ConnectableSubscriber.prototype._complete = function () {
6933         this._unsubscribe();
6934         _super.prototype._complete.call(this);
6935     };
6936     ConnectableSubscriber.prototype._unsubscribe = function () {
6937         var connectable = this.connectable;
6938         if (connectable) {
6939             this.connectable = null;
6940             var connection = connectable._connection;
6941             connectable._refCount = 0;
6942             connectable._subject = null;
6943             connectable._connection = null;
6944             if (connection) {
6945                 connection.unsubscribe();
6946             }
6947         }
6948     };
6949     return ConnectableSubscriber;
6950 }(Subject_1.SubjectSubscriber));
6951 var RefCountOperator = (function () {
6952     function RefCountOperator(connectable) {
6953         this.connectable = connectable;
6954     }
6955     RefCountOperator.prototype.call = function (subscriber, source) {
6956         var connectable = this.connectable;
6957         connectable._refCount++;
6958         var refCounter = new RefCountSubscriber(subscriber, connectable);
6959         var subscription = source.subscribe(refCounter);
6960         if (!refCounter.closed) {
6961             refCounter.connection = connectable.connect();
6962         }
6963         return subscription;
6964     };
6965     return RefCountOperator;
6966 }());
6967 var RefCountSubscriber = (function (_super) {
6968     __extends(RefCountSubscriber, _super);
6969     function RefCountSubscriber(destination, connectable) {
6970         _super.call(this, destination);
6971         this.connectable = connectable;
6972     }
6973     RefCountSubscriber.prototype._unsubscribe = function () {
6974         var connectable = this.connectable;
6975         if (!connectable) {
6976             this.connection = null;
6977             return;
6978         }
6979         this.connectable = null;
6980         var refCount = connectable._refCount;
6981         if (refCount <= 0) {
6982             this.connection = null;
6983             return;
6984         }
6985         connectable._refCount = refCount - 1;
6986         if (refCount > 1) {
6987             this.connection = null;
6988             return;
6989         }
6990         ///
6991         // Compare the local RefCountSubscriber's connection Subscription to the
6992         // connection Subscription on the shared ConnectableObservable. In cases
6993         // where the ConnectableObservable source synchronously emits values, and
6994         // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
6995         // execution continues to here before the RefCountOperator has a chance to
6996         // supply the RefCountSubscriber with the shared connection Subscription.
6997         // For example:
6998         // ```
6999         // Observable.range(0, 10)
7000         //   .publish()
7001         //   .refCount()
7002         //   .take(5)
7003         //   .subscribe();
7004         // ```
7005         // In order to account for this case, RefCountSubscriber should only dispose
7006         // the ConnectableObservable's shared connection Subscription if the
7007         // connection Subscription exists, *and* either:
7008         //   a. RefCountSubscriber doesn't have a reference to the shared connection
7009         //      Subscription yet, or,
7010         //   b. RefCountSubscriber's connection Subscription reference is identical
7011         //      to the shared connection Subscription
7012         ///
7013         var connection = this.connection;
7014         var sharedConnection = connectable._connection;
7015         this.connection = null;
7016         if (sharedConnection && (!connection || sharedConnection === connection)) {
7017             sharedConnection.unsubscribe();
7018         }
7019     };
7020     return RefCountSubscriber;
7021 }(Subscriber_1.Subscriber));
7022
7023 },{"../Observable":28,"../Subject":33,"../Subscriber":35,"../Subscription":36}],87:[function(require,module,exports){
7024 "use strict";
7025 var __extends = (this && this.__extends) || function (d, b) {
7026     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7027     function __() { this.constructor = d; }
7028     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7029 };
7030 var Observable_1 = require('../Observable');
7031 var subscribeToResult_1 = require('../util/subscribeToResult');
7032 var OuterSubscriber_1 = require('../OuterSubscriber');
7033 /**
7034  * We need this JSDoc comment for affecting ESDoc.
7035  * @extends {Ignored}
7036  * @hide true
7037  */
7038 var DeferObservable = (function (_super) {
7039     __extends(DeferObservable, _super);
7040     function DeferObservable(observableFactory) {
7041         _super.call(this);
7042         this.observableFactory = observableFactory;
7043     }
7044     /**
7045      * Creates an Observable that, on subscribe, calls an Observable factory to
7046      * make an Observable for each new Observer.
7047      *
7048      * <span class="informal">Creates the Observable lazily, that is, only when it
7049      * is subscribed.
7050      * </span>
7051      *
7052      * <img src="./img/defer.png" width="100%">
7053      *
7054      * `defer` allows you to create the Observable only when the Observer
7055      * subscribes, and create a fresh Observable for each Observer. It waits until
7056      * an Observer subscribes to it, and then it generates an Observable,
7057      * typically with an Observable factory function. It does this afresh for each
7058      * subscriber, so although each subscriber may think it is subscribing to the
7059      * same Observable, in fact each subscriber gets its own individual
7060      * Observable.
7061      *
7062      * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7063      * var clicksOrInterval = Rx.Observable.defer(function () {
7064      *   if (Math.random() > 0.5) {
7065      *     return Rx.Observable.fromEvent(document, 'click');
7066      *   } else {
7067      *     return Rx.Observable.interval(1000);
7068      *   }
7069      * });
7070      * clicksOrInterval.subscribe(x => console.log(x));
7071      *
7072      * // Results in the following behavior:
7073      * // If the result of Math.random() is greater than 0.5 it will listen
7074      * // for clicks anywhere on the "document"; when document is clicked it
7075      * // will log a MouseEvent object to the console. If the result is less
7076      * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7077      *
7078      * @see {@link create}
7079      *
7080      * @param {function(): SubscribableOrPromise} observableFactory The Observable
7081      * factory function to invoke for each Observer that subscribes to the output
7082      * Observable. May also return a Promise, which will be converted on the fly
7083      * to an Observable.
7084      * @return {Observable} An Observable whose Observers' subscriptions trigger
7085      * an invocation of the given Observable factory function.
7086      * @static true
7087      * @name defer
7088      * @owner Observable
7089      */
7090     DeferObservable.create = function (observableFactory) {
7091         return new DeferObservable(observableFactory);
7092     };
7093     DeferObservable.prototype._subscribe = function (subscriber) {
7094         return new DeferSubscriber(subscriber, this.observableFactory);
7095     };
7096     return DeferObservable;
7097 }(Observable_1.Observable));
7098 exports.DeferObservable = DeferObservable;
7099 var DeferSubscriber = (function (_super) {
7100     __extends(DeferSubscriber, _super);
7101     function DeferSubscriber(destination, factory) {
7102         _super.call(this, destination);
7103         this.factory = factory;
7104         this.tryDefer();
7105     }
7106     DeferSubscriber.prototype.tryDefer = function () {
7107         try {
7108             this._callFactory();
7109         }
7110         catch (err) {
7111             this._error(err);
7112         }
7113     };
7114     DeferSubscriber.prototype._callFactory = function () {
7115         var result = this.factory();
7116         if (result) {
7117             this.add(subscribeToResult_1.subscribeToResult(this, result));
7118         }
7119     };
7120     return DeferSubscriber;
7121 }(OuterSubscriber_1.OuterSubscriber));
7122
7123 },{"../Observable":28,"../OuterSubscriber":30,"../util/subscribeToResult":171}],88:[function(require,module,exports){
7124 "use strict";
7125 var __extends = (this && this.__extends) || function (d, b) {
7126     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7127     function __() { this.constructor = d; }
7128     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7129 };
7130 var Observable_1 = require('../Observable');
7131 /**
7132  * We need this JSDoc comment for affecting ESDoc.
7133  * @extends {Ignored}
7134  * @hide true
7135  */
7136 var EmptyObservable = (function (_super) {
7137     __extends(EmptyObservable, _super);
7138     function EmptyObservable(scheduler) {
7139         _super.call(this);
7140         this.scheduler = scheduler;
7141     }
7142     /**
7143      * Creates an Observable that emits no items to the Observer and immediately
7144      * emits a complete notification.
7145      *
7146      * <span class="informal">Just emits 'complete', and nothing else.
7147      * </span>
7148      *
7149      * <img src="./img/empty.png" width="100%">
7150      *
7151      * This static operator is useful for creating a simple Observable that only
7152      * emits the complete notification. It can be used for composing with other
7153      * Observables, such as in a {@link mergeMap}.
7154      *
7155      * @example <caption>Emit the number 7, then complete.</caption>
7156      * var result = Rx.Observable.empty().startWith(7);
7157      * result.subscribe(x => console.log(x));
7158      *
7159      * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7160      * var interval = Rx.Observable.interval(1000);
7161      * var result = interval.mergeMap(x =>
7162      *   x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7163      * );
7164      * result.subscribe(x => console.log(x));
7165      *
7166      * // Results in the following to the console:
7167      * // x is equal to the count on the interval eg(0,1,2,3,...)
7168      * // x will occur every 1000ms
7169      * // if x % 2 is equal to 1 print abc
7170      * // if x % 2 is not equal to 1 nothing will be output
7171      *
7172      * @see {@link create}
7173      * @see {@link never}
7174      * @see {@link of}
7175      * @see {@link throw}
7176      *
7177      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7178      * the emission of the complete notification.
7179      * @return {Observable} An "empty" Observable: emits only the complete
7180      * notification.
7181      * @static true
7182      * @name empty
7183      * @owner Observable
7184      */
7185     EmptyObservable.create = function (scheduler) {
7186         return new EmptyObservable(scheduler);
7187     };
7188     EmptyObservable.dispatch = function (arg) {
7189         var subscriber = arg.subscriber;
7190         subscriber.complete();
7191     };
7192     EmptyObservable.prototype._subscribe = function (subscriber) {
7193         var scheduler = this.scheduler;
7194         if (scheduler) {
7195             return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7196         }
7197         else {
7198             subscriber.complete();
7199         }
7200     };
7201     return EmptyObservable;
7202 }(Observable_1.Observable));
7203 exports.EmptyObservable = EmptyObservable;
7204
7205 },{"../Observable":28}],89:[function(require,module,exports){
7206 "use strict";
7207 var __extends = (this && this.__extends) || function (d, b) {
7208     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7209     function __() { this.constructor = d; }
7210     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7211 };
7212 var Observable_1 = require('../Observable');
7213 /**
7214  * We need this JSDoc comment for affecting ESDoc.
7215  * @extends {Ignored}
7216  * @hide true
7217  */
7218 var ErrorObservable = (function (_super) {
7219     __extends(ErrorObservable, _super);
7220     function ErrorObservable(error, scheduler) {
7221         _super.call(this);
7222         this.error = error;
7223         this.scheduler = scheduler;
7224     }
7225     /**
7226      * Creates an Observable that emits no items to the Observer and immediately
7227      * emits an error notification.
7228      *
7229      * <span class="informal">Just emits 'error', and nothing else.
7230      * </span>
7231      *
7232      * <img src="./img/throw.png" width="100%">
7233      *
7234      * This static operator is useful for creating a simple Observable that only
7235      * emits the error notification. It can be used for composing with other
7236      * Observables, such as in a {@link mergeMap}.
7237      *
7238      * @example <caption>Emit the number 7, then emit an error.</caption>
7239      * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7240      * result.subscribe(x => console.log(x), e => console.error(e));
7241      *
7242      * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7243      * var interval = Rx.Observable.interval(1000);
7244      * var result = interval.mergeMap(x =>
7245      *   x === 13 ?
7246      *     Rx.Observable.throw('Thirteens are bad') :
7247      *     Rx.Observable.of('a', 'b', 'c')
7248      * );
7249      * result.subscribe(x => console.log(x), e => console.error(e));
7250      *
7251      * @see {@link create}
7252      * @see {@link empty}
7253      * @see {@link never}
7254      * @see {@link of}
7255      *
7256      * @param {any} error The particular Error to pass to the error notification.
7257      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7258      * the emission of the error notification.
7259      * @return {Observable} An error Observable: emits only the error notification
7260      * using the given error argument.
7261      * @static true
7262      * @name throw
7263      * @owner Observable
7264      */
7265     ErrorObservable.create = function (error, scheduler) {
7266         return new ErrorObservable(error, scheduler);
7267     };
7268     ErrorObservable.dispatch = function (arg) {
7269         var error = arg.error, subscriber = arg.subscriber;
7270         subscriber.error(error);
7271     };
7272     ErrorObservable.prototype._subscribe = function (subscriber) {
7273         var error = this.error;
7274         var scheduler = this.scheduler;
7275         if (scheduler) {
7276             return scheduler.schedule(ErrorObservable.dispatch, 0, {
7277                 error: error, subscriber: subscriber
7278             });
7279         }
7280         else {
7281             subscriber.error(error);
7282         }
7283     };
7284     return ErrorObservable;
7285 }(Observable_1.Observable));
7286 exports.ErrorObservable = ErrorObservable;
7287
7288 },{"../Observable":28}],90:[function(require,module,exports){
7289 "use strict";
7290 var __extends = (this && this.__extends) || function (d, b) {
7291     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7292     function __() { this.constructor = d; }
7293     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7294 };
7295 var Observable_1 = require('../Observable');
7296 var tryCatch_1 = require('../util/tryCatch');
7297 var isFunction_1 = require('../util/isFunction');
7298 var errorObject_1 = require('../util/errorObject');
7299 var Subscription_1 = require('../Subscription');
7300 var toString = Object.prototype.toString;
7301 function isNodeStyleEventEmitter(sourceObj) {
7302     return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7303 }
7304 function isJQueryStyleEventEmitter(sourceObj) {
7305     return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7306 }
7307 function isNodeList(sourceObj) {
7308     return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7309 }
7310 function isHTMLCollection(sourceObj) {
7311     return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7312 }
7313 function isEventTarget(sourceObj) {
7314     return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7315 }
7316 /**
7317  * We need this JSDoc comment for affecting ESDoc.
7318  * @extends {Ignored}
7319  * @hide true
7320  */
7321 var FromEventObservable = (function (_super) {
7322     __extends(FromEventObservable, _super);
7323     function FromEventObservable(sourceObj, eventName, selector, options) {
7324         _super.call(this);
7325         this.sourceObj = sourceObj;
7326         this.eventName = eventName;
7327         this.selector = selector;
7328         this.options = options;
7329     }
7330     /* tslint:enable:max-line-length */
7331     /**
7332      * Creates an Observable that emits events of a specific type coming from the
7333      * given event target.
7334      *
7335      * <span class="informal">Creates an Observable from DOM events, or Node
7336      * EventEmitter events or others.</span>
7337      *
7338      * <img src="./img/fromEvent.png" width="100%">
7339      *
7340      * Creates an Observable by attaching an event listener to an "event target",
7341      * which may be an object with `addEventListener` and `removeEventListener`,
7342      * a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the
7343      * DOM, or an HTMLCollection from the DOM. The event handler is attached when
7344      * the output Observable is subscribed, and removed when the Subscription is
7345      * unsubscribed.
7346      *
7347      * @example <caption>Emits clicks happening on the DOM document</caption>
7348      * var clicks = Rx.Observable.fromEvent(document, 'click');
7349      * clicks.subscribe(x => console.log(x));
7350      *
7351      * // Results in:
7352      * // MouseEvent object logged to console everytime a click
7353      * // occurs on the document.
7354      *
7355      * @see {@link from}
7356      * @see {@link fromEventPattern}
7357      *
7358      * @param {EventTargetLike} target The DOMElement, event target, Node.js
7359      * EventEmitter, NodeList or HTMLCollection to attach the event handler to.
7360      * @param {string} eventName The event name of interest, being emitted by the
7361      * `target`.
7362      * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7363      * @param {SelectorMethodSignature<T>} [selector] An optional function to
7364      * post-process results. It takes the arguments from the event handler and
7365      * should return a single value.
7366      * @return {Observable<T>}
7367      * @static true
7368      * @name fromEvent
7369      * @owner Observable
7370      */
7371     FromEventObservable.create = function (target, eventName, options, selector) {
7372         if (isFunction_1.isFunction(options)) {
7373             selector = options;
7374             options = undefined;
7375         }
7376         return new FromEventObservable(target, eventName, selector, options);
7377     };
7378     FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7379         var unsubscribe;
7380         if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7381             for (var i = 0, len = sourceObj.length; i < len; i++) {
7382                 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7383             }
7384         }
7385         else if (isEventTarget(sourceObj)) {
7386             var source_1 = sourceObj;
7387             sourceObj.addEventListener(eventName, handler, options);
7388             unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7389         }
7390         else if (isJQueryStyleEventEmitter(sourceObj)) {
7391             var source_2 = sourceObj;
7392             sourceObj.on(eventName, handler);
7393             unsubscribe = function () { return source_2.off(eventName, handler); };
7394         }
7395         else if (isNodeStyleEventEmitter(sourceObj)) {
7396             var source_3 = sourceObj;
7397             sourceObj.addListener(eventName, handler);
7398             unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7399         }
7400         else {
7401             throw new TypeError('Invalid event target');
7402         }
7403         subscriber.add(new Subscription_1.Subscription(unsubscribe));
7404     };
7405     FromEventObservable.prototype._subscribe = function (subscriber) {
7406         var sourceObj = this.sourceObj;
7407         var eventName = this.eventName;
7408         var options = this.options;
7409         var selector = this.selector;
7410         var handler = selector ? function () {
7411             var args = [];
7412             for (var _i = 0; _i < arguments.length; _i++) {
7413                 args[_i - 0] = arguments[_i];
7414             }
7415             var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7416             if (result === errorObject_1.errorObject) {
7417                 subscriber.error(errorObject_1.errorObject.e);
7418             }
7419             else {
7420                 subscriber.next(result);
7421             }
7422         } : function (e) { return subscriber.next(e); };
7423         FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7424     };
7425     return FromEventObservable;
7426 }(Observable_1.Observable));
7427 exports.FromEventObservable = FromEventObservable;
7428
7429 },{"../Observable":28,"../Subscription":36,"../util/errorObject":161,"../util/isFunction":165,"../util/tryCatch":173}],91:[function(require,module,exports){
7430 "use strict";
7431 var __extends = (this && this.__extends) || function (d, b) {
7432     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7433     function __() { this.constructor = d; }
7434     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7435 };
7436 var isArray_1 = require('../util/isArray');
7437 var isArrayLike_1 = require('../util/isArrayLike');
7438 var isPromise_1 = require('../util/isPromise');
7439 var PromiseObservable_1 = require('./PromiseObservable');
7440 var IteratorObservable_1 = require('./IteratorObservable');
7441 var ArrayObservable_1 = require('./ArrayObservable');
7442 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7443 var iterator_1 = require('../symbol/iterator');
7444 var Observable_1 = require('../Observable');
7445 var observeOn_1 = require('../operator/observeOn');
7446 var observable_1 = require('../symbol/observable');
7447 /**
7448  * We need this JSDoc comment for affecting ESDoc.
7449  * @extends {Ignored}
7450  * @hide true
7451  */
7452 var FromObservable = (function (_super) {
7453     __extends(FromObservable, _super);
7454     function FromObservable(ish, scheduler) {
7455         _super.call(this, null);
7456         this.ish = ish;
7457         this.scheduler = scheduler;
7458     }
7459     /**
7460      * Creates an Observable from an Array, an array-like object, a Promise, an
7461      * iterable object, or an Observable-like object.
7462      *
7463      * <span class="informal">Converts almost anything to an Observable.</span>
7464      *
7465      * <img src="./img/from.png" width="100%">
7466      *
7467      * Convert various other objects and data types into Observables. `from`
7468      * converts a Promise or an array-like or an
7469      * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7470      * object into an Observable that emits the items in that promise or array or
7471      * iterable. A String, in this context, is treated as an array of characters.
7472      * Observable-like objects (contains a function named with the ES2015 Symbol
7473      * for Observable) can also be converted through this operator.
7474      *
7475      * @example <caption>Converts an array to an Observable</caption>
7476      * var array = [10, 20, 30];
7477      * var result = Rx.Observable.from(array);
7478      * result.subscribe(x => console.log(x));
7479      *
7480      * // Results in the following:
7481      * // 10 20 30
7482      *
7483      * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7484      * function* generateDoubles(seed) {
7485      *   var i = seed;
7486      *   while (true) {
7487      *     yield i;
7488      *     i = 2 * i; // double it
7489      *   }
7490      * }
7491      *
7492      * var iterator = generateDoubles(3);
7493      * var result = Rx.Observable.from(iterator).take(10);
7494      * result.subscribe(x => console.log(x));
7495      *
7496      * // Results in the following:
7497      * // 3 6 12 24 48 96 192 384 768 1536
7498      *
7499      * @see {@link create}
7500      * @see {@link fromEvent}
7501      * @see {@link fromEventPattern}
7502      * @see {@link fromPromise}
7503      *
7504      * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7505      * Observable-like, an Array, an iterable or an array-like object to be
7506      * converted.
7507      * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7508      * emissions of values.
7509      * @return {Observable<T>} The Observable whose values are originally from the
7510      * input object that was converted.
7511      * @static true
7512      * @name from
7513      * @owner Observable
7514      */
7515     FromObservable.create = function (ish, scheduler) {
7516         if (ish != null) {
7517             if (typeof ish[observable_1.$$observable] === 'function') {
7518                 if (ish instanceof Observable_1.Observable && !scheduler) {
7519                     return ish;
7520                 }
7521                 return new FromObservable(ish, scheduler);
7522             }
7523             else if (isArray_1.isArray(ish)) {
7524                 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
7525             }
7526             else if (isPromise_1.isPromise(ish)) {
7527                 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
7528             }
7529             else if (typeof ish[iterator_1.$$iterator] === 'function' || typeof ish === 'string') {
7530                 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
7531             }
7532             else if (isArrayLike_1.isArrayLike(ish)) {
7533                 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
7534             }
7535         }
7536         throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
7537     };
7538     FromObservable.prototype._subscribe = function (subscriber) {
7539         var ish = this.ish;
7540         var scheduler = this.scheduler;
7541         if (scheduler == null) {
7542             return ish[observable_1.$$observable]().subscribe(subscriber);
7543         }
7544         else {
7545             return ish[observable_1.$$observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
7546         }
7547     };
7548     return FromObservable;
7549 }(Observable_1.Observable));
7550 exports.FromObservable = FromObservable;
7551
7552 },{"../Observable":28,"../operator/observeOn":128,"../symbol/iterator":152,"../symbol/observable":153,"../util/isArray":162,"../util/isArrayLike":163,"../util/isPromise":168,"./ArrayLikeObservable":84,"./ArrayObservable":85,"./IteratorObservable":92,"./PromiseObservable":93}],92:[function(require,module,exports){
7553 "use strict";
7554 var __extends = (this && this.__extends) || function (d, b) {
7555     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7556     function __() { this.constructor = d; }
7557     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7558 };
7559 var root_1 = require('../util/root');
7560 var Observable_1 = require('../Observable');
7561 var iterator_1 = require('../symbol/iterator');
7562 /**
7563  * We need this JSDoc comment for affecting ESDoc.
7564  * @extends {Ignored}
7565  * @hide true
7566  */
7567 var IteratorObservable = (function (_super) {
7568     __extends(IteratorObservable, _super);
7569     function IteratorObservable(iterator, scheduler) {
7570         _super.call(this);
7571         this.scheduler = scheduler;
7572         if (iterator == null) {
7573             throw new Error('iterator cannot be null.');
7574         }
7575         this.iterator = getIterator(iterator);
7576     }
7577     IteratorObservable.create = function (iterator, scheduler) {
7578         return new IteratorObservable(iterator, scheduler);
7579     };
7580     IteratorObservable.dispatch = function (state) {
7581         var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
7582         if (hasError) {
7583             subscriber.error(state.error);
7584             return;
7585         }
7586         var result = iterator.next();
7587         if (result.done) {
7588             subscriber.complete();
7589             return;
7590         }
7591         subscriber.next(result.value);
7592         state.index = index + 1;
7593         if (subscriber.closed) {
7594             if (typeof iterator.return === 'function') {
7595                 iterator.return();
7596             }
7597             return;
7598         }
7599         this.schedule(state);
7600     };
7601     IteratorObservable.prototype._subscribe = function (subscriber) {
7602         var index = 0;
7603         var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
7604         if (scheduler) {
7605             return scheduler.schedule(IteratorObservable.dispatch, 0, {
7606                 index: index, iterator: iterator, subscriber: subscriber
7607             });
7608         }
7609         else {
7610             do {
7611                 var result = iterator.next();
7612                 if (result.done) {
7613                     subscriber.complete();
7614                     break;
7615                 }
7616                 else {
7617                     subscriber.next(result.value);
7618                 }
7619                 if (subscriber.closed) {
7620                     if (typeof iterator.return === 'function') {
7621                         iterator.return();
7622                     }
7623                     break;
7624                 }
7625             } while (true);
7626         }
7627     };
7628     return IteratorObservable;
7629 }(Observable_1.Observable));
7630 exports.IteratorObservable = IteratorObservable;
7631 var StringIterator = (function () {
7632     function StringIterator(str, idx, len) {
7633         if (idx === void 0) { idx = 0; }
7634         if (len === void 0) { len = str.length; }
7635         this.str = str;
7636         this.idx = idx;
7637         this.len = len;
7638     }
7639     StringIterator.prototype[iterator_1.$$iterator] = function () { return (this); };
7640     StringIterator.prototype.next = function () {
7641         return this.idx < this.len ? {
7642             done: false,
7643             value: this.str.charAt(this.idx++)
7644         } : {
7645             done: true,
7646             value: undefined
7647         };
7648     };
7649     return StringIterator;
7650 }());
7651 var ArrayIterator = (function () {
7652     function ArrayIterator(arr, idx, len) {
7653         if (idx === void 0) { idx = 0; }
7654         if (len === void 0) { len = toLength(arr); }
7655         this.arr = arr;
7656         this.idx = idx;
7657         this.len = len;
7658     }
7659     ArrayIterator.prototype[iterator_1.$$iterator] = function () { return this; };
7660     ArrayIterator.prototype.next = function () {
7661         return this.idx < this.len ? {
7662             done: false,
7663             value: this.arr[this.idx++]
7664         } : {
7665             done: true,
7666             value: undefined
7667         };
7668     };
7669     return ArrayIterator;
7670 }());
7671 function getIterator(obj) {
7672     var i = obj[iterator_1.$$iterator];
7673     if (!i && typeof obj === 'string') {
7674         return new StringIterator(obj);
7675     }
7676     if (!i && obj.length !== undefined) {
7677         return new ArrayIterator(obj);
7678     }
7679     if (!i) {
7680         throw new TypeError('object is not iterable');
7681     }
7682     return obj[iterator_1.$$iterator]();
7683 }
7684 var maxSafeInteger = Math.pow(2, 53) - 1;
7685 function toLength(o) {
7686     var len = +o.length;
7687     if (isNaN(len)) {
7688         return 0;
7689     }
7690     if (len === 0 || !numberIsFinite(len)) {
7691         return len;
7692     }
7693     len = sign(len) * Math.floor(Math.abs(len));
7694     if (len <= 0) {
7695         return 0;
7696     }
7697     if (len > maxSafeInteger) {
7698         return maxSafeInteger;
7699     }
7700     return len;
7701 }
7702 function numberIsFinite(value) {
7703     return typeof value === 'number' && root_1.root.isFinite(value);
7704 }
7705 function sign(value) {
7706     var valueAsNumber = +value;
7707     if (valueAsNumber === 0) {
7708         return valueAsNumber;
7709     }
7710     if (isNaN(valueAsNumber)) {
7711         return valueAsNumber;
7712     }
7713     return valueAsNumber < 0 ? -1 : 1;
7714 }
7715
7716 },{"../Observable":28,"../symbol/iterator":152,"../util/root":170}],93:[function(require,module,exports){
7717 "use strict";
7718 var __extends = (this && this.__extends) || function (d, b) {
7719     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7720     function __() { this.constructor = d; }
7721     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7722 };
7723 var root_1 = require('../util/root');
7724 var Observable_1 = require('../Observable');
7725 /**
7726  * We need this JSDoc comment for affecting ESDoc.
7727  * @extends {Ignored}
7728  * @hide true
7729  */
7730 var PromiseObservable = (function (_super) {
7731     __extends(PromiseObservable, _super);
7732     function PromiseObservable(promise, scheduler) {
7733         _super.call(this);
7734         this.promise = promise;
7735         this.scheduler = scheduler;
7736     }
7737     /**
7738      * Converts a Promise to an Observable.
7739      *
7740      * <span class="informal">Returns an Observable that just emits the Promise's
7741      * resolved value, then completes.</span>
7742      *
7743      * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
7744      * Observable. If the Promise resolves with a value, the output Observable
7745      * emits that resolved value as a `next`, and then completes. If the Promise
7746      * is rejected, then the output Observable emits the corresponding Error.
7747      *
7748      * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
7749      * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
7750      * result.subscribe(x => console.log(x), e => console.error(e));
7751      *
7752      * @see {@link bindCallback}
7753      * @see {@link from}
7754      *
7755      * @param {Promise<T>} promise The promise to be converted.
7756      * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
7757      * the delivery of the resolved value (or the rejection).
7758      * @return {Observable<T>} An Observable which wraps the Promise.
7759      * @static true
7760      * @name fromPromise
7761      * @owner Observable
7762      */
7763     PromiseObservable.create = function (promise, scheduler) {
7764         return new PromiseObservable(promise, scheduler);
7765     };
7766     PromiseObservable.prototype._subscribe = function (subscriber) {
7767         var _this = this;
7768         var promise = this.promise;
7769         var scheduler = this.scheduler;
7770         if (scheduler == null) {
7771             if (this._isScalar) {
7772                 if (!subscriber.closed) {
7773                     subscriber.next(this.value);
7774                     subscriber.complete();
7775                 }
7776             }
7777             else {
7778                 promise.then(function (value) {
7779                     _this.value = value;
7780                     _this._isScalar = true;
7781                     if (!subscriber.closed) {
7782                         subscriber.next(value);
7783                         subscriber.complete();
7784                     }
7785                 }, function (err) {
7786                     if (!subscriber.closed) {
7787                         subscriber.error(err);
7788                     }
7789                 })
7790                     .then(null, function (err) {
7791                     // escape the promise trap, throw unhandled errors
7792                     root_1.root.setTimeout(function () { throw err; });
7793                 });
7794             }
7795         }
7796         else {
7797             if (this._isScalar) {
7798                 if (!subscriber.closed) {
7799                     return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
7800                 }
7801             }
7802             else {
7803                 promise.then(function (value) {
7804                     _this.value = value;
7805                     _this._isScalar = true;
7806                     if (!subscriber.closed) {
7807                         subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
7808                     }
7809                 }, function (err) {
7810                     if (!subscriber.closed) {
7811                         subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
7812                     }
7813                 })
7814                     .then(null, function (err) {
7815                     // escape the promise trap, throw unhandled errors
7816                     root_1.root.setTimeout(function () { throw err; });
7817                 });
7818             }
7819         }
7820     };
7821     return PromiseObservable;
7822 }(Observable_1.Observable));
7823 exports.PromiseObservable = PromiseObservable;
7824 function dispatchNext(arg) {
7825     var value = arg.value, subscriber = arg.subscriber;
7826     if (!subscriber.closed) {
7827         subscriber.next(value);
7828         subscriber.complete();
7829     }
7830 }
7831 function dispatchError(arg) {
7832     var err = arg.err, subscriber = arg.subscriber;
7833     if (!subscriber.closed) {
7834         subscriber.error(err);
7835     }
7836 }
7837
7838 },{"../Observable":28,"../util/root":170}],94:[function(require,module,exports){
7839 "use strict";
7840 var __extends = (this && this.__extends) || function (d, b) {
7841     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7842     function __() { this.constructor = d; }
7843     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7844 };
7845 var Observable_1 = require('../Observable');
7846 /**
7847  * We need this JSDoc comment for affecting ESDoc.
7848  * @extends {Ignored}
7849  * @hide true
7850  */
7851 var ScalarObservable = (function (_super) {
7852     __extends(ScalarObservable, _super);
7853     function ScalarObservable(value, scheduler) {
7854         _super.call(this);
7855         this.value = value;
7856         this.scheduler = scheduler;
7857         this._isScalar = true;
7858         if (scheduler) {
7859             this._isScalar = false;
7860         }
7861     }
7862     ScalarObservable.create = function (value, scheduler) {
7863         return new ScalarObservable(value, scheduler);
7864     };
7865     ScalarObservable.dispatch = function (state) {
7866         var done = state.done, value = state.value, subscriber = state.subscriber;
7867         if (done) {
7868             subscriber.complete();
7869             return;
7870         }
7871         subscriber.next(value);
7872         if (subscriber.closed) {
7873             return;
7874         }
7875         state.done = true;
7876         this.schedule(state);
7877     };
7878     ScalarObservable.prototype._subscribe = function (subscriber) {
7879         var value = this.value;
7880         var scheduler = this.scheduler;
7881         if (scheduler) {
7882             return scheduler.schedule(ScalarObservable.dispatch, 0, {
7883                 done: false, value: value, subscriber: subscriber
7884             });
7885         }
7886         else {
7887             subscriber.next(value);
7888             if (!subscriber.closed) {
7889                 subscriber.complete();
7890             }
7891         }
7892     };
7893     return ScalarObservable;
7894 }(Observable_1.Observable));
7895 exports.ScalarObservable = ScalarObservable;
7896
7897 },{"../Observable":28}],95:[function(require,module,exports){
7898 "use strict";
7899 var __extends = (this && this.__extends) || function (d, b) {
7900     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7901     function __() { this.constructor = d; }
7902     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7903 };
7904 var isNumeric_1 = require('../util/isNumeric');
7905 var Observable_1 = require('../Observable');
7906 var async_1 = require('../scheduler/async');
7907 var isScheduler_1 = require('../util/isScheduler');
7908 var isDate_1 = require('../util/isDate');
7909 /**
7910  * We need this JSDoc comment for affecting ESDoc.
7911  * @extends {Ignored}
7912  * @hide true
7913  */
7914 var TimerObservable = (function (_super) {
7915     __extends(TimerObservable, _super);
7916     function TimerObservable(dueTime, period, scheduler) {
7917         if (dueTime === void 0) { dueTime = 0; }
7918         _super.call(this);
7919         this.period = -1;
7920         this.dueTime = 0;
7921         if (isNumeric_1.isNumeric(period)) {
7922             this.period = Number(period) < 1 && 1 || Number(period);
7923         }
7924         else if (isScheduler_1.isScheduler(period)) {
7925             scheduler = period;
7926         }
7927         if (!isScheduler_1.isScheduler(scheduler)) {
7928             scheduler = async_1.async;
7929         }
7930         this.scheduler = scheduler;
7931         this.dueTime = isDate_1.isDate(dueTime) ?
7932             (+dueTime - this.scheduler.now()) :
7933             dueTime;
7934     }
7935     /**
7936      * Creates an Observable that starts emitting after an `initialDelay` and
7937      * emits ever increasing numbers after each `period` of time thereafter.
7938      *
7939      * <span class="informal">Its like {@link interval}, but you can specify when
7940      * should the emissions start.</span>
7941      *
7942      * <img src="./img/timer.png" width="100%">
7943      *
7944      * `timer` returns an Observable that emits an infinite sequence of ascending
7945      * integers, with a constant interval of time, `period` of your choosing
7946      * between those emissions. The first emission happens after the specified
7947      * `initialDelay`. The initial delay may be a {@link Date}. By default, this
7948      * operator uses the `async` IScheduler to provide a notion of time, but you
7949      * may pass any IScheduler to it. If `period` is not specified, the output
7950      * Observable emits only one value, `0`. Otherwise, it emits an infinite
7951      * sequence.
7952      *
7953      * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
7954      * var numbers = Rx.Observable.timer(3000, 1000);
7955      * numbers.subscribe(x => console.log(x));
7956      *
7957      * @example <caption>Emits one number after five seconds</caption>
7958      * var numbers = Rx.Observable.timer(5000);
7959      * numbers.subscribe(x => console.log(x));
7960      *
7961      * @see {@link interval}
7962      * @see {@link delay}
7963      *
7964      * @param {number|Date} initialDelay The initial delay time to wait before
7965      * emitting the first value of `0`.
7966      * @param {number} [period] The period of time between emissions of the
7967      * subsequent numbers.
7968      * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
7969      * the emission of values, and providing a notion of "time".
7970      * @return {Observable} An Observable that emits a `0` after the
7971      * `initialDelay` and ever increasing numbers after each `period` of time
7972      * thereafter.
7973      * @static true
7974      * @name timer
7975      * @owner Observable
7976      */
7977     TimerObservable.create = function (initialDelay, period, scheduler) {
7978         if (initialDelay === void 0) { initialDelay = 0; }
7979         return new TimerObservable(initialDelay, period, scheduler);
7980     };
7981     TimerObservable.dispatch = function (state) {
7982         var index = state.index, period = state.period, subscriber = state.subscriber;
7983         var action = this;
7984         subscriber.next(index);
7985         if (subscriber.closed) {
7986             return;
7987         }
7988         else if (period === -1) {
7989             return subscriber.complete();
7990         }
7991         state.index = index + 1;
7992         action.schedule(state, period);
7993     };
7994     TimerObservable.prototype._subscribe = function (subscriber) {
7995         var index = 0;
7996         var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
7997         return scheduler.schedule(TimerObservable.dispatch, dueTime, {
7998             index: index, period: period, subscriber: subscriber
7999         });
8000     };
8001     return TimerObservable;
8002 }(Observable_1.Observable));
8003 exports.TimerObservable = TimerObservable;
8004
8005 },{"../Observable":28,"../scheduler/async":150,"../util/isDate":164,"../util/isNumeric":166,"../util/isScheduler":169}],96:[function(require,module,exports){
8006 "use strict";
8007 var isScheduler_1 = require('../util/isScheduler');
8008 var isArray_1 = require('../util/isArray');
8009 var ArrayObservable_1 = require('./ArrayObservable');
8010 var combineLatest_1 = require('../operator/combineLatest');
8011 /* tslint:enable:max-line-length */
8012 /**
8013  * Combines multiple Observables to create an Observable whose values are
8014  * calculated from the latest values of each of its input Observables.
8015  *
8016  * <span class="informal">Whenever any input Observable emits a value, it
8017  * computes a formula using the latest values from all the inputs, then emits
8018  * the output of that formula.</span>
8019  *
8020  * <img src="./img/combineLatest.png" width="100%">
8021  *
8022  * `combineLatest` combines the values from all the Observables passed as
8023  * arguments. This is done by subscribing to each Observable in order and,
8024  * whenever any Observable emits, collecting an array of the most recent
8025  * values from each Observable. So if you pass `n` Observables to operator,
8026  * returned Observable will always emit an array of `n` values, in order
8027  * corresponding to order of passed Observables (value from the first Observable
8028  * on the first place and so on).
8029  *
8030  * Static version of `combineLatest` accepts either an array of Observables
8031  * or each Observable can be put directly as an argument. Note that array of
8032  * Observables is good choice, if you don't know beforehand how many Observables
8033  * you will combine. Passing empty array will result in Observable that
8034  * completes immediately.
8035  *
8036  * To ensure output array has always the same length, `combineLatest` will
8037  * actually wait for all input Observables to emit at least once,
8038  * before it starts emitting results. This means if some Observable emits
8039  * values before other Observables started emitting, all that values but last
8040  * will be lost. On the other hand, is some Observable does not emit value but
8041  * completes, resulting Observable will complete at the same moment without
8042  * emitting anything, since it will be now impossible to include value from
8043  * completed Observable in resulting array. Also, if some input Observable does
8044  * not emit any value and never completes, `combineLatest` will also never emit
8045  * and never complete, since, again, it will wait for all streams to emit some
8046  * value.
8047  *
8048  * If at least one Observable was passed to `combineLatest` and all passed Observables
8049  * emitted something, resulting Observable will complete when all combined
8050  * streams complete. So even if some Observable completes, result of
8051  * `combineLatest` will still emit values when other Observables do. In case
8052  * of completed Observable, its value from now on will always be the last
8053  * emitted value. On the other hand, if any Observable errors, `combineLatest`
8054  * will error immediately as well, and all other Observables will be unsubscribed.
8055  *
8056  * `combineLatest` accepts as optional parameter `project` function, which takes
8057  * as arguments all values that would normally be emitted by resulting Observable.
8058  * `project` can return any kind of value, which will be then emitted by Observable
8059  * instead of default array. Note that `project` does not take as argument that array
8060  * of values, but values themselves. That means default `project` can be imagined
8061  * as function that takes all its arguments and puts them into an array.
8062  *
8063  *
8064  * @example <caption>Combine two timer Observables</caption>
8065  * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
8066  * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
8067  * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
8068  * combinedTimers.subscribe(value => console.log(value));
8069  * // Logs
8070  * // [0, 0] after 0.5s
8071  * // [1, 0] after 1s
8072  * // [1, 1] after 1.5s
8073  * // [2, 1] after 2s
8074  *
8075  *
8076  * @example <caption>Combine an array of Observables</caption>
8077  * const observables = [1, 5, 10].map(
8078  *   n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
8079  * );
8080  * const combined = Rx.Observable.combineLatest(observables);
8081  * combined.subscribe(value => console.log(value));
8082  * // Logs
8083  * // [0, 0, 0] immediately
8084  * // [1, 0, 0] after 1s
8085  * // [1, 5, 0] after 5s
8086  * // [1, 5, 10] after 10s
8087  *
8088  *
8089  * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
8090  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8091  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8092  * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
8093  * bmi.subscribe(x => console.log('BMI is ' + x));
8094  *
8095  * // With output to console:
8096  * // BMI is 24.212293388429753
8097  * // BMI is 23.93948099205209
8098  * // BMI is 23.671253629592222
8099  *
8100  *
8101  * @see {@link combineAll}
8102  * @see {@link merge}
8103  * @see {@link withLatestFrom}
8104  *
8105  * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
8106  * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
8107  * More than one input Observables may be given as arguments
8108  * or an array of Observables may be given as the first argument.
8109  * @param {function} [project] An optional function to project the values from
8110  * the combined latest values into a new value on the output Observable.
8111  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
8112  * each input Observable.
8113  * @return {Observable} An Observable of projected values from the most recent
8114  * values from each input Observable, or an array of the most recent values from
8115  * each input Observable.
8116  * @static true
8117  * @name combineLatest
8118  * @owner Observable
8119  */
8120 function combineLatest() {
8121     var observables = [];
8122     for (var _i = 0; _i < arguments.length; _i++) {
8123         observables[_i - 0] = arguments[_i];
8124     }
8125     var project = null;
8126     var scheduler = null;
8127     if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8128         scheduler = observables.pop();
8129     }
8130     if (typeof observables[observables.length - 1] === 'function') {
8131         project = observables.pop();
8132     }
8133     // if the first and only other argument besides the resultSelector is an array
8134     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8135     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8136         observables = observables[0];
8137     }
8138     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
8139 }
8140 exports.combineLatest = combineLatest;
8141
8142 },{"../operator/combineLatest":111,"../util/isArray":162,"../util/isScheduler":169,"./ArrayObservable":85}],97:[function(require,module,exports){
8143 "use strict";
8144 var DeferObservable_1 = require('./DeferObservable');
8145 exports.defer = DeferObservable_1.DeferObservable.create;
8146
8147 },{"./DeferObservable":87}],98:[function(require,module,exports){
8148 "use strict";
8149 var EmptyObservable_1 = require('./EmptyObservable');
8150 exports.empty = EmptyObservable_1.EmptyObservable.create;
8151
8152 },{"./EmptyObservable":88}],99:[function(require,module,exports){
8153 "use strict";
8154 var FromObservable_1 = require('./FromObservable');
8155 exports.from = FromObservable_1.FromObservable.create;
8156
8157 },{"./FromObservable":91}],100:[function(require,module,exports){
8158 "use strict";
8159 var FromEventObservable_1 = require('./FromEventObservable');
8160 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
8161
8162 },{"./FromEventObservable":90}],101:[function(require,module,exports){
8163 "use strict";
8164 var PromiseObservable_1 = require('./PromiseObservable');
8165 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
8166
8167 },{"./PromiseObservable":93}],102:[function(require,module,exports){
8168 "use strict";
8169 var merge_1 = require('../operator/merge');
8170 exports.merge = merge_1.mergeStatic;
8171
8172 },{"../operator/merge":124}],103:[function(require,module,exports){
8173 "use strict";
8174 var ArrayObservable_1 = require('./ArrayObservable');
8175 exports.of = ArrayObservable_1.ArrayObservable.of;
8176
8177 },{"./ArrayObservable":85}],104:[function(require,module,exports){
8178 "use strict";
8179 var ErrorObservable_1 = require('./ErrorObservable');
8180 exports._throw = ErrorObservable_1.ErrorObservable.create;
8181
8182 },{"./ErrorObservable":89}],105:[function(require,module,exports){
8183 "use strict";
8184 var TimerObservable_1 = require('./TimerObservable');
8185 exports.timer = TimerObservable_1.TimerObservable.create;
8186
8187 },{"./TimerObservable":95}],106:[function(require,module,exports){
8188 "use strict";
8189 var zip_1 = require('../operator/zip');
8190 exports.zip = zip_1.zipStatic;
8191
8192 },{"../operator/zip":144}],107:[function(require,module,exports){
8193 "use strict";
8194 var __extends = (this && this.__extends) || function (d, b) {
8195     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8196     function __() { this.constructor = d; }
8197     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8198 };
8199 var OuterSubscriber_1 = require('../OuterSubscriber');
8200 var subscribeToResult_1 = require('../util/subscribeToResult');
8201 /**
8202  * Buffers the source Observable values until `closingNotifier` emits.
8203  *
8204  * <span class="informal">Collects values from the past as an array, and emits
8205  * that array only when another Observable emits.</span>
8206  *
8207  * <img src="./img/buffer.png" width="100%">
8208  *
8209  * Buffers the incoming Observable values until the given `closingNotifier`
8210  * Observable emits a value, at which point it emits the buffer on the output
8211  * Observable and starts a new buffer internally, awaiting the next time
8212  * `closingNotifier` emits.
8213  *
8214  * @example <caption>On every click, emit array of most recent interval events</caption>
8215  * var clicks = Rx.Observable.fromEvent(document, 'click');
8216  * var interval = Rx.Observable.interval(1000);
8217  * var buffered = interval.buffer(clicks);
8218  * buffered.subscribe(x => console.log(x));
8219  *
8220  * @see {@link bufferCount}
8221  * @see {@link bufferTime}
8222  * @see {@link bufferToggle}
8223  * @see {@link bufferWhen}
8224  * @see {@link window}
8225  *
8226  * @param {Observable<any>} closingNotifier An Observable that signals the
8227  * buffer to be emitted on the output Observable.
8228  * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8229  * values.
8230  * @method buffer
8231  * @owner Observable
8232  */
8233 function buffer(closingNotifier) {
8234     return this.lift(new BufferOperator(closingNotifier));
8235 }
8236 exports.buffer = buffer;
8237 var BufferOperator = (function () {
8238     function BufferOperator(closingNotifier) {
8239         this.closingNotifier = closingNotifier;
8240     }
8241     BufferOperator.prototype.call = function (subscriber, source) {
8242         return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
8243     };
8244     return BufferOperator;
8245 }());
8246 /**
8247  * We need this JSDoc comment for affecting ESDoc.
8248  * @ignore
8249  * @extends {Ignored}
8250  */
8251 var BufferSubscriber = (function (_super) {
8252     __extends(BufferSubscriber, _super);
8253     function BufferSubscriber(destination, closingNotifier) {
8254         _super.call(this, destination);
8255         this.buffer = [];
8256         this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8257     }
8258     BufferSubscriber.prototype._next = function (value) {
8259         this.buffer.push(value);
8260     };
8261     BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8262         var buffer = this.buffer;
8263         this.buffer = [];
8264         this.destination.next(buffer);
8265     };
8266     return BufferSubscriber;
8267 }(OuterSubscriber_1.OuterSubscriber));
8268
8269 },{"../OuterSubscriber":30,"../util/subscribeToResult":171}],108:[function(require,module,exports){
8270 "use strict";
8271 var __extends = (this && this.__extends) || function (d, b) {
8272     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8273     function __() { this.constructor = d; }
8274     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8275 };
8276 var Subscriber_1 = require('../Subscriber');
8277 /**
8278  * Buffers the source Observable values until the size hits the maximum
8279  * `bufferSize` given.
8280  *
8281  * <span class="informal">Collects values from the past as an array, and emits
8282  * that array only when its size reaches `bufferSize`.</span>
8283  *
8284  * <img src="./img/bufferCount.png" width="100%">
8285  *
8286  * Buffers a number of values from the source Observable by `bufferSize` then
8287  * emits the buffer and clears it, and starts a new buffer each
8288  * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8289  * `null`, then new buffers are started immediately at the start of the source
8290  * and when each buffer closes and is emitted.
8291  *
8292  * @example <caption>Emit the last two click events as an array</caption>
8293  * var clicks = Rx.Observable.fromEvent(document, 'click');
8294  * var buffered = clicks.bufferCount(2);
8295  * buffered.subscribe(x => console.log(x));
8296  *
8297  * @example <caption>On every click, emit the last two click events as an array</caption>
8298  * var clicks = Rx.Observable.fromEvent(document, 'click');
8299  * var buffered = clicks.bufferCount(2, 1);
8300  * buffered.subscribe(x => console.log(x));
8301  *
8302  * @see {@link buffer}
8303  * @see {@link bufferTime}
8304  * @see {@link bufferToggle}
8305  * @see {@link bufferWhen}
8306  * @see {@link pairwise}
8307  * @see {@link windowCount}
8308  *
8309  * @param {number} bufferSize The maximum size of the buffer emitted.
8310  * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8311  * For example if `startBufferEvery` is `2`, then a new buffer will be started
8312  * on every other value from the source. A new buffer is started at the
8313  * beginning of the source by default.
8314  * @return {Observable<T[]>} An Observable of arrays of buffered values.
8315  * @method bufferCount
8316  * @owner Observable
8317  */
8318 function bufferCount(bufferSize, startBufferEvery) {
8319     if (startBufferEvery === void 0) { startBufferEvery = null; }
8320     return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
8321 }
8322 exports.bufferCount = bufferCount;
8323 var BufferCountOperator = (function () {
8324     function BufferCountOperator(bufferSize, startBufferEvery) {
8325         this.bufferSize = bufferSize;
8326         this.startBufferEvery = startBufferEvery;
8327     }
8328     BufferCountOperator.prototype.call = function (subscriber, source) {
8329         return source.subscribe(new BufferCountSubscriber(subscriber, this.bufferSize, this.startBufferEvery));
8330     };
8331     return BufferCountOperator;
8332 }());
8333 /**
8334  * We need this JSDoc comment for affecting ESDoc.
8335  * @ignore
8336  * @extends {Ignored}
8337  */
8338 var BufferCountSubscriber = (function (_super) {
8339     __extends(BufferCountSubscriber, _super);
8340     function BufferCountSubscriber(destination, bufferSize, startBufferEvery) {
8341         _super.call(this, destination);
8342         this.bufferSize = bufferSize;
8343         this.startBufferEvery = startBufferEvery;
8344         this.buffers = [];
8345         this.count = 0;
8346     }
8347     BufferCountSubscriber.prototype._next = function (value) {
8348         var count = this.count++;
8349         var _a = this, destination = _a.destination, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers;
8350         var startOn = (startBufferEvery == null) ? bufferSize : startBufferEvery;
8351         if (count % startOn === 0) {
8352             buffers.push([]);
8353         }
8354         for (var i = buffers.length; i--;) {
8355             var buffer = buffers[i];
8356             buffer.push(value);
8357             if (buffer.length === bufferSize) {
8358                 buffers.splice(i, 1);
8359                 destination.next(buffer);
8360             }
8361         }
8362     };
8363     BufferCountSubscriber.prototype._complete = function () {
8364         var destination = this.destination;
8365         var buffers = this.buffers;
8366         while (buffers.length > 0) {
8367             var buffer = buffers.shift();
8368             if (buffer.length > 0) {
8369                 destination.next(buffer);
8370             }
8371         }
8372         _super.prototype._complete.call(this);
8373     };
8374     return BufferCountSubscriber;
8375 }(Subscriber_1.Subscriber));
8376
8377 },{"../Subscriber":35}],109:[function(require,module,exports){
8378 "use strict";
8379 var __extends = (this && this.__extends) || function (d, b) {
8380     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8381     function __() { this.constructor = d; }
8382     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8383 };
8384 var Subscription_1 = require('../Subscription');
8385 var tryCatch_1 = require('../util/tryCatch');
8386 var errorObject_1 = require('../util/errorObject');
8387 var OuterSubscriber_1 = require('../OuterSubscriber');
8388 var subscribeToResult_1 = require('../util/subscribeToResult');
8389 /**
8390  * Buffers the source Observable values, using a factory function of closing
8391  * Observables to determine when to close, emit, and reset the buffer.
8392  *
8393  * <span class="informal">Collects values from the past as an array. When it
8394  * starts collecting values, it calls a function that returns an Observable that
8395  * tells when to close the buffer and restart collecting.</span>
8396  *
8397  * <img src="./img/bufferWhen.png" width="100%">
8398  *
8399  * Opens a buffer immediately, then closes the buffer when the observable
8400  * returned by calling `closingSelector` function emits a value. When it closes
8401  * the buffer, it immediately opens a new buffer and repeats the process.
8402  *
8403  * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
8404  * var clicks = Rx.Observable.fromEvent(document, 'click');
8405  * var buffered = clicks.bufferWhen(() =>
8406  *   Rx.Observable.interval(1000 + Math.random() * 4000)
8407  * );
8408  * buffered.subscribe(x => console.log(x));
8409  *
8410  * @see {@link buffer}
8411  * @see {@link bufferCount}
8412  * @see {@link bufferTime}
8413  * @see {@link bufferToggle}
8414  * @see {@link windowWhen}
8415  *
8416  * @param {function(): Observable} closingSelector A function that takes no
8417  * arguments and returns an Observable that signals buffer closure.
8418  * @return {Observable<T[]>} An observable of arrays of buffered values.
8419  * @method bufferWhen
8420  * @owner Observable
8421  */
8422 function bufferWhen(closingSelector) {
8423     return this.lift(new BufferWhenOperator(closingSelector));
8424 }
8425 exports.bufferWhen = bufferWhen;
8426 var BufferWhenOperator = (function () {
8427     function BufferWhenOperator(closingSelector) {
8428         this.closingSelector = closingSelector;
8429     }
8430     BufferWhenOperator.prototype.call = function (subscriber, source) {
8431         return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
8432     };
8433     return BufferWhenOperator;
8434 }());
8435 /**
8436  * We need this JSDoc comment for affecting ESDoc.
8437  * @ignore
8438  * @extends {Ignored}
8439  */
8440 var BufferWhenSubscriber = (function (_super) {
8441     __extends(BufferWhenSubscriber, _super);
8442     function BufferWhenSubscriber(destination, closingSelector) {
8443         _super.call(this, destination);
8444         this.closingSelector = closingSelector;
8445         this.subscribing = false;
8446         this.openBuffer();
8447     }
8448     BufferWhenSubscriber.prototype._next = function (value) {
8449         this.buffer.push(value);
8450     };
8451     BufferWhenSubscriber.prototype._complete = function () {
8452         var buffer = this.buffer;
8453         if (buffer) {
8454             this.destination.next(buffer);
8455         }
8456         _super.prototype._complete.call(this);
8457     };
8458     BufferWhenSubscriber.prototype._unsubscribe = function () {
8459         this.buffer = null;
8460         this.subscribing = false;
8461     };
8462     BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8463         this.openBuffer();
8464     };
8465     BufferWhenSubscriber.prototype.notifyComplete = function () {
8466         if (this.subscribing) {
8467             this.complete();
8468         }
8469         else {
8470             this.openBuffer();
8471         }
8472     };
8473     BufferWhenSubscriber.prototype.openBuffer = function () {
8474         var closingSubscription = this.closingSubscription;
8475         if (closingSubscription) {
8476             this.remove(closingSubscription);
8477             closingSubscription.unsubscribe();
8478         }
8479         var buffer = this.buffer;
8480         if (this.buffer) {
8481             this.destination.next(buffer);
8482         }
8483         this.buffer = [];
8484         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
8485         if (closingNotifier === errorObject_1.errorObject) {
8486             this.error(errorObject_1.errorObject.e);
8487         }
8488         else {
8489             closingSubscription = new Subscription_1.Subscription();
8490             this.closingSubscription = closingSubscription;
8491             this.add(closingSubscription);
8492             this.subscribing = true;
8493             closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8494             this.subscribing = false;
8495         }
8496     };
8497     return BufferWhenSubscriber;
8498 }(OuterSubscriber_1.OuterSubscriber));
8499
8500 },{"../OuterSubscriber":30,"../Subscription":36,"../util/errorObject":161,"../util/subscribeToResult":171,"../util/tryCatch":173}],110:[function(require,module,exports){
8501 "use strict";
8502 var __extends = (this && this.__extends) || function (d, b) {
8503     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8504     function __() { this.constructor = d; }
8505     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8506 };
8507 var OuterSubscriber_1 = require('../OuterSubscriber');
8508 var subscribeToResult_1 = require('../util/subscribeToResult');
8509 /**
8510  * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8511  *
8512  * <img src="./img/catch.png" width="100%">
8513  *
8514  * @example <caption>Continues with a different Observable when there's an error</caption>
8515  *
8516  * Observable.of(1, 2, 3, 4, 5)
8517  *   .map(n => {
8518  *         if (n == 4) {
8519  *           throw 'four!';
8520  *     }
8521  *         return n;
8522  *   })
8523  *   .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
8524  *   .subscribe(x => console.log(x));
8525  *   // 1, 2, 3, I, II, III, IV, V
8526  *
8527  * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
8528  *
8529  * Observable.of(1, 2, 3, 4, 5)
8530  *   .map(n => {
8531  *         if (n === 4) {
8532  *           throw 'four!';
8533  *     }
8534  *         return n;
8535  *   })
8536  *   .catch((err, caught) => caught)
8537  *   .take(30)
8538  *   .subscribe(x => console.log(x));
8539  *   // 1, 2, 3, 1, 2, 3, ...
8540  *
8541  * @example <caption>Throws a new error when the source Observable throws an error</caption>
8542  *
8543  * Observable.of(1, 2, 3, 4, 5)
8544  *   .map(n => {
8545  *     if (n == 4) {
8546  *       throw 'four!';
8547  *     }
8548  *     return n;
8549  *   })
8550  *   .catch(err => {
8551  *     throw 'error in source. Details: ' + err;
8552  *   })
8553  *   .subscribe(
8554  *     x => console.log(x),
8555  *     err => console.log(err)
8556  *   );
8557  *   // 1, 2, 3, error in source. Details: four!
8558  *
8559  * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
8560  *  is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
8561  *  is returned by the `selector` will be used to continue the observable chain.
8562  * @return {Observable} An observable that originates from either the source or the observable returned by the
8563  *  catch `selector` function.
8564  * @method catch
8565  * @name catch
8566  * @owner Observable
8567  */
8568 function _catch(selector) {
8569     var operator = new CatchOperator(selector);
8570     var caught = this.lift(operator);
8571     return (operator.caught = caught);
8572 }
8573 exports._catch = _catch;
8574 var CatchOperator = (function () {
8575     function CatchOperator(selector) {
8576         this.selector = selector;
8577     }
8578     CatchOperator.prototype.call = function (subscriber, source) {
8579         return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
8580     };
8581     return CatchOperator;
8582 }());
8583 /**
8584  * We need this JSDoc comment for affecting ESDoc.
8585  * @ignore
8586  * @extends {Ignored}
8587  */
8588 var CatchSubscriber = (function (_super) {
8589     __extends(CatchSubscriber, _super);
8590     function CatchSubscriber(destination, selector, caught) {
8591         _super.call(this, destination);
8592         this.selector = selector;
8593         this.caught = caught;
8594     }
8595     // NOTE: overriding `error` instead of `_error` because we don't want
8596     // to have this flag this subscriber as `isStopped`. We can mimic the
8597     // behavior of the RetrySubscriber (from the `retry` operator), where
8598     // we unsubscribe from our source chain, reset our Subscriber flags,
8599     // then subscribe to the selector result.
8600     CatchSubscriber.prototype.error = function (err) {
8601         if (!this.isStopped) {
8602             var result = void 0;
8603             try {
8604                 result = this.selector(err, this.caught);
8605             }
8606             catch (err2) {
8607                 _super.prototype.error.call(this, err2);
8608                 return;
8609             }
8610             this._unsubscribeAndRecycle();
8611             this.add(subscribeToResult_1.subscribeToResult(this, result));
8612         }
8613     };
8614     return CatchSubscriber;
8615 }(OuterSubscriber_1.OuterSubscriber));
8616
8617 },{"../OuterSubscriber":30,"../util/subscribeToResult":171}],111:[function(require,module,exports){
8618 "use strict";
8619 var __extends = (this && this.__extends) || function (d, b) {
8620     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8621     function __() { this.constructor = d; }
8622     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8623 };
8624 var ArrayObservable_1 = require('../observable/ArrayObservable');
8625 var isArray_1 = require('../util/isArray');
8626 var OuterSubscriber_1 = require('../OuterSubscriber');
8627 var subscribeToResult_1 = require('../util/subscribeToResult');
8628 var none = {};
8629 /* tslint:enable:max-line-length */
8630 /**
8631  * Combines multiple Observables to create an Observable whose values are
8632  * calculated from the latest values of each of its input Observables.
8633  *
8634  * <span class="informal">Whenever any input Observable emits a value, it
8635  * computes a formula using the latest values from all the inputs, then emits
8636  * the output of that formula.</span>
8637  *
8638  * <img src="./img/combineLatest.png" width="100%">
8639  *
8640  * `combineLatest` combines the values from this Observable with values from
8641  * Observables passed as arguments. This is done by subscribing to each
8642  * Observable, in order, and collecting an array of each of the most recent
8643  * values any time any of the input Observables emits, then either taking that
8644  * array and passing it as arguments to an optional `project` function and
8645  * emitting the return value of that, or just emitting the array of recent
8646  * values directly if there is no `project` function.
8647  *
8648  * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
8649  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8650  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8651  * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
8652  * bmi.subscribe(x => console.log('BMI is ' + x));
8653  *
8654  * // With output to console:
8655  * // BMI is 24.212293388429753
8656  * // BMI is 23.93948099205209
8657  * // BMI is 23.671253629592222
8658  *
8659  * @see {@link combineAll}
8660  * @see {@link merge}
8661  * @see {@link withLatestFrom}
8662  *
8663  * @param {ObservableInput} other An input Observable to combine with the source
8664  * Observable. More than one input Observables may be given as argument.
8665  * @param {function} [project] An optional function to project the values from
8666  * the combined latest values into a new value on the output Observable.
8667  * @return {Observable} An Observable of projected values from the most recent
8668  * values from each input Observable, or an array of the most recent values from
8669  * each input Observable.
8670  * @method combineLatest
8671  * @owner Observable
8672  */
8673 function combineLatest() {
8674     var observables = [];
8675     for (var _i = 0; _i < arguments.length; _i++) {
8676         observables[_i - 0] = arguments[_i];
8677     }
8678     var project = null;
8679     if (typeof observables[observables.length - 1] === 'function') {
8680         project = observables.pop();
8681     }
8682     // if the first and only other argument besides the resultSelector is an array
8683     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8684     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8685         observables = observables[0].slice();
8686     }
8687     observables.unshift(this);
8688     return this.lift.call(new ArrayObservable_1.ArrayObservable(observables), new CombineLatestOperator(project));
8689 }
8690 exports.combineLatest = combineLatest;
8691 var CombineLatestOperator = (function () {
8692     function CombineLatestOperator(project) {
8693         this.project = project;
8694     }
8695     CombineLatestOperator.prototype.call = function (subscriber, source) {
8696         return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
8697     };
8698     return CombineLatestOperator;
8699 }());
8700 exports.CombineLatestOperator = CombineLatestOperator;
8701 /**
8702  * We need this JSDoc comment for affecting ESDoc.
8703  * @ignore
8704  * @extends {Ignored}
8705  */
8706 var CombineLatestSubscriber = (function (_super) {
8707     __extends(CombineLatestSubscriber, _super);
8708     function CombineLatestSubscriber(destination, project) {
8709         _super.call(this, destination);
8710         this.project = project;
8711         this.active = 0;
8712         this.values = [];
8713         this.observables = [];
8714     }
8715     CombineLatestSubscriber.prototype._next = function (observable) {
8716         this.values.push(none);
8717         this.observables.push(observable);
8718     };
8719     CombineLatestSubscriber.prototype._complete = function () {
8720         var observables = this.observables;
8721         var len = observables.length;
8722         if (len === 0) {
8723             this.destination.complete();
8724         }
8725         else {
8726             this.active = len;
8727             this.toRespond = len;
8728             for (var i = 0; i < len; i++) {
8729                 var observable = observables[i];
8730                 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
8731             }
8732         }
8733     };
8734     CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
8735         if ((this.active -= 1) === 0) {
8736             this.destination.complete();
8737         }
8738     };
8739     CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8740         var values = this.values;
8741         var oldVal = values[outerIndex];
8742         var toRespond = !this.toRespond
8743             ? 0
8744             : oldVal === none ? --this.toRespond : this.toRespond;
8745         values[outerIndex] = innerValue;
8746         if (toRespond === 0) {
8747             if (this.project) {
8748                 this._tryProject(values);
8749             }
8750             else {
8751                 this.destination.next(values.slice());
8752             }
8753         }
8754     };
8755     CombineLatestSubscriber.prototype._tryProject = function (values) {
8756         var result;
8757         try {
8758             result = this.project.apply(this, values);
8759         }
8760         catch (err) {
8761             this.destination.error(err);
8762             return;
8763         }
8764         this.destination.next(result);
8765     };
8766     return CombineLatestSubscriber;
8767 }(OuterSubscriber_1.OuterSubscriber));
8768 exports.CombineLatestSubscriber = CombineLatestSubscriber;
8769
8770 },{"../OuterSubscriber":30,"../observable/ArrayObservable":85,"../util/isArray":162,"../util/subscribeToResult":171}],112:[function(require,module,exports){
8771 "use strict";
8772 var Observable_1 = require('../Observable');
8773 var isScheduler_1 = require('../util/isScheduler');
8774 var ArrayObservable_1 = require('../observable/ArrayObservable');
8775 var mergeAll_1 = require('./mergeAll');
8776 /* tslint:enable:max-line-length */
8777 /**
8778  * Creates an output Observable which sequentially emits all values from every
8779  * given input Observable after the current Observable.
8780  *
8781  * <span class="informal">Concatenates multiple Observables together by
8782  * sequentially emitting their values, one Observable after the other.</span>
8783  *
8784  * <img src="./img/concat.png" width="100%">
8785  *
8786  * Joins this Observable with multiple other Observables by subscribing to them
8787  * one at a time, starting with the source, and merging their results into the
8788  * output Observable. Will wait for each Observable to complete before moving
8789  * on to the next.
8790  *
8791  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8792  * var timer = Rx.Observable.interval(1000).take(4);
8793  * var sequence = Rx.Observable.range(1, 10);
8794  * var result = timer.concat(sequence);
8795  * result.subscribe(x => console.log(x));
8796  *
8797  * // results in:
8798  * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8799  *
8800  * @example <caption>Concatenate 3 Observables</caption>
8801  * var timer1 = Rx.Observable.interval(1000).take(10);
8802  * var timer2 = Rx.Observable.interval(2000).take(6);
8803  * var timer3 = Rx.Observable.interval(500).take(10);
8804  * var result = timer1.concat(timer2, timer3);
8805  * result.subscribe(x => console.log(x));
8806  *
8807  * // results in the following:
8808  * // (Prints to console sequentially)
8809  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8810  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8811  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8812  *
8813  * @see {@link concatAll}
8814  * @see {@link concatMap}
8815  * @see {@link concatMapTo}
8816  *
8817  * @param {ObservableInput} other An input Observable to concatenate after the source
8818  * Observable. More than one input Observables may be given as argument.
8819  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8820  * Observable subscription on.
8821  * @return {Observable} All values of each passed Observable merged into a
8822  * single Observable, in order, in serial fashion.
8823  * @method concat
8824  * @owner Observable
8825  */
8826 function concat() {
8827     var observables = [];
8828     for (var _i = 0; _i < arguments.length; _i++) {
8829         observables[_i - 0] = arguments[_i];
8830     }
8831     return this.lift.call(concatStatic.apply(void 0, [this].concat(observables)));
8832 }
8833 exports.concat = concat;
8834 /* tslint:enable:max-line-length */
8835 /**
8836  * Creates an output Observable which sequentially emits all values from given
8837  * Observable and then moves on to the next.
8838  *
8839  * <span class="informal">Concatenates multiple Observables together by
8840  * sequentially emitting their values, one Observable after the other.</span>
8841  *
8842  * <img src="./img/concat.png" width="100%">
8843  *
8844  * `concat` joins multiple Observables together, by subscribing to them one at a time and
8845  * merging their results into the output Observable. You can pass either an array of
8846  * Observables, or put them directly as arguments. Passing an empty array will result
8847  * in Observable that completes immediately.
8848  *
8849  * `concat` will subscribe to first input Observable and emit all its values, without
8850  * changing or affecting them in any way. When that Observable completes, it will
8851  * subscribe to then next Observable passed and, again, emit its values. This will be
8852  * repeated, until the operator runs out of Observables. When last input Observable completes,
8853  * `concat` will complete as well. At any given moment only one Observable passed to operator
8854  * emits values. If you would like to emit values from passed Observables concurrently, check out
8855  * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
8856  * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
8857  *
8858  * Note that if some input Observable never completes, `concat` will also never complete
8859  * and Observables following the one that did not complete will never be subscribed. On the other
8860  * hand, if some Observable simply completes immediately after it is subscribed, it will be
8861  * invisible for `concat`, which will just move on to the next Observable.
8862  *
8863  * If any Observable in chain errors, instead of passing control to the next Observable,
8864  * `concat` will error immediately as well. Observables that would be subscribed after
8865  * the one that emitted error, never will.
8866  *
8867  * If you pass to `concat` the same Observable many times, its stream of values
8868  * will be "replayed" on every subscription, which means you can repeat given Observable
8869  * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
8870  * you can always use {@link repeat}.
8871  *
8872  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8873  * var timer = Rx.Observable.interval(1000).take(4);
8874  * var sequence = Rx.Observable.range(1, 10);
8875  * var result = Rx.Observable.concat(timer, sequence);
8876  * result.subscribe(x => console.log(x));
8877  *
8878  * // results in:
8879  * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8880  *
8881  *
8882  * @example <caption>Concatenate an array of 3 Observables</caption>
8883  * var timer1 = Rx.Observable.interval(1000).take(10);
8884  * var timer2 = Rx.Observable.interval(2000).take(6);
8885  * var timer3 = Rx.Observable.interval(500).take(10);
8886  * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
8887  * result.subscribe(x => console.log(x));
8888  *
8889  * // results in the following:
8890  * // (Prints to console sequentially)
8891  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8892  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8893  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8894  *
8895  *
8896  * @example <caption>Concatenate the same Observable to repeat it</caption>
8897  * const timer = Rx.Observable.interval(1000).take(2);
8898  *
8899  * Rx.Observable.concat(timer, timer) // concating the same Observable!
8900  * .subscribe(
8901  *   value => console.log(value),
8902  *   err => {},
8903  *   () => console.log('...and it is done!')
8904  * );
8905  *
8906  * // Logs:
8907  * // 0 after 1s
8908  * // 1 after 2s
8909  * // 0 after 3s
8910  * // 1 after 4s
8911  * // "...and it is done!" also after 4s
8912  *
8913  * @see {@link concatAll}
8914  * @see {@link concatMap}
8915  * @see {@link concatMapTo}
8916  *
8917  * @param {ObservableInput} input1 An input Observable to concatenate with others.
8918  * @param {ObservableInput} input2 An input Observable to concatenate with others.
8919  * More than one input Observables may be given as argument.
8920  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8921  * Observable subscription on.
8922  * @return {Observable} All values of each passed Observable merged into a
8923  * single Observable, in order, in serial fashion.
8924  * @static true
8925  * @name concat
8926  * @owner Observable
8927  */
8928 function concatStatic() {
8929     var observables = [];
8930     for (var _i = 0; _i < arguments.length; _i++) {
8931         observables[_i - 0] = arguments[_i];
8932     }
8933     var scheduler = null;
8934     var args = observables;
8935     if (isScheduler_1.isScheduler(args[observables.length - 1])) {
8936         scheduler = args.pop();
8937     }
8938     if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
8939         return observables[0];
8940     }
8941     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1));
8942 }
8943 exports.concatStatic = concatStatic;
8944
8945 },{"../Observable":28,"../observable/ArrayObservable":85,"../util/isScheduler":169,"./mergeAll":125}],113:[function(require,module,exports){
8946 "use strict";
8947 var __extends = (this && this.__extends) || function (d, b) {
8948     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8949     function __() { this.constructor = d; }
8950     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8951 };
8952 var Subscriber_1 = require('../Subscriber');
8953 var async_1 = require('../scheduler/async');
8954 /**
8955  * Emits a value from the source Observable only after a particular time span
8956  * has passed without another source emission.
8957  *
8958  * <span class="informal">It's like {@link delay}, but passes only the most
8959  * recent value from each burst of emissions.</span>
8960  *
8961  * <img src="./img/debounceTime.png" width="100%">
8962  *
8963  * `debounceTime` delays values emitted by the source Observable, but drops
8964  * previous pending delayed emissions if a new value arrives on the source
8965  * Observable. This operator keeps track of the most recent value from the
8966  * source Observable, and emits that only when `dueTime` enough time has passed
8967  * without any other value appearing on the source Observable. If a new value
8968  * appears before `dueTime` silence occurs, the previous value will be dropped
8969  * and will not be emitted on the output Observable.
8970  *
8971  * This is a rate-limiting operator, because it is impossible for more than one
8972  * value to be emitted in any time window of duration `dueTime`, but it is also
8973  * a delay-like operator since output emissions do not occur at the same time as
8974  * they did on the source Observable. Optionally takes a {@link IScheduler} for
8975  * managing timers.
8976  *
8977  * @example <caption>Emit the most recent click after a burst of clicks</caption>
8978  * var clicks = Rx.Observable.fromEvent(document, 'click');
8979  * var result = clicks.debounceTime(1000);
8980  * result.subscribe(x => console.log(x));
8981  *
8982  * @see {@link auditTime}
8983  * @see {@link debounce}
8984  * @see {@link delay}
8985  * @see {@link sampleTime}
8986  * @see {@link throttleTime}
8987  *
8988  * @param {number} dueTime The timeout duration in milliseconds (or the time
8989  * unit determined internally by the optional `scheduler`) for the window of
8990  * time required to wait for emission silence before emitting the most recent
8991  * source value.
8992  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
8993  * managing the timers that handle the timeout for each value.
8994  * @return {Observable} An Observable that delays the emissions of the source
8995  * Observable by the specified `dueTime`, and may drop some values if they occur
8996  * too frequently.
8997  * @method debounceTime
8998  * @owner Observable
8999  */
9000 function debounceTime(dueTime, scheduler) {
9001     if (scheduler === void 0) { scheduler = async_1.async; }
9002     return this.lift(new DebounceTimeOperator(dueTime, scheduler));
9003 }
9004 exports.debounceTime = debounceTime;
9005 var DebounceTimeOperator = (function () {
9006     function DebounceTimeOperator(dueTime, scheduler) {
9007         this.dueTime = dueTime;
9008         this.scheduler = scheduler;
9009     }
9010     DebounceTimeOperator.prototype.call = function (subscriber, source) {
9011         return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
9012     };
9013     return DebounceTimeOperator;
9014 }());
9015 /**
9016  * We need this JSDoc comment for affecting ESDoc.
9017  * @ignore
9018  * @extends {Ignored}
9019  */
9020 var DebounceTimeSubscriber = (function (_super) {
9021     __extends(DebounceTimeSubscriber, _super);
9022     function DebounceTimeSubscriber(destination, dueTime, scheduler) {
9023         _super.call(this, destination);
9024         this.dueTime = dueTime;
9025         this.scheduler = scheduler;
9026         this.debouncedSubscription = null;
9027         this.lastValue = null;
9028         this.hasValue = false;
9029     }
9030     DebounceTimeSubscriber.prototype._next = function (value) {
9031         this.clearDebounce();
9032         this.lastValue = value;
9033         this.hasValue = true;
9034         this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
9035     };
9036     DebounceTimeSubscriber.prototype._complete = function () {
9037         this.debouncedNext();
9038         this.destination.complete();
9039     };
9040     DebounceTimeSubscriber.prototype.debouncedNext = function () {
9041         this.clearDebounce();
9042         if (this.hasValue) {
9043             this.destination.next(this.lastValue);
9044             this.lastValue = null;
9045             this.hasValue = false;
9046         }
9047     };
9048     DebounceTimeSubscriber.prototype.clearDebounce = function () {
9049         var debouncedSubscription = this.debouncedSubscription;
9050         if (debouncedSubscription !== null) {
9051             this.remove(debouncedSubscription);
9052             debouncedSubscription.unsubscribe();
9053             this.debouncedSubscription = null;
9054         }
9055     };
9056     return DebounceTimeSubscriber;
9057 }(Subscriber_1.Subscriber));
9058 function dispatchNext(subscriber) {
9059     subscriber.debouncedNext();
9060 }
9061
9062 },{"../Subscriber":35,"../scheduler/async":150}],114:[function(require,module,exports){
9063 "use strict";
9064 var __extends = (this && this.__extends) || function (d, b) {
9065     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9066     function __() { this.constructor = d; }
9067     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9068 };
9069 var async_1 = require('../scheduler/async');
9070 var isDate_1 = require('../util/isDate');
9071 var Subscriber_1 = require('../Subscriber');
9072 var Notification_1 = require('../Notification');
9073 /**
9074  * Delays the emission of items from the source Observable by a given timeout or
9075  * until a given Date.
9076  *
9077  * <span class="informal">Time shifts each item by some specified amount of
9078  * milliseconds.</span>
9079  *
9080  * <img src="./img/delay.png" width="100%">
9081  *
9082  * If the delay argument is a Number, this operator time shifts the source
9083  * Observable by that amount of time expressed in milliseconds. The relative
9084  * time intervals between the values are preserved.
9085  *
9086  * If the delay argument is a Date, this operator time shifts the start of the
9087  * Observable execution until the given date occurs.
9088  *
9089  * @example <caption>Delay each click by one second</caption>
9090  * var clicks = Rx.Observable.fromEvent(document, 'click');
9091  * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
9092  * delayedClicks.subscribe(x => console.log(x));
9093  *
9094  * @example <caption>Delay all clicks until a future date happens</caption>
9095  * var clicks = Rx.Observable.fromEvent(document, 'click');
9096  * var date = new Date('March 15, 2050 12:00:00'); // in the future
9097  * var delayedClicks = clicks.delay(date); // click emitted only after that date
9098  * delayedClicks.subscribe(x => console.log(x));
9099  *
9100  * @see {@link debounceTime}
9101  * @see {@link delayWhen}
9102  *
9103  * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
9104  * a `Date` until which the emission of the source items is delayed.
9105  * @param {Scheduler} [scheduler=async] The IScheduler to use for
9106  * managing the timers that handle the time-shift for each item.
9107  * @return {Observable} An Observable that delays the emissions of the source
9108  * Observable by the specified timeout or Date.
9109  * @method delay
9110  * @owner Observable
9111  */
9112 function delay(delay, scheduler) {
9113     if (scheduler === void 0) { scheduler = async_1.async; }
9114     var absoluteDelay = isDate_1.isDate(delay);
9115     var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
9116     return this.lift(new DelayOperator(delayFor, scheduler));
9117 }
9118 exports.delay = delay;
9119 var DelayOperator = (function () {
9120     function DelayOperator(delay, scheduler) {
9121         this.delay = delay;
9122         this.scheduler = scheduler;
9123     }
9124     DelayOperator.prototype.call = function (subscriber, source) {
9125         return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
9126     };
9127     return DelayOperator;
9128 }());
9129 /**
9130  * We need this JSDoc comment for affecting ESDoc.
9131  * @ignore
9132  * @extends {Ignored}
9133  */
9134 var DelaySubscriber = (function (_super) {
9135     __extends(DelaySubscriber, _super);
9136     function DelaySubscriber(destination, delay, scheduler) {
9137         _super.call(this, destination);
9138         this.delay = delay;
9139         this.scheduler = scheduler;
9140         this.queue = [];
9141         this.active = false;
9142         this.errored = false;
9143     }
9144     DelaySubscriber.dispatch = function (state) {
9145         var source = state.source;
9146         var queue = source.queue;
9147         var scheduler = state.scheduler;
9148         var destination = state.destination;
9149         while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
9150             queue.shift().notification.observe(destination);
9151         }
9152         if (queue.length > 0) {
9153             var delay_1 = Math.max(0, queue[0].time - scheduler.now());
9154             this.schedule(state, delay_1);
9155         }
9156         else {
9157             source.active = false;
9158         }
9159     };
9160     DelaySubscriber.prototype._schedule = function (scheduler) {
9161         this.active = true;
9162         this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
9163             source: this, destination: this.destination, scheduler: scheduler
9164         }));
9165     };
9166     DelaySubscriber.prototype.scheduleNotification = function (notification) {
9167         if (this.errored === true) {
9168             return;
9169         }
9170         var scheduler = this.scheduler;
9171         var message = new DelayMessage(scheduler.now() + this.delay, notification);
9172         this.queue.push(message);
9173         if (this.active === false) {
9174             this._schedule(scheduler);
9175         }
9176     };
9177     DelaySubscriber.prototype._next = function (value) {
9178         this.scheduleNotification(Notification_1.Notification.createNext(value));
9179     };
9180     DelaySubscriber.prototype._error = function (err) {
9181         this.errored = true;
9182         this.queue = [];
9183         this.destination.error(err);
9184     };
9185     DelaySubscriber.prototype._complete = function () {
9186         this.scheduleNotification(Notification_1.Notification.createComplete());
9187     };
9188     return DelaySubscriber;
9189 }(Subscriber_1.Subscriber));
9190 var DelayMessage = (function () {
9191     function DelayMessage(time, notification) {
9192         this.time = time;
9193         this.notification = notification;
9194     }
9195     return DelayMessage;
9196 }());
9197
9198 },{"../Notification":27,"../Subscriber":35,"../scheduler/async":150,"../util/isDate":164}],115:[function(require,module,exports){
9199 "use strict";
9200 var __extends = (this && this.__extends) || function (d, b) {
9201     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9202     function __() { this.constructor = d; }
9203     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9204 };
9205 var OuterSubscriber_1 = require('../OuterSubscriber');
9206 var subscribeToResult_1 = require('../util/subscribeToResult');
9207 var Set_1 = require('../util/Set');
9208 /**
9209  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
9210  *
9211  * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
9212  * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
9213  * source observable directly with an equality check against previous values.
9214  *
9215  * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
9216  *
9217  * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
9218  * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
9219  * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
9220  * that the internal `Set` can be "flushed", basically clearing it of values.
9221  *
9222  * @example <caption>A simple example with numbers</caption>
9223  * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
9224  *   .distinct()
9225  *   .subscribe(x => console.log(x)); // 1, 2, 3, 4
9226  *
9227  * @example <caption>An example using a keySelector function</caption>
9228  * interface Person {
9229  *    age: number,
9230  *    name: string
9231  * }
9232  *
9233  * Observable.of<Person>(
9234  *     { age: 4, name: 'Foo'},
9235  *     { age: 7, name: 'Bar'},
9236  *     { age: 5, name: 'Foo'})
9237  *     .distinct((p: Person) => p.name)
9238  *     .subscribe(x => console.log(x));
9239  *
9240  * // displays:
9241  * // { age: 4, name: 'Foo' }
9242  * // { age: 7, name: 'Bar' }
9243  *
9244  * @see {@link distinctUntilChanged}
9245  * @see {@link distinctUntilKeyChanged}
9246  *
9247  * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
9248  * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
9249  * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9250  * @method distinct
9251  * @owner Observable
9252  */
9253 function distinct(keySelector, flushes) {
9254     return this.lift(new DistinctOperator(keySelector, flushes));
9255 }
9256 exports.distinct = distinct;
9257 var DistinctOperator = (function () {
9258     function DistinctOperator(keySelector, flushes) {
9259         this.keySelector = keySelector;
9260         this.flushes = flushes;
9261     }
9262     DistinctOperator.prototype.call = function (subscriber, source) {
9263         return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
9264     };
9265     return DistinctOperator;
9266 }());
9267 /**
9268  * We need this JSDoc comment for affecting ESDoc.
9269  * @ignore
9270  * @extends {Ignored}
9271  */
9272 var DistinctSubscriber = (function (_super) {
9273     __extends(DistinctSubscriber, _super);
9274     function DistinctSubscriber(destination, keySelector, flushes) {
9275         _super.call(this, destination);
9276         this.keySelector = keySelector;
9277         this.values = new Set_1.Set();
9278         if (flushes) {
9279             this.add(subscribeToResult_1.subscribeToResult(this, flushes));
9280         }
9281     }
9282     DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9283         this.values.clear();
9284     };
9285     DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
9286         this._error(error);
9287     };
9288     DistinctSubscriber.prototype._next = function (value) {
9289         if (this.keySelector) {
9290             this._useKeySelector(value);
9291         }
9292         else {
9293             this._finalizeNext(value, value);
9294         }
9295     };
9296     DistinctSubscriber.prototype._useKeySelector = function (value) {
9297         var key;
9298         var destination = this.destination;
9299         try {
9300             key = this.keySelector(value);
9301         }
9302         catch (err) {
9303             destination.error(err);
9304             return;
9305         }
9306         this._finalizeNext(key, value);
9307     };
9308     DistinctSubscriber.prototype._finalizeNext = function (key, value) {
9309         var values = this.values;
9310         if (!values.has(key)) {
9311             values.add(key);
9312             this.destination.next(value);
9313         }
9314     };
9315     return DistinctSubscriber;
9316 }(OuterSubscriber_1.OuterSubscriber));
9317 exports.DistinctSubscriber = DistinctSubscriber;
9318
9319 },{"../OuterSubscriber":30,"../util/Set":159,"../util/subscribeToResult":171}],116:[function(require,module,exports){
9320 "use strict";
9321 var __extends = (this && this.__extends) || function (d, b) {
9322     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9323     function __() { this.constructor = d; }
9324     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9325 };
9326 var Subscriber_1 = require('../Subscriber');
9327 var tryCatch_1 = require('../util/tryCatch');
9328 var errorObject_1 = require('../util/errorObject');
9329 /* tslint:enable:max-line-length */
9330 /**
9331  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
9332  *
9333  * 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.
9334  *
9335  * If a comparator function is not provided, an equality check is used by default.
9336  *
9337  * @example <caption>A simple example with numbers</caption>
9338  * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
9339  *   .distinctUntilChanged()
9340  *   .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
9341  *
9342  * @example <caption>An example using a compare function</caption>
9343  * interface Person {
9344  *    age: number,
9345  *    name: string
9346  * }
9347  *
9348  * Observable.of<Person>(
9349  *     { age: 4, name: 'Foo'},
9350  *     { age: 7, name: 'Bar'},
9351  *     { age: 5, name: 'Foo'})
9352  *     { age: 6, name: 'Foo'})
9353  *     .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
9354  *     .subscribe(x => console.log(x));
9355  *
9356  * // displays:
9357  * // { age: 4, name: 'Foo' }
9358  * // { age: 7, name: 'Bar' }
9359  * // { age: 5, name: 'Foo' }
9360  *
9361  * @see {@link distinct}
9362  * @see {@link distinctUntilKeyChanged}
9363  *
9364  * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
9365  * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9366  * @method distinctUntilChanged
9367  * @owner Observable
9368  */
9369 function distinctUntilChanged(compare, keySelector) {
9370     return this.lift(new DistinctUntilChangedOperator(compare, keySelector));
9371 }
9372 exports.distinctUntilChanged = distinctUntilChanged;
9373 var DistinctUntilChangedOperator = (function () {
9374     function DistinctUntilChangedOperator(compare, keySelector) {
9375         this.compare = compare;
9376         this.keySelector = keySelector;
9377     }
9378     DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
9379         return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
9380     };
9381     return DistinctUntilChangedOperator;
9382 }());
9383 /**
9384  * We need this JSDoc comment for affecting ESDoc.
9385  * @ignore
9386  * @extends {Ignored}
9387  */
9388 var DistinctUntilChangedSubscriber = (function (_super) {
9389     __extends(DistinctUntilChangedSubscriber, _super);
9390     function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
9391         _super.call(this, destination);
9392         this.keySelector = keySelector;
9393         this.hasKey = false;
9394         if (typeof compare === 'function') {
9395             this.compare = compare;
9396         }
9397     }
9398     DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
9399         return x === y;
9400     };
9401     DistinctUntilChangedSubscriber.prototype._next = function (value) {
9402         var keySelector = this.keySelector;
9403         var key = value;
9404         if (keySelector) {
9405             key = tryCatch_1.tryCatch(this.keySelector)(value);
9406             if (key === errorObject_1.errorObject) {
9407                 return this.destination.error(errorObject_1.errorObject.e);
9408             }
9409         }
9410         var result = false;
9411         if (this.hasKey) {
9412             result = tryCatch_1.tryCatch(this.compare)(this.key, key);
9413             if (result === errorObject_1.errorObject) {
9414                 return this.destination.error(errorObject_1.errorObject.e);
9415             }
9416         }
9417         else {
9418             this.hasKey = true;
9419         }
9420         if (Boolean(result) === false) {
9421             this.key = key;
9422             this.destination.next(value);
9423         }
9424     };
9425     return DistinctUntilChangedSubscriber;
9426 }(Subscriber_1.Subscriber));
9427
9428 },{"../Subscriber":35,"../util/errorObject":161,"../util/tryCatch":173}],117:[function(require,module,exports){
9429 "use strict";
9430 var __extends = (this && this.__extends) || function (d, b) {
9431     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9432     function __() { this.constructor = d; }
9433     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9434 };
9435 var Subscriber_1 = require('../Subscriber');
9436 /* tslint:enable:max-line-length */
9437 /**
9438  * Perform a side effect for every emission on the source Observable, but return
9439  * an Observable that is identical to the source.
9440  *
9441  * <span class="informal">Intercepts each emission on the source and runs a
9442  * function, but returns an output which is identical to the source.</span>
9443  *
9444  * <img src="./img/do.png" width="100%">
9445  *
9446  * Returns a mirrored Observable of the source Observable, but modified so that
9447  * the provided Observer is called to perform a side effect for every value,
9448  * error, and completion emitted by the source. Any errors that are thrown in
9449  * the aforementioned Observer or handlers are safely sent down the error path
9450  * of the output Observable.
9451  *
9452  * This operator is useful for debugging your Observables for the correct values
9453  * or performing other side effects.
9454  *
9455  * Note: this is different to a `subscribe` on the Observable. If the Observable
9456  * returned by `do` is not subscribed, the side effects specified by the
9457  * Observer will never happen. `do` therefore simply spies on existing
9458  * execution, it does not trigger an execution to happen like `subscribe` does.
9459  *
9460  * @example <caption>Map every every click to the clientX position of that click, while also logging the click event</caption>
9461  * var clicks = Rx.Observable.fromEvent(document, 'click');
9462  * var positions = clicks
9463  *   .do(ev => console.log(ev))
9464  *   .map(ev => ev.clientX);
9465  * positions.subscribe(x => console.log(x));
9466  *
9467  * @see {@link map}
9468  * @see {@link subscribe}
9469  *
9470  * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9471  * callback for `next`.
9472  * @param {function} [error] Callback for errors in the source.
9473  * @param {function} [complete] Callback for the completion of the source.
9474  * @return {Observable} An Observable identical to the source, but runs the
9475  * specified Observer or callback(s) for each item.
9476  * @method do
9477  * @name do
9478  * @owner Observable
9479  */
9480 function _do(nextOrObserver, error, complete) {
9481     return this.lift(new DoOperator(nextOrObserver, error, complete));
9482 }
9483 exports._do = _do;
9484 var DoOperator = (function () {
9485     function DoOperator(nextOrObserver, error, complete) {
9486         this.nextOrObserver = nextOrObserver;
9487         this.error = error;
9488         this.complete = complete;
9489     }
9490     DoOperator.prototype.call = function (subscriber, source) {
9491         return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
9492     };
9493     return DoOperator;
9494 }());
9495 /**
9496  * We need this JSDoc comment for affecting ESDoc.
9497  * @ignore
9498  * @extends {Ignored}
9499  */
9500 var DoSubscriber = (function (_super) {
9501     __extends(DoSubscriber, _super);
9502     function DoSubscriber(destination, nextOrObserver, error, complete) {
9503         _super.call(this, destination);
9504         var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
9505         safeSubscriber.syncErrorThrowable = true;
9506         this.add(safeSubscriber);
9507         this.safeSubscriber = safeSubscriber;
9508     }
9509     DoSubscriber.prototype._next = function (value) {
9510         var safeSubscriber = this.safeSubscriber;
9511         safeSubscriber.next(value);
9512         if (safeSubscriber.syncErrorThrown) {
9513             this.destination.error(safeSubscriber.syncErrorValue);
9514         }
9515         else {
9516             this.destination.next(value);
9517         }
9518     };
9519     DoSubscriber.prototype._error = function (err) {
9520         var safeSubscriber = this.safeSubscriber;
9521         safeSubscriber.error(err);
9522         if (safeSubscriber.syncErrorThrown) {
9523             this.destination.error(safeSubscriber.syncErrorValue);
9524         }
9525         else {
9526             this.destination.error(err);
9527         }
9528     };
9529     DoSubscriber.prototype._complete = function () {
9530         var safeSubscriber = this.safeSubscriber;
9531         safeSubscriber.complete();
9532         if (safeSubscriber.syncErrorThrown) {
9533             this.destination.error(safeSubscriber.syncErrorValue);
9534         }
9535         else {
9536             this.destination.complete();
9537         }
9538     };
9539     return DoSubscriber;
9540 }(Subscriber_1.Subscriber));
9541
9542 },{"../Subscriber":35}],118:[function(require,module,exports){
9543 "use strict";
9544 var __extends = (this && this.__extends) || function (d, b) {
9545     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9546     function __() { this.constructor = d; }
9547     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9548 };
9549 var tryCatch_1 = require('../util/tryCatch');
9550 var errorObject_1 = require('../util/errorObject');
9551 var OuterSubscriber_1 = require('../OuterSubscriber');
9552 var subscribeToResult_1 = require('../util/subscribeToResult');
9553 /* tslint:enable:max-line-length */
9554 /**
9555  * Recursively projects each source value to an Observable which is merged in
9556  * the output Observable.
9557  *
9558  * <span class="informal">It's similar to {@link mergeMap}, but applies the
9559  * projection function to every source value as well as every output value.
9560  * It's recursive.</span>
9561  *
9562  * <img src="./img/expand.png" width="100%">
9563  *
9564  * Returns an Observable that emits items based on applying a function that you
9565  * supply to each item emitted by the source Observable, where that function
9566  * returns an Observable, and then merging those resulting Observables and
9567  * emitting the results of this merger. *Expand* will re-emit on the output
9568  * Observable every source value. Then, each output value is given to the
9569  * `project` function which returns an inner Observable to be merged on the
9570  * output Observable. Those output values resulting from the projection are also
9571  * given to the `project` function to produce new output values. This is how
9572  * *expand* behaves recursively.
9573  *
9574  * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9575  * var clicks = Rx.Observable.fromEvent(document, 'click');
9576  * var powersOfTwo = clicks
9577  *   .mapTo(1)
9578  *   .expand(x => Rx.Observable.of(2 * x).delay(1000))
9579  *   .take(10);
9580  * powersOfTwo.subscribe(x => console.log(x));
9581  *
9582  * @see {@link mergeMap}
9583  * @see {@link mergeScan}
9584  *
9585  * @param {function(value: T, index: number) => Observable} project A function
9586  * that, when applied to an item emitted by the source or the output Observable,
9587  * returns an Observable.
9588  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9589  * Observables being subscribed to concurrently.
9590  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9591  * each projected inner Observable.
9592  * @return {Observable} An Observable that emits the source values and also
9593  * result of applying the projection function to each value emitted on the
9594  * output Observable and and merging the results of the Observables obtained
9595  * from this transformation.
9596  * @method expand
9597  * @owner Observable
9598  */
9599 function expand(project, concurrent, scheduler) {
9600     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9601     if (scheduler === void 0) { scheduler = undefined; }
9602     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9603     return this.lift(new ExpandOperator(project, concurrent, scheduler));
9604 }
9605 exports.expand = expand;
9606 var ExpandOperator = (function () {
9607     function ExpandOperator(project, concurrent, scheduler) {
9608         this.project = project;
9609         this.concurrent = concurrent;
9610         this.scheduler = scheduler;
9611     }
9612     ExpandOperator.prototype.call = function (subscriber, source) {
9613         return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
9614     };
9615     return ExpandOperator;
9616 }());
9617 exports.ExpandOperator = ExpandOperator;
9618 /**
9619  * We need this JSDoc comment for affecting ESDoc.
9620  * @ignore
9621  * @extends {Ignored}
9622  */
9623 var ExpandSubscriber = (function (_super) {
9624     __extends(ExpandSubscriber, _super);
9625     function ExpandSubscriber(destination, project, concurrent, scheduler) {
9626         _super.call(this, destination);
9627         this.project = project;
9628         this.concurrent = concurrent;
9629         this.scheduler = scheduler;
9630         this.index = 0;
9631         this.active = 0;
9632         this.hasCompleted = false;
9633         if (concurrent < Number.POSITIVE_INFINITY) {
9634             this.buffer = [];
9635         }
9636     }
9637     ExpandSubscriber.dispatch = function (arg) {
9638         var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
9639         subscriber.subscribeToProjection(result, value, index);
9640     };
9641     ExpandSubscriber.prototype._next = function (value) {
9642         var destination = this.destination;
9643         if (destination.closed) {
9644             this._complete();
9645             return;
9646         }
9647         var index = this.index++;
9648         if (this.active < this.concurrent) {
9649             destination.next(value);
9650             var result = tryCatch_1.tryCatch(this.project)(value, index);
9651             if (result === errorObject_1.errorObject) {
9652                 destination.error(errorObject_1.errorObject.e);
9653             }
9654             else if (!this.scheduler) {
9655                 this.subscribeToProjection(result, value, index);
9656             }
9657             else {
9658                 var state = { subscriber: this, result: result, value: value, index: index };
9659                 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
9660             }
9661         }
9662         else {
9663             this.buffer.push(value);
9664         }
9665     };
9666     ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
9667         this.active++;
9668         this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
9669     };
9670     ExpandSubscriber.prototype._complete = function () {
9671         this.hasCompleted = true;
9672         if (this.hasCompleted && this.active === 0) {
9673             this.destination.complete();
9674         }
9675     };
9676     ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9677         this._next(innerValue);
9678     };
9679     ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
9680         var buffer = this.buffer;
9681         this.remove(innerSub);
9682         this.active--;
9683         if (buffer && buffer.length > 0) {
9684             this._next(buffer.shift());
9685         }
9686         if (this.hasCompleted && this.active === 0) {
9687             this.destination.complete();
9688         }
9689     };
9690     return ExpandSubscriber;
9691 }(OuterSubscriber_1.OuterSubscriber));
9692 exports.ExpandSubscriber = ExpandSubscriber;
9693
9694 },{"../OuterSubscriber":30,"../util/errorObject":161,"../util/subscribeToResult":171,"../util/tryCatch":173}],119:[function(require,module,exports){
9695 "use strict";
9696 var __extends = (this && this.__extends) || function (d, b) {
9697     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9698     function __() { this.constructor = d; }
9699     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9700 };
9701 var Subscriber_1 = require('../Subscriber');
9702 /* tslint:enable:max-line-length */
9703 /**
9704  * Filter items emitted by the source Observable by only emitting those that
9705  * satisfy a specified predicate.
9706  *
9707  * <span class="informal">Like
9708  * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
9709  * it only emits a value from the source if it passes a criterion function.</span>
9710  *
9711  * <img src="./img/filter.png" width="100%">
9712  *
9713  * Similar to the well-known `Array.prototype.filter` method, this operator
9714  * takes values from the source Observable, passes them through a `predicate`
9715  * function and only emits those values that yielded `true`.
9716  *
9717  * @example <caption>Emit only click events whose target was a DIV element</caption>
9718  * var clicks = Rx.Observable.fromEvent(document, 'click');
9719  * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
9720  * clicksOnDivs.subscribe(x => console.log(x));
9721  *
9722  * @see {@link distinct}
9723  * @see {@link distinctUntilChanged}
9724  * @see {@link distinctUntilKeyChanged}
9725  * @see {@link ignoreElements}
9726  * @see {@link partition}
9727  * @see {@link skip}
9728  *
9729  * @param {function(value: T, index: number): boolean} predicate A function that
9730  * evaluates each value emitted by the source Observable. If it returns `true`,
9731  * the value is emitted, if `false` the value is not passed to the output
9732  * Observable. The `index` parameter is the number `i` for the i-th source
9733  * emission that has happened since the subscription, starting from the number
9734  * `0`.
9735  * @param {any} [thisArg] An optional argument to determine the value of `this`
9736  * in the `predicate` function.
9737  * @return {Observable} An Observable of values from the source that were
9738  * allowed by the `predicate` function.
9739  * @method filter
9740  * @owner Observable
9741  */
9742 function filter(predicate, thisArg) {
9743     return this.lift(new FilterOperator(predicate, thisArg));
9744 }
9745 exports.filter = filter;
9746 var FilterOperator = (function () {
9747     function FilterOperator(predicate, thisArg) {
9748         this.predicate = predicate;
9749         this.thisArg = thisArg;
9750     }
9751     FilterOperator.prototype.call = function (subscriber, source) {
9752         return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
9753     };
9754     return FilterOperator;
9755 }());
9756 /**
9757  * We need this JSDoc comment for affecting ESDoc.
9758  * @ignore
9759  * @extends {Ignored}
9760  */
9761 var FilterSubscriber = (function (_super) {
9762     __extends(FilterSubscriber, _super);
9763     function FilterSubscriber(destination, predicate, thisArg) {
9764         _super.call(this, destination);
9765         this.predicate = predicate;
9766         this.thisArg = thisArg;
9767         this.count = 0;
9768         this.predicate = predicate;
9769     }
9770     // the try catch block below is left specifically for
9771     // optimization and perf reasons. a tryCatcher is not necessary here.
9772     FilterSubscriber.prototype._next = function (value) {
9773         var result;
9774         try {
9775             result = this.predicate.call(this.thisArg, value, this.count++);
9776         }
9777         catch (err) {
9778             this.destination.error(err);
9779             return;
9780         }
9781         if (result) {
9782             this.destination.next(value);
9783         }
9784     };
9785     return FilterSubscriber;
9786 }(Subscriber_1.Subscriber));
9787
9788 },{"../Subscriber":35}],120:[function(require,module,exports){
9789 "use strict";
9790 var __extends = (this && this.__extends) || function (d, b) {
9791     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9792     function __() { this.constructor = d; }
9793     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9794 };
9795 var Subscriber_1 = require('../Subscriber');
9796 var Subscription_1 = require('../Subscription');
9797 /**
9798  * Returns an Observable that mirrors the source Observable, but will call a specified function when
9799  * the source terminates on complete or error.
9800  * @param {function} callback Function to be called when source terminates.
9801  * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
9802  * @method finally
9803  * @owner Observable
9804  */
9805 function _finally(callback) {
9806     return this.lift(new FinallyOperator(callback));
9807 }
9808 exports._finally = _finally;
9809 var FinallyOperator = (function () {
9810     function FinallyOperator(callback) {
9811         this.callback = callback;
9812     }
9813     FinallyOperator.prototype.call = function (subscriber, source) {
9814         return source.subscribe(new FinallySubscriber(subscriber, this.callback));
9815     };
9816     return FinallyOperator;
9817 }());
9818 /**
9819  * We need this JSDoc comment for affecting ESDoc.
9820  * @ignore
9821  * @extends {Ignored}
9822  */
9823 var FinallySubscriber = (function (_super) {
9824     __extends(FinallySubscriber, _super);
9825     function FinallySubscriber(destination, callback) {
9826         _super.call(this, destination);
9827         this.add(new Subscription_1.Subscription(callback));
9828     }
9829     return FinallySubscriber;
9830 }(Subscriber_1.Subscriber));
9831
9832 },{"../Subscriber":35,"../Subscription":36}],121:[function(require,module,exports){
9833 "use strict";
9834 var __extends = (this && this.__extends) || function (d, b) {
9835     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9836     function __() { this.constructor = d; }
9837     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9838 };
9839 var Subscriber_1 = require('../Subscriber');
9840 var EmptyError_1 = require('../util/EmptyError');
9841 /**
9842  * Emits only the first value (or the first value that meets some condition)
9843  * emitted by the source Observable.
9844  *
9845  * <span class="informal">Emits only the first value. Or emits only the first
9846  * value that passes some test.</span>
9847  *
9848  * <img src="./img/first.png" width="100%">
9849  *
9850  * If called with no arguments, `first` emits the first value of the source
9851  * Observable, then completes. If called with a `predicate` function, `first`
9852  * emits the first value of the source that matches the specified condition. It
9853  * may also take a `resultSelector` function to produce the output value from
9854  * the input value, and a `defaultValue` to emit in case the source completes
9855  * before it is able to emit a valid value. Throws an error if `defaultValue`
9856  * was not provided and a matching element is not found.
9857  *
9858  * @example <caption>Emit only the first click that happens on the DOM</caption>
9859  * var clicks = Rx.Observable.fromEvent(document, 'click');
9860  * var result = clicks.first();
9861  * result.subscribe(x => console.log(x));
9862  *
9863  * @example <caption>Emits the first click that happens on a DIV</caption>
9864  * var clicks = Rx.Observable.fromEvent(document, 'click');
9865  * var result = clicks.first(ev => ev.target.tagName === 'DIV');
9866  * result.subscribe(x => console.log(x));
9867  *
9868  * @see {@link filter}
9869  * @see {@link find}
9870  * @see {@link take}
9871  *
9872  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9873  * callback if the Observable completes before any `next` notification was sent.
9874  *
9875  * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
9876  * An optional function called with each item to test for condition matching.
9877  * @param {function(value: T, index: number): R} [resultSelector] A function to
9878  * produce the value on the output Observable based on the values
9879  * and the indices of the source Observable. The arguments passed to this
9880  * function are:
9881  * - `value`: the value that was emitted on the source.
9882  * - `index`: the "index" of the value from the source.
9883  * @param {R} [defaultValue] The default value emitted in case no valid value
9884  * was found on the source.
9885  * @return {Observable<T|R>} An Observable of the first item that matches the
9886  * condition.
9887  * @method first
9888  * @owner Observable
9889  */
9890 function first(predicate, resultSelector, defaultValue) {
9891     return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this));
9892 }
9893 exports.first = first;
9894 var FirstOperator = (function () {
9895     function FirstOperator(predicate, resultSelector, defaultValue, source) {
9896         this.predicate = predicate;
9897         this.resultSelector = resultSelector;
9898         this.defaultValue = defaultValue;
9899         this.source = source;
9900     }
9901     FirstOperator.prototype.call = function (observer, source) {
9902         return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
9903     };
9904     return FirstOperator;
9905 }());
9906 /**
9907  * We need this JSDoc comment for affecting ESDoc.
9908  * @ignore
9909  * @extends {Ignored}
9910  */
9911 var FirstSubscriber = (function (_super) {
9912     __extends(FirstSubscriber, _super);
9913     function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
9914         _super.call(this, destination);
9915         this.predicate = predicate;
9916         this.resultSelector = resultSelector;
9917         this.defaultValue = defaultValue;
9918         this.source = source;
9919         this.index = 0;
9920         this.hasCompleted = false;
9921         this._emitted = false;
9922     }
9923     FirstSubscriber.prototype._next = function (value) {
9924         var index = this.index++;
9925         if (this.predicate) {
9926             this._tryPredicate(value, index);
9927         }
9928         else {
9929             this._emit(value, index);
9930         }
9931     };
9932     FirstSubscriber.prototype._tryPredicate = function (value, index) {
9933         var result;
9934         try {
9935             result = this.predicate(value, index, this.source);
9936         }
9937         catch (err) {
9938             this.destination.error(err);
9939             return;
9940         }
9941         if (result) {
9942             this._emit(value, index);
9943         }
9944     };
9945     FirstSubscriber.prototype._emit = function (value, index) {
9946         if (this.resultSelector) {
9947             this._tryResultSelector(value, index);
9948             return;
9949         }
9950         this._emitFinal(value);
9951     };
9952     FirstSubscriber.prototype._tryResultSelector = function (value, index) {
9953         var result;
9954         try {
9955             result = this.resultSelector(value, index);
9956         }
9957         catch (err) {
9958             this.destination.error(err);
9959             return;
9960         }
9961         this._emitFinal(result);
9962     };
9963     FirstSubscriber.prototype._emitFinal = function (value) {
9964         var destination = this.destination;
9965         if (!this._emitted) {
9966             this._emitted = true;
9967             destination.next(value);
9968             destination.complete();
9969             this.hasCompleted = true;
9970         }
9971     };
9972     FirstSubscriber.prototype._complete = function () {
9973         var destination = this.destination;
9974         if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
9975             destination.next(this.defaultValue);
9976             destination.complete();
9977         }
9978         else if (!this.hasCompleted) {
9979             destination.error(new EmptyError_1.EmptyError);
9980         }
9981     };
9982     return FirstSubscriber;
9983 }(Subscriber_1.Subscriber));
9984
9985 },{"../Subscriber":35,"../util/EmptyError":157}],122:[function(require,module,exports){
9986 "use strict";
9987 var __extends = (this && this.__extends) || function (d, b) {
9988     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9989     function __() { this.constructor = d; }
9990     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9991 };
9992 var Subscriber_1 = require('../Subscriber');
9993 var EmptyError_1 = require('../util/EmptyError');
9994 /* tslint:enable:max-line-length */
9995 /**
9996  * Returns an Observable that emits only the last item emitted by the source Observable.
9997  * It optionally takes a predicate function as a parameter, in which case, rather than emitting
9998  * the last item from the source Observable, the resulting Observable will emit the last item
9999  * from the source Observable that satisfies the predicate.
10000  *
10001  * <img src="./img/last.png" width="100%">
10002  *
10003  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
10004  * callback if the Observable completes before any `next` notification was sent.
10005  * @param {function} predicate - The condition any source emitted item has to satisfy.
10006  * @return {Observable} An Observable that emits only the last item satisfying the given condition
10007  * from the source, or an NoSuchElementException if no such items are emitted.
10008  * @throws - Throws if no items that match the predicate are emitted by the source Observable.
10009  * @method last
10010  * @owner Observable
10011  */
10012 function last(predicate, resultSelector, defaultValue) {
10013     return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this));
10014 }
10015 exports.last = last;
10016 var LastOperator = (function () {
10017     function LastOperator(predicate, resultSelector, defaultValue, source) {
10018         this.predicate = predicate;
10019         this.resultSelector = resultSelector;
10020         this.defaultValue = defaultValue;
10021         this.source = source;
10022     }
10023     LastOperator.prototype.call = function (observer, source) {
10024         return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
10025     };
10026     return LastOperator;
10027 }());
10028 /**
10029  * We need this JSDoc comment for affecting ESDoc.
10030  * @ignore
10031  * @extends {Ignored}
10032  */
10033 var LastSubscriber = (function (_super) {
10034     __extends(LastSubscriber, _super);
10035     function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
10036         _super.call(this, destination);
10037         this.predicate = predicate;
10038         this.resultSelector = resultSelector;
10039         this.defaultValue = defaultValue;
10040         this.source = source;
10041         this.hasValue = false;
10042         this.index = 0;
10043         if (typeof defaultValue !== 'undefined') {
10044             this.lastValue = defaultValue;
10045             this.hasValue = true;
10046         }
10047     }
10048     LastSubscriber.prototype._next = function (value) {
10049         var index = this.index++;
10050         if (this.predicate) {
10051             this._tryPredicate(value, index);
10052         }
10053         else {
10054             if (this.resultSelector) {
10055                 this._tryResultSelector(value, index);
10056                 return;
10057             }
10058             this.lastValue = value;
10059             this.hasValue = true;
10060         }
10061     };
10062     LastSubscriber.prototype._tryPredicate = function (value, index) {
10063         var result;
10064         try {
10065             result = this.predicate(value, index, this.source);
10066         }
10067         catch (err) {
10068             this.destination.error(err);
10069             return;
10070         }
10071         if (result) {
10072             if (this.resultSelector) {
10073                 this._tryResultSelector(value, index);
10074                 return;
10075             }
10076             this.lastValue = value;
10077             this.hasValue = true;
10078         }
10079     };
10080     LastSubscriber.prototype._tryResultSelector = function (value, index) {
10081         var result;
10082         try {
10083             result = this.resultSelector(value, index);
10084         }
10085         catch (err) {
10086             this.destination.error(err);
10087             return;
10088         }
10089         this.lastValue = result;
10090         this.hasValue = true;
10091     };
10092     LastSubscriber.prototype._complete = function () {
10093         var destination = this.destination;
10094         if (this.hasValue) {
10095             destination.next(this.lastValue);
10096             destination.complete();
10097         }
10098         else {
10099             destination.error(new EmptyError_1.EmptyError);
10100         }
10101     };
10102     return LastSubscriber;
10103 }(Subscriber_1.Subscriber));
10104
10105 },{"../Subscriber":35,"../util/EmptyError":157}],123:[function(require,module,exports){
10106 "use strict";
10107 var __extends = (this && this.__extends) || function (d, b) {
10108     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10109     function __() { this.constructor = d; }
10110     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10111 };
10112 var Subscriber_1 = require('../Subscriber');
10113 /**
10114  * Applies a given `project` function to each value emitted by the source
10115  * Observable, and emits the resulting values as an Observable.
10116  *
10117  * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
10118  * it passes each source value through a transformation function to get
10119  * corresponding output values.</span>
10120  *
10121  * <img src="./img/map.png" width="100%">
10122  *
10123  * Similar to the well known `Array.prototype.map` function, this operator
10124  * applies a projection to each value and emits that projection in the output
10125  * Observable.
10126  *
10127  * @example <caption>Map every every click to the clientX position of that click</caption>
10128  * var clicks = Rx.Observable.fromEvent(document, 'click');
10129  * var positions = clicks.map(ev => ev.clientX);
10130  * positions.subscribe(x => console.log(x));
10131  *
10132  * @see {@link mapTo}
10133  * @see {@link pluck}
10134  *
10135  * @param {function(value: T, index: number): R} project The function to apply
10136  * to each `value` emitted by the source Observable. The `index` parameter is
10137  * the number `i` for the i-th emission that has happened since the
10138  * subscription, starting from the number `0`.
10139  * @param {any} [thisArg] An optional argument to define what `this` is in the
10140  * `project` function.
10141  * @return {Observable<R>} An Observable that emits the values from the source
10142  * Observable transformed by the given `project` function.
10143  * @method map
10144  * @owner Observable
10145  */
10146 function map(project, thisArg) {
10147     if (typeof project !== 'function') {
10148         throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
10149     }
10150     return this.lift(new MapOperator(project, thisArg));
10151 }
10152 exports.map = map;
10153 var MapOperator = (function () {
10154     function MapOperator(project, thisArg) {
10155         this.project = project;
10156         this.thisArg = thisArg;
10157     }
10158     MapOperator.prototype.call = function (subscriber, source) {
10159         return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
10160     };
10161     return MapOperator;
10162 }());
10163 exports.MapOperator = MapOperator;
10164 /**
10165  * We need this JSDoc comment for affecting ESDoc.
10166  * @ignore
10167  * @extends {Ignored}
10168  */
10169 var MapSubscriber = (function (_super) {
10170     __extends(MapSubscriber, _super);
10171     function MapSubscriber(destination, project, thisArg) {
10172         _super.call(this, destination);
10173         this.project = project;
10174         this.count = 0;
10175         this.thisArg = thisArg || this;
10176     }
10177     // NOTE: This looks unoptimized, but it's actually purposefully NOT
10178     // using try/catch optimizations.
10179     MapSubscriber.prototype._next = function (value) {
10180         var result;
10181         try {
10182             result = this.project.call(this.thisArg, value, this.count++);
10183         }
10184         catch (err) {
10185             this.destination.error(err);
10186             return;
10187         }
10188         this.destination.next(result);
10189     };
10190     return MapSubscriber;
10191 }(Subscriber_1.Subscriber));
10192
10193 },{"../Subscriber":35}],124:[function(require,module,exports){
10194 "use strict";
10195 var Observable_1 = require('../Observable');
10196 var ArrayObservable_1 = require('../observable/ArrayObservable');
10197 var mergeAll_1 = require('./mergeAll');
10198 var isScheduler_1 = require('../util/isScheduler');
10199 /* tslint:enable:max-line-length */
10200 /**
10201  * Creates an output Observable which concurrently emits all values from every
10202  * given input Observable.
10203  *
10204  * <span class="informal">Flattens multiple Observables together by blending
10205  * their values into one Observable.</span>
10206  *
10207  * <img src="./img/merge.png" width="100%">
10208  *
10209  * `merge` subscribes to each given input Observable (either the source or an
10210  * Observable given as argument), and simply forwards (without doing any
10211  * transformation) all the values from all the input Observables to the output
10212  * Observable. The output Observable only completes once all input Observables
10213  * have completed. Any error delivered by an input Observable will be immediately
10214  * emitted on the output Observable.
10215  *
10216  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10217  * var clicks = Rx.Observable.fromEvent(document, 'click');
10218  * var timer = Rx.Observable.interval(1000);
10219  * var clicksOrTimer = clicks.merge(timer);
10220  * clicksOrTimer.subscribe(x => console.log(x));
10221  *
10222  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10223  * var timer1 = Rx.Observable.interval(1000).take(10);
10224  * var timer2 = Rx.Observable.interval(2000).take(6);
10225  * var timer3 = Rx.Observable.interval(500).take(10);
10226  * var concurrent = 2; // the argument
10227  * var merged = timer1.merge(timer2, timer3, concurrent);
10228  * merged.subscribe(x => console.log(x));
10229  *
10230  * @see {@link mergeAll}
10231  * @see {@link mergeMap}
10232  * @see {@link mergeMapTo}
10233  * @see {@link mergeScan}
10234  *
10235  * @param {ObservableInput} other An input Observable to merge with the source
10236  * Observable. More than one input Observables may be given as argument.
10237  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10238  * Observables being subscribed to concurrently.
10239  * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10240  * concurrency of input Observables.
10241  * @return {Observable} An Observable that emits items that are the result of
10242  * every input Observable.
10243  * @method merge
10244  * @owner Observable
10245  */
10246 function merge() {
10247     var observables = [];
10248     for (var _i = 0; _i < arguments.length; _i++) {
10249         observables[_i - 0] = arguments[_i];
10250     }
10251     return this.lift.call(mergeStatic.apply(void 0, [this].concat(observables)));
10252 }
10253 exports.merge = merge;
10254 /* tslint:enable:max-line-length */
10255 /**
10256  * Creates an output Observable which concurrently emits all values from every
10257  * given input Observable.
10258  *
10259  * <span class="informal">Flattens multiple Observables together by blending
10260  * their values into one Observable.</span>
10261  *
10262  * <img src="./img/merge.png" width="100%">
10263  *
10264  * `merge` subscribes to each given input Observable (as arguments), and simply
10265  * forwards (without doing any transformation) all the values from all the input
10266  * Observables to the output Observable. The output Observable only completes
10267  * once all input Observables have completed. Any error delivered by an input
10268  * Observable will be immediately emitted on the output Observable.
10269  *
10270  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10271  * var clicks = Rx.Observable.fromEvent(document, 'click');
10272  * var timer = Rx.Observable.interval(1000);
10273  * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
10274  * clicksOrTimer.subscribe(x => console.log(x));
10275  *
10276  * // Results in the following:
10277  * // timer will emit ascending values, one every second(1000ms) to console
10278  * // clicks logs MouseEvents to console everytime the "document" is clicked
10279  * // Since the two streams are merged you see these happening
10280  * // as they occur.
10281  *
10282  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10283  * var timer1 = Rx.Observable.interval(1000).take(10);
10284  * var timer2 = Rx.Observable.interval(2000).take(6);
10285  * var timer3 = Rx.Observable.interval(500).take(10);
10286  * var concurrent = 2; // the argument
10287  * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
10288  * merged.subscribe(x => console.log(x));
10289  *
10290  * // Results in the following:
10291  * // - First timer1 and timer2 will run concurrently
10292  * // - timer1 will emit a value every 1000ms for 10 iterations
10293  * // - timer2 will emit a value every 2000ms for 6 iterations
10294  * // - after timer1 hits it's max iteration, timer2 will
10295  * //   continue, and timer3 will start to run concurrently with timer2
10296  * // - when timer2 hits it's max iteration it terminates, and
10297  * //   timer3 will continue to emit a value every 500ms until it is complete
10298  *
10299  * @see {@link mergeAll}
10300  * @see {@link mergeMap}
10301  * @see {@link mergeMapTo}
10302  * @see {@link mergeScan}
10303  *
10304  * @param {...ObservableInput} observables Input Observables to merge together.
10305  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10306  * Observables being subscribed to concurrently.
10307  * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10308  * concurrency of input Observables.
10309  * @return {Observable} an Observable that emits items that are the result of
10310  * every input Observable.
10311  * @static true
10312  * @name merge
10313  * @owner Observable
10314  */
10315 function mergeStatic() {
10316     var observables = [];
10317     for (var _i = 0; _i < arguments.length; _i++) {
10318         observables[_i - 0] = arguments[_i];
10319     }
10320     var concurrent = Number.POSITIVE_INFINITY;
10321     var scheduler = null;
10322     var last = observables[observables.length - 1];
10323     if (isScheduler_1.isScheduler(last)) {
10324         scheduler = observables.pop();
10325         if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
10326             concurrent = observables.pop();
10327         }
10328     }
10329     else if (typeof last === 'number') {
10330         concurrent = observables.pop();
10331     }
10332     if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
10333         return observables[0];
10334     }
10335     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent));
10336 }
10337 exports.mergeStatic = mergeStatic;
10338
10339 },{"../Observable":28,"../observable/ArrayObservable":85,"../util/isScheduler":169,"./mergeAll":125}],125:[function(require,module,exports){
10340 "use strict";
10341 var __extends = (this && this.__extends) || function (d, b) {
10342     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10343     function __() { this.constructor = d; }
10344     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10345 };
10346 var OuterSubscriber_1 = require('../OuterSubscriber');
10347 var subscribeToResult_1 = require('../util/subscribeToResult');
10348 /**
10349  * Converts a higher-order Observable into a first-order Observable which
10350  * concurrently delivers all values that are emitted on the inner Observables.
10351  *
10352  * <span class="informal">Flattens an Observable-of-Observables.</span>
10353  *
10354  * <img src="./img/mergeAll.png" width="100%">
10355  *
10356  * `mergeAll` subscribes to an Observable that emits Observables, also known as
10357  * a higher-order Observable. Each time it observes one of these emitted inner
10358  * Observables, it subscribes to that and delivers all the values from the
10359  * inner Observable on the output Observable. The output Observable only
10360  * completes once all inner Observables have completed. Any error delivered by
10361  * a inner Observable will be immediately emitted on the output Observable.
10362  *
10363  * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
10364  * var clicks = Rx.Observable.fromEvent(document, 'click');
10365  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
10366  * var firstOrder = higherOrder.mergeAll();
10367  * firstOrder.subscribe(x => console.log(x));
10368  *
10369  * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
10370  * var clicks = Rx.Observable.fromEvent(document, 'click');
10371  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
10372  * var firstOrder = higherOrder.mergeAll(2);
10373  * firstOrder.subscribe(x => console.log(x));
10374  *
10375  * @see {@link combineAll}
10376  * @see {@link concatAll}
10377  * @see {@link exhaust}
10378  * @see {@link merge}
10379  * @see {@link mergeMap}
10380  * @see {@link mergeMapTo}
10381  * @see {@link mergeScan}
10382  * @see {@link switch}
10383  * @see {@link zipAll}
10384  *
10385  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
10386  * Observables being subscribed to concurrently.
10387  * @return {Observable} An Observable that emits values coming from all the
10388  * inner Observables emitted by the source Observable.
10389  * @method mergeAll
10390  * @owner Observable
10391  */
10392 function mergeAll(concurrent) {
10393     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10394     return this.lift(new MergeAllOperator(concurrent));
10395 }
10396 exports.mergeAll = mergeAll;
10397 var MergeAllOperator = (function () {
10398     function MergeAllOperator(concurrent) {
10399         this.concurrent = concurrent;
10400     }
10401     MergeAllOperator.prototype.call = function (observer, source) {
10402         return source.subscribe(new MergeAllSubscriber(observer, this.concurrent));
10403     };
10404     return MergeAllOperator;
10405 }());
10406 exports.MergeAllOperator = MergeAllOperator;
10407 /**
10408  * We need this JSDoc comment for affecting ESDoc.
10409  * @ignore
10410  * @extends {Ignored}
10411  */
10412 var MergeAllSubscriber = (function (_super) {
10413     __extends(MergeAllSubscriber, _super);
10414     function MergeAllSubscriber(destination, concurrent) {
10415         _super.call(this, destination);
10416         this.concurrent = concurrent;
10417         this.hasCompleted = false;
10418         this.buffer = [];
10419         this.active = 0;
10420     }
10421     MergeAllSubscriber.prototype._next = function (observable) {
10422         if (this.active < this.concurrent) {
10423             this.active++;
10424             this.add(subscribeToResult_1.subscribeToResult(this, observable));
10425         }
10426         else {
10427             this.buffer.push(observable);
10428         }
10429     };
10430     MergeAllSubscriber.prototype._complete = function () {
10431         this.hasCompleted = true;
10432         if (this.active === 0 && this.buffer.length === 0) {
10433             this.destination.complete();
10434         }
10435     };
10436     MergeAllSubscriber.prototype.notifyComplete = function (innerSub) {
10437         var buffer = this.buffer;
10438         this.remove(innerSub);
10439         this.active--;
10440         if (buffer.length > 0) {
10441             this._next(buffer.shift());
10442         }
10443         else if (this.active === 0 && this.hasCompleted) {
10444             this.destination.complete();
10445         }
10446     };
10447     return MergeAllSubscriber;
10448 }(OuterSubscriber_1.OuterSubscriber));
10449 exports.MergeAllSubscriber = MergeAllSubscriber;
10450
10451 },{"../OuterSubscriber":30,"../util/subscribeToResult":171}],126:[function(require,module,exports){
10452 "use strict";
10453 var __extends = (this && this.__extends) || function (d, b) {
10454     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10455     function __() { this.constructor = d; }
10456     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10457 };
10458 var subscribeToResult_1 = require('../util/subscribeToResult');
10459 var OuterSubscriber_1 = require('../OuterSubscriber');
10460 /* tslint:enable:max-line-length */
10461 /**
10462  * Projects each source value to an Observable which is merged in the output
10463  * Observable.
10464  *
10465  * <span class="informal">Maps each value to an Observable, then flattens all of
10466  * these inner Observables using {@link mergeAll}.</span>
10467  *
10468  * <img src="./img/mergeMap.png" width="100%">
10469  *
10470  * Returns an Observable that emits items based on applying a function that you
10471  * supply to each item emitted by the source Observable, where that function
10472  * returns an Observable, and then merging those resulting Observables and
10473  * emitting the results of this merger.
10474  *
10475  * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
10476  * var letters = Rx.Observable.of('a', 'b', 'c');
10477  * var result = letters.mergeMap(x =>
10478  *   Rx.Observable.interval(1000).map(i => x+i)
10479  * );
10480  * result.subscribe(x => console.log(x));
10481  *
10482  * // Results in the following:
10483  * // a0
10484  * // b0
10485  * // c0
10486  * // a1
10487  * // b1
10488  * // c1
10489  * // continues to list a,b,c with respective ascending integers
10490  *
10491  * @see {@link concatMap}
10492  * @see {@link exhaustMap}
10493  * @see {@link merge}
10494  * @see {@link mergeAll}
10495  * @see {@link mergeMapTo}
10496  * @see {@link mergeScan}
10497  * @see {@link switchMap}
10498  *
10499  * @param {function(value: T, ?index: number): ObservableInput} project A function
10500  * that, when applied to an item emitted by the source Observable, returns an
10501  * Observable.
10502  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10503  * A function to produce the value on the output Observable based on the values
10504  * and the indices of the source (outer) emission and the inner Observable
10505  * emission. The arguments passed to this function are:
10506  * - `outerValue`: the value that came from the source
10507  * - `innerValue`: the value that came from the projected Observable
10508  * - `outerIndex`: the "index" of the value that came from the source
10509  * - `innerIndex`: the "index" of the value from the projected Observable
10510  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10511  * Observables being subscribed to concurrently.
10512  * @return {Observable} An Observable that emits the result of applying the
10513  * projection function (and the optional `resultSelector`) to each item emitted
10514  * by the source Observable and merging the results of the Observables obtained
10515  * from this transformation.
10516  * @method mergeMap
10517  * @owner Observable
10518  */
10519 function mergeMap(project, resultSelector, concurrent) {
10520     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10521     if (typeof resultSelector === 'number') {
10522         concurrent = resultSelector;
10523         resultSelector = null;
10524     }
10525     return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
10526 }
10527 exports.mergeMap = mergeMap;
10528 var MergeMapOperator = (function () {
10529     function MergeMapOperator(project, resultSelector, concurrent) {
10530         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10531         this.project = project;
10532         this.resultSelector = resultSelector;
10533         this.concurrent = concurrent;
10534     }
10535     MergeMapOperator.prototype.call = function (observer, source) {
10536         return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
10537     };
10538     return MergeMapOperator;
10539 }());
10540 exports.MergeMapOperator = MergeMapOperator;
10541 /**
10542  * We need this JSDoc comment for affecting ESDoc.
10543  * @ignore
10544  * @extends {Ignored}
10545  */
10546 var MergeMapSubscriber = (function (_super) {
10547     __extends(MergeMapSubscriber, _super);
10548     function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
10549         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10550         _super.call(this, destination);
10551         this.project = project;
10552         this.resultSelector = resultSelector;
10553         this.concurrent = concurrent;
10554         this.hasCompleted = false;
10555         this.buffer = [];
10556         this.active = 0;
10557         this.index = 0;
10558     }
10559     MergeMapSubscriber.prototype._next = function (value) {
10560         if (this.active < this.concurrent) {
10561             this._tryNext(value);
10562         }
10563         else {
10564             this.buffer.push(value);
10565         }
10566     };
10567     MergeMapSubscriber.prototype._tryNext = function (value) {
10568         var result;
10569         var index = this.index++;
10570         try {
10571             result = this.project(value, index);
10572         }
10573         catch (err) {
10574             this.destination.error(err);
10575             return;
10576         }
10577         this.active++;
10578         this._innerSub(result, value, index);
10579     };
10580     MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
10581         this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
10582     };
10583     MergeMapSubscriber.prototype._complete = function () {
10584         this.hasCompleted = true;
10585         if (this.active === 0 && this.buffer.length === 0) {
10586             this.destination.complete();
10587         }
10588     };
10589     MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10590         if (this.resultSelector) {
10591             this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
10592         }
10593         else {
10594             this.destination.next(innerValue);
10595         }
10596     };
10597     MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
10598         var result;
10599         try {
10600             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
10601         }
10602         catch (err) {
10603             this.destination.error(err);
10604             return;
10605         }
10606         this.destination.next(result);
10607     };
10608     MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
10609         var buffer = this.buffer;
10610         this.remove(innerSub);
10611         this.active--;
10612         if (buffer.length > 0) {
10613             this._next(buffer.shift());
10614         }
10615         else if (this.active === 0 && this.hasCompleted) {
10616             this.destination.complete();
10617         }
10618     };
10619     return MergeMapSubscriber;
10620 }(OuterSubscriber_1.OuterSubscriber));
10621 exports.MergeMapSubscriber = MergeMapSubscriber;
10622
10623 },{"../OuterSubscriber":30,"../util/subscribeToResult":171}],127:[function(require,module,exports){
10624 "use strict";
10625 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
10626 /* tslint:enable:max-line-length */
10627 /**
10628  * Returns an Observable that emits the results of invoking a specified selector on items
10629  * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
10630  *
10631  * <img src="./img/multicast.png" width="100%">
10632  *
10633  * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
10634  * which the source sequence's elements will be multicast to the selector function
10635  * or Subject to push source elements into.
10636  * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
10637  * as many times as needed, without causing multiple subscriptions to the source stream.
10638  * Subscribers to the given source will receive all notifications of the source from the
10639  * time of the subscription forward.
10640  * @return {Observable} An Observable that emits the results of invoking the selector
10641  * on the items emitted by a `ConnectableObservable` that shares a single subscription to
10642  * the underlying stream.
10643  * @method multicast
10644  * @owner Observable
10645  */
10646 function multicast(subjectOrSubjectFactory, selector) {
10647     var subjectFactory;
10648     if (typeof subjectOrSubjectFactory === 'function') {
10649         subjectFactory = subjectOrSubjectFactory;
10650     }
10651     else {
10652         subjectFactory = function subjectFactory() {
10653             return subjectOrSubjectFactory;
10654         };
10655     }
10656     if (typeof selector === 'function') {
10657         return this.lift(new MulticastOperator(subjectFactory, selector));
10658     }
10659     var connectable = Object.create(this, ConnectableObservable_1.connectableObservableDescriptor);
10660     connectable.source = this;
10661     connectable.subjectFactory = subjectFactory;
10662     return connectable;
10663 }
10664 exports.multicast = multicast;
10665 var MulticastOperator = (function () {
10666     function MulticastOperator(subjectFactory, selector) {
10667         this.subjectFactory = subjectFactory;
10668         this.selector = selector;
10669     }
10670     MulticastOperator.prototype.call = function (subscriber, source) {
10671         var selector = this.selector;
10672         var subject = this.subjectFactory();
10673         var subscription = selector(subject).subscribe(subscriber);
10674         subscription.add(source.subscribe(subject));
10675         return subscription;
10676     };
10677     return MulticastOperator;
10678 }());
10679 exports.MulticastOperator = MulticastOperator;
10680
10681 },{"../observable/ConnectableObservable":86}],128:[function(require,module,exports){
10682 "use strict";
10683 var __extends = (this && this.__extends) || function (d, b) {
10684     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10685     function __() { this.constructor = d; }
10686     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10687 };
10688 var Subscriber_1 = require('../Subscriber');
10689 var Notification_1 = require('../Notification');
10690 /**
10691  * @see {@link Notification}
10692  *
10693  * @param scheduler
10694  * @param delay
10695  * @return {Observable<R>|WebSocketSubject<T>|Observable<T>}
10696  * @method observeOn
10697  * @owner Observable
10698  */
10699 function observeOn(scheduler, delay) {
10700     if (delay === void 0) { delay = 0; }
10701     return this.lift(new ObserveOnOperator(scheduler, delay));
10702 }
10703 exports.observeOn = observeOn;
10704 var ObserveOnOperator = (function () {
10705     function ObserveOnOperator(scheduler, delay) {
10706         if (delay === void 0) { delay = 0; }
10707         this.scheduler = scheduler;
10708         this.delay = delay;
10709     }
10710     ObserveOnOperator.prototype.call = function (subscriber, source) {
10711         return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
10712     };
10713     return ObserveOnOperator;
10714 }());
10715 exports.ObserveOnOperator = ObserveOnOperator;
10716 /**
10717  * We need this JSDoc comment for affecting ESDoc.
10718  * @ignore
10719  * @extends {Ignored}
10720  */
10721 var ObserveOnSubscriber = (function (_super) {
10722     __extends(ObserveOnSubscriber, _super);
10723     function ObserveOnSubscriber(destination, scheduler, delay) {
10724         if (delay === void 0) { delay = 0; }
10725         _super.call(this, destination);
10726         this.scheduler = scheduler;
10727         this.delay = delay;
10728     }
10729     ObserveOnSubscriber.dispatch = function (arg) {
10730         var notification = arg.notification, destination = arg.destination;
10731         notification.observe(destination);
10732         this.unsubscribe();
10733     };
10734     ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
10735         this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
10736     };
10737     ObserveOnSubscriber.prototype._next = function (value) {
10738         this.scheduleMessage(Notification_1.Notification.createNext(value));
10739     };
10740     ObserveOnSubscriber.prototype._error = function (err) {
10741         this.scheduleMessage(Notification_1.Notification.createError(err));
10742     };
10743     ObserveOnSubscriber.prototype._complete = function () {
10744         this.scheduleMessage(Notification_1.Notification.createComplete());
10745     };
10746     return ObserveOnSubscriber;
10747 }(Subscriber_1.Subscriber));
10748 exports.ObserveOnSubscriber = ObserveOnSubscriber;
10749 var ObserveOnMessage = (function () {
10750     function ObserveOnMessage(notification, destination) {
10751         this.notification = notification;
10752         this.destination = destination;
10753     }
10754     return ObserveOnMessage;
10755 }());
10756 exports.ObserveOnMessage = ObserveOnMessage;
10757
10758 },{"../Notification":27,"../Subscriber":35}],129:[function(require,module,exports){
10759 "use strict";
10760 var __extends = (this && this.__extends) || function (d, b) {
10761     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10762     function __() { this.constructor = d; }
10763     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10764 };
10765 var Subscriber_1 = require('../Subscriber');
10766 /**
10767  * Groups pairs of consecutive emissions together and emits them as an array of
10768  * two values.
10769  *
10770  * <span class="informal">Puts the current value and previous value together as
10771  * an array, and emits that.</span>
10772  *
10773  * <img src="./img/pairwise.png" width="100%">
10774  *
10775  * The Nth emission from the source Observable will cause the output Observable
10776  * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
10777  * pair. For this reason, `pairwise` emits on the second and subsequent
10778  * emissions from the source Observable, but not on the first emission, because
10779  * there is no previous value in that case.
10780  *
10781  * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
10782  * var clicks = Rx.Observable.fromEvent(document, 'click');
10783  * var pairs = clicks.pairwise();
10784  * var distance = pairs.map(pair => {
10785  *   var x0 = pair[0].clientX;
10786  *   var y0 = pair[0].clientY;
10787  *   var x1 = pair[1].clientX;
10788  *   var y1 = pair[1].clientY;
10789  *   return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
10790  * });
10791  * distance.subscribe(x => console.log(x));
10792  *
10793  * @see {@link buffer}
10794  * @see {@link bufferCount}
10795  *
10796  * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
10797  * consecutive values from the source Observable.
10798  * @method pairwise
10799  * @owner Observable
10800  */
10801 function pairwise() {
10802     return this.lift(new PairwiseOperator());
10803 }
10804 exports.pairwise = pairwise;
10805 var PairwiseOperator = (function () {
10806     function PairwiseOperator() {
10807     }
10808     PairwiseOperator.prototype.call = function (subscriber, source) {
10809         return source.subscribe(new PairwiseSubscriber(subscriber));
10810     };
10811     return PairwiseOperator;
10812 }());
10813 /**
10814  * We need this JSDoc comment for affecting ESDoc.
10815  * @ignore
10816  * @extends {Ignored}
10817  */
10818 var PairwiseSubscriber = (function (_super) {
10819     __extends(PairwiseSubscriber, _super);
10820     function PairwiseSubscriber(destination) {
10821         _super.call(this, destination);
10822         this.hasPrev = false;
10823     }
10824     PairwiseSubscriber.prototype._next = function (value) {
10825         if (this.hasPrev) {
10826             this.destination.next([this.prev, value]);
10827         }
10828         else {
10829             this.hasPrev = true;
10830         }
10831         this.prev = value;
10832     };
10833     return PairwiseSubscriber;
10834 }(Subscriber_1.Subscriber));
10835
10836 },{"../Subscriber":35}],130:[function(require,module,exports){
10837 "use strict";
10838 var map_1 = require('./map');
10839 /**
10840  * Maps each source value (an object) to its specified nested property.
10841  *
10842  * <span class="informal">Like {@link map}, but meant only for picking one of
10843  * the nested properties of every emitted object.</span>
10844  *
10845  * <img src="./img/pluck.png" width="100%">
10846  *
10847  * Given a list of strings describing a path to an object property, retrieves
10848  * the value of a specified nested property from all values in the source
10849  * Observable. If a property can't be resolved, it will return `undefined` for
10850  * that value.
10851  *
10852  * @example <caption>Map every every click to the tagName of the clicked target element</caption>
10853  * var clicks = Rx.Observable.fromEvent(document, 'click');
10854  * var tagNames = clicks.pluck('target', 'tagName');
10855  * tagNames.subscribe(x => console.log(x));
10856  *
10857  * @see {@link map}
10858  *
10859  * @param {...string} properties The nested properties to pluck from each source
10860  * value (an object).
10861  * @return {Observable} A new Observable of property values from the source values.
10862  * @method pluck
10863  * @owner Observable
10864  */
10865 function pluck() {
10866     var properties = [];
10867     for (var _i = 0; _i < arguments.length; _i++) {
10868         properties[_i - 0] = arguments[_i];
10869     }
10870     var length = properties.length;
10871     if (length === 0) {
10872         throw new Error('list of properties cannot be empty.');
10873     }
10874     return map_1.map.call(this, plucker(properties, length));
10875 }
10876 exports.pluck = pluck;
10877 function plucker(props, length) {
10878     var mapper = function (x) {
10879         var currentProp = x;
10880         for (var i = 0; i < length; i++) {
10881             var p = currentProp[props[i]];
10882             if (typeof p !== 'undefined') {
10883                 currentProp = p;
10884             }
10885             else {
10886                 return undefined;
10887             }
10888         }
10889         return currentProp;
10890     };
10891     return mapper;
10892 }
10893
10894 },{"./map":123}],131:[function(require,module,exports){
10895 "use strict";
10896 var Subject_1 = require('../Subject');
10897 var multicast_1 = require('./multicast');
10898 /* tslint:enable:max-line-length */
10899 /**
10900  * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
10901  * before it begins emitting items to those Observers that have subscribed to it.
10902  *
10903  * <img src="./img/publish.png" width="100%">
10904  *
10905  * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
10906  * as needed, without causing multiple subscriptions to the source sequence.
10907  * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
10908  * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
10909  * @method publish
10910  * @owner Observable
10911  */
10912 function publish(selector) {
10913     return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
10914         multicast_1.multicast.call(this, new Subject_1.Subject());
10915 }
10916 exports.publish = publish;
10917
10918 },{"../Subject":33,"./multicast":127}],132:[function(require,module,exports){
10919 "use strict";
10920 var ReplaySubject_1 = require('../ReplaySubject');
10921 var multicast_1 = require('./multicast');
10922 /**
10923  * @param bufferSize
10924  * @param windowTime
10925  * @param scheduler
10926  * @return {ConnectableObservable<T>}
10927  * @method publishReplay
10928  * @owner Observable
10929  */
10930 function publishReplay(bufferSize, windowTime, scheduler) {
10931     if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
10932     if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
10933     return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler));
10934 }
10935 exports.publishReplay = publishReplay;
10936
10937 },{"../ReplaySubject":31,"./multicast":127}],133:[function(require,module,exports){
10938 "use strict";
10939 var __extends = (this && this.__extends) || function (d, b) {
10940     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10941     function __() { this.constructor = d; }
10942     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10943 };
10944 var Subscriber_1 = require('../Subscriber');
10945 /* tslint:enable:max-line-length */
10946 /**
10947  * Applies an accumulator function over the source Observable, and returns each
10948  * intermediate result, with an optional seed value.
10949  *
10950  * <span class="informal">It's like {@link reduce}, but emits the current
10951  * accumulation whenever the source emits a value.</span>
10952  *
10953  * <img src="./img/scan.png" width="100%">
10954  *
10955  * Combines together all values emitted on the source, using an accumulator
10956  * function that knows how to join a new source value into the accumulation from
10957  * the past. Is similar to {@link reduce}, but emits the intermediate
10958  * accumulations.
10959  *
10960  * Returns an Observable that applies a specified `accumulator` function to each
10961  * item emitted by the source Observable. If a `seed` value is specified, then
10962  * that value will be used as the initial value for the accumulator. If no seed
10963  * value is specified, the first item of the source is used as the seed.
10964  *
10965  * @example <caption>Count the number of click events</caption>
10966  * var clicks = Rx.Observable.fromEvent(document, 'click');
10967  * var ones = clicks.mapTo(1);
10968  * var seed = 0;
10969  * var count = ones.scan((acc, one) => acc + one, seed);
10970  * count.subscribe(x => console.log(x));
10971  *
10972  * @see {@link expand}
10973  * @see {@link mergeScan}
10974  * @see {@link reduce}
10975  *
10976  * @param {function(acc: R, value: T, index: number): R} accumulator
10977  * The accumulator function called on each source value.
10978  * @param {T|R} [seed] The initial accumulation value.
10979  * @return {Observable<R>} An observable of the accumulated values.
10980  * @method scan
10981  * @owner Observable
10982  */
10983 function scan(accumulator, seed) {
10984     var hasSeed = false;
10985     // providing a seed of `undefined` *should* be valid and trigger
10986     // hasSeed! so don't use `seed !== undefined` checks!
10987     // For this reason, we have to check it here at the original call site
10988     // otherwise inside Operator/Subscriber we won't know if `undefined`
10989     // means they didn't provide anything or if they literally provided `undefined`
10990     if (arguments.length >= 2) {
10991         hasSeed = true;
10992     }
10993     return this.lift(new ScanOperator(accumulator, seed, hasSeed));
10994 }
10995 exports.scan = scan;
10996 var ScanOperator = (function () {
10997     function ScanOperator(accumulator, seed, hasSeed) {
10998         if (hasSeed === void 0) { hasSeed = false; }
10999         this.accumulator = accumulator;
11000         this.seed = seed;
11001         this.hasSeed = hasSeed;
11002     }
11003     ScanOperator.prototype.call = function (subscriber, source) {
11004         return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
11005     };
11006     return ScanOperator;
11007 }());
11008 /**
11009  * We need this JSDoc comment for affecting ESDoc.
11010  * @ignore
11011  * @extends {Ignored}
11012  */
11013 var ScanSubscriber = (function (_super) {
11014     __extends(ScanSubscriber, _super);
11015     function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
11016         _super.call(this, destination);
11017         this.accumulator = accumulator;
11018         this._seed = _seed;
11019         this.hasSeed = hasSeed;
11020         this.index = 0;
11021     }
11022     Object.defineProperty(ScanSubscriber.prototype, "seed", {
11023         get: function () {
11024             return this._seed;
11025         },
11026         set: function (value) {
11027             this.hasSeed = true;
11028             this._seed = value;
11029         },
11030         enumerable: true,
11031         configurable: true
11032     });
11033     ScanSubscriber.prototype._next = function (value) {
11034         if (!this.hasSeed) {
11035             this.seed = value;
11036             this.destination.next(value);
11037         }
11038         else {
11039             return this._tryNext(value);
11040         }
11041     };
11042     ScanSubscriber.prototype._tryNext = function (value) {
11043         var index = this.index++;
11044         var result;
11045         try {
11046             result = this.accumulator(this.seed, value, index);
11047         }
11048         catch (err) {
11049             this.destination.error(err);
11050         }
11051         this.seed = result;
11052         this.destination.next(result);
11053     };
11054     return ScanSubscriber;
11055 }(Subscriber_1.Subscriber));
11056
11057 },{"../Subscriber":35}],134:[function(require,module,exports){
11058 "use strict";
11059 var multicast_1 = require('./multicast');
11060 var Subject_1 = require('../Subject');
11061 function shareSubjectFactory() {
11062     return new Subject_1.Subject();
11063 }
11064 /**
11065  * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
11066  * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
11067  * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
11068  * This is an alias for .publish().refCount().
11069  *
11070  * <img src="./img/share.png" width="100%">
11071  *
11072  * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
11073  * @method share
11074  * @owner Observable
11075  */
11076 function share() {
11077     return multicast_1.multicast.call(this, shareSubjectFactory).refCount();
11078 }
11079 exports.share = share;
11080 ;
11081
11082 },{"../Subject":33,"./multicast":127}],135:[function(require,module,exports){
11083 "use strict";
11084 var __extends = (this && this.__extends) || function (d, b) {
11085     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11086     function __() { this.constructor = d; }
11087     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11088 };
11089 var Subscriber_1 = require('../Subscriber');
11090 /**
11091  * Returns an Observable that skips the first `count` items emitted by the source Observable.
11092  *
11093  * <img src="./img/skip.png" width="100%">
11094  *
11095  * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
11096  * @return {Observable} An Observable that skips values emitted by the source Observable.
11097  *
11098  * @method skip
11099  * @owner Observable
11100  */
11101 function skip(count) {
11102     return this.lift(new SkipOperator(count));
11103 }
11104 exports.skip = skip;
11105 var SkipOperator = (function () {
11106     function SkipOperator(total) {
11107         this.total = total;
11108     }
11109     SkipOperator.prototype.call = function (subscriber, source) {
11110         return source.subscribe(new SkipSubscriber(subscriber, this.total));
11111     };
11112     return SkipOperator;
11113 }());
11114 /**
11115  * We need this JSDoc comment for affecting ESDoc.
11116  * @ignore
11117  * @extends {Ignored}
11118  */
11119 var SkipSubscriber = (function (_super) {
11120     __extends(SkipSubscriber, _super);
11121     function SkipSubscriber(destination, total) {
11122         _super.call(this, destination);
11123         this.total = total;
11124         this.count = 0;
11125     }
11126     SkipSubscriber.prototype._next = function (x) {
11127         if (++this.count > this.total) {
11128             this.destination.next(x);
11129         }
11130     };
11131     return SkipSubscriber;
11132 }(Subscriber_1.Subscriber));
11133
11134 },{"../Subscriber":35}],136:[function(require,module,exports){
11135 "use strict";
11136 var __extends = (this && this.__extends) || function (d, b) {
11137     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11138     function __() { this.constructor = d; }
11139     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11140 };
11141 var OuterSubscriber_1 = require('../OuterSubscriber');
11142 var subscribeToResult_1 = require('../util/subscribeToResult');
11143 /**
11144  * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
11145  *
11146  * <img src="./img/skipUntil.png" width="100%">
11147  *
11148  * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
11149  * be mirrored by the resulting Observable.
11150  * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
11151  * an item, then emits the remaining items.
11152  * @method skipUntil
11153  * @owner Observable
11154  */
11155 function skipUntil(notifier) {
11156     return this.lift(new SkipUntilOperator(notifier));
11157 }
11158 exports.skipUntil = skipUntil;
11159 var SkipUntilOperator = (function () {
11160     function SkipUntilOperator(notifier) {
11161         this.notifier = notifier;
11162     }
11163     SkipUntilOperator.prototype.call = function (subscriber, source) {
11164         return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
11165     };
11166     return SkipUntilOperator;
11167 }());
11168 /**
11169  * We need this JSDoc comment for affecting ESDoc.
11170  * @ignore
11171  * @extends {Ignored}
11172  */
11173 var SkipUntilSubscriber = (function (_super) {
11174     __extends(SkipUntilSubscriber, _super);
11175     function SkipUntilSubscriber(destination, notifier) {
11176         _super.call(this, destination);
11177         this.hasValue = false;
11178         this.isInnerStopped = false;
11179         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11180     }
11181     SkipUntilSubscriber.prototype._next = function (value) {
11182         if (this.hasValue) {
11183             _super.prototype._next.call(this, value);
11184         }
11185     };
11186     SkipUntilSubscriber.prototype._complete = function () {
11187         if (this.isInnerStopped) {
11188             _super.prototype._complete.call(this);
11189         }
11190         else {
11191             this.unsubscribe();
11192         }
11193     };
11194     SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11195         this.hasValue = true;
11196     };
11197     SkipUntilSubscriber.prototype.notifyComplete = function () {
11198         this.isInnerStopped = true;
11199         if (this.isStopped) {
11200             _super.prototype._complete.call(this);
11201         }
11202     };
11203     return SkipUntilSubscriber;
11204 }(OuterSubscriber_1.OuterSubscriber));
11205
11206 },{"../OuterSubscriber":30,"../util/subscribeToResult":171}],137:[function(require,module,exports){
11207 "use strict";
11208 var __extends = (this && this.__extends) || function (d, b) {
11209     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11210     function __() { this.constructor = d; }
11211     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11212 };
11213 var Subscriber_1 = require('../Subscriber');
11214 /**
11215  * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
11216  * true, but emits all further source items as soon as the condition becomes false.
11217  *
11218  * <img src="./img/skipWhile.png" width="100%">
11219  *
11220  * @param {Function} predicate - A function to test each item emitted from the source Observable.
11221  * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
11222  * specified predicate becomes false.
11223  * @method skipWhile
11224  * @owner Observable
11225  */
11226 function skipWhile(predicate) {
11227     return this.lift(new SkipWhileOperator(predicate));
11228 }
11229 exports.skipWhile = skipWhile;
11230 var SkipWhileOperator = (function () {
11231     function SkipWhileOperator(predicate) {
11232         this.predicate = predicate;
11233     }
11234     SkipWhileOperator.prototype.call = function (subscriber, source) {
11235         return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
11236     };
11237     return SkipWhileOperator;
11238 }());
11239 /**
11240  * We need this JSDoc comment for affecting ESDoc.
11241  * @ignore
11242  * @extends {Ignored}
11243  */
11244 var SkipWhileSubscriber = (function (_super) {
11245     __extends(SkipWhileSubscriber, _super);
11246     function SkipWhileSubscriber(destination, predicate) {
11247         _super.call(this, destination);
11248         this.predicate = predicate;
11249         this.skipping = true;
11250         this.index = 0;
11251     }
11252     SkipWhileSubscriber.prototype._next = function (value) {
11253         var destination = this.destination;
11254         if (this.skipping) {
11255             this.tryCallPredicate(value);
11256         }
11257         if (!this.skipping) {
11258             destination.next(value);
11259         }
11260     };
11261     SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
11262         try {
11263             var result = this.predicate(value, this.index++);
11264             this.skipping = Boolean(result);
11265         }
11266         catch (err) {
11267             this.destination.error(err);
11268         }
11269     };
11270     return SkipWhileSubscriber;
11271 }(Subscriber_1.Subscriber));
11272
11273 },{"../Subscriber":35}],138:[function(require,module,exports){
11274 "use strict";
11275 var ArrayObservable_1 = require('../observable/ArrayObservable');
11276 var ScalarObservable_1 = require('../observable/ScalarObservable');
11277 var EmptyObservable_1 = require('../observable/EmptyObservable');
11278 var concat_1 = require('./concat');
11279 var isScheduler_1 = require('../util/isScheduler');
11280 /* tslint:enable:max-line-length */
11281 /**
11282  * Returns an Observable that emits the items you specify as arguments before it begins to emit
11283  * items emitted by the source Observable.
11284  *
11285  * <img src="./img/startWith.png" width="100%">
11286  *
11287  * @param {...T} values - Items you want the modified Observable to emit first.
11288  * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
11289  * the emissions of the `next` notifications.
11290  * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
11291  * emitted by the source Observable.
11292  * @method startWith
11293  * @owner Observable
11294  */
11295 function startWith() {
11296     var array = [];
11297     for (var _i = 0; _i < arguments.length; _i++) {
11298         array[_i - 0] = arguments[_i];
11299     }
11300     var scheduler = array[array.length - 1];
11301     if (isScheduler_1.isScheduler(scheduler)) {
11302         array.pop();
11303     }
11304     else {
11305         scheduler = null;
11306     }
11307     var len = array.length;
11308     if (len === 1) {
11309         return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this);
11310     }
11311     else if (len > 1) {
11312         return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this);
11313     }
11314     else {
11315         return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this);
11316     }
11317 }
11318 exports.startWith = startWith;
11319
11320 },{"../observable/ArrayObservable":85,"../observable/EmptyObservable":88,"../observable/ScalarObservable":94,"../util/isScheduler":169,"./concat":112}],139:[function(require,module,exports){
11321 "use strict";
11322 var __extends = (this && this.__extends) || function (d, b) {
11323     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11324     function __() { this.constructor = d; }
11325     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11326 };
11327 var OuterSubscriber_1 = require('../OuterSubscriber');
11328 var subscribeToResult_1 = require('../util/subscribeToResult');
11329 /* tslint:enable:max-line-length */
11330 /**
11331  * Projects each source value to an Observable which is merged in the output
11332  * Observable, emitting values only from the most recently projected Observable.
11333  *
11334  * <span class="informal">Maps each value to an Observable, then flattens all of
11335  * these inner Observables using {@link switch}.</span>
11336  *
11337  * <img src="./img/switchMap.png" width="100%">
11338  *
11339  * Returns an Observable that emits items based on applying a function that you
11340  * supply to each item emitted by the source Observable, where that function
11341  * returns an (so-called "inner") Observable. Each time it observes one of these
11342  * inner Observables, the output Observable begins emitting the items emitted by
11343  * that inner Observable. When a new inner Observable is emitted, `switchMap`
11344  * stops emitting items from the earlier-emitted inner Observable and begins
11345  * emitting items from the new one. It continues to behave like this for
11346  * subsequent inner Observables.
11347  *
11348  * @example <caption>Rerun an interval Observable on every click event</caption>
11349  * var clicks = Rx.Observable.fromEvent(document, 'click');
11350  * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
11351  * result.subscribe(x => console.log(x));
11352  *
11353  * @see {@link concatMap}
11354  * @see {@link exhaustMap}
11355  * @see {@link mergeMap}
11356  * @see {@link switch}
11357  * @see {@link switchMapTo}
11358  *
11359  * @param {function(value: T, ?index: number): ObservableInput} project A function
11360  * that, when applied to an item emitted by the source Observable, returns an
11361  * Observable.
11362  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
11363  * A function to produce the value on the output Observable based on the values
11364  * and the indices of the source (outer) emission and the inner Observable
11365  * emission. The arguments passed to this function are:
11366  * - `outerValue`: the value that came from the source
11367  * - `innerValue`: the value that came from the projected Observable
11368  * - `outerIndex`: the "index" of the value that came from the source
11369  * - `innerIndex`: the "index" of the value from the projected Observable
11370  * @return {Observable} An Observable that emits the result of applying the
11371  * projection function (and the optional `resultSelector`) to each item emitted
11372  * by the source Observable and taking only the values from the most recently
11373  * projected inner Observable.
11374  * @method switchMap
11375  * @owner Observable
11376  */
11377 function switchMap(project, resultSelector) {
11378     return this.lift(new SwitchMapOperator(project, resultSelector));
11379 }
11380 exports.switchMap = switchMap;
11381 var SwitchMapOperator = (function () {
11382     function SwitchMapOperator(project, resultSelector) {
11383         this.project = project;
11384         this.resultSelector = resultSelector;
11385     }
11386     SwitchMapOperator.prototype.call = function (subscriber, source) {
11387         return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
11388     };
11389     return SwitchMapOperator;
11390 }());
11391 /**
11392  * We need this JSDoc comment for affecting ESDoc.
11393  * @ignore
11394  * @extends {Ignored}
11395  */
11396 var SwitchMapSubscriber = (function (_super) {
11397     __extends(SwitchMapSubscriber, _super);
11398     function SwitchMapSubscriber(destination, project, resultSelector) {
11399         _super.call(this, destination);
11400         this.project = project;
11401         this.resultSelector = resultSelector;
11402         this.index = 0;
11403     }
11404     SwitchMapSubscriber.prototype._next = function (value) {
11405         var result;
11406         var index = this.index++;
11407         try {
11408             result = this.project(value, index);
11409         }
11410         catch (error) {
11411             this.destination.error(error);
11412             return;
11413         }
11414         this._innerSub(result, value, index);
11415     };
11416     SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
11417         var innerSubscription = this.innerSubscription;
11418         if (innerSubscription) {
11419             innerSubscription.unsubscribe();
11420         }
11421         this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
11422     };
11423     SwitchMapSubscriber.prototype._complete = function () {
11424         var innerSubscription = this.innerSubscription;
11425         if (!innerSubscription || innerSubscription.closed) {
11426             _super.prototype._complete.call(this);
11427         }
11428     };
11429     SwitchMapSubscriber.prototype._unsubscribe = function () {
11430         this.innerSubscription = null;
11431     };
11432     SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
11433         this.remove(innerSub);
11434         this.innerSubscription = null;
11435         if (this.isStopped) {
11436             _super.prototype._complete.call(this);
11437         }
11438     };
11439     SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11440         if (this.resultSelector) {
11441             this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
11442         }
11443         else {
11444             this.destination.next(innerValue);
11445         }
11446     };
11447     SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
11448         var result;
11449         try {
11450             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
11451         }
11452         catch (err) {
11453             this.destination.error(err);
11454             return;
11455         }
11456         this.destination.next(result);
11457     };
11458     return SwitchMapSubscriber;
11459 }(OuterSubscriber_1.OuterSubscriber));
11460
11461 },{"../OuterSubscriber":30,"../util/subscribeToResult":171}],140:[function(require,module,exports){
11462 "use strict";
11463 var __extends = (this && this.__extends) || function (d, b) {
11464     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11465     function __() { this.constructor = d; }
11466     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11467 };
11468 var Subscriber_1 = require('../Subscriber');
11469 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
11470 var EmptyObservable_1 = require('../observable/EmptyObservable');
11471 /**
11472  * Emits only the first `count` values emitted by the source Observable.
11473  *
11474  * <span class="informal">Takes the first `count` values from the source, then
11475  * completes.</span>
11476  *
11477  * <img src="./img/take.png" width="100%">
11478  *
11479  * `take` returns an Observable that emits only the first `count` values emitted
11480  * by the source Observable. If the source emits fewer than `count` values then
11481  * all of its values are emitted. After that, it completes, regardless if the
11482  * source completes.
11483  *
11484  * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
11485  * var interval = Rx.Observable.interval(1000);
11486  * var five = interval.take(5);
11487  * five.subscribe(x => console.log(x));
11488  *
11489  * @see {@link takeLast}
11490  * @see {@link takeUntil}
11491  * @see {@link takeWhile}
11492  * @see {@link skip}
11493  *
11494  * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
11495  * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
11496  *
11497  * @param {number} count The maximum number of `next` values to emit.
11498  * @return {Observable<T>} An Observable that emits only the first `count`
11499  * values emitted by the source Observable, or all of the values from the source
11500  * if the source emits fewer than `count` values.
11501  * @method take
11502  * @owner Observable
11503  */
11504 function take(count) {
11505     if (count === 0) {
11506         return new EmptyObservable_1.EmptyObservable();
11507     }
11508     else {
11509         return this.lift(new TakeOperator(count));
11510     }
11511 }
11512 exports.take = take;
11513 var TakeOperator = (function () {
11514     function TakeOperator(total) {
11515         this.total = total;
11516         if (this.total < 0) {
11517             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
11518         }
11519     }
11520     TakeOperator.prototype.call = function (subscriber, source) {
11521         return source.subscribe(new TakeSubscriber(subscriber, this.total));
11522     };
11523     return TakeOperator;
11524 }());
11525 /**
11526  * We need this JSDoc comment for affecting ESDoc.
11527  * @ignore
11528  * @extends {Ignored}
11529  */
11530 var TakeSubscriber = (function (_super) {
11531     __extends(TakeSubscriber, _super);
11532     function TakeSubscriber(destination, total) {
11533         _super.call(this, destination);
11534         this.total = total;
11535         this.count = 0;
11536     }
11537     TakeSubscriber.prototype._next = function (value) {
11538         var total = this.total;
11539         var count = ++this.count;
11540         if (count <= total) {
11541             this.destination.next(value);
11542             if (count === total) {
11543                 this.destination.complete();
11544                 this.unsubscribe();
11545             }
11546         }
11547     };
11548     return TakeSubscriber;
11549 }(Subscriber_1.Subscriber));
11550
11551 },{"../Subscriber":35,"../observable/EmptyObservable":88,"../util/ArgumentOutOfRangeError":156}],141:[function(require,module,exports){
11552 "use strict";
11553 var __extends = (this && this.__extends) || function (d, b) {
11554     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11555     function __() { this.constructor = d; }
11556     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11557 };
11558 var OuterSubscriber_1 = require('../OuterSubscriber');
11559 var subscribeToResult_1 = require('../util/subscribeToResult');
11560 /**
11561  * Emits the values emitted by the source Observable until a `notifier`
11562  * Observable emits a value.
11563  *
11564  * <span class="informal">Lets values pass until a second Observable,
11565  * `notifier`, emits something. Then, it completes.</span>
11566  *
11567  * <img src="./img/takeUntil.png" width="100%">
11568  *
11569  * `takeUntil` subscribes and begins mirroring the source Observable. It also
11570  * monitors a second Observable, `notifier` that you provide. If the `notifier`
11571  * emits a value or a complete notification, the output Observable stops
11572  * mirroring the source Observable and completes.
11573  *
11574  * @example <caption>Tick every second until the first click happens</caption>
11575  * var interval = Rx.Observable.interval(1000);
11576  * var clicks = Rx.Observable.fromEvent(document, 'click');
11577  * var result = interval.takeUntil(clicks);
11578  * result.subscribe(x => console.log(x));
11579  *
11580  * @see {@link take}
11581  * @see {@link takeLast}
11582  * @see {@link takeWhile}
11583  * @see {@link skip}
11584  *
11585  * @param {Observable} notifier The Observable whose first emitted value will
11586  * cause the output Observable of `takeUntil` to stop emitting values from the
11587  * source Observable.
11588  * @return {Observable<T>} An Observable that emits the values from the source
11589  * Observable until such time as `notifier` emits its first value.
11590  * @method takeUntil
11591  * @owner Observable
11592  */
11593 function takeUntil(notifier) {
11594     return this.lift(new TakeUntilOperator(notifier));
11595 }
11596 exports.takeUntil = takeUntil;
11597 var TakeUntilOperator = (function () {
11598     function TakeUntilOperator(notifier) {
11599         this.notifier = notifier;
11600     }
11601     TakeUntilOperator.prototype.call = function (subscriber, source) {
11602         return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
11603     };
11604     return TakeUntilOperator;
11605 }());
11606 /**
11607  * We need this JSDoc comment for affecting ESDoc.
11608  * @ignore
11609  * @extends {Ignored}
11610  */
11611 var TakeUntilSubscriber = (function (_super) {
11612     __extends(TakeUntilSubscriber, _super);
11613     function TakeUntilSubscriber(destination, notifier) {
11614         _super.call(this, destination);
11615         this.notifier = notifier;
11616         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11617     }
11618     TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11619         this.complete();
11620     };
11621     TakeUntilSubscriber.prototype.notifyComplete = function () {
11622         // noop
11623     };
11624     return TakeUntilSubscriber;
11625 }(OuterSubscriber_1.OuterSubscriber));
11626
11627 },{"../OuterSubscriber":30,"../util/subscribeToResult":171}],142:[function(require,module,exports){
11628 "use strict";
11629 var __extends = (this && this.__extends) || function (d, b) {
11630     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11631     function __() { this.constructor = d; }
11632     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11633 };
11634 var Subscriber_1 = require('../Subscriber');
11635 var async_1 = require('../scheduler/async');
11636 /**
11637  * Emits a value from the source Observable, then ignores subsequent source
11638  * values for `duration` milliseconds, then repeats this process.
11639  *
11640  * <span class="informal">Lets a value pass, then ignores source values for the
11641  * next `duration` milliseconds.</span>
11642  *
11643  * <img src="./img/throttleTime.png" width="100%">
11644  *
11645  * `throttleTime` emits the source Observable values on the output Observable
11646  * when its internal timer is disabled, and ignores source values when the timer
11647  * is enabled. Initially, the timer is disabled. As soon as the first source
11648  * value arrives, it is forwarded to the output Observable, and then the timer
11649  * is enabled. After `duration` milliseconds (or the time unit determined
11650  * internally by the optional `scheduler`) has passed, the timer is disabled,
11651  * and this process repeats for the next source value. Optionally takes a
11652  * {@link IScheduler} for managing timers.
11653  *
11654  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
11655  * var clicks = Rx.Observable.fromEvent(document, 'click');
11656  * var result = clicks.throttleTime(1000);
11657  * result.subscribe(x => console.log(x));
11658  *
11659  * @see {@link auditTime}
11660  * @see {@link debounceTime}
11661  * @see {@link delay}
11662  * @see {@link sampleTime}
11663  * @see {@link throttle}
11664  *
11665  * @param {number} duration Time to wait before emitting another value after
11666  * emitting the last value, measured in milliseconds or the time unit determined
11667  * internally by the optional `scheduler`.
11668  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
11669  * managing the timers that handle the sampling.
11670  * @return {Observable<T>} An Observable that performs the throttle operation to
11671  * limit the rate of emissions from the source.
11672  * @method throttleTime
11673  * @owner Observable
11674  */
11675 function throttleTime(duration, scheduler) {
11676     if (scheduler === void 0) { scheduler = async_1.async; }
11677     return this.lift(new ThrottleTimeOperator(duration, scheduler));
11678 }
11679 exports.throttleTime = throttleTime;
11680 var ThrottleTimeOperator = (function () {
11681     function ThrottleTimeOperator(duration, scheduler) {
11682         this.duration = duration;
11683         this.scheduler = scheduler;
11684     }
11685     ThrottleTimeOperator.prototype.call = function (subscriber, source) {
11686         return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler));
11687     };
11688     return ThrottleTimeOperator;
11689 }());
11690 /**
11691  * We need this JSDoc comment for affecting ESDoc.
11692  * @ignore
11693  * @extends {Ignored}
11694  */
11695 var ThrottleTimeSubscriber = (function (_super) {
11696     __extends(ThrottleTimeSubscriber, _super);
11697     function ThrottleTimeSubscriber(destination, duration, scheduler) {
11698         _super.call(this, destination);
11699         this.duration = duration;
11700         this.scheduler = scheduler;
11701     }
11702     ThrottleTimeSubscriber.prototype._next = function (value) {
11703         if (!this.throttled) {
11704             this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
11705             this.destination.next(value);
11706         }
11707     };
11708     ThrottleTimeSubscriber.prototype.clearThrottle = function () {
11709         var throttled = this.throttled;
11710         if (throttled) {
11711             throttled.unsubscribe();
11712             this.remove(throttled);
11713             this.throttled = null;
11714         }
11715     };
11716     return ThrottleTimeSubscriber;
11717 }(Subscriber_1.Subscriber));
11718 function dispatchNext(arg) {
11719     var subscriber = arg.subscriber;
11720     subscriber.clearThrottle();
11721 }
11722
11723 },{"../Subscriber":35,"../scheduler/async":150}],143:[function(require,module,exports){
11724 "use strict";
11725 var __extends = (this && this.__extends) || function (d, b) {
11726     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11727     function __() { this.constructor = d; }
11728     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11729 };
11730 var OuterSubscriber_1 = require('../OuterSubscriber');
11731 var subscribeToResult_1 = require('../util/subscribeToResult');
11732 /* tslint:enable:max-line-length */
11733 /**
11734  * Combines the source Observable with other Observables to create an Observable
11735  * whose values are calculated from the latest values of each, only when the
11736  * source emits.
11737  *
11738  * <span class="informal">Whenever the source Observable emits a value, it
11739  * computes a formula using that value plus the latest values from other input
11740  * Observables, then emits the output of that formula.</span>
11741  *
11742  * <img src="./img/withLatestFrom.png" width="100%">
11743  *
11744  * `withLatestFrom` combines each value from the source Observable (the
11745  * instance) with the latest values from the other input Observables only when
11746  * the source emits a value, optionally using a `project` function to determine
11747  * the value to be emitted on the output Observable. All input Observables must
11748  * emit at least one value before the output Observable will emit a value.
11749  *
11750  * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
11751  * var clicks = Rx.Observable.fromEvent(document, 'click');
11752  * var timer = Rx.Observable.interval(1000);
11753  * var result = clicks.withLatestFrom(timer);
11754  * result.subscribe(x => console.log(x));
11755  *
11756  * @see {@link combineLatest}
11757  *
11758  * @param {ObservableInput} other An input Observable to combine with the source
11759  * Observable. More than one input Observables may be given as argument.
11760  * @param {Function} [project] Projection function for combining values
11761  * together. Receives all values in order of the Observables passed, where the
11762  * first parameter is a value from the source Observable. (e.g.
11763  * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
11764  * passed, arrays will be emitted on the output Observable.
11765  * @return {Observable} An Observable of projected values from the most recent
11766  * values from each input Observable, or an array of the most recent values from
11767  * each input Observable.
11768  * @method withLatestFrom
11769  * @owner Observable
11770  */
11771 function withLatestFrom() {
11772     var args = [];
11773     for (var _i = 0; _i < arguments.length; _i++) {
11774         args[_i - 0] = arguments[_i];
11775     }
11776     var project;
11777     if (typeof args[args.length - 1] === 'function') {
11778         project = args.pop();
11779     }
11780     var observables = args;
11781     return this.lift(new WithLatestFromOperator(observables, project));
11782 }
11783 exports.withLatestFrom = withLatestFrom;
11784 var WithLatestFromOperator = (function () {
11785     function WithLatestFromOperator(observables, project) {
11786         this.observables = observables;
11787         this.project = project;
11788     }
11789     WithLatestFromOperator.prototype.call = function (subscriber, source) {
11790         return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
11791     };
11792     return WithLatestFromOperator;
11793 }());
11794 /**
11795  * We need this JSDoc comment for affecting ESDoc.
11796  * @ignore
11797  * @extends {Ignored}
11798  */
11799 var WithLatestFromSubscriber = (function (_super) {
11800     __extends(WithLatestFromSubscriber, _super);
11801     function WithLatestFromSubscriber(destination, observables, project) {
11802         _super.call(this, destination);
11803         this.observables = observables;
11804         this.project = project;
11805         this.toRespond = [];
11806         var len = observables.length;
11807         this.values = new Array(len);
11808         for (var i = 0; i < len; i++) {
11809             this.toRespond.push(i);
11810         }
11811         for (var i = 0; i < len; i++) {
11812             var observable = observables[i];
11813             this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
11814         }
11815     }
11816     WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11817         this.values[outerIndex] = innerValue;
11818         var toRespond = this.toRespond;
11819         if (toRespond.length > 0) {
11820             var found = toRespond.indexOf(outerIndex);
11821             if (found !== -1) {
11822                 toRespond.splice(found, 1);
11823             }
11824         }
11825     };
11826     WithLatestFromSubscriber.prototype.notifyComplete = function () {
11827         // noop
11828     };
11829     WithLatestFromSubscriber.prototype._next = function (value) {
11830         if (this.toRespond.length === 0) {
11831             var args = [value].concat(this.values);
11832             if (this.project) {
11833                 this._tryProject(args);
11834             }
11835             else {
11836                 this.destination.next(args);
11837             }
11838         }
11839     };
11840     WithLatestFromSubscriber.prototype._tryProject = function (args) {
11841         var result;
11842         try {
11843             result = this.project.apply(this, args);
11844         }
11845         catch (err) {
11846             this.destination.error(err);
11847             return;
11848         }
11849         this.destination.next(result);
11850     };
11851     return WithLatestFromSubscriber;
11852 }(OuterSubscriber_1.OuterSubscriber));
11853
11854 },{"../OuterSubscriber":30,"../util/subscribeToResult":171}],144:[function(require,module,exports){
11855 "use strict";
11856 var __extends = (this && this.__extends) || function (d, b) {
11857     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11858     function __() { this.constructor = d; }
11859     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11860 };
11861 var ArrayObservable_1 = require('../observable/ArrayObservable');
11862 var isArray_1 = require('../util/isArray');
11863 var Subscriber_1 = require('../Subscriber');
11864 var OuterSubscriber_1 = require('../OuterSubscriber');
11865 var subscribeToResult_1 = require('../util/subscribeToResult');
11866 var iterator_1 = require('../symbol/iterator');
11867 /* tslint:enable:max-line-length */
11868 /**
11869  * @param observables
11870  * @return {Observable<R>}
11871  * @method zip
11872  * @owner Observable
11873  */
11874 function zipProto() {
11875     var observables = [];
11876     for (var _i = 0; _i < arguments.length; _i++) {
11877         observables[_i - 0] = arguments[_i];
11878     }
11879     return this.lift.call(zipStatic.apply(void 0, [this].concat(observables)));
11880 }
11881 exports.zipProto = zipProto;
11882 /* tslint:enable:max-line-length */
11883 /**
11884  * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
11885  * of its input Observables.
11886  *
11887  * If the latest parameter is a function, this function is used to compute the created value from the input values.
11888  * Otherwise, an array of the input values is returned.
11889  *
11890  * @example <caption>Combine age and name from different sources</caption>
11891  *
11892  * let age$ = Observable.of<number>(27, 25, 29);
11893  * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
11894  * let isDev$ = Observable.of<boolean>(true, true, false);
11895  *
11896  * Observable
11897  *     .zip(age$,
11898  *          name$,
11899  *          isDev$,
11900  *          (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
11901  *     .subscribe(x => console.log(x));
11902  *
11903  * // outputs
11904  * // { age: 27, name: 'Foo', isDev: true }
11905  * // { age: 25, name: 'Bar', isDev: true }
11906  * // { age: 29, name: 'Beer', isDev: false }
11907  *
11908  * @param observables
11909  * @return {Observable<R>}
11910  * @static true
11911  * @name zip
11912  * @owner Observable
11913  */
11914 function zipStatic() {
11915     var observables = [];
11916     for (var _i = 0; _i < arguments.length; _i++) {
11917         observables[_i - 0] = arguments[_i];
11918     }
11919     var project = observables[observables.length - 1];
11920     if (typeof project === 'function') {
11921         observables.pop();
11922     }
11923     return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
11924 }
11925 exports.zipStatic = zipStatic;
11926 var ZipOperator = (function () {
11927     function ZipOperator(project) {
11928         this.project = project;
11929     }
11930     ZipOperator.prototype.call = function (subscriber, source) {
11931         return source.subscribe(new ZipSubscriber(subscriber, this.project));
11932     };
11933     return ZipOperator;
11934 }());
11935 exports.ZipOperator = ZipOperator;
11936 /**
11937  * We need this JSDoc comment for affecting ESDoc.
11938  * @ignore
11939  * @extends {Ignored}
11940  */
11941 var ZipSubscriber = (function (_super) {
11942     __extends(ZipSubscriber, _super);
11943     function ZipSubscriber(destination, project, values) {
11944         if (values === void 0) { values = Object.create(null); }
11945         _super.call(this, destination);
11946         this.iterators = [];
11947         this.active = 0;
11948         this.project = (typeof project === 'function') ? project : null;
11949         this.values = values;
11950     }
11951     ZipSubscriber.prototype._next = function (value) {
11952         var iterators = this.iterators;
11953         if (isArray_1.isArray(value)) {
11954             iterators.push(new StaticArrayIterator(value));
11955         }
11956         else if (typeof value[iterator_1.$$iterator] === 'function') {
11957             iterators.push(new StaticIterator(value[iterator_1.$$iterator]()));
11958         }
11959         else {
11960             iterators.push(new ZipBufferIterator(this.destination, this, value));
11961         }
11962     };
11963     ZipSubscriber.prototype._complete = function () {
11964         var iterators = this.iterators;
11965         var len = iterators.length;
11966         this.active = len;
11967         for (var i = 0; i < len; i++) {
11968             var iterator = iterators[i];
11969             if (iterator.stillUnsubscribed) {
11970                 this.add(iterator.subscribe(iterator, i));
11971             }
11972             else {
11973                 this.active--; // not an observable
11974             }
11975         }
11976     };
11977     ZipSubscriber.prototype.notifyInactive = function () {
11978         this.active--;
11979         if (this.active === 0) {
11980             this.destination.complete();
11981         }
11982     };
11983     ZipSubscriber.prototype.checkIterators = function () {
11984         var iterators = this.iterators;
11985         var len = iterators.length;
11986         var destination = this.destination;
11987         // abort if not all of them have values
11988         for (var i = 0; i < len; i++) {
11989             var iterator = iterators[i];
11990             if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
11991                 return;
11992             }
11993         }
11994         var shouldComplete = false;
11995         var args = [];
11996         for (var i = 0; i < len; i++) {
11997             var iterator = iterators[i];
11998             var result = iterator.next();
11999             // check to see if it's completed now that you've gotten
12000             // the next value.
12001             if (iterator.hasCompleted()) {
12002                 shouldComplete = true;
12003             }
12004             if (result.done) {
12005                 destination.complete();
12006                 return;
12007             }
12008             args.push(result.value);
12009         }
12010         if (this.project) {
12011             this._tryProject(args);
12012         }
12013         else {
12014             destination.next(args);
12015         }
12016         if (shouldComplete) {
12017             destination.complete();
12018         }
12019     };
12020     ZipSubscriber.prototype._tryProject = function (args) {
12021         var result;
12022         try {
12023             result = this.project.apply(this, args);
12024         }
12025         catch (err) {
12026             this.destination.error(err);
12027             return;
12028         }
12029         this.destination.next(result);
12030     };
12031     return ZipSubscriber;
12032 }(Subscriber_1.Subscriber));
12033 exports.ZipSubscriber = ZipSubscriber;
12034 var StaticIterator = (function () {
12035     function StaticIterator(iterator) {
12036         this.iterator = iterator;
12037         this.nextResult = iterator.next();
12038     }
12039     StaticIterator.prototype.hasValue = function () {
12040         return true;
12041     };
12042     StaticIterator.prototype.next = function () {
12043         var result = this.nextResult;
12044         this.nextResult = this.iterator.next();
12045         return result;
12046     };
12047     StaticIterator.prototype.hasCompleted = function () {
12048         var nextResult = this.nextResult;
12049         return nextResult && nextResult.done;
12050     };
12051     return StaticIterator;
12052 }());
12053 var StaticArrayIterator = (function () {
12054     function StaticArrayIterator(array) {
12055         this.array = array;
12056         this.index = 0;
12057         this.length = 0;
12058         this.length = array.length;
12059     }
12060     StaticArrayIterator.prototype[iterator_1.$$iterator] = function () {
12061         return this;
12062     };
12063     StaticArrayIterator.prototype.next = function (value) {
12064         var i = this.index++;
12065         var array = this.array;
12066         return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
12067     };
12068     StaticArrayIterator.prototype.hasValue = function () {
12069         return this.array.length > this.index;
12070     };
12071     StaticArrayIterator.prototype.hasCompleted = function () {
12072         return this.array.length === this.index;
12073     };
12074     return StaticArrayIterator;
12075 }());
12076 /**
12077  * We need this JSDoc comment for affecting ESDoc.
12078  * @ignore
12079  * @extends {Ignored}
12080  */
12081 var ZipBufferIterator = (function (_super) {
12082     __extends(ZipBufferIterator, _super);
12083     function ZipBufferIterator(destination, parent, observable) {
12084         _super.call(this, destination);
12085         this.parent = parent;
12086         this.observable = observable;
12087         this.stillUnsubscribed = true;
12088         this.buffer = [];
12089         this.isComplete = false;
12090     }
12091     ZipBufferIterator.prototype[iterator_1.$$iterator] = function () {
12092         return this;
12093     };
12094     // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
12095     //    this is legit because `next()` will never be called by a subscription in this case.
12096     ZipBufferIterator.prototype.next = function () {
12097         var buffer = this.buffer;
12098         if (buffer.length === 0 && this.isComplete) {
12099             return { value: null, done: true };
12100         }
12101         else {
12102             return { value: buffer.shift(), done: false };
12103         }
12104     };
12105     ZipBufferIterator.prototype.hasValue = function () {
12106         return this.buffer.length > 0;
12107     };
12108     ZipBufferIterator.prototype.hasCompleted = function () {
12109         return this.buffer.length === 0 && this.isComplete;
12110     };
12111     ZipBufferIterator.prototype.notifyComplete = function () {
12112         if (this.buffer.length > 0) {
12113             this.isComplete = true;
12114             this.parent.notifyInactive();
12115         }
12116         else {
12117             this.destination.complete();
12118         }
12119     };
12120     ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12121         this.buffer.push(innerValue);
12122         this.parent.checkIterators();
12123     };
12124     ZipBufferIterator.prototype.subscribe = function (value, index) {
12125         return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
12126     };
12127     return ZipBufferIterator;
12128 }(OuterSubscriber_1.OuterSubscriber));
12129
12130 },{"../OuterSubscriber":30,"../Subscriber":35,"../observable/ArrayObservable":85,"../symbol/iterator":152,"../util/isArray":162,"../util/subscribeToResult":171}],145:[function(require,module,exports){
12131 "use strict";
12132 var __extends = (this && this.__extends) || function (d, b) {
12133     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12134     function __() { this.constructor = d; }
12135     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12136 };
12137 var Subscription_1 = require('../Subscription');
12138 /**
12139  * A unit of work to be executed in a {@link Scheduler}. An action is typically
12140  * created from within a Scheduler and an RxJS user does not need to concern
12141  * themselves about creating and manipulating an Action.
12142  *
12143  * ```ts
12144  * class Action<T> extends Subscription {
12145  *   new (scheduler: Scheduler, work: (state?: T) => void);
12146  *   schedule(state?: T, delay: number = 0): Subscription;
12147  * }
12148  * ```
12149  *
12150  * @class Action<T>
12151  */
12152 var Action = (function (_super) {
12153     __extends(Action, _super);
12154     function Action(scheduler, work) {
12155         _super.call(this);
12156     }
12157     /**
12158      * Schedules this action on its parent Scheduler for execution. May be passed
12159      * some context object, `state`. May happen at some point in the future,
12160      * according to the `delay` parameter, if specified.
12161      * @param {T} [state] Some contextual data that the `work` function uses when
12162      * called by the Scheduler.
12163      * @param {number} [delay] Time to wait before executing the work, where the
12164      * time unit is implicit and defined by the Scheduler.
12165      * @return {void}
12166      */
12167     Action.prototype.schedule = function (state, delay) {
12168         if (delay === void 0) { delay = 0; }
12169         return this;
12170     };
12171     return Action;
12172 }(Subscription_1.Subscription));
12173 exports.Action = Action;
12174
12175 },{"../Subscription":36}],146:[function(require,module,exports){
12176 "use strict";
12177 var __extends = (this && this.__extends) || function (d, b) {
12178     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12179     function __() { this.constructor = d; }
12180     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12181 };
12182 var root_1 = require('../util/root');
12183 var Action_1 = require('./Action');
12184 /**
12185  * We need this JSDoc comment for affecting ESDoc.
12186  * @ignore
12187  * @extends {Ignored}
12188  */
12189 var AsyncAction = (function (_super) {
12190     __extends(AsyncAction, _super);
12191     function AsyncAction(scheduler, work) {
12192         _super.call(this, scheduler, work);
12193         this.scheduler = scheduler;
12194         this.work = work;
12195         this.pending = false;
12196     }
12197     AsyncAction.prototype.schedule = function (state, delay) {
12198         if (delay === void 0) { delay = 0; }
12199         if (this.closed) {
12200             return this;
12201         }
12202         // Always replace the current state with the new state.
12203         this.state = state;
12204         // Set the pending flag indicating that this action has been scheduled, or
12205         // has recursively rescheduled itself.
12206         this.pending = true;
12207         var id = this.id;
12208         var scheduler = this.scheduler;
12209         //
12210         // Important implementation note:
12211         //
12212         // Actions only execute once by default, unless rescheduled from within the
12213         // scheduled callback. This allows us to implement single and repeat
12214         // actions via the same code path, without adding API surface area, as well
12215         // as mimic traditional recursion but across asynchronous boundaries.
12216         //
12217         // However, JS runtimes and timers distinguish between intervals achieved by
12218         // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
12219         // serial `setTimeout` calls can be individually delayed, which delays
12220         // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
12221         // guarantee the interval callback will be invoked more precisely to the
12222         // interval period, regardless of load.
12223         //
12224         // Therefore, we use `setInterval` to schedule single and repeat actions.
12225         // If the action reschedules itself with the same delay, the interval is not
12226         // canceled. If the action doesn't reschedule, or reschedules with a
12227         // different delay, the interval will be canceled after scheduled callback
12228         // execution.
12229         //
12230         if (id != null) {
12231             this.id = this.recycleAsyncId(scheduler, id, delay);
12232         }
12233         this.delay = delay;
12234         // If this action has already an async Id, don't request a new one.
12235         this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
12236         return this;
12237     };
12238     AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12239         if (delay === void 0) { delay = 0; }
12240         return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
12241     };
12242     AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
12243         if (delay === void 0) { delay = 0; }
12244         // If this action is rescheduled with the same delay time, don't clear the interval id.
12245         if (delay !== null && this.delay === delay) {
12246             return id;
12247         }
12248         // Otherwise, if the action's delay time is different from the current delay,
12249         // clear the interval id
12250         return root_1.root.clearInterval(id) && undefined || undefined;
12251     };
12252     /**
12253      * Immediately executes this action and the `work` it contains.
12254      * @return {any}
12255      */
12256     AsyncAction.prototype.execute = function (state, delay) {
12257         if (this.closed) {
12258             return new Error('executing a cancelled action');
12259         }
12260         this.pending = false;
12261         var error = this._execute(state, delay);
12262         if (error) {
12263             return error;
12264         }
12265         else if (this.pending === false && this.id != null) {
12266             // Dequeue if the action didn't reschedule itself. Don't call
12267             // unsubscribe(), because the action could reschedule later.
12268             // For example:
12269             // ```
12270             // scheduler.schedule(function doWork(counter) {
12271             //   /* ... I'm a busy worker bee ... */
12272             //   var originalAction = this;
12273             //   /* wait 100ms before rescheduling the action */
12274             //   setTimeout(function () {
12275             //     originalAction.schedule(counter + 1);
12276             //   }, 100);
12277             // }, 1000);
12278             // ```
12279             this.id = this.recycleAsyncId(this.scheduler, this.id, null);
12280         }
12281     };
12282     AsyncAction.prototype._execute = function (state, delay) {
12283         var errored = false;
12284         var errorValue = undefined;
12285         try {
12286             this.work(state);
12287         }
12288         catch (e) {
12289             errored = true;
12290             errorValue = !!e && e || new Error(e);
12291         }
12292         if (errored) {
12293             this.unsubscribe();
12294             return errorValue;
12295         }
12296     };
12297     AsyncAction.prototype._unsubscribe = function () {
12298         var id = this.id;
12299         var scheduler = this.scheduler;
12300         var actions = scheduler.actions;
12301         var index = actions.indexOf(this);
12302         this.work = null;
12303         this.delay = null;
12304         this.state = null;
12305         this.pending = false;
12306         this.scheduler = null;
12307         if (index !== -1) {
12308             actions.splice(index, 1);
12309         }
12310         if (id != null) {
12311             this.id = this.recycleAsyncId(scheduler, id, null);
12312         }
12313     };
12314     return AsyncAction;
12315 }(Action_1.Action));
12316 exports.AsyncAction = AsyncAction;
12317
12318 },{"../util/root":170,"./Action":145}],147:[function(require,module,exports){
12319 "use strict";
12320 var __extends = (this && this.__extends) || function (d, b) {
12321     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12322     function __() { this.constructor = d; }
12323     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12324 };
12325 var Scheduler_1 = require('../Scheduler');
12326 var AsyncScheduler = (function (_super) {
12327     __extends(AsyncScheduler, _super);
12328     function AsyncScheduler() {
12329         _super.apply(this, arguments);
12330         this.actions = [];
12331         /**
12332          * A flag to indicate whether the Scheduler is currently executing a batch of
12333          * queued actions.
12334          * @type {boolean}
12335          */
12336         this.active = false;
12337         /**
12338          * An internal ID used to track the latest asynchronous task such as those
12339          * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
12340          * others.
12341          * @type {any}
12342          */
12343         this.scheduled = undefined;
12344     }
12345     AsyncScheduler.prototype.flush = function (action) {
12346         var actions = this.actions;
12347         if (this.active) {
12348             actions.push(action);
12349             return;
12350         }
12351         var error;
12352         this.active = true;
12353         do {
12354             if (error = action.execute(action.state, action.delay)) {
12355                 break;
12356             }
12357         } while (action = actions.shift()); // exhaust the scheduler queue
12358         this.active = false;
12359         if (error) {
12360             while (action = actions.shift()) {
12361                 action.unsubscribe();
12362             }
12363             throw error;
12364         }
12365     };
12366     return AsyncScheduler;
12367 }(Scheduler_1.Scheduler));
12368 exports.AsyncScheduler = AsyncScheduler;
12369
12370 },{"../Scheduler":32}],148:[function(require,module,exports){
12371 "use strict";
12372 var __extends = (this && this.__extends) || function (d, b) {
12373     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12374     function __() { this.constructor = d; }
12375     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12376 };
12377 var AsyncAction_1 = require('./AsyncAction');
12378 /**
12379  * We need this JSDoc comment for affecting ESDoc.
12380  * @ignore
12381  * @extends {Ignored}
12382  */
12383 var QueueAction = (function (_super) {
12384     __extends(QueueAction, _super);
12385     function QueueAction(scheduler, work) {
12386         _super.call(this, scheduler, work);
12387         this.scheduler = scheduler;
12388         this.work = work;
12389     }
12390     QueueAction.prototype.schedule = function (state, delay) {
12391         if (delay === void 0) { delay = 0; }
12392         if (delay > 0) {
12393             return _super.prototype.schedule.call(this, state, delay);
12394         }
12395         this.delay = delay;
12396         this.state = state;
12397         this.scheduler.flush(this);
12398         return this;
12399     };
12400     QueueAction.prototype.execute = function (state, delay) {
12401         return (delay > 0 || this.closed) ?
12402             _super.prototype.execute.call(this, state, delay) :
12403             this._execute(state, delay);
12404     };
12405     QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12406         if (delay === void 0) { delay = 0; }
12407         // If delay exists and is greater than 0, or if the delay is null (the
12408         // action wasn't rescheduled) but was originally scheduled as an async
12409         // action, then recycle as an async action.
12410         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
12411             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
12412         }
12413         // Otherwise flush the scheduler starting with this action.
12414         return scheduler.flush(this);
12415     };
12416     return QueueAction;
12417 }(AsyncAction_1.AsyncAction));
12418 exports.QueueAction = QueueAction;
12419
12420 },{"./AsyncAction":146}],149:[function(require,module,exports){
12421 "use strict";
12422 var __extends = (this && this.__extends) || function (d, b) {
12423     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12424     function __() { this.constructor = d; }
12425     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12426 };
12427 var AsyncScheduler_1 = require('./AsyncScheduler');
12428 var QueueScheduler = (function (_super) {
12429     __extends(QueueScheduler, _super);
12430     function QueueScheduler() {
12431         _super.apply(this, arguments);
12432     }
12433     return QueueScheduler;
12434 }(AsyncScheduler_1.AsyncScheduler));
12435 exports.QueueScheduler = QueueScheduler;
12436
12437 },{"./AsyncScheduler":147}],150:[function(require,module,exports){
12438 "use strict";
12439 var AsyncAction_1 = require('./AsyncAction');
12440 var AsyncScheduler_1 = require('./AsyncScheduler');
12441 /**
12442  *
12443  * Async Scheduler
12444  *
12445  * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
12446  *
12447  * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
12448  * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
12449  * in intervals.
12450  *
12451  * If you just want to "defer" task, that is to perform it right after currently
12452  * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
12453  * better choice will be the {@link asap} scheduler.
12454  *
12455  * @example <caption>Use async scheduler to delay task</caption>
12456  * const task = () => console.log('it works!');
12457  *
12458  * Rx.Scheduler.async.schedule(task, 2000);
12459  *
12460  * // After 2 seconds logs:
12461  * // "it works!"
12462  *
12463  *
12464  * @example <caption>Use async scheduler to repeat task in intervals</caption>
12465  * function task(state) {
12466  *   console.log(state);
12467  *   this.schedule(state + 1, 1000); // `this` references currently executing Action,
12468  *                                   // which we reschedule with new state and delay
12469  * }
12470  *
12471  * Rx.Scheduler.async.schedule(task, 3000, 0);
12472  *
12473  * // Logs:
12474  * // 0 after 3s
12475  * // 1 after 4s
12476  * // 2 after 5s
12477  * // 3 after 6s
12478  *
12479  * @static true
12480  * @name async
12481  * @owner Scheduler
12482  */
12483 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
12484
12485 },{"./AsyncAction":146,"./AsyncScheduler":147}],151:[function(require,module,exports){
12486 "use strict";
12487 var QueueAction_1 = require('./QueueAction');
12488 var QueueScheduler_1 = require('./QueueScheduler');
12489 /**
12490  *
12491  * Queue Scheduler
12492  *
12493  * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
12494  *
12495  * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
12496  *
12497  * When used without delay, it schedules given task synchronously - executes it right when
12498  * it is scheduled. However when called recursively, that is when inside the scheduled task,
12499  * another task is scheduled with queue scheduler, instead of executing immediately as well,
12500  * that task will be put on a queue and wait for current one to finish.
12501  *
12502  * This means that when you execute task with `queue` scheduler, you are sure it will end
12503  * before any other task scheduled with that scheduler will start.
12504  *
12505  * @examples <caption>Schedule recursively first, then do something</caption>
12506  *
12507  * Rx.Scheduler.queue.schedule(() => {
12508  *   Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
12509  *
12510  *   console.log('first');
12511  * });
12512  *
12513  * // Logs:
12514  * // "first"
12515  * // "second"
12516  *
12517  *
12518  * @example <caption>Reschedule itself recursively</caption>
12519  *
12520  * Rx.Scheduler.queue.schedule(function(state) {
12521  *   if (state !== 0) {
12522  *     console.log('before', state);
12523  *     this.schedule(state - 1); // `this` references currently executing Action,
12524  *                               // which we reschedule with new state
12525  *     console.log('after', state);
12526  *   }
12527  * }, 0, 3);
12528  *
12529  * // In scheduler that runs recursively, you would expect:
12530  * // "before", 3
12531  * // "before", 2
12532  * // "before", 1
12533  * // "after", 1
12534  * // "after", 2
12535  * // "after", 3
12536  *
12537  * // But with queue it logs:
12538  * // "before", 3
12539  * // "after", 3
12540  * // "before", 2
12541  * // "after", 2
12542  * // "before", 1
12543  * // "after", 1
12544  *
12545  *
12546  * @static true
12547  * @name queue
12548  * @owner Scheduler
12549  */
12550 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
12551
12552 },{"./QueueAction":148,"./QueueScheduler":149}],152:[function(require,module,exports){
12553 "use strict";
12554 var root_1 = require('../util/root');
12555 function symbolIteratorPonyfill(root) {
12556     var Symbol = root.Symbol;
12557     if (typeof Symbol === 'function') {
12558         if (!Symbol.iterator) {
12559             Symbol.iterator = Symbol('iterator polyfill');
12560         }
12561         return Symbol.iterator;
12562     }
12563     else {
12564         // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
12565         var Set_1 = root.Set;
12566         if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
12567             return '@@iterator';
12568         }
12569         var Map_1 = root.Map;
12570         // required for compatability with es6-shim
12571         if (Map_1) {
12572             var keys = Object.getOwnPropertyNames(Map_1.prototype);
12573             for (var i = 0; i < keys.length; ++i) {
12574                 var key = keys[i];
12575                 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
12576                 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
12577                     return key;
12578                 }
12579             }
12580         }
12581         return '@@iterator';
12582     }
12583 }
12584 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
12585 exports.$$iterator = symbolIteratorPonyfill(root_1.root);
12586
12587 },{"../util/root":170}],153:[function(require,module,exports){
12588 "use strict";
12589 var root_1 = require('../util/root');
12590 function getSymbolObservable(context) {
12591     var $$observable;
12592     var Symbol = context.Symbol;
12593     if (typeof Symbol === 'function') {
12594         if (Symbol.observable) {
12595             $$observable = Symbol.observable;
12596         }
12597         else {
12598             $$observable = Symbol('observable');
12599             Symbol.observable = $$observable;
12600         }
12601     }
12602     else {
12603         $$observable = '@@observable';
12604     }
12605     return $$observable;
12606 }
12607 exports.getSymbolObservable = getSymbolObservable;
12608 exports.$$observable = getSymbolObservable(root_1.root);
12609
12610 },{"../util/root":170}],154:[function(require,module,exports){
12611 "use strict";
12612 var root_1 = require('../util/root');
12613 var Symbol = root_1.root.Symbol;
12614 exports.$$rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
12615     Symbol.for('rxSubscriber') : '@@rxSubscriber';
12616
12617 },{"../util/root":170}],155:[function(require,module,exports){
12618 "use strict";
12619 var root_1 = require('./root');
12620 var RequestAnimationFrameDefinition = (function () {
12621     function RequestAnimationFrameDefinition(root) {
12622         if (root.requestAnimationFrame) {
12623             this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
12624             this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
12625         }
12626         else if (root.mozRequestAnimationFrame) {
12627             this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
12628             this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
12629         }
12630         else if (root.webkitRequestAnimationFrame) {
12631             this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
12632             this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
12633         }
12634         else if (root.msRequestAnimationFrame) {
12635             this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
12636             this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
12637         }
12638         else if (root.oRequestAnimationFrame) {
12639             this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
12640             this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
12641         }
12642         else {
12643             this.cancelAnimationFrame = root.clearTimeout.bind(root);
12644             this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
12645         }
12646     }
12647     return RequestAnimationFrameDefinition;
12648 }());
12649 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
12650 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
12651
12652 },{"./root":170}],156:[function(require,module,exports){
12653 "use strict";
12654 var __extends = (this && this.__extends) || function (d, b) {
12655     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12656     function __() { this.constructor = d; }
12657     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12658 };
12659 /**
12660  * An error thrown when an element was queried at a certain index of an
12661  * Observable, but no such index or position exists in that sequence.
12662  *
12663  * @see {@link elementAt}
12664  * @see {@link take}
12665  * @see {@link takeLast}
12666  *
12667  * @class ArgumentOutOfRangeError
12668  */
12669 var ArgumentOutOfRangeError = (function (_super) {
12670     __extends(ArgumentOutOfRangeError, _super);
12671     function ArgumentOutOfRangeError() {
12672         var err = _super.call(this, 'argument out of range');
12673         this.name = err.name = 'ArgumentOutOfRangeError';
12674         this.stack = err.stack;
12675         this.message = err.message;
12676     }
12677     return ArgumentOutOfRangeError;
12678 }(Error));
12679 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
12680
12681 },{}],157:[function(require,module,exports){
12682 "use strict";
12683 var __extends = (this && this.__extends) || function (d, b) {
12684     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12685     function __() { this.constructor = d; }
12686     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12687 };
12688 /**
12689  * An error thrown when an Observable or a sequence was queried but has no
12690  * elements.
12691  *
12692  * @see {@link first}
12693  * @see {@link last}
12694  * @see {@link single}
12695  *
12696  * @class EmptyError
12697  */
12698 var EmptyError = (function (_super) {
12699     __extends(EmptyError, _super);
12700     function EmptyError() {
12701         var err = _super.call(this, 'no elements in sequence');
12702         this.name = err.name = 'EmptyError';
12703         this.stack = err.stack;
12704         this.message = err.message;
12705     }
12706     return EmptyError;
12707 }(Error));
12708 exports.EmptyError = EmptyError;
12709
12710 },{}],158:[function(require,module,exports){
12711 "use strict";
12712 var __extends = (this && this.__extends) || function (d, b) {
12713     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12714     function __() { this.constructor = d; }
12715     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12716 };
12717 /**
12718  * An error thrown when an action is invalid because the object has been
12719  * unsubscribed.
12720  *
12721  * @see {@link Subject}
12722  * @see {@link BehaviorSubject}
12723  *
12724  * @class ObjectUnsubscribedError
12725  */
12726 var ObjectUnsubscribedError = (function (_super) {
12727     __extends(ObjectUnsubscribedError, _super);
12728     function ObjectUnsubscribedError() {
12729         var err = _super.call(this, 'object unsubscribed');
12730         this.name = err.name = 'ObjectUnsubscribedError';
12731         this.stack = err.stack;
12732         this.message = err.message;
12733     }
12734     return ObjectUnsubscribedError;
12735 }(Error));
12736 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
12737
12738 },{}],159:[function(require,module,exports){
12739 "use strict";
12740 var root_1 = require('./root');
12741 function minimalSetImpl() {
12742     // THIS IS NOT a full impl of Set, this is just the minimum
12743     // bits of functionality we need for this library.
12744     return (function () {
12745         function MinimalSet() {
12746             this._values = [];
12747         }
12748         MinimalSet.prototype.add = function (value) {
12749             if (!this.has(value)) {
12750                 this._values.push(value);
12751             }
12752         };
12753         MinimalSet.prototype.has = function (value) {
12754             return this._values.indexOf(value) !== -1;
12755         };
12756         Object.defineProperty(MinimalSet.prototype, "size", {
12757             get: function () {
12758                 return this._values.length;
12759             },
12760             enumerable: true,
12761             configurable: true
12762         });
12763         MinimalSet.prototype.clear = function () {
12764             this._values.length = 0;
12765         };
12766         return MinimalSet;
12767     }());
12768 }
12769 exports.minimalSetImpl = minimalSetImpl;
12770 exports.Set = root_1.root.Set || minimalSetImpl();
12771
12772 },{"./root":170}],160:[function(require,module,exports){
12773 "use strict";
12774 var __extends = (this && this.__extends) || function (d, b) {
12775     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12776     function __() { this.constructor = d; }
12777     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12778 };
12779 /**
12780  * An error thrown when one or more errors have occurred during the
12781  * `unsubscribe` of a {@link Subscription}.
12782  */
12783 var UnsubscriptionError = (function (_super) {
12784     __extends(UnsubscriptionError, _super);
12785     function UnsubscriptionError(errors) {
12786         _super.call(this);
12787         this.errors = errors;
12788         var err = Error.call(this, errors ?
12789             errors.length + " errors occurred during unsubscription:\n  " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n  ') : '');
12790         this.name = err.name = 'UnsubscriptionError';
12791         this.stack = err.stack;
12792         this.message = err.message;
12793     }
12794     return UnsubscriptionError;
12795 }(Error));
12796 exports.UnsubscriptionError = UnsubscriptionError;
12797
12798 },{}],161:[function(require,module,exports){
12799 "use strict";
12800 // typeof any so that it we don't have to cast when comparing a result to the error object
12801 exports.errorObject = { e: {} };
12802
12803 },{}],162:[function(require,module,exports){
12804 "use strict";
12805 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
12806
12807 },{}],163:[function(require,module,exports){
12808 "use strict";
12809 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
12810
12811 },{}],164:[function(require,module,exports){
12812 "use strict";
12813 function isDate(value) {
12814     return value instanceof Date && !isNaN(+value);
12815 }
12816 exports.isDate = isDate;
12817
12818 },{}],165:[function(require,module,exports){
12819 "use strict";
12820 function isFunction(x) {
12821     return typeof x === 'function';
12822 }
12823 exports.isFunction = isFunction;
12824
12825 },{}],166:[function(require,module,exports){
12826 "use strict";
12827 var isArray_1 = require('../util/isArray');
12828 function isNumeric(val) {
12829     // parseFloat NaNs numeric-cast false positives (null|true|false|"")
12830     // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
12831     // subtraction forces infinities to NaN
12832     // adding 1 corrects loss of precision from parseFloat (#15100)
12833     return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
12834 }
12835 exports.isNumeric = isNumeric;
12836 ;
12837
12838 },{"../util/isArray":162}],167:[function(require,module,exports){
12839 "use strict";
12840 function isObject(x) {
12841     return x != null && typeof x === 'object';
12842 }
12843 exports.isObject = isObject;
12844
12845 },{}],168:[function(require,module,exports){
12846 "use strict";
12847 function isPromise(value) {
12848     return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
12849 }
12850 exports.isPromise = isPromise;
12851
12852 },{}],169:[function(require,module,exports){
12853 "use strict";
12854 function isScheduler(value) {
12855     return value && typeof value.schedule === 'function';
12856 }
12857 exports.isScheduler = isScheduler;
12858
12859 },{}],170:[function(require,module,exports){
12860 (function (global){
12861 "use strict";
12862 /**
12863  * window: browser in DOM main thread
12864  * self: browser in WebWorker
12865  * global: Node.js/other
12866  */
12867 exports.root = (typeof window == 'object' && window.window === window && window
12868     || typeof self == 'object' && self.self === self && self
12869     || typeof global == 'object' && global.global === global && global);
12870 if (!exports.root) {
12871     throw new Error('RxJS could not find any global context (window, self, global)');
12872 }
12873
12874 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12875
12876 },{}],171:[function(require,module,exports){
12877 "use strict";
12878 var root_1 = require('./root');
12879 var isArrayLike_1 = require('./isArrayLike');
12880 var isPromise_1 = require('./isPromise');
12881 var isObject_1 = require('./isObject');
12882 var Observable_1 = require('../Observable');
12883 var iterator_1 = require('../symbol/iterator');
12884 var InnerSubscriber_1 = require('../InnerSubscriber');
12885 var observable_1 = require('../symbol/observable');
12886 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
12887     var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
12888     if (destination.closed) {
12889         return null;
12890     }
12891     if (result instanceof Observable_1.Observable) {
12892         if (result._isScalar) {
12893             destination.next(result.value);
12894             destination.complete();
12895             return null;
12896         }
12897         else {
12898             return result.subscribe(destination);
12899         }
12900     }
12901     else if (isArrayLike_1.isArrayLike(result)) {
12902         for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
12903             destination.next(result[i]);
12904         }
12905         if (!destination.closed) {
12906             destination.complete();
12907         }
12908     }
12909     else if (isPromise_1.isPromise(result)) {
12910         result.then(function (value) {
12911             if (!destination.closed) {
12912                 destination.next(value);
12913                 destination.complete();
12914             }
12915         }, function (err) { return destination.error(err); })
12916             .then(null, function (err) {
12917             // Escaping the Promise trap: globally throw unhandled errors
12918             root_1.root.setTimeout(function () { throw err; });
12919         });
12920         return destination;
12921     }
12922     else if (result && typeof result[iterator_1.$$iterator] === 'function') {
12923         var iterator = result[iterator_1.$$iterator]();
12924         do {
12925             var item = iterator.next();
12926             if (item.done) {
12927                 destination.complete();
12928                 break;
12929             }
12930             destination.next(item.value);
12931             if (destination.closed) {
12932                 break;
12933             }
12934         } while (true);
12935     }
12936     else if (result && typeof result[observable_1.$$observable] === 'function') {
12937         var obs = result[observable_1.$$observable]();
12938         if (typeof obs.subscribe !== 'function') {
12939             destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
12940         }
12941         else {
12942             return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
12943         }
12944     }
12945     else {
12946         var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
12947         var msg = ("You provided " + value + " where a stream was expected.")
12948             + ' You can provide an Observable, Promise, Array, or Iterable.';
12949         destination.error(new TypeError(msg));
12950     }
12951     return null;
12952 }
12953 exports.subscribeToResult = subscribeToResult;
12954
12955 },{"../InnerSubscriber":26,"../Observable":28,"../symbol/iterator":152,"../symbol/observable":153,"./isArrayLike":163,"./isObject":167,"./isPromise":168,"./root":170}],172:[function(require,module,exports){
12956 "use strict";
12957 var Subscriber_1 = require('../Subscriber');
12958 var rxSubscriber_1 = require('../symbol/rxSubscriber');
12959 var Observer_1 = require('../Observer');
12960 function toSubscriber(nextOrObserver, error, complete) {
12961     if (nextOrObserver) {
12962         if (nextOrObserver instanceof Subscriber_1.Subscriber) {
12963             return nextOrObserver;
12964         }
12965         if (nextOrObserver[rxSubscriber_1.$$rxSubscriber]) {
12966             return nextOrObserver[rxSubscriber_1.$$rxSubscriber]();
12967         }
12968     }
12969     if (!nextOrObserver && !error && !complete) {
12970         return new Subscriber_1.Subscriber(Observer_1.empty);
12971     }
12972     return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
12973 }
12974 exports.toSubscriber = toSubscriber;
12975
12976 },{"../Observer":29,"../Subscriber":35,"../symbol/rxSubscriber":154}],173:[function(require,module,exports){
12977 "use strict";
12978 var errorObject_1 = require('./errorObject');
12979 var tryCatchTarget;
12980 function tryCatcher() {
12981     try {
12982         return tryCatchTarget.apply(this, arguments);
12983     }
12984     catch (e) {
12985         errorObject_1.errorObject.e = e;
12986         return errorObject_1.errorObject;
12987     }
12988 }
12989 function tryCatch(fn) {
12990     tryCatchTarget = fn;
12991     return tryCatcher;
12992 }
12993 exports.tryCatch = tryCatch;
12994 ;
12995
12996 },{"./errorObject":161}],174:[function(require,module,exports){
12997 // threejs.org/license
12998 (function(l,oa){"object"===typeof exports&&"undefined"!==typeof module?oa(exports):"function"===typeof define&&define.amd?define(["exports"],oa):oa(l.THREE=l.THREE||{})})(this,function(l){function oa(){}function C(a,b){this.x=a||0;this.y=b||0}function ea(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:Oe++});this.uuid=Q.generateUUID();this.name="";this.image=void 0!==a?a:ea.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ea.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=
12999 void 0!==d?d:1001;this.magFilter=void 0!==e?e:1006;this.minFilter=void 0!==f?f:1008;this.anisotropy=void 0!==k?k:1;this.format=void 0!==g?g:1023;this.type=void 0!==h?h:1009;this.offset=new C(0,0);this.repeat=new C(1,1);this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==m?m:3E3;this.version=0;this.onUpdate=null}function ga(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Db(a,b,c){this.uuid=Q.generateUUID();this.width=
13000 a;this.height=b;this.scissor=new ga(0,0,a,b);this.scissorTest=!1;this.viewport=new ga(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new ea(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function Eb(a,b,c){Db.call(this,a,b,c);this.activeMipMapLevel=
13001 this.activeCubeFace=0}function da(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function q(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function H(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);0<arguments.length&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function Za(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];ea.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,m);this.flipY=!1}function Fb(a,b,c){var d=a[0];if(0>=
13002 d||0<d)return a;var e=b*c,f=pe[e];void 0===f&&(f=new Float32Array(e),pe[e]=f);if(0!==b)for(d.toArray(f,0),d=1,e=0;d!==b;++d)e+=c,a[d].toArray(f,e);return f}function qe(a,b){var c=re[b];void 0===c&&(c=new Int32Array(b),re[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function Pe(a,b){a.uniform1f(this.addr,b)}function Qe(a,b){a.uniform1i(this.addr,b)}function Re(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function Se(a,b){void 0!==b.x?a.uniform3f(this.addr,
13003 b.x,b.y,b.z):void 0!==b.r?a.uniform3f(this.addr,b.r,b.g,b.b):a.uniform3fv(this.addr,b)}function Te(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function Ue(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function Ve(a,b){a.uniformMatrix3fv(this.addr,!1,b.elements||b)}function We(a,b){a.uniformMatrix4fv(this.addr,!1,b.elements||b)}function Xe(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||se,d)}function Ye(a,b,c){var d=c.allocTextureUnit();
13004 a.uniform1i(this.addr,d);c.setTextureCube(b||te,d)}function ue(a,b){a.uniform2iv(this.addr,b)}function ve(a,b){a.uniform3iv(this.addr,b)}function we(a,b){a.uniform4iv(this.addr,b)}function Ze(a){switch(a){case 5126:return Pe;case 35664:return Re;case 35665:return Se;case 35666:return Te;case 35674:return Ue;case 35675:return Ve;case 35676:return We;case 35678:return Xe;case 35680:return Ye;case 5124:case 35670:return Qe;case 35667:case 35671:return ue;case 35668:case 35672:return ve;case 35669:case 35673:return we}}
13005 function $e(a,b){a.uniform1fv(this.addr,b)}function af(a,b){a.uniform1iv(this.addr,b)}function bf(a,b){a.uniform2fv(this.addr,Fb(b,this.size,2))}function cf(a,b){a.uniform3fv(this.addr,Fb(b,this.size,3))}function df(a,b){a.uniform4fv(this.addr,Fb(b,this.size,4))}function ef(a,b){a.uniformMatrix2fv(this.addr,!1,Fb(b,this.size,4))}function ff(a,b){a.uniformMatrix3fv(this.addr,!1,Fb(b,this.size,9))}function gf(a,b){a.uniformMatrix4fv(this.addr,!1,Fb(b,this.size,16))}function hf(a,b,c){var d=b.length,
13006 e=qe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||se,e[a])}function jf(a,b,c){var d=b.length,e=qe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||te,e[a])}function kf(a){switch(a){case 5126:return $e;case 35664:return bf;case 35665:return cf;case 35666:return df;case 35674:return ef;case 35675:return ff;case 35676:return gf;case 35678:return hf;case 35680:return jf;case 5124:case 35670:return af;case 35667:case 35671:return ue;case 35668:case 35672:return ve;
13007 case 35669:case 35673:return we}}function lf(a,b,c){this.id=a;this.addr=c;this.setValue=Ze(b.type)}function mf(a,b,c){this.id=a;this.addr=c;this.size=b.size;this.setValue=kf(b.type)}function xe(a){this.id=a;this.seq=[];this.map={}}function $a(a,b,c){this.seq=[];this.map={};this.renderer=c;c=a.getProgramParameter(b,a.ACTIVE_UNIFORMS);for(var d=0;d!==c;++d){var e=a.getActiveUniform(b,d),f=a.getUniformLocation(b,e.name),g=this,h=e.name,k=h.length;for(Id.lastIndex=0;;){var m=Id.exec(h),x=Id.lastIndex,
13008 p=m[1],n=m[3];"]"===m[2]&&(p|=0);if(void 0===n||"["===n&&x+2===k){h=g;e=void 0===n?new lf(p,e,f):new mf(p,e,f);h.seq.push(e);h.map[e.id]=e;break}else n=g.map[p],void 0===n&&(n=new xe(p),p=g,g=n,p.seq.push(g),p.map[g.id]=g),g=n}}}function N(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function db(a,b,c,d,e,f,g,h,k,m,x,p){ea.call(this,null,f,g,h,k,m,d,e,x,p);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==m?m:1003;this.flipY=this.generateMipmaps=
13009 !1;this.unpackAlignment=1}function pc(a,b){this.min=void 0!==a?a:new C(Infinity,Infinity);this.max=void 0!==b?b:new C(-Infinity,-Infinity)}function nf(a,b){var c,d,e,f,g,h,k,m,x,p,n=a.context,r=a.state,w,l,F,t,v,M;this.render=function(z,A,I){if(0!==b.length){z=new q;var E=I.w/I.z,K=.5*I.z,la=.5*I.w,J=16/I.w,ca=new C(J*E,J),Da=new q(1,1,0),eb=new C(1,1),Na=new pc;Na.min.set(I.x,I.y);Na.max.set(I.x+(I.z-16),I.y+(I.w-16));if(void 0===t){var J=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),O=
13010 new Uint16Array([0,1,2,0,2,3]);w=n.createBuffer();l=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,w);n.bufferData(n.ARRAY_BUFFER,J,n.STATIC_DRAW);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,l);n.bufferData(n.ELEMENT_ARRAY_BUFFER,O,n.STATIC_DRAW);v=n.createTexture();M=n.createTexture();r.bindTexture(n.TEXTURE_2D,v);n.texImage2D(n.TEXTURE_2D,0,n.RGB,16,16,0,n.RGB,n.UNSIGNED_BYTE,null);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);
13011 n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST);r.bindTexture(n.TEXTURE_2D,M);n.texImage2D(n.TEXTURE_2D,0,n.RGBA,16,16,0,n.RGBA,n.UNSIGNED_BYTE,null);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST);var J=F={vertexShader:"uniform lowp int renderType;\nuniform vec3 screenPosition;\nuniform vec2 scale;\nuniform float rotation;\nuniform sampler2D occlusionMap;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nvUV = uv;\nvec2 pos = position;\nif ( renderType == 2 ) {\nvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );\nvVisibility =        visibility.r / 9.0;\nvVisibility *= 1.0 - visibility.g / 9.0;\nvVisibility *=       visibility.b / 9.0;\nvVisibility *= 1.0 - visibility.a / 9.0;\npos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\npos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n}\ngl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",
13012 fragmentShader:"uniform lowp int renderType;\nuniform sampler2D map;\nuniform float opacity;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nif ( renderType == 0 ) {\ngl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n} else if ( renderType == 1 ) {\ngl_FragColor = texture2D( map, vUV );\n} else {\nvec4 texture = texture2D( map, vUV );\ntexture.a *= opacity * vVisibility;\ngl_FragColor = texture;\ngl_FragColor.rgb *= color;\n}\n}"},O=n.createProgram(),P=n.createShader(n.FRAGMENT_SHADER),
13013 R=n.createShader(n.VERTEX_SHADER),T="precision "+a.getPrecision()+" float;\n";n.shaderSource(P,T+J.fragmentShader);n.shaderSource(R,T+J.vertexShader);n.compileShader(P);n.compileShader(R);n.attachShader(O,P);n.attachShader(O,R);n.linkProgram(O);t=O;x=n.getAttribLocation(t,"position");p=n.getAttribLocation(t,"uv");c=n.getUniformLocation(t,"renderType");d=n.getUniformLocation(t,"map");e=n.getUniformLocation(t,"occlusionMap");f=n.getUniformLocation(t,"opacity");g=n.getUniformLocation(t,"color");h=n.getUniformLocation(t,
13014 "scale");k=n.getUniformLocation(t,"rotation");m=n.getUniformLocation(t,"screenPosition")}n.useProgram(t);r.initAttributes();r.enableAttribute(x);r.enableAttribute(p);r.disableUnusedAttributes();n.uniform1i(e,0);n.uniform1i(d,1);n.bindBuffer(n.ARRAY_BUFFER,w);n.vertexAttribPointer(x,2,n.FLOAT,!1,16,0);n.vertexAttribPointer(p,2,n.FLOAT,!1,16,8);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,l);r.disable(n.CULL_FACE);r.setDepthWrite(!1);O=0;for(P=b.length;O<P;O++)if(J=16/I.w,ca.set(J*E,J),R=b[O],z.set(R.matrixWorld.elements[12],
13015 R.matrixWorld.elements[13],R.matrixWorld.elements[14]),z.applyMatrix4(A.matrixWorldInverse),z.applyProjection(A.projectionMatrix),Da.copy(z),eb.x=I.x+Da.x*K+K-8,eb.y=I.y+Da.y*la+la-8,!0===Na.containsPoint(eb)){r.activeTexture(n.TEXTURE0);r.bindTexture(n.TEXTURE_2D,null);r.activeTexture(n.TEXTURE1);r.bindTexture(n.TEXTURE_2D,v);n.copyTexImage2D(n.TEXTURE_2D,0,n.RGB,eb.x,eb.y,16,16,0);n.uniform1i(c,0);n.uniform2f(h,ca.x,ca.y);n.uniform3f(m,Da.x,Da.y,Da.z);r.disable(n.BLEND);r.enable(n.DEPTH_TEST);n.drawElements(n.TRIANGLES,
13016 6,n.UNSIGNED_SHORT,0);r.activeTexture(n.TEXTURE0);r.bindTexture(n.TEXTURE_2D,M);n.copyTexImage2D(n.TEXTURE_2D,0,n.RGBA,eb.x,eb.y,16,16,0);n.uniform1i(c,1);r.disable(n.DEPTH_TEST);r.activeTexture(n.TEXTURE1);r.bindTexture(n.TEXTURE_2D,v);n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0);R.positionScreen.copy(Da);R.customUpdateCallback?R.customUpdateCallback(R):R.updateLensFlares();n.uniform1i(c,2);r.enable(n.BLEND);for(var T=0,y=R.lensFlares.length;T<y;T++){var V=R.lensFlares[T];.001<V.opacity&&.001<
13017 V.scale&&(Da.x=V.x,Da.y=V.y,Da.z=V.z,J=V.size*V.scale/I.w,ca.x=J*E,ca.y=J,n.uniform3f(m,Da.x,Da.y,Da.z),n.uniform2f(h,ca.x,ca.y),n.uniform1f(k,V.rotation),n.uniform1f(f,V.opacity),n.uniform3f(g,V.color.r,V.color.g,V.color.b),r.setBlending(V.blending,V.blendEquation,V.blendSrc,V.blendDst),a.setTexture2D(V.texture,1),n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0))}}r.enable(n.CULL_FACE);r.enable(n.DEPTH_TEST);r.setDepthWrite(!0);a.resetGLState()}}}function of(a,b){var c,d,e,f,g,h,k,m,x,p,n,r,w,l,
13018 F,t,v;function M(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var z=a.context,A=a.state,I,E,K,la,J=new q,ca=new da,Da=new q;this.render=function(q,Na){if(0!==b.length){if(void 0===K){var O=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),P=new Uint16Array([0,1,2,0,2,3]);I=z.createBuffer();E=z.createBuffer();z.bindBuffer(z.ARRAY_BUFFER,I);z.bufferData(z.ARRAY_BUFFER,O,z.STATIC_DRAW);z.bindBuffer(z.ELEMENT_ARRAY_BUFFER,E);z.bufferData(z.ELEMENT_ARRAY_BUFFER,
13019 P,z.STATIC_DRAW);var O=z.createProgram(),P=z.createShader(z.VERTEX_SHADER),R=z.createShader(z.FRAGMENT_SHADER);z.shaderSource(P,["precision "+a.getPrecision()+" float;","uniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform float rotation;\nuniform vec2 scale;\nuniform vec2 uvOffset;\nuniform vec2 uvScale;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvoid main() {\nvUV = uvOffset + uv * uvScale;\nvec2 alignedPosition = position * scale;\nvec2 rotatedPosition;\nrotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\nrotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\nvec4 finalPosition;\nfinalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\nfinalPosition.xy += rotatedPosition;\nfinalPosition = projectionMatrix * finalPosition;\ngl_Position = finalPosition;\n}"].join("\n"));
13020 z.shaderSource(R,["precision "+a.getPrecision()+" float;","uniform vec3 color;\nuniform sampler2D map;\nuniform float opacity;\nuniform int fogType;\nuniform vec3 fogColor;\nuniform float fogDensity;\nuniform float fogNear;\nuniform float fogFar;\nuniform float alphaTest;\nvarying vec2 vUV;\nvoid main() {\nvec4 texture = texture2D( map, vUV );\nif ( texture.a < alphaTest ) discard;\ngl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\nif ( fogType > 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n"));
13021 z.compileShader(P);z.compileShader(R);z.attachShader(O,P);z.attachShader(O,R);z.linkProgram(O);K=O;t=z.getAttribLocation(K,"position");v=z.getAttribLocation(K,"uv");c=z.getUniformLocation(K,"uvOffset");d=z.getUniformLocation(K,"uvScale");e=z.getUniformLocation(K,"rotation");f=z.getUniformLocation(K,"scale");g=z.getUniformLocation(K,"color");h=z.getUniformLocation(K,"map");k=z.getUniformLocation(K,"opacity");m=z.getUniformLocation(K,"modelViewMatrix");x=z.getUniformLocation(K,"projectionMatrix");p=
13022 z.getUniformLocation(K,"fogType");n=z.getUniformLocation(K,"fogDensity");r=z.getUniformLocation(K,"fogNear");w=z.getUniformLocation(K,"fogFar");l=z.getUniformLocation(K,"fogColor");F=z.getUniformLocation(K,"alphaTest");O=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");O.width=8;O.height=8;P=O.getContext("2d");P.fillStyle="white";P.fillRect(0,0,8,8);la=new ea(O);la.needsUpdate=!0}z.useProgram(K);A.initAttributes();A.enableAttribute(t);A.enableAttribute(v);A.disableUnusedAttributes();
13023 A.disable(z.CULL_FACE);A.enable(z.BLEND);z.bindBuffer(z.ARRAY_BUFFER,I);z.vertexAttribPointer(t,2,z.FLOAT,!1,16,0);z.vertexAttribPointer(v,2,z.FLOAT,!1,16,8);z.bindBuffer(z.ELEMENT_ARRAY_BUFFER,E);z.uniformMatrix4fv(x,!1,Na.projectionMatrix.elements);A.activeTexture(z.TEXTURE0);z.uniform1i(h,0);P=O=0;(R=q.fog)?(z.uniform3f(l,R.color.r,R.color.g,R.color.b),R.isFog?(z.uniform1f(r,R.near),z.uniform1f(w,R.far),z.uniform1i(p,1),P=O=1):R.isFogExp2&&(z.uniform1f(n,R.density),z.uniform1i(p,2),P=O=2)):(z.uniform1i(p,
13024 0),P=O=0);for(var R=0,T=b.length;R<T;R++){var y=b[R];y.modelViewMatrix.multiplyMatrices(Na.matrixWorldInverse,y.matrixWorld);y.z=-y.modelViewMatrix.elements[14]}b.sort(M);for(var V=[],R=0,T=b.length;R<T;R++){var y=b[R],ra=y.material;!1!==ra.visible&&(z.uniform1f(F,ra.alphaTest),z.uniformMatrix4fv(m,!1,y.modelViewMatrix.elements),y.matrixWorld.decompose(J,ca,Da),V[0]=Da.x,V[1]=Da.y,y=0,q.fog&&ra.fog&&(y=P),O!==y&&(z.uniform1i(p,y),O=y),null!==ra.map?(z.uniform2f(c,ra.map.offset.x,ra.map.offset.y),
13025 z.uniform2f(d,ra.map.repeat.x,ra.map.repeat.y)):(z.uniform2f(c,0,0),z.uniform2f(d,1,1)),z.uniform1f(k,ra.opacity),z.uniform3f(g,ra.color.r,ra.color.g,ra.color.b),z.uniform1f(e,ra.rotation),z.uniform2fv(f,V),A.setBlending(ra.blending,ra.blendEquation,ra.blendSrc,ra.blendDst),A.setDepthTest(ra.depthTest),A.setDepthWrite(ra.depthWrite),ra.map?a.setTexture2D(ra.map,0):a.setTexture2D(la,0),z.drawElements(z.TRIANGLES,6,z.UNSIGNED_SHORT,0))}A.enable(z.CULL_FACE);a.resetGLState()}}}function W(){Object.defineProperty(this,
13026 "id",{value:pf++});this.uuid=Q.generateUUID();this.name="";this.type="Material";this.lights=this.fog=!0;this.blending=1;this.side=0;this.shading=2;this.vertexColors=0;this.opacity=1;this.transparent=!1;this.blendSrc=204;this.blendDst=205;this.blendEquation=100;this.blendEquationAlpha=this.blendDstAlpha=this.blendSrcAlpha=null;this.depthFunc=3;this.depthWrite=this.depthTest=!0;this.clippingPlanes=null;this.clipShadows=this.clipIntersection=!1;this.colorWrite=!0;this.precision=null;this.polygonOffset=
13027 !1;this.alphaTest=this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.premultipliedAlpha=!1;this.overdraw=0;this._needsUpdate=this.visible=!0}function Ia(a){W.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";this.linewidth=1;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=
13028 this.morphTargets=this.skinning=this.clipping=this.lights=this.fog=!1;this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=void 0;void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(a))}function ab(a){W.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=
13029 this.skinning=!1;this.displacementMap=this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.lights=this.fog=!1;this.setValues(a)}function ya(a,b){this.min=void 0!==a?a:new q(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new q(-Infinity,-Infinity,-Infinity)}function Fa(a,b){this.center=void 0!==a?a:new q;this.radius=void 0!==b?b:0}function za(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1]);0<arguments.length&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}
13030 function ma(a,b){this.normal=void 0!==a?a:new q(1,0,0);this.constant=void 0!==b?b:0}function qc(a,b,c,d,e,f){this.planes=[void 0!==a?a:new ma,void 0!==b?b:new ma,void 0!==c?c:new ma,void 0!==d?d:new ma,void 0!==e?e:new ma,void 0!==f?f:new ma]}function ye(a,b,c,d){function e(b,c,d,e){var f=b.geometry,g;g=F;var h=b.customDepthMaterial;d&&(g=t,h=b.customDistanceMaterial);h?g=h:(h=!1,c.morphTargets&&(f&&f.isBufferGeometry?h=f.morphAttributes&&f.morphAttributes.position&&0<f.morphAttributes.position.length:
13031 f&&f.isGeometry&&(h=f.morphTargets&&0<f.morphTargets.length)),b=b.isSkinnedMesh&&c.skinning,f=0,h&&(f|=1),b&&(f|=2),g=g[f]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(f=g.uuid,h=c.uuid,b=v[f],void 0===b&&(b={},v[f]=b),f=b[h],void 0===f&&(f=g.clone(),b[h]=f),g=f);g.visible=c.visible;g.wireframe=c.wireframe;h=c.side;ca.renderSingleSided&&2==h&&(h=0);ca.renderReverseSided&&(0===h?h=1:1===h&&(h=0));g.side=h;g.clipShadows=c.clipShadows;g.clippingPlanes=c.clippingPlanes;g.wireframeLinewidth=
13032 c.wireframeLinewidth;g.linewidth=c.linewidth;d&&void 0!==g.uniforms.lightPos&&g.uniforms.lightPos.value.copy(e);return g}function f(a,b,c){if(!1!==a.visible){0!==(a.layers.mask&b.layers.mask)&&(a.isMesh||a.isLine||a.isPoints)&&a.castShadow&&(!1===a.frustumCulled||!0===k.intersectsObject(a))&&!0===a.material.visible&&(a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,a.matrixWorld),l.push(a));a=a.children;for(var d=0,e=a.length;d<e;d++)f(a[d],b,c)}}var g=a.context,h=a.state,k=new qc,m=new H,
13033 x=b.shadows,p=new C,n=new C(d.maxTextureSize,d.maxTextureSize),r=new q,w=new q,l=[],F=Array(4),t=Array(4),v={},M=[new q(1,0,0),new q(-1,0,0),new q(0,0,1),new q(0,0,-1),new q(0,1,0),new q(0,-1,0)],z=[new q(0,1,0),new q(0,1,0),new q(0,1,0),new q(0,1,0),new q(0,0,1),new q(0,0,-1)],A=[new ga,new ga,new ga,new ga,new ga,new ga];b=new ab;b.depthPacking=3201;b.clipping=!0;d=Gb.distanceRGBA;for(var I=Ja.clone(d.uniforms),E=0;4!==E;++E){var K=0!==(E&1),la=0!==(E&2),J=b.clone();J.morphTargets=K;J.skinning=
13034 la;F[E]=J;K=new Ia({defines:{USE_SHADOWMAP:""},uniforms:I,vertexShader:d.vertexShader,fragmentShader:d.fragmentShader,morphTargets:K,skinning:la,clipping:!0});t[E]=K}var ca=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,d){if(!1!==ca.enabled&&(!1!==ca.autoUpdate||!1!==ca.needsUpdate)&&0!==x.length){h.buffers.color.setClear(1,1,1,1);h.disable(g.BLEND);h.setDepthTest(!0);h.setScissorTest(!1);for(var v,
13035 q,t=0,F=x.length;t<F;t++){var I=x[t],E=I.shadow;if(void 0===E)console.warn("THREE.WebGLShadowMap:",I,"has no shadow.");else{var K=E.camera;p.copy(E.mapSize);p.min(n);if(I&&I.isPointLight){v=6;q=!0;var J=p.x,la=p.y;A[0].set(2*J,la,J,la);A[1].set(0,la,J,la);A[2].set(3*J,la,J,la);A[3].set(J,la,J,la);A[4].set(3*J,0,J,la);A[5].set(J,0,J,la);p.x*=4;p.y*=2}else v=1,q=!1;null===E.map&&(E.map=new Db(p.x,p.y,{minFilter:1003,magFilter:1003,format:1023}),K.updateProjectionMatrix());E.isSpotLightShadow&&E.update(I);
13036 E&&E.isRectAreaLightShadow&&E.update(I);J=E.map;E=E.matrix;w.setFromMatrixPosition(I.matrixWorld);K.position.copy(w);a.setRenderTarget(J);a.clear();for(J=0;J<v;J++){q?(r.copy(K.position),r.add(M[J]),K.up.copy(z[J]),K.lookAt(r),h.viewport(A[J])):(r.setFromMatrixPosition(I.target.matrixWorld),K.lookAt(r));K.updateMatrixWorld();K.matrixWorldInverse.getInverse(K.matrixWorld);E.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1);E.multiply(K.projectionMatrix);E.multiply(K.matrixWorldInverse);m.multiplyMatrices(K.projectionMatrix,
13037 K.matrixWorldInverse);k.setFromMatrix(m);l.length=0;f(b,d,K);for(var la=0,y=l.length;la<y;la++){var C=l[la],Jd=c.update(C),Ta=C.material;if(Ta&&Ta.isMultiMaterial)for(var G=Jd.groups,Ta=Ta.materials,D=0,Ga=G.length;D<Ga;D++){var N=G[D],H=Ta[N.materialIndex];!0===H.visible&&(H=e(C,H,q,w),a.renderBufferDirect(K,null,Jd,H,C,N))}else H=e(C,Ta,q,w),a.renderBufferDirect(K,null,Jd,H,C,null)}}}}v=a.getClearColor();q=a.getClearAlpha();a.setClearColor(v,q);ca.needsUpdate=!1}}}function bb(a,b){this.origin=void 0!==
13038 a?a:new q;this.direction=void 0!==b?b:new q}function cb(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||cb.DefaultOrder}function gd(){this.mask=1}function G(){Object.defineProperty(this,"id",{value:qf++});this.uuid=Q.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=G.DefaultUp.clone();var a=new q,b=new cb,c=new da,d=new q(1,1,1);b.onChange(function(){c.setFromEuler(b,!1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,
13039 {position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new H},normalMatrix:{value:new za}});this.matrix=new H;this.matrixWorld=new H;this.matrixAutoUpdate=G.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new gd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=0;this.userData={};this.onBeforeRender=function(){};this.onAfterRender=function(){}}
13040 function gb(a,b){this.start=void 0!==a?a:new q;this.end=void 0!==b?b:new q}function Aa(a,b,c){this.a=void 0!==a?a:new q;this.b=void 0!==b?b:new q;this.c=void 0!==c?c:new q}function ha(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new q;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?e:new N;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function Ka(a){W.call(this);this.type="MeshBasicMaterial";this.color=new N(16777215);this.lightMap=
13041 this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=this.morphTargets=this.skinning=!1;this.setValues(a)}function y(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=Q.generateUUID();this.array=a;
13042 this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===c;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function rc(a,b){y.call(this,new Int8Array(a),b)}function sc(a,b){y.call(this,new Uint8Array(a),b)}function tc(a,b){y.call(this,new Uint8ClampedArray(a),b)}function uc(a,b){y.call(this,new Int16Array(a),b)}function Ra(a,b){y.call(this,new Uint16Array(a),b)}function vc(a,b){y.call(this,new Int32Array(a),b)}function Ua(a,b){y.call(this,
13043 new Uint32Array(a),b)}function X(a,b){y.call(this,new Float32Array(a),b)}function wc(a,b){y.call(this,new Float64Array(a),b)}function ze(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function S(){Object.defineProperty(this,"id",
13044 {value:Kd++});this.uuid=Q.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function D(){Object.defineProperty(this,"id",
13045 {value:Kd++});this.uuid=Q.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function Ba(a,b){G.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new Ka({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function hb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,k,m,y,C){var Na=f/m,O=g/y,
13046 P=f/2,R=g/2,T=k/2;g=m+1;for(var G=y+1,V=f=0,D=new q,L=0;L<G;L++)for(var N=L*O-R,H=0;H<g;H++)D[a]=(H*Na-P)*d,D[b]=N*e,D[c]=T,p[w]=D.x,p[w+1]=D.y,p[w+2]=D.z,D[a]=0,D[b]=0,D[c]=0<k?1:-1,n[w]=D.x,n[w+1]=D.y,n[w+2]=D.z,r[l]=H/m,r[l+1]=1-L/y,w+=3,l+=2,f+=1;for(L=0;L<y;L++)for(H=0;H<m;H++)a=t+H+g*(L+1),b=t+(H+1)+g*(L+1),c=t+(H+1)+g*L,x[F]=t+H+g*L,x[F+1]=a,x[F+2]=c,x[F+3]=a,x[F+4]=b,x[F+5]=c,F+=6,V+=6;h.addGroup(v,V,C);v+=V;t+=f}D.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,
13047 depth:c,widthSegments:d,heightSegments:e,depthSegments:f};var h=this;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=function(a,b,c){return a=0+(a+1)*(b+1)*2+(a+1)*(c+1)*2+(c+1)*(b+1)*2}(d,e,f),m=function(a,b,c){a=0+a*b*2+a*c*2+c*b*2;return 6*a}(d,e,f),x=new (65535<m?Uint32Array:Uint16Array)(m),p=new Float32Array(3*k),n=new Float32Array(3*k),r=new Float32Array(2*k),w=0,l=0,F=0,t=0,v=0;g("z","y","x",-1,-1,c,b,a,f,e,0);g("z","y","x",1,-1,c,b,-a,f,e,1);g("x","z","y",1,1,a,c,b,d,f,2);g("x",
13048 "z","y",1,-1,a,c,-b,d,f,3);g("x","y","z",1,-1,a,b,c,d,e,4);g("x","y","z",-1,-1,a,b,-c,d,e,5);this.setIndex(new y(x,1));this.addAttribute("position",new y(p,3));this.addAttribute("normal",new y(n,3));this.addAttribute("uv",new y(r,2))}function ib(a,b,c,d){D.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};var e=a/2,f=b/2;c=Math.floor(c)||1;d=Math.floor(d)||1;var g=c+1,h=d+1,k=a/c,m=b/d;b=new Float32Array(g*h*3);a=new Float32Array(g*h*3);
13049 for(var x=new Float32Array(g*h*2),p=0,n=0,r=0;r<h;r++)for(var w=r*m-f,l=0;l<g;l++)b[p]=l*k-e,b[p+1]=-w,a[p+2]=1,x[n]=l/c,x[n+1]=1-r/d,p+=3,n+=2;p=0;e=new (65535<b.length/3?Uint32Array:Uint16Array)(c*d*6);for(r=0;r<d;r++)for(l=0;l<c;l++)f=l+g*(r+1),h=l+1+g*(r+1),k=l+1+g*r,e[p]=l+g*r,e[p+1]=f,e[p+2]=k,e[p+3]=f,e[p+4]=h,e[p+5]=k,p+=6;this.setIndex(new y(e,1));this.addAttribute("position",new y(b,3));this.addAttribute("normal",new y(a,3));this.addAttribute("uv",new y(x,2))}function sa(){G.call(this);
13050 this.type="Camera";this.matrixWorldInverse=new H;this.projectionMatrix=new H}function Ha(a,b,c,d){sa.call(this);this.type="PerspectiveCamera";this.fov=void 0!==a?a:50;this.zoom=1;this.near=void 0!==c?c:.1;this.far=void 0!==d?d:2E3;this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}function Hb(a,b,c,d,e,f){sa.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=
13051 void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function rf(a,b,c){var d,e,f;return{setMode:function(a){d=a},setIndex:function(c){c.array instanceof Uint32Array&&b.get("OES_element_index_uint")?(e=a.UNSIGNED_INT,f=4):c.array instanceof Uint16Array?(e=a.UNSIGNED_SHORT,f=2):(e=a.UNSIGNED_BYTE,f=1)},render:function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES&&(c.faces+=h/3)},renderInstances:function(g,h,k){var m=b.get("ANGLE_instanced_arrays");null===
13052 m?console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(m.drawElementsInstancedANGLE(d,k,e,h*f,g.maxInstancedCount),c.calls++,c.vertices+=k*g.maxInstancedCount,d===a.TRIANGLES&&(c.faces+=g.maxInstancedCount*k/3))}}}function sf(a,b,c){var d;return{setMode:function(a){d=a},render:function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES&&(c.faces+=f/3)},renderInstances:function(e){var f=b.get("ANGLE_instanced_arrays");
13053 if(null===f)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{var g=e.attributes.position,g=g.isInterleavedBufferAttribute?g.data.count:g.count;f.drawArraysInstancedANGLE(d,0,g,e.maxInstancedCount);c.calls++;c.vertices+=g*e.maxInstancedCount;d===a.TRIANGLES&&(c.faces+=e.maxInstancedCount*g/3)}}}}function tf(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];var c;switch(b.type){case "DirectionalLight":c=
13054 {direction:new q,color:new N,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "SpotLight":c={position:new q,direction:new q,color:new N,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "PointLight":c={position:new q,color:new N,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "HemisphereLight":c={direction:new q,skyColor:new N,groundColor:new N};break;case "RectAreaLight":c=
13055 {color:new N,position:new q,halfWidth:new q,halfHeight:new q}}return a[b.id]=c}}}function uf(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Ae(a,b,c){var d=a.createShader(b);a.shaderSource(d,c);a.compileShader(d);!1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),
13056 uf(c));return d}function Be(a){switch(a){case 3E3:return["Linear","( value )"];case 3001:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+a);}}function Ld(a,b){var c=Be(b);return"vec4 "+a+"( vec4 value ) { return "+c[0]+"ToLinear"+c[1]+"; }"}function vf(a,
13057 b){var c=Be(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+c[0]+c[1]+"; }"}function wf(a,b){var c;switch(b){case 1:c="Linear";break;case 2:c="Reinhard";break;case 3:c="Uncharted2";break;case 4:c="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+b);}return"vec3 "+a+"( vec3 color ) { return "+c+"ToneMapping( color ); }"}function xf(a,b,c){a=a||{};return[a.derivatives||b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":
13058 "",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(xc).join("\n")}function yf(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function xc(a){return""!==a}function Ce(a,b){return a.replace(/NUM_DIR_LIGHTS/g,
13059 b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,b.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function Md(a){return a.replace(/#include +<([\w\d.]+)>/g,function(a,c){var d=Z[c];if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Md(d)})}function De(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c<
13060 parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function zf(a,b,c,d){var e=a.context,f=c.extensions,g=c.defines,h=c.__webglShader.vertexShader,k=c.__webglShader.fragmentShader,m="SHADOWMAP_TYPE_BASIC";1===d.shadowMapType?m="SHADOWMAP_TYPE_PCF":2===d.shadowMapType&&(m="SHADOWMAP_TYPE_PCF_SOFT");var x="ENVMAP_TYPE_CUBE",p="ENVMAP_MODE_REFLECTION",n="ENVMAP_BLENDING_MULTIPLY";if(d.envMap){switch(c.envMap.mapping){case 301:case 302:x="ENVMAP_TYPE_CUBE";break;case 306:case 307:x="ENVMAP_TYPE_CUBE_UV";
13061 break;case 303:case 304:x="ENVMAP_TYPE_EQUIREC";break;case 305:x="ENVMAP_TYPE_SPHERE"}switch(c.envMap.mapping){case 302:case 304:p="ENVMAP_MODE_REFRACTION"}switch(c.combine){case 0:n="ENVMAP_BLENDING_MULTIPLY";break;case 1:n="ENVMAP_BLENDING_MIX";break;case 2:n="ENVMAP_BLENDING_ADD"}}var r=0<a.gammaFactor?a.gammaFactor:1,f=xf(f,d,a.extensions),l=yf(g),u=e.createProgram();c.isRawShaderMaterial?(g=[l,"\n"].filter(xc).join("\n"),m=[f,l,"\n"].filter(xc).join("\n")):(g=["precision "+d.precision+" float;",
13062 "precision "+d.precision+" int;","#define SHADER_NAME "+c.__webglShader.name,l,d.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+r,"#define MAX_BONES "+d.maxBones,d.map?"#define USE_MAP":"",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+p:"",d.lightMap?"#define USE_LIGHTMAP":"",d.aoMap?"#define USE_AOMAP":"",d.emissiveMap?"#define USE_EMISSIVEMAP":"",d.bumpMap?"#define USE_BUMPMAP":"",d.normalMap?"#define USE_NORMALMAP":"",d.displacementMap&&d.supportsVertexTextures?
13063 "#define USE_DISPLACEMENTMAP":"",d.specularMap?"#define USE_SPECULARMAP":"",d.roughnessMap?"#define USE_ROUGHNESSMAP":"",d.metalnessMap?"#define USE_METALNESSMAP":"",d.alphaMap?"#define USE_ALPHAMAP":"",d.vertexColors?"#define USE_COLOR":"",d.flatShading?"#define FLAT_SHADED":"",d.skinning?"#define USE_SKINNING":"",d.useVertexTexture?"#define BONE_TEXTURE":"",d.morphTargets?"#define USE_MORPHTARGETS":"",d.morphNormals&&!1===d.flatShading?"#define USE_MORPHNORMALS":"",d.doubleSided?"#define DOUBLE_SIDED":
13064 "",d.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+d.numClippingPlanes,d.shadowMapEnabled?"#define USE_SHADOWMAP":"",d.shadowMapEnabled?"#define "+m:"",d.sizeAttenuation?"#define USE_SIZEATTENUATION":"",d.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",d.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;",
13065 "uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;",
13066 "\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(xc).join("\n"),m=[f,"precision "+d.precision+" float;","precision "+d.precision+" int;","#define SHADER_NAME "+c.__webglShader.name,l,d.alphaTest?"#define ALPHATEST "+d.alphaTest:"","#define GAMMA_FACTOR "+r,d.useFog&&d.fog?"#define USE_FOG":"",d.useFog&&d.fogExp?"#define FOG_EXP2":
13067 "",d.map?"#define USE_MAP":"",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+x:"",d.envMap?"#define "+p:"",d.envMap?"#define "+n:"",d.lightMap?"#define USE_LIGHTMAP":"",d.aoMap?"#define USE_AOMAP":"",d.emissiveMap?"#define USE_EMISSIVEMAP":"",d.bumpMap?"#define USE_BUMPMAP":"",d.normalMap?"#define USE_NORMALMAP":"",d.specularMap?"#define USE_SPECULARMAP":"",d.roughnessMap?"#define USE_ROUGHNESSMAP":"",d.metalnessMap?"#define USE_METALNESSMAP":"",d.alphaMap?"#define USE_ALPHAMAP":"",d.vertexColors?
13068 "#define USE_COLOR":"",d.gradientMap?"#define USE_GRADIENTMAP":"",d.flatShading?"#define FLAT_SHADED":"",d.doubleSided?"#define DOUBLE_SIDED":"",d.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+d.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+(d.numClippingPlanes-d.numClipIntersection),d.shadowMapEnabled?"#define USE_SHADOWMAP":"",d.shadowMapEnabled?"#define "+m:"",d.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",d.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":
13069 "",d.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",d.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",d.envMap&&a.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==d.toneMapping?"#define TONE_MAPPING":"",0!==d.toneMapping?Z.tonemapping_pars_fragment:"",0!==d.toneMapping?wf("toneMapping",d.toneMapping):"",d.outputEncoding||d.mapEncoding||d.envMapEncoding||d.emissiveMapEncoding?
13070 Z.encodings_pars_fragment:"",d.mapEncoding?Ld("mapTexelToLinear",d.mapEncoding):"",d.envMapEncoding?Ld("envMapTexelToLinear",d.envMapEncoding):"",d.emissiveMapEncoding?Ld("emissiveMapTexelToLinear",d.emissiveMapEncoding):"",d.outputEncoding?vf("linearToOutputTexel",d.outputEncoding):"",d.depthPacking?"#define DEPTH_PACKING "+c.depthPacking:"","\n"].filter(xc).join("\n"));h=Md(h,d);h=Ce(h,d);k=Md(k,d);k=Ce(k,d);c.isShaderMaterial||(h=De(h),k=De(k));k=m+k;h=Ae(e,e.VERTEX_SHADER,g+h);k=Ae(e,e.FRAGMENT_SHADER,
13071 k);e.attachShader(u,h);e.attachShader(u,k);void 0!==c.index0AttributeName?e.bindAttribLocation(u,0,c.index0AttributeName):!0===d.morphTargets&&e.bindAttribLocation(u,0,"position");e.linkProgram(u);d=e.getProgramInfoLog(u);x=e.getShaderInfoLog(h);p=e.getShaderInfoLog(k);r=n=!0;if(!1===e.getProgramParameter(u,e.LINK_STATUS))n=!1,console.error("THREE.WebGLProgram: shader error: ",e.getError(),"gl.VALIDATE_STATUS",e.getProgramParameter(u,e.VALIDATE_STATUS),"gl.getProgramInfoLog",d,x,p);else if(""!==d)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",
13072 d);else if(""===x||""===p)r=!1;r&&(this.diagnostics={runnable:n,material:c,programLog:d,vertexShader:{log:x,prefix:g},fragmentShader:{log:p,prefix:m}});e.deleteShader(h);e.deleteShader(k);var q;this.getUniforms=function(){void 0===q&&(q=new $a(e,u,a));return q};var t;this.getAttributes=function(){if(void 0===t){for(var a={},b=e.getProgramParameter(u,e.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=e.getActiveAttrib(u,c).name;a[d]=e.getAttribLocation(u,d)}t=a}return t};this.destroy=function(){e.deleteProgram(u);
13073 this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=Af++;this.code=b;this.usedTimes=1;this.program=u;this.vertexShader=h;this.fragmentShader=k;return this}function Bf(a,b){function c(a,b){var c;a?a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&
13074 (console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=a.texture.encoding):c=3E3;3E3===c&&b&&(c=3007);return c}var d=[],e={MeshDepthMaterial:"depth",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points"},
13075 f="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap displacementMap specularMap roughnessMap metalnessMap gradientMap alphaMap combine vertexColors fog useFog fogExp flatShading sizeAttenuation logarithmicDepthBuffer skinning maxBones useVertexTexture morphTargets morphNormals maxMorphTargets maxMorphNormals premultipliedAlpha numDirLights numPointLights numSpotLights numHemiLights numRectAreaLights shadowMapEnabled shadowMapType toneMapping physicallyCorrectLights alphaTest doubleSided flipSided numClippingPlanes numClipIntersection depthPacking".split(" ");
13076 this.getParameters=function(d,f,k,m,x,p){var n=e[d.type],r;b.floatVertexTextures&&p&&p.skeleton&&p.skeleton.useVertexTexture?r=1024:(r=Math.floor((b.maxVertexUniforms-20)/4),void 0!==p&&p&&p.isSkinnedMesh&&(r=Math.min(p.skeleton.bones.length,r),r<p.skeleton.bones.length&&console.warn("WebGLRenderer: too many bones - "+p.skeleton.bones.length+", this GPU supports just "+r+" (try OpenGL instead of ANGLE)")));var l=a.getPrecision();null!==d.precision&&(l=b.getMaxPrecision(d.precision),l!==d.precision&&
13077 console.warn("THREE.WebGLProgram.getParameters:",d.precision,"not supported, using",l,"instead."));var u=a.getCurrentRenderTarget();return{shaderID:n,precision:l,supportsVertexTextures:b.vertexTextures,outputEncoding:c(u?u.texture:null,a.gammaOutput),map:!!d.map,mapEncoding:c(d.map,a.gammaInput),envMap:!!d.envMap,envMapMode:d.envMap&&d.envMap.mapping,envMapEncoding:c(d.envMap,a.gammaInput),envMapCubeUV:!!d.envMap&&(306===d.envMap.mapping||307===d.envMap.mapping),lightMap:!!d.lightMap,aoMap:!!d.aoMap,
13078 emissiveMap:!!d.emissiveMap,emissiveMapEncoding:c(d.emissiveMap,a.gammaInput),bumpMap:!!d.bumpMap,normalMap:!!d.normalMap,displacementMap:!!d.displacementMap,roughnessMap:!!d.roughnessMap,metalnessMap:!!d.metalnessMap,specularMap:!!d.specularMap,alphaMap:!!d.alphaMap,gradientMap:!!d.gradientMap,combine:d.combine,vertexColors:d.vertexColors,fog:!!k,useFog:d.fog,fogExp:k&&k.isFogExp2,flatShading:1===d.shading,sizeAttenuation:d.sizeAttenuation,logarithmicDepthBuffer:b.logarithmicDepthBuffer,skinning:d.skinning,
13079 maxBones:r,useVertexTexture:b.floatVertexTextures&&p&&p.skeleton&&p.skeleton.useVertexTexture,morphTargets:d.morphTargets,morphNormals:d.morphNormals,maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:f.directional.length,numPointLights:f.point.length,numSpotLights:f.spot.length,numRectAreaLights:f.rectArea.length,numHemiLights:f.hemi.length,numClippingPlanes:m,numClipIntersection:x,shadowMapEnabled:a.shadowMap.enabled&&p.receiveShadow&&0<f.shadows.length,shadowMapType:a.shadowMap.type,
13080 toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:d.premultipliedAlpha,alphaTest:d.alphaTest,doubleSided:2===d.side,flipSided:1===d.side,depthPacking:void 0!==d.depthPacking?d.depthPacking:!1}};this.getProgramCode=function(a,b){var c=[];b.shaderID?c.push(b.shaderID):(c.push(a.fragmentShader),c.push(a.vertexShader));if(void 0!==a.defines)for(var d in a.defines)c.push(d),c.push(a.defines[d]);for(d=0;d<f.length;d++)c.push(b[f[d]]);return c.join()};this.acquireProgram=
13081 function(b,c,e){for(var f,x=0,p=d.length;x<p;x++){var n=d[x];if(n.code===e){f=n;++f.usedTimes;break}}void 0===f&&(f=new zf(a,e,b,c),d.push(f));return f};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=d.indexOf(a);d[b]=d[d.length-1];d.pop();a.destroy()}};this.programs=d}function Cf(a,b,c){function d(a){var h=a.target;a=f[h.id];null!==a.index&&e(a.index);var k=a.attributes,m;for(m in k)e(k[m]);h.removeEventListener("dispose",d);delete f[h.id];m=b.get(h);m.wireframe&&e(m.wireframe);b["delete"](h);
13082 h=b.get(a);h.wireframe&&e(h.wireframe);b["delete"](a);c.memory.geometries--}function e(c){var d;d=c.isInterleavedBufferAttribute?b.get(c.data).__webglBuffer:b.get(c).__webglBuffer;void 0!==d&&(a.deleteBuffer(d),c.isInterleavedBufferAttribute?b["delete"](c.data):b["delete"](c))}var f={};return{get:function(a){var b=a.geometry;if(void 0!==f[b.id])return f[b.id];b.addEventListener("dispose",d);var e;b.isBufferGeometry?e=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new D).setFromObject(a)),
13083 e=b._bufferGeometry);f[b.id]=e;c.memory.geometries++;return e}}}function Df(a,b,c){function d(c,d){var e=c.isInterleavedBufferAttribute?c.data:c,k=b.get(e);if(void 0===k.__webglBuffer){k.__webglBuffer=a.createBuffer();a.bindBuffer(d,k.__webglBuffer);a.bufferData(d,e.array,e.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW);var m=a.FLOAT,x=e.array;x instanceof Float32Array?m=a.FLOAT:x instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):x instanceof Uint16Array?m=a.UNSIGNED_SHORT:
13084 x instanceof Int16Array?m=a.SHORT:x instanceof Uint32Array?m=a.UNSIGNED_INT:x instanceof Int32Array?m=a.INT:x instanceof Int8Array?m=a.BYTE:x instanceof Uint8Array&&(m=a.UNSIGNED_BYTE);k.bytesPerElement=x.BYTES_PER_ELEMENT;k.type=m;k.version=e.version;e.onUploadCallback()}else k.version!==e.version&&(a.bindBuffer(d,k.__webglBuffer),!1===e.dynamic?a.bufferData(d,e.array,a.STATIC_DRAW):-1===e.updateRange.count?a.bufferSubData(d,0,e.array):0===e.updateRange.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):
13085 (a.bufferSubData(d,e.updateRange.offset*e.array.BYTES_PER_ELEMENT,e.array.subarray(e.updateRange.offset,e.updateRange.offset+e.updateRange.count)),e.updateRange.count=0),k.version=e.version)}var e=new Cf(a,b,c);return{getAttributeBuffer:function(a){return a.isInterleavedBufferAttribute?b.get(a.data).__webglBuffer:b.get(a).__webglBuffer},getAttributeProperties:function(a){return a.isInterleavedBufferAttribute?b.get(a.data):b.get(a)},getWireframeAttribute:function(c){var e=b.get(c);if(void 0!==e.wireframe)return e.wireframe;
13086 var h=[],k=c.index,m=c.attributes;c=m.position;if(null!==k)for(var k=k.array,m=0,x=k.length;m<x;m+=3){var p=k[m+0],n=k[m+1],r=k[m+2];h.push(p,n,n,r,r,p)}else for(k=m.position.array,m=0,x=k.length/3-1;m<x;m+=3)p=m+0,n=m+1,r=m+2,h.push(p,n,n,r,r,p);h=new y(new (65535<c.count?Uint32Array:Uint16Array)(h),1);d(h,a.ELEMENT_ARRAY_BUFFER);return e.wireframe=h},update:function(b){var c=e.get(b);b.geometry.isGeometry&&c.updateFromObject(b);b=c.index;var h=c.attributes;null!==b&&d(b,a.ELEMENT_ARRAY_BUFFER);
13087 for(var k in h)d(h[k],a.ARRAY_BUFFER);b=c.morphAttributes;for(k in b)for(var h=b[k],m=0,x=h.length;m<x;m++)d(h[m],a.ARRAY_BUFFER);return c}}}function Ef(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+
13088 a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return Q.isPowerOfTwo(a.width)&&Q.isPowerOfTwo(a.height)}function m(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function x(b){b=b.target;b.removeEventListener("dispose",x);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d["delete"](b)}q.textures--}function p(b){b=b.target;
13089 b.removeEventListener("dispose",p);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d["delete"](b.texture);d["delete"](b)}q.textures--}function n(b,
13090 g){var m=d.get(b);if(0<b.version&&m.__version!==b.version){var n=b.image;if(void 0===n)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===n.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b);else{void 0===m.__webglInit&&(m.__webglInit=!0,b.addEventListener("dispose",x),m.__webglTexture=a.createTexture(),q.textures++);c.activeTexture(a.TEXTURE0+g);c.bindTexture(a.TEXTURE_2D,m.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,
13091 b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var p=h(b.image,e.maxTextureSize);if((1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(p))if(n=p,n instanceof HTMLImageElement||n instanceof HTMLCanvasElement){var l=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");l.width=Q.nearestPowerOfTwo(n.width);l.height=Q.nearestPowerOfTwo(n.height);l.getContext("2d").drawImage(n,0,0,
13092 l.width,l.height);console.warn("THREE.WebGLRenderer: image is not power of two ("+n.width+"x"+n.height+"). Resized to "+l.width+"x"+l.height,n);p=l}else p=n;var n=k(p),l=f(b.format),w=f(b.type);r(a.TEXTURE_2D,b,n);var u=b.mipmaps;if(b.isDepthTexture){u=a.DEPTH_COMPONENT;if(1015===b.type){if(!t)throw Error("Float Depth Texture only supported in WebGL2.0");u=a.DEPTH_COMPONENT32F}else t&&(u=a.DEPTH_COMPONENT16);1026===b.format&&u===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),
13093 b.type=1012,w=f(b.type));1027===b.format&&(u=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,w=f(b.type)));c.texImage2D(a.TEXTURE_2D,0,u,p.width,p.height,0,l,w,null)}else if(b.isDataTexture)if(0<u.length&&n){for(var J=0,ca=u.length;J<ca;J++)p=u[J],c.texImage2D(a.TEXTURE_2D,J,l,p.width,p.height,0,l,w,p.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,l,p.width,p.height,0,l,w,p.data);else if(b.isCompressedTexture)for(J=
13094 0,ca=u.length;J<ca;J++)p=u[J],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(l)?c.compressedTexImage2D(a.TEXTURE_2D,J,l,p.width,p.height,0,p.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):c.texImage2D(a.TEXTURE_2D,J,l,p.width,p.height,0,l,w,p.data);else if(0<u.length&&n){J=0;for(ca=u.length;J<ca;J++)p=u[J],c.texImage2D(a.TEXTURE_2D,J,l,l,w,p);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,l,l,
13095 w,p);b.generateMipmaps&&n&&a.generateMipmap(a.TEXTURE_2D);m.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+g);c.bindTexture(a.TEXTURE_2D,m.__webglTexture)}function r(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,f(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,
13096 a.CLAMP_TO_EDGE),1001===g.wrapS&&1001===g.wrapT||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",g),a.texParameteri(c,a.TEXTURE_MAG_FILTER,m(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,m(g.minFilter)),1003!==g.minFilter&&1006!==g.minFilter&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",g));!(h=b.get("EXT_texture_filter_anisotropic"))||
13097 1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===b.get("OES_texture_half_float_linear")||!(1<g.anisotropy||d.get(g).__currentAnisotropy)||(a.texParameterf(c,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=g.anisotropy)}function l(b,e,g,h){var k=f(e.texture.format),m=f(e.texture.type);c.texImage2D(h,0,k,e.width,e.height,0,k,m,null);a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,
13098 0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function u(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,b)):c.depthBuffer&&c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,
13099 a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var q=g.memory,t="undefined"!==typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext;this.setTexture2D=n;this.setTextureCube=function(b,g){var m=d.get(b);if(6===b.image.length)if(0<b.version&&m.__version!==b.version){m.__image__webglTextureCube||(b.addEventListener("dispose",x),m.__image__webglTextureCube=a.createTexture(),q.textures++);c.activeTexture(a.TEXTURE0+g);c.bindTexture(a.TEXTURE_CUBE_MAP,m.__image__webglTextureCube);
13100 a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);for(var n=b&&b.isCompressedTexture,p=b.image[0]&&b.image[0].isDataTexture,l=[],w=0;6>w;w++)l[w]=n||p?p?b.image[w].image:b.image[w]:h(b.image[w],e.maxCubemapSize);var u=k(l[0]),t=f(b.format),ca=f(b.type);r(a.TEXTURE_CUBE_MAP,b,u);for(w=0;6>w;w++)if(n)for(var y,C=l[w].mipmaps,D=0,O=C.length;D<O;D++)y=C[D],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(t)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,D,t,y.width,y.height,
13101 0,y.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,D,t,y.width,y.height,0,t,ca,y.data);else p?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,0,t,l[w].width,l[w].height,0,t,ca,l[w].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,0,t,t,ca,l[w]);b.generateMipmaps&&u&&a.generateMipmap(a.TEXTURE_CUBE_MAP);m.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+
13102 g),c.bindTexture(a.TEXTURE_CUBE_MAP,m.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",p);f.__webglTexture=a.createTexture();q.textures++;var g=!0===b.isWebGLRenderTargetCube,h=k(b);if(g){e.__webglFramebuffer=[];for(var m=0;6>m;m++)e.__webglFramebuffer[m]=a.createFramebuffer()}else e.__webglFramebuffer=
13103 a.createFramebuffer();if(g){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);r(a.TEXTURE_CUBE_MAP,b.texture,h);for(m=0;6>m;m++)l(e.__webglFramebuffer[m],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+m);b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),r(a.TEXTURE_2D,b.texture,h),l(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_2D),
13104 c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&
13105 b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);n(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");
13106 }else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),u(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),u(e.__webglDepthbuffer,b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture;e.generateMipmaps&&k(b)&&1003!==e.minFilter&&1006!==e.minFilter&&(b=b&&b.isWebGLRenderTargetCube?
13107 a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function Ff(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},"delete":function(b){delete a[b.uuid]},clear:function(){a={}}}}function Gf(a,b,c){function d(b,c,d){var e=new Uint8Array(4),f=a.createTexture();a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b<d;b++)a.texImage2D(c+
13108 b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function e(b){!0!==v[b]&&(a.enable(b),v[b]=!0)}function f(b){!1!==v[b]&&(a.disable(b),v[b]=!1)}function g(b,d,g,h,k,m,n,p){0!==b?e(a.BLEND):f(a.BLEND);if(b!==z||p!==ca)2===b?p?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.SRC_ALPHA,a.ONE)):3===b?p?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):
13109 (a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR)):4===b?p?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR)):p?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)),
13110 z=b,ca=p;if(5===b){k=k||d;m=m||g;n=n||h;if(d!==A||k!==K)a.blendEquationSeparate(c(d),c(k)),A=d,K=k;if(g!==I||h!==E||m!==y||n!==J)a.blendFuncSeparate(c(g),c(h),c(m),c(n)),I=g,E=h,y=m,J=n}else J=y=K=E=I=A=null}function h(a){n.setFunc(a)}function k(b){C!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),C=b)}function m(b){0!==b?(e(a.CULL_FACE),b!==D&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);D=b}function x(b){void 0===b&&(b=a.TEXTURE0+T-1);V!==b&&(a.activeTexture(b),
13111 V=b)}var p=new function(){var b=!1,c=new ga,d=null,e=new ga;return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},setClear:function(b,d,f,g,h){!0===h&&(b*=g,d*=g,f*=g);c.set(b,d,f,g);!1===e.equals(c)&&(a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1;d=null;e.set(0,0,0,1)}}},n=new function(){var b=!1,c=null,d=null,g=null;return{setTest:function(b){b?e(a.DEPTH_TEST):f(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==
13112 b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);break;case 7:a.depthFunc(a.NOTEQUAL);break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){g!==b&&(a.clearDepth(b),g=b)},reset:function(){b=!1;g=d=c=null}}},r=new function(){var b=!1,c=
13113 null,d=null,g=null,h=null,k=null,m=null,n=null,p=null;return{setTest:function(b){b?e(a.STENCIL_TEST):f(a.STENCIL_TEST)},setMask:function(d){c===d||b||(a.stencilMask(d),c=d)},setFunc:function(b,c,e){if(d!==b||g!==c||h!==e)a.stencilFunc(b,c,e),d=b,g=c,h=e},setOp:function(b,c,d){if(k!==b||m!==c||n!==d)a.stencilOp(b,c,d),k=b,m=c,n=d},setLocked:function(a){b=a},setClear:function(b){p!==b&&(a.clearStencil(b),p=b)},reset:function(){b=!1;p=n=m=k=h=g=d=c=null}}},l=a.getParameter(a.MAX_VERTEX_ATTRIBS),u=new Uint8Array(l),
13114 q=new Uint8Array(l),t=new Uint8Array(l),v={},M=null,z=null,A=null,I=null,E=null,K=null,y=null,J=null,ca=!1,C=null,D=null,G=null,O=null,P=null,R=null,T=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),l=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),H=1<=parseFloat(l),V=null,N={},L=new ga,S=new ga,Q={};Q[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);Q[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);return{buffers:{color:p,depth:n,stencil:r},init:function(){p.setClear(0,
13115 0,0,1);n.setClear(1);r.setClear(0);e(a.DEPTH_TEST);h(3);k(!1);m(1);e(a.CULL_FACE);e(a.BLEND);g(1)},initAttributes:function(){for(var a=0,b=u.length;a<b;a++)u[a]=0},enableAttribute:function(c){u[c]=1;0===q[c]&&(a.enableVertexAttribArray(c),q[c]=1);0!==t[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),t[c]=0)},enableAttributeAndDivisor:function(b,c,d){u[b]=1;0===q[b]&&(a.enableVertexAttribArray(b),q[b]=1);t[b]!==c&&(d.vertexAttribDivisorANGLE(b,c),t[b]=c)},disableUnusedAttributes:function(){for(var b=
13116 0,c=q.length;b!==c;++b)q[b]!==u[b]&&(a.disableVertexAttribArray(b),q[b]=0)},enable:e,disable:f,getCompressedTextureFormats:function(){if(null===M&&(M=[],b.get("WEBGL_compressed_texture_pvrtc")||b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)M.push(c[d]);return M},setBlending:g,setColorWrite:function(a){p.setMask(a)},setDepthTest:function(a){n.setTest(a)},setDepthWrite:function(a){n.setMask(a)},
13117 setDepthFunc:h,setStencilTest:function(a){r.setTest(a)},setStencilWrite:function(a){r.setMask(a)},setStencilFunc:function(a,b,c){r.setFunc(a,b,c)},setStencilOp:function(a,b,c){r.setOp(a,b,c)},setFlipSided:k,setCullFace:m,setLineWidth:function(b){b!==G&&(H&&a.lineWidth(b),G=b)},setPolygonOffset:function(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),O!==c||P!==d)a.polygonOffset(c,d),O=c,P=d}else f(a.POLYGON_OFFSET_FILL)},getScissorTest:function(){return R},setScissorTest:function(b){(R=b)?e(a.SCISSOR_TEST):
13118 f(a.SCISSOR_TEST)},activeTexture:x,bindTexture:function(b,c){null===V&&x();var d=N[V];void 0===d&&(d={type:void 0,texture:void 0},N[V]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||Q[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,arguments)}catch(b){console.error(b)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(b){console.error(b)}},scissor:function(b){!1===L.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),L.copy(b))},viewport:function(b){!1===
13119 S.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),S.copy(b))},reset:function(){for(var b=0;b<q.length;b++)1===q[b]&&(a.disableVertexAttribArray(b),q[b]=0);v={};V=M=null;N={};D=C=z=null;p.reset();n.reset();r.reset()}}}function Hf(a,b,c){function d(b){if("highp"===b){if(0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.HIGH_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision)return"highp";b="mediump"}return"mediump"===b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&
13120 0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.MEDIUM_FLOAT).precision?"mediump":"lowp"}var e,f=void 0!==c.precision?c.precision:"highp",g=d(f);g!==f&&(console.warn("THREE.WebGLRenderer:",f,"not supported, using",g,"instead."),f=g);c=!0===c.logarithmicDepthBuffer&&!!b.get("EXT_frag_depth");var g=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),h=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),k=a.getParameter(a.MAX_TEXTURE_SIZE),m=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),x=a.getParameter(a.MAX_VERTEX_ATTRIBS),
13121 p=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),n=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<h,u=!!b.get("OES_texture_float");return{getMaxAnisotropy:function(){if(void 0!==e)return e;var c=b.get("EXT_texture_filter_anisotropic");return e=null!==c?a.getParameter(c.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0},getMaxPrecision:d,precision:f,logarithmicDepthBuffer:c,maxTextures:g,maxVertexTextures:h,maxTextureSize:k,maxCubemapSize:m,maxAttributes:x,maxVertexUniforms:p,
13122 maxVaryings:n,maxFragmentUniforms:r,vertexTextures:l,floatFragmentTextures:u,floatVertexTextures:l&&u}}function If(a){var b={};return{get:function(c){if(void 0!==b[c])return b[c];var d;switch(c){case "WEBGL_depth_texture":d=a.getExtension("WEBGL_depth_texture")||a.getExtension("MOZ_WEBGL_depth_texture")||a.getExtension("WEBKIT_WEBGL_depth_texture");break;case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||
13123 a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case "WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case "WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");
13124 break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function Jf(){function a(){m.value!==d&&(m.value=d,m.needsUpdate=0<e);c.numPlanes=e;c.numIntersection=0}function b(a,b,d,e){var f=null!==a?a.length:0,g=null;if(0!==f){g=m.value;if(!0!==e||null===g){e=d+4*f;b=b.matrixWorldInverse;k.getNormalMatrix(b);if(null===g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+
13125 3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new ma,k=new za,m={value:null,needsUpdate:!1};this.uniform=m;this.numIntersection=this.numPlanes=0;this.init=function(a,c,g){var h=0!==a.length||c||0!==e||f;f=c;d=b(a,g,0);e=a.length;return h};this.beginShadows=function(){g=!0;b(null)};this.endShadows=function(){g=!1;a()};this.setState=function(c,h,k,r,l,u){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var q=4*k,t=l.clippingState||null;
13126 m.value=t;t=b(c,r,q,u);for(c=0;c!==q;++c)t[c]=d[c];l.clippingState=t;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Nd(a){function b(){Y.init();Y.scissor(X.copy(fa).multiplyScalar(Sa));Y.viewport(Z.copy(ia).multiplyScalar(Sa));Y.buffers.color.setClear(Ga.r,Ga.g,Ga.b,fb,K)}function c(){W=Q=null;U="";L=-1;Y.reset()}function d(a){a.preventDefault();c();b();ha.clear()}function e(a){a=a.target;a.removeEventListener("dispose",e);f(a);ha["delete"](a)}function f(a){var b=ha.get(a).program;
13127 a.program=void 0;void 0!==b&&za.releaseProgram(b)}function g(a,b){return Math.abs(b[0])-Math.abs(a[0])}function h(a,b){return a.object.renderOrder!==b.object.renderOrder?a.object.renderOrder-b.object.renderOrder:a.material.program&&b.material.program&&a.material.program!==b.material.program?a.material.program.id-b.material.program.id:a.material.id!==b.material.id?a.material.id-b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function k(a,b){return a.object.renderOrder!==b.object.renderOrder?a.object.renderOrder-
13128 b.object.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function m(a,b,c,d,e){var f;c.transparent?(d=G,f=++Na):(d=ca,f=++C);f=d[f];void 0!==f?(f.id=a.id,f.object=a,f.geometry=b,f.material=c,f.z=ba.z,f.group=e):(f={id:a.id,object:a,geometry:b,material:c,z:ba.z,group:e},d.push(f))}function x(a){if(!na.intersectsSphere(a))return!1;var b=da.numPlanes;if(0===b)return!0;var c=T.clippingPlanes,d=a.center;a=-a.radius;var e=0;do if(c[e].distanceToPoint(d)<a)return!1;while(++e!==b);return!0}function p(a,b){if(!1!==
13129 a.visible){if(0!==(a.layers.mask&b.layers.mask))if(a.isLight)J.push(a);else if(a.isSprite){var c;(c=!1===a.frustumCulled)||(oa.center.set(0,0,0),oa.radius=.7071067811865476,oa.applyMatrix4(a.matrixWorld),c=!0===x(oa));c&&P.push(a)}else if(a.isLensFlare)R.push(a);else if(a.isImmediateRenderObject)!0===T.sortObjects&&(ba.setFromMatrixPosition(a.matrixWorld),ba.applyProjection(sa)),m(a,null,a.material,ba.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),(c=!1===a.frustumCulled)||
13130 (c=a.geometry,null===c.boundingSphere&&c.computeBoundingSphere(),oa.copy(c.boundingSphere).applyMatrix4(a.matrixWorld),c=!0===x(oa)),c){var d=a.material;if(!0===d.visible)if(!0===T.sortObjects&&(ba.setFromMatrixPosition(a.matrixWorld),ba.applyProjection(sa)),c=ta.update(a),d.isMultiMaterial)for(var e=c.groups,f=d.materials,d=0,g=e.length;d<g;d++){var h=e[d],k=f[h.materialIndex];!0===k.visible&&m(a,c,k,ba.z,h)}else m(a,c,d,ba.z,null)}c=a.children;d=0;for(g=c.length;d<g;d++)p(c[d],b)}}function n(a,
13131 b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,k=g.geometry,m=void 0===d?g.material:d,g=g.group;h.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,h.matrixWorld);h.normalMatrix.getNormalMatrix(h.modelViewMatrix);h.onBeforeRender(T,b,c,k,m,g);if(h.isImmediateRenderObject){r(m);var n=l(c,b.fog,m,h);U="";h.render(function(a){T.renderBufferImmediate(a,n,m)})}else T.renderBufferDirect(c,b.fog,k,m,h,g);h.onAfterRender(T,b,c,k,m,g)}}function r(a){2===a.side?Y.disable(B.CULL_FACE):Y.enable(B.CULL_FACE);
13132 Y.setFlipSided(1===a.side);!0===a.transparent?Y.setBlending(a.blending,a.blendEquation,a.blendSrc,a.blendDst,a.blendEquationAlpha,a.blendSrcAlpha,a.blendDstAlpha,a.premultipliedAlpha):Y.setBlending(0);Y.setDepthFunc(a.depthFunc);Y.setDepthTest(a.depthTest);Y.setDepthWrite(a.depthWrite);Y.setColorWrite(a.colorWrite);Y.setPolygonOffset(a.polygonOffset,a.polygonOffsetFactor,a.polygonOffsetUnits)}function l(a,b,c,d){ea=0;var g=ha.get(c);pa&&(ua||a!==W)&&da.setState(c.clippingPlanes,c.clipIntersection,
13133 c.clipShadows,a,g,a===W&&c.id===L);!1===c.needsUpdate&&(void 0===g.program?c.needsUpdate=!0:c.fog&&g.fog!==b?c.needsUpdate=!0:c.lights&&g.lightsHash!==aa.hash?c.needsUpdate=!0:void 0===g.numClippingPlanes||g.numClippingPlanes===da.numPlanes&&g.numIntersection===da.numIntersection||(c.needsUpdate=!0));if(c.needsUpdate){a:{var h=ha.get(c),k=za.getParameters(c,aa,b,da.numPlanes,da.numIntersection,d),m=za.getProgramCode(c,k),n=h.program,p=!0;if(void 0===n)c.addEventListener("dispose",e);else if(n.code!==
13134 m)f(c);else if(void 0!==k.shaderID)break a;else p=!1;p&&(k.shaderID?(n=Gb[k.shaderID],h.__webglShader={name:c.type,uniforms:Ja.clone(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader}):h.__webglShader={name:c.type,uniforms:c.uniforms,vertexShader:c.vertexShader,fragmentShader:c.fragmentShader},c.__webglShader=h.__webglShader,n=za.acquireProgram(c,k,m),h.program=n,c.program=n);k=n.getAttributes();if(c.morphTargets)for(m=c.numSupportedMorphTargets=0;m<T.maxMorphTargets;m++)0<=
13135 k["morphTarget"+m]&&c.numSupportedMorphTargets++;if(c.morphNormals)for(m=c.numSupportedMorphNormals=0;m<T.maxMorphNormals;m++)0<=k["morphNormal"+m]&&c.numSupportedMorphNormals++;k=h.__webglShader.uniforms;if(!c.isShaderMaterial&&!c.isRawShaderMaterial||!0===c.clipping)h.numClippingPlanes=da.numPlanes,h.numIntersection=da.numIntersection,k.clippingPlanes=da.uniform;h.fog=b;h.lightsHash=aa.hash;c.lights&&(k.ambientLightColor.value=aa.ambient,k.directionalLights.value=aa.directional,k.spotLights.value=
13136 aa.spot,k.rectAreaLights.value=aa.rectArea,k.pointLights.value=aa.point,k.hemisphereLights.value=aa.hemi,k.directionalShadowMap.value=aa.directionalShadowMap,k.directionalShadowMatrix.value=aa.directionalShadowMatrix,k.spotShadowMap.value=aa.spotShadowMap,k.spotShadowMatrix.value=aa.spotShadowMatrix,k.pointShadowMap.value=aa.pointShadowMap,k.pointShadowMatrix.value=aa.pointShadowMatrix);m=h.program.getUniforms();k=$a.seqWithValue(m.seq,k);h.uniformsList=k}c.needsUpdate=!1}var x=!1,p=n=!1,h=g.program,
13137 k=h.getUniforms(),m=g.__webglShader.uniforms;h.id!==Q&&(B.useProgram(h.program),Q=h.id,p=n=x=!0);c.id!==L&&(L=c.id,n=!0);if(x||a!==W){k.set(B,a,"projectionMatrix");ma.logarithmicDepthBuffer&&k.setValue(B,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));a!==W&&(W=a,p=n=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)x=k.map.cameraPosition,void 0!==x&&x.setValue(B,ba.setFromMatrixPosition(a.matrixWorld));(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||
13138 c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&k.setValue(B,"viewMatrix",a.matrixWorldInverse);k.set(B,T,"toneMappingExposure");k.set(B,T,"toneMappingWhitePoint")}c.skinning&&(k.setOptional(B,d,"bindMatrix"),k.setOptional(B,d,"bindMatrixInverse"),a=d.skeleton)&&(ma.floatVertexTextures&&a.useVertexTexture?(k.set(B,a,"boneTexture"),k.set(B,a,"boneTextureWidth"),k.set(B,a,"boneTextureHeight")):k.setOptional(B,a,"boneMatrices"));if(n){c.lights&&(a=p,m.ambientLightColor.needsUpdate=a,m.directionalLights.needsUpdate=
13139 a,m.pointLights.needsUpdate=a,m.spotLights.needsUpdate=a,m.rectAreaLights.needsUpdate=a,m.hemisphereLights.needsUpdate=a);b&&c.fog&&(m.fogColor.value=b.color,b.isFog?(m.fogNear.value=b.near,m.fogFar.value=b.far):b.isFogExp2&&(m.fogDensity.value=b.density));if(c.isMeshBasicMaterial||c.isMeshLambertMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.isMeshNormalMaterial||c.isMeshDepthMaterial){m.opacity.value=c.opacity;m.diffuse.value=c.color;c.emissive&&m.emissive.value.copy(c.emissive).multiplyScalar(c.emissiveIntensity);
13140 m.map.value=c.map;m.specularMap.value=c.specularMap;m.alphaMap.value=c.alphaMap;c.lightMap&&(m.lightMap.value=c.lightMap,m.lightMapIntensity.value=c.lightMapIntensity);c.aoMap&&(m.aoMap.value=c.aoMap,m.aoMapIntensity.value=c.aoMapIntensity);var r;c.map?r=c.map:c.specularMap?r=c.specularMap:c.displacementMap?r=c.displacementMap:c.normalMap?r=c.normalMap:c.bumpMap?r=c.bumpMap:c.roughnessMap?r=c.roughnessMap:c.metalnessMap?r=c.metalnessMap:c.alphaMap?r=c.alphaMap:c.emissiveMap&&(r=c.emissiveMap);void 0!==
13141 r&&(r.isWebGLRenderTarget&&(r=r.texture),b=r.offset,r=r.repeat,m.offsetRepeat.value.set(b.x,b.y,r.x,r.y));m.envMap.value=c.envMap;m.flipEnvMap.value=c.envMap&&c.envMap.isCubeTexture?-1:1;m.reflectivity.value=c.reflectivity;m.refractionRatio.value=c.refractionRatio}c.isLineBasicMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity):c.isLineDashedMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity,m.dashSize.value=c.dashSize,m.totalSize.value=c.dashSize+c.gapSize,m.scale.value=c.scale):
13142 c.isPointsMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity,m.size.value=c.size*Sa,m.scale.value=.5*yc,m.map.value=c.map,null!==c.map&&(r=c.map.offset,c=c.map.repeat,m.offsetRepeat.value.set(r.x,r.y,c.x,c.y))):c.isMeshLambertMaterial?c.emissiveMap&&(m.emissiveMap.value=c.emissiveMap):c.isMeshToonMaterial?(u(m,c),c.gradientMap&&(m.gradientMap.value=c.gradientMap)):c.isMeshPhongMaterial?u(m,c):c.isMeshPhysicalMaterial?(m.clearCoat.value=c.clearCoat,m.clearCoatRoughness.value=c.clearCoatRoughness,
13143 F(m,c)):c.isMeshStandardMaterial?F(m,c):c.isMeshDepthMaterial?c.displacementMap&&(m.displacementMap.value=c.displacementMap,m.displacementScale.value=c.displacementScale,m.displacementBias.value=c.displacementBias):c.isMeshNormalMaterial&&(c.bumpMap&&(m.bumpMap.value=c.bumpMap,m.bumpScale.value=c.bumpScale),c.normalMap&&(m.normalMap.value=c.normalMap,m.normalScale.value.copy(c.normalScale)),c.displacementMap&&(m.displacementMap.value=c.displacementMap,m.displacementScale.value=c.displacementScale,
13144 m.displacementBias.value=c.displacementBias));void 0!==m.ltcMat&&(m.ltcMat.value=THREE.UniformsLib.LTC_MAT_TEXTURE);void 0!==m.ltcMag&&(m.ltcMag.value=THREE.UniformsLib.LTC_MAG_TEXTURE);$a.upload(B,g.uniformsList,m,T)}k.set(B,d,"modelViewMatrix");k.set(B,d,"normalMatrix");k.setValue(B,"modelMatrix",d.matrixWorld);return h}function u(a,b){a.specular.value=b.specular;a.shininess.value=Math.max(b.shininess,1E-4);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,
13145 a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function F(a,b){a.roughness.value=b.roughness;a.metalness.value=b.metalness;b.roughnessMap&&(a.roughnessMap.value=b.roughnessMap);b.metalnessMap&&(a.metalnessMap.value=b.metalnessMap);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);
13146 b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}function t(a){var b;if(1E3===a)return B.REPEAT;if(1001===a)return B.CLAMP_TO_EDGE;if(1002===a)return B.MIRRORED_REPEAT;if(1003===a)return B.NEAREST;
13147 if(1004===a)return B.NEAREST_MIPMAP_NEAREST;if(1005===a)return B.NEAREST_MIPMAP_LINEAR;if(1006===a)return B.LINEAR;if(1007===a)return B.LINEAR_MIPMAP_NEAREST;if(1008===a)return B.LINEAR_MIPMAP_LINEAR;if(1009===a)return B.UNSIGNED_BYTE;if(1017===a)return B.UNSIGNED_SHORT_4_4_4_4;if(1018===a)return B.UNSIGNED_SHORT_5_5_5_1;if(1019===a)return B.UNSIGNED_SHORT_5_6_5;if(1010===a)return B.BYTE;if(1011===a)return B.SHORT;if(1012===a)return B.UNSIGNED_SHORT;if(1013===a)return B.INT;if(1014===a)return B.UNSIGNED_INT;
13148 if(1015===a)return B.FLOAT;if(1016===a&&(b=ja.get("OES_texture_half_float"),null!==b))return b.HALF_FLOAT_OES;if(1021===a)return B.ALPHA;if(1022===a)return B.RGB;if(1023===a)return B.RGBA;if(1024===a)return B.LUMINANCE;if(1025===a)return B.LUMINANCE_ALPHA;if(1026===a)return B.DEPTH_COMPONENT;if(1027===a)return B.DEPTH_STENCIL;if(100===a)return B.FUNC_ADD;if(101===a)return B.FUNC_SUBTRACT;if(102===a)return B.FUNC_REVERSE_SUBTRACT;if(200===a)return B.ZERO;if(201===a)return B.ONE;if(202===a)return B.SRC_COLOR;
13149 if(203===a)return B.ONE_MINUS_SRC_COLOR;if(204===a)return B.SRC_ALPHA;if(205===a)return B.ONE_MINUS_SRC_ALPHA;if(206===a)return B.DST_ALPHA;if(207===a)return B.ONE_MINUS_DST_ALPHA;if(208===a)return B.DST_COLOR;if(209===a)return B.ONE_MINUS_DST_COLOR;if(210===a)return B.SRC_ALPHA_SATURATE;if(2001===a||2002===a||2003===a||2004===a)if(b=ja.get("WEBGL_compressed_texture_s3tc"),null!==b){if(2001===a)return b.COMPRESSED_RGB_S3TC_DXT1_EXT;if(2002===a)return b.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===a)return b.COMPRESSED_RGBA_S3TC_DXT3_EXT;
13150 if(2004===a)return b.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===a||2101===a||2102===a||2103===a)if(b=ja.get("WEBGL_compressed_texture_pvrtc"),null!==b){if(2100===a)return b.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(2101===a)return b.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(2102===a)return b.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(2103===a)return b.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(2151===a&&(b=ja.get("WEBGL_compressed_texture_etc1"),null!==b))return b.COMPRESSED_RGB_ETC1_WEBGL;if(103===a||104===a)if(b=ja.get("EXT_blend_minmax"),
13151 null!==b){if(103===a)return b.MIN_EXT;if(104===a)return b.MAX_EXT}return 1020===a&&(b=ja.get("WEBGL_depth_texture"),null!==b)?b.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer","83");a=a||{};var v=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),M=void 0!==a.context?a.context:null,z=void 0!==a.alpha?a.alpha:!1,A=void 0!==a.depth?a.depth:!0,I=void 0!==a.stencil?a.stencil:!0,E=void 0!==a.antialias?a.antialias:!1,K=void 0!==a.premultipliedAlpha?
13152 a.premultipliedAlpha:!0,y=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,J=[],ca=[],C=-1,G=[],Na=-1,O=new Float32Array(8),P=[],R=[];this.domElement=v;this.context=null;this.sortObjects=this.autoClearStencil=this.autoClearDepth=this.autoClearColor=this.autoClear=!0;this.clippingPlanes=[];this.localClippingEnabled=!1;this.gammaFactor=2;this.physicallyCorrectLights=this.gammaOutput=this.gammaInput=!1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=
13153 8;this.maxMorphNormals=4;var T=this,Q=null,V=null,S=null,L=-1,U="",W=null,X=new ga,Ta=null,Z=new ga,ea=0,Ga=new N(0),fb=0,fd=v.width,yc=v.height,Sa=1,fa=new ga(0,0,fd,yc),ka=!1,ia=new ga(0,0,fd,yc),na=new qc,da=new Jf,pa=!1,ua=!1,oa=new Fa,sa=new H,ba=new q,wa=new H,xa=new H,aa={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},qa={calls:0,
13154 vertices:0,faces:0,points:0};this.info={render:qa,memory:{geometries:0,textures:0},programs:null};var B;try{z={alpha:z,depth:A,stencil:I,antialias:E,premultipliedAlpha:K,preserveDrawingBuffer:y};B=M||v.getContext("webgl",z)||v.getContext("experimental-webgl",z);if(null===B){if(null!==v.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";throw"Error creating WebGL context.";}void 0===B.getShaderPrecisionFormat&&(B.getShaderPrecisionFormat=function(){return{rangeMin:1,
13155 rangeMax:1,precision:1}});v.addEventListener("webglcontextlost",d,!1)}catch(Kf){console.error("THREE.WebGLRenderer: "+Kf)}var ja=new If(B);ja.get("WEBGL_depth_texture");ja.get("OES_texture_float");ja.get("OES_texture_float_linear");ja.get("OES_texture_half_float");ja.get("OES_texture_half_float_linear");ja.get("OES_standard_derivatives");ja.get("ANGLE_instanced_arrays");ja.get("OES_element_index_uint")&&(D.MaxIndex=4294967296);var ma=new Hf(B,ja,a),Y=new Gf(B,ja,t),ha=new Ff,va=new Ef(B,ja,Y,ha,ma,
13156 t,this.info),ta=new Df(B,ha,this.info),za=new Bf(this,ma),Aa=new tf;this.info.programs=za.programs;var La=new sf(B,ja,qa),Ma=new rf(B,ja,qa),Oa=new Hb(-1,1,1,-1,0,1),Ca=new Ha,Ea=new Ba(new ib(2,2),new Ka({depthTest:!1,depthWrite:!1,fog:!1}));a=Gb.cube;var ya=new Ba(new hb(5,5,5),new Ia({uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1}));b();this.context=B;this.capabilities=ma;this.extensions=ja;this.properties=ha;this.state=
13157 Y;var Pa=new ye(this,aa,ta,ma);this.shadowMap=Pa;var Qa=new of(this,P),Ra=new nf(this,R);this.getContext=function(){return B};this.getContextAttributes=function(){return B.getContextAttributes()};this.forceContextLoss=function(){ja.get("WEBGL_lose_context").loseContext()};this.getMaxAnisotropy=function(){return ma.getMaxAnisotropy()};this.getPrecision=function(){return ma.precision};this.getPixelRatio=function(){return Sa};this.setPixelRatio=function(a){void 0!==a&&(Sa=a,this.setSize(ia.z,ia.w,!1))};
13158 this.getSize=function(){return{width:fd,height:yc}};this.setSize=function(a,b,c){fd=a;yc=b;v.width=a*Sa;v.height=b*Sa;!1!==c&&(v.style.width=a+"px",v.style.height=b+"px");this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){Y.viewport(ia.set(a,b,c,d))};this.setScissor=function(a,b,c,d){Y.scissor(fa.set(a,b,c,d))};this.setScissorTest=function(a){Y.setScissorTest(ka=a)};this.getClearColor=function(){return Ga};this.setClearColor=function(a,b){Ga.set(a);fb=void 0!==b?b:1;Y.buffers.color.setClear(Ga.r,
13159 Ga.g,Ga.b,fb,K)};this.getClearAlpha=function(){return fb};this.setClearAlpha=function(a){fb=a;Y.buffers.color.setClear(Ga.r,Ga.g,Ga.b,fb,K)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=B.COLOR_BUFFER_BIT;if(void 0===b||b)d|=B.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=B.STENCIL_BUFFER_BIT;B.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};this.clearDepth=function(){this.clear(!1,!0,!1)};this.clearStencil=function(){this.clear(!1,!1,!0)};this.clearTarget=function(a,b,c,d){this.setRenderTarget(a);
13160 this.clear(b,c,d)};this.resetGLState=c;this.dispose=function(){G=[];Na=-1;ca=[];C=-1;v.removeEventListener("webglcontextlost",d,!1)};this.renderBufferImmediate=function(a,b,c){Y.initAttributes();var d=ha.get(a);a.hasPositions&&!d.position&&(d.position=B.createBuffer());a.hasNormals&&!d.normal&&(d.normal=B.createBuffer());a.hasUvs&&!d.uv&&(d.uv=B.createBuffer());a.hasColors&&!d.color&&(d.color=B.createBuffer());b=b.getAttributes();a.hasPositions&&(B.bindBuffer(B.ARRAY_BUFFER,d.position),B.bufferData(B.ARRAY_BUFFER,
13161 a.positionArray,B.DYNAMIC_DRAW),Y.enableAttribute(b.position),B.vertexAttribPointer(b.position,3,B.FLOAT,!1,0,0));if(a.hasNormals){B.bindBuffer(B.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&1===c.shading)for(var e=0,f=3*a.count;e<f;e+=9){var g=a.normalArray,h=(g[e+0]+g[e+3]+g[e+6])/3,k=(g[e+1]+g[e+4]+g[e+7])/3,m=(g[e+2]+g[e+5]+g[e+8])/3;g[e+0]=h;g[e+1]=k;g[e+2]=m;g[e+3]=h;g[e+4]=k;g[e+5]=m;g[e+6]=h;g[e+7]=k;g[e+8]=m}B.bufferData(B.ARRAY_BUFFER,
13162 a.normalArray,B.DYNAMIC_DRAW);Y.enableAttribute(b.normal);B.vertexAttribPointer(b.normal,3,B.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(B.bindBuffer(B.ARRAY_BUFFER,d.uv),B.bufferData(B.ARRAY_BUFFER,a.uvArray,B.DYNAMIC_DRAW),Y.enableAttribute(b.uv),B.vertexAttribPointer(b.uv,2,B.FLOAT,!1,0,0));a.hasColors&&0!==c.vertexColors&&(B.bindBuffer(B.ARRAY_BUFFER,d.color),B.bufferData(B.ARRAY_BUFFER,a.colorArray,B.DYNAMIC_DRAW),Y.enableAttribute(b.color),B.vertexAttribPointer(b.color,3,B.FLOAT,!1,0,0));Y.disableUnusedAttributes();
13163 B.drawArrays(B.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){r(d);var h=l(a,b,d,e),k=!1;a=c.id+"_"+h.id+"_"+d.wireframe;a!==U&&(U=a,k=!0);b=e.morphTargetInfluences;if(void 0!==b){var m=[];a=0;for(var n=b.length;a<n;a++)k=b[a],m.push([k,a]);m.sort(g);8<m.length&&(m.length=8);var p=c.morphAttributes;a=0;for(n=m.length;a<n;a++)k=m[a],O[a]=k[0],0!==k[0]?(b=k[1],!0===d.morphTargets&&p.position&&c.addAttribute("morphTarget"+a,p.position[b]),!0===d.morphNormals&&p.normal&&
13164 c.addAttribute("morphNormal"+a,p.normal[b])):(!0===d.morphTargets&&c.removeAttribute("morphTarget"+a),!0===d.morphNormals&&c.removeAttribute("morphNormal"+a));a=m.length;for(b=O.length;a<b;a++)O[a]=0;h.getUniforms().setValue(B,"morphTargetInfluences",O);k=!0}b=c.index;n=c.attributes.position;m=1;!0===d.wireframe&&(b=ta.getWireframeAttribute(c),m=2);null!==b?(a=Ma,a.setIndex(b)):a=La;if(k){a:{var k=void 0,x;if(c&&c.isInstancedBufferGeometry&&(x=ja.get("ANGLE_instanced_arrays"),null===x)){console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
13165 break a}void 0===k&&(k=0);Y.initAttributes();var p=c.attributes,h=h.getAttributes(),u=d.defaultAttributeValues,q;for(q in h){var v=h[q];if(0<=v){var t=p[q];if(void 0!==t){var z=t.normalized,F=t.itemSize,I=ta.getAttributeProperties(t),E=I.__webglBuffer,M=I.type,I=I.bytesPerElement;if(t.isInterleavedBufferAttribute){var A=t.data,K=A.stride,t=t.offset;A&&A.isInstancedInterleavedBuffer?(Y.enableAttributeAndDivisor(v,A.meshPerAttribute,x),void 0===c.maxInstancedCount&&(c.maxInstancedCount=A.meshPerAttribute*
13166 A.count)):Y.enableAttribute(v);B.bindBuffer(B.ARRAY_BUFFER,E);B.vertexAttribPointer(v,F,M,z,K*I,(k*K+t)*I)}else t.isInstancedBufferAttribute?(Y.enableAttributeAndDivisor(v,t.meshPerAttribute,x),void 0===c.maxInstancedCount&&(c.maxInstancedCount=t.meshPerAttribute*t.count)):Y.enableAttribute(v),B.bindBuffer(B.ARRAY_BUFFER,E),B.vertexAttribPointer(v,F,M,z,0,k*F*I)}else if(void 0!==u&&(z=u[q],void 0!==z))switch(z.length){case 2:B.vertexAttrib2fv(v,z);break;case 3:B.vertexAttrib3fv(v,z);break;case 4:B.vertexAttrib4fv(v,
13167 z);break;default:B.vertexAttrib1fv(v,z)}}}Y.disableUnusedAttributes()}null!==b&&B.bindBuffer(B.ELEMENT_ARRAY_BUFFER,ta.getAttributeBuffer(b))}x=0;null!==b?x=b.count:void 0!==n&&(x=n.count);b=c.drawRange.start*m;n=null!==f?f.start*m:0;q=Math.max(b,n);f=Math.max(0,Math.min(x,b+c.drawRange.count*m,n+(null!==f?f.count*m:Infinity))-1-q+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)Y.setLineWidth(d.wireframeLinewidth*(null===V?Sa:1)),a.setMode(B.LINES);else switch(e.drawMode){case 0:a.setMode(B.TRIANGLES);
13168 break;case 1:a.setMode(B.TRIANGLE_STRIP);break;case 2:a.setMode(B.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),Y.setLineWidth(d*(null===V?Sa:1)),e.isLineSegments?a.setMode(B.LINES):a.setMode(B.LINE_STRIP)):e.isPoints&&a.setMode(B.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,q,f):a.render(q,f)}};this.render=function(a,b,c,d){if(void 0!==b&&!0!==b.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");else{U=
13169 "";L=-1;W=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===b.parent&&b.updateMatrixWorld();b.matrixWorldInverse.getInverse(b.matrixWorld);sa.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);na.setFromMatrix(sa);J.length=0;Na=C=-1;P.length=0;R.length=0;ua=this.localClippingEnabled;pa=da.init(this.clippingPlanes,ua,b);p(a,b);ca.length=C+1;G.length=Na+1;!0===T.sortObjects&&(ca.sort(h),G.sort(k));pa&&da.beginShadows();for(var e=J,f=0,g=0,m=e.length;g<m;g++){var x=e[g];x.castShadow&&(aa.shadows[f++]=
13170 x)}aa.shadows.length=f;Pa.render(a,b);for(var e=J,r=x=0,l=0,w,u,v,q,t=b.matrixWorldInverse,z=0,F=0,I=0,E=0,M=0,f=0,g=e.length;f<g;f++)if(m=e[f],w=m.color,u=m.intensity,v=m.distance,q=m.shadow&&m.shadow.map?m.shadow.map.texture:null,m.isAmbientLight)x+=w.r*u,r+=w.g*u,l+=w.b*u;else if(m.isDirectionalLight){var A=Aa.get(m);A.color.copy(m.color).multiplyScalar(m.intensity);A.direction.setFromMatrixPosition(m.matrixWorld);ba.setFromMatrixPosition(m.target.matrixWorld);A.direction.sub(ba);A.direction.transformDirection(t);
13171 if(A.shadow=m.castShadow)A.shadowBias=m.shadow.bias,A.shadowRadius=m.shadow.radius,A.shadowMapSize=m.shadow.mapSize;aa.directionalShadowMap[z]=q;aa.directionalShadowMatrix[z]=m.shadow.matrix;aa.directional[z++]=A}else if(m.isSpotLight){A=Aa.get(m);A.position.setFromMatrixPosition(m.matrixWorld);A.position.applyMatrix4(t);A.color.copy(w).multiplyScalar(u);A.distance=v;A.direction.setFromMatrixPosition(m.matrixWorld);ba.setFromMatrixPosition(m.target.matrixWorld);A.direction.sub(ba);A.direction.transformDirection(t);
13172 A.coneCos=Math.cos(m.angle);A.penumbraCos=Math.cos(m.angle*(1-m.penumbra));A.decay=0===m.distance?0:m.decay;if(A.shadow=m.castShadow)A.shadowBias=m.shadow.bias,A.shadowRadius=m.shadow.radius,A.shadowMapSize=m.shadow.mapSize;aa.spotShadowMap[I]=q;aa.spotShadowMatrix[I]=m.shadow.matrix;aa.spot[I++]=A}else if(m.isRectAreaLight)A=Aa.get(m),A.color.copy(w).multiplyScalar(u/(m.width*m.height)),A.position.setFromMatrixPosition(m.matrixWorld),A.position.applyMatrix4(t),xa.identity(),wa.copy(m.matrixWorld),
13173 wa.premultiply(t),xa.extractRotation(wa),A.halfWidth.set(.5*m.width,0,0),A.halfHeight.set(0,.5*m.height,0),A.halfWidth.applyMatrix4(xa),A.halfHeight.applyMatrix4(xa),aa.rectArea[E++]=A;else if(m.isPointLight){A=Aa.get(m);A.position.setFromMatrixPosition(m.matrixWorld);A.position.applyMatrix4(t);A.color.copy(m.color).multiplyScalar(m.intensity);A.distance=m.distance;A.decay=0===m.distance?0:m.decay;if(A.shadow=m.castShadow)A.shadowBias=m.shadow.bias,A.shadowRadius=m.shadow.radius,A.shadowMapSize=m.shadow.mapSize;
13174 aa.pointShadowMap[F]=q;void 0===aa.pointShadowMatrix[F]&&(aa.pointShadowMatrix[F]=new H);ba.setFromMatrixPosition(m.matrixWorld).negate();aa.pointShadowMatrix[F].identity().setPosition(ba);aa.point[F++]=A}else m.isHemisphereLight&&(A=Aa.get(m),A.direction.setFromMatrixPosition(m.matrixWorld),A.direction.transformDirection(t),A.direction.normalize(),A.skyColor.copy(m.color).multiplyScalar(u),A.groundColor.copy(m.groundColor).multiplyScalar(u),aa.hemi[M++]=A);aa.ambient[0]=x;aa.ambient[1]=r;aa.ambient[2]=
13175 l;aa.directional.length=z;aa.spot.length=I;aa.rectArea.length=E;aa.point.length=F;aa.hemi.length=M;aa.hash=z+","+F+","+I+","+E+","+M+","+aa.shadows.length;pa&&da.endShadows();qa.calls=0;qa.vertices=0;qa.faces=0;qa.points=0;void 0===c&&(c=null);this.setRenderTarget(c);e=a.background;null===e?Y.buffers.color.setClear(Ga.r,Ga.g,Ga.b,fb,K):e&&e.isColor&&(Y.buffers.color.setClear(e.r,e.g,e.b,1,K),d=!0);(this.autoClear||d)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil);e&&e.isCubeTexture?
13176 (Ca.projectionMatrix.copy(b.projectionMatrix),Ca.matrixWorld.extractRotation(b.matrixWorld),Ca.matrixWorldInverse.getInverse(Ca.matrixWorld),ya.material.uniforms.tCube.value=e,ya.modelViewMatrix.multiplyMatrices(Ca.matrixWorldInverse,ya.matrixWorld),ta.update(ya),T.renderBufferDirect(Ca,null,ya.geometry,ya.material,ya,null)):e&&e.isTexture&&(Ea.material.map=e,ta.update(Ea),T.renderBufferDirect(Oa,null,Ea.geometry,Ea.material,Ea,null));a.overrideMaterial?(d=a.overrideMaterial,n(ca,a,b,d),n(G,a,b,d)):
13177 (Y.setBlending(0),n(ca,a,b),n(G,a,b));Qa.render(a,b);Ra.render(a,b,Z);c&&va.updateRenderTargetMipmap(c);Y.setDepthTest(!0);Y.setDepthWrite(!0);Y.setColorWrite(!0)}};this.setFaceCulling=function(a,b){Y.setCullFace(a);Y.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=ea;a>=ma.maxTextures&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+ma.maxTextures);ea+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&
13178 (a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);va.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);va.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),
13179 a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?va.setTextureCube(b,c):va.setTextureCubeDynamic(b,c)}}();this.getCurrentRenderTarget=function(){return V};this.setRenderTarget=function(a){(V=a)&&void 0===ha.get(a).__webglFramebuffer&&va.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube,c;a?(c=ha.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,X.copy(a.scissor),Ta=a.scissorTest,Z.copy(a.viewport)):(c=null,X.copy(fa).multiplyScalar(Sa),Ta=
13180 ka,Z.copy(ia).multiplyScalar(Sa));S!==c&&(B.bindFramebuffer(B.FRAMEBUFFER,c),S=c);Y.scissor(X);Y.setScissorTest(Ta);Y.viewport(Z);b&&(b=ha.get(a.texture),B.framebufferTexture2D(B.FRAMEBUFFER,B.COLOR_ATTACHMENT0,B.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=function(a,b,c,d,e,f){if(!1===(a&&a.isWebGLRenderTarget))console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");else{var g=ha.get(a).__webglFramebuffer;
13181 if(g){var h=!1;g!==S&&(B.bindFramebuffer(B.FRAMEBUFFER,g),h=!0);try{var k=a.texture,m=k.format,n=k.type;1023!==m&&t(m)!==B.getParameter(B.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||t(n)===B.getParameter(B.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ja.get("OES_texture_float")||ja.get("WEBGL_color_buffer_float"))||1016===n&&ja.get("EXT_color_buffer_half_float")?B.checkFramebufferStatus(B.FRAMEBUFFER)===
13182 B.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&B.readPixels(b,c,d,e,t(m),t(n),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&B.bindFramebuffer(B.FRAMEBUFFER,S)}}}}}function Ib(a,b){this.name="";this.color=new N(a);this.density=void 0!==b?b:2.5E-4}function Jb(a,
13183 b,c){this.name="";this.color=new N(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function jb(){G.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Od(a,b,c,d,e){G.call(this);this.lensFlares=[];this.positionScreen=new q;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function kb(a){W.call(this);this.type="SpriteMaterial";this.color=new N(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}
13184 function zc(a){G.call(this);this.type="Sprite";this.material=void 0!==a?a:new kb}function Ac(){G.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function hd(a,b,c){this.useVertexTexture=void 0!==c?c:!0;this.identityMatrix=new H;a=a||[];this.bones=a.slice(0);this.useVertexTexture?(a=Math.sqrt(4*this.bones.length),a=Q.nextPowerOfTwo(Math.ceil(a)),this.boneTextureHeight=this.boneTextureWidth=a=Math.max(a,4),this.boneMatrices=new Float32Array(this.boneTextureWidth*
13185 this.boneTextureHeight*4),this.boneTexture=new db(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,1023,1015)):this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else for(console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[],b=0,a=this.bones.length;b<a;b++)this.boneInverses.push(new H)}function id(){G.call(this);this.type="Bone"}function jd(a,
13186 b,c){Ba.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new H;this.bindMatrixInverse=new H;a=[];if(this.geometry&&void 0!==this.geometry.bones){for(var d,e=0,f=this.geometry.bones.length;e<f;++e)d=this.geometry.bones[e],b=new id,a.push(b),b.name=d.name,b.position.fromArray(d.pos),b.quaternion.fromArray(d.rotq),void 0!==d.scl&&b.scale.fromArray(d.scl);e=0;for(f=this.geometry.bones.length;e<f;++e)d=this.geometry.bones[e],-1!==d.parent&&null!==d.parent&&void 0!==a[d.parent]?
13187 a[d.parent].add(a[e]):this.add(a[e])}this.normalizeSkinWeights();this.updateMatrixWorld(!0);this.bind(new hd(a,void 0,c),this.matrixWorld)}function ia(a){W.call(this);this.type="LineBasicMaterial";this.color=new N(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;this.setValues(a)}function Va(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),new fa(a,b);G.call(this);this.type="Line";this.geometry=
13188 void 0!==a?a:new D;this.material=void 0!==b?b:new ia({color:16777215*Math.random()})}function fa(a,b){Va.call(this,a,b);this.type="LineSegments"}function Oa(a){W.call(this);this.type="PointsMaterial";this.color=new N(16777215);this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Kb(a,b){G.call(this);this.type="Points";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new Oa({color:16777215*Math.random()})}function Bc(){G.call(this);this.type="Group"}
13189 function kd(a,b,c,d,e,f,g,h,k){function m(){requestAnimationFrame(m);a.readyState>=a.HAVE_CURRENT_DATA&&(x.needsUpdate=!0)}ea.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var x=this;m()}function Lb(a,b,c,d,e,f,g,h,k,m,x,p){ea.call(this,null,f,g,h,k,m,d,e,x,p);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function ld(a,b,c,d,e,f,g,h,k){ea.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Cc(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==
13190 m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===m&&(c=1012);void 0===c&&1027===m&&(c=1020);ea.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a,height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==h?h:1003;this.generateMipmaps=this.flipY=!1}function Mb(a){function b(a,b){return a-b}D.call(this);var c=[0,0],d={},e=["a","b","c"];if(a&&a.isGeometry){var f=a.vertices,g=a.faces,h=0,k=new Uint32Array(6*g.length);a=0;for(var m=
13191 g.length;a<m;a++)for(var x=g[a],p=0;3>p;p++){c[0]=x[e[p]];c[1]=x[e[(p+1)%3]];c.sort(b);var n=c.toString();void 0===d[n]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[n]=!0,h++)}c=new Float32Array(6*h);a=0;for(m=h;a<m;a++)for(p=0;2>p;p++)d=f[k[2*a+p]],h=6*a+3*p,c[h+0]=d.x,c[h+1]=d.y,c[h+2]=d.z;this.addAttribute("position",new y(c,3))}else if(a&&a.isBufferGeometry){if(null!==a.index){m=a.index.array;f=a.attributes.position;e=a.groups;h=0;0===e.length&&a.addGroup(0,m.length);k=new Uint32Array(2*m.length);g=0;for(x=
13192 e.length;g<x;++g){a=e[g];p=a.start;n=a.count;a=p;for(var r=p+n;a<r;a+=3)for(p=0;3>p;p++)c[0]=m[a+p],c[1]=m[a+(p+1)%3],c.sort(b),n=c.toString(),void 0===d[n]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[n]=!0,h++)}c=new Float32Array(6*h);a=0;for(m=h;a<m;a++)for(p=0;2>p;p++)h=6*a+3*p,d=k[2*a+p],c[h+0]=f.getX(d),c[h+1]=f.getY(d),c[h+2]=f.getZ(d)}else for(f=a.attributes.position.array,h=f.length/3,k=h/3,c=new Float32Array(6*h),a=0,m=k;a<m;a++)for(p=0;3>p;p++)h=18*a+6*p,k=9*a+3*p,c[h+0]=f[k],c[h+1]=f[k+1],c[h+2]=f[k+
13193 2],d=9*a+(p+1)%3*3,c[h+3]=f[d],c[h+4]=f[d+1],c[h+5]=f[d+2];this.addAttribute("position",new y(c,3))}}function Nb(a,b,c){D.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f,g,h,k,m,x=b+1;for(f=0;f<=c;f++)for(m=f/c,g=0;g<=b;g++)k=g/b,h=a(k,m),d.push(h.x,h.y,h.z),e.push(k,m);a=[];var p;for(f=0;f<c;f++)for(g=0;g<b;g++)h=f*x+g,k=f*x+g+1,m=(f+1)*x+g+1,p=(f+1)*x+g,a.push(h,k,p),a.push(k,m,p);this.setIndex(new (65535<a.length?Ua:Ra)(a,1));this.addAttribute("position",
13194 new X(d,3));this.addAttribute("uv",new X(e,2));this.computeVertexNormals()}function Dc(a,b,c){S.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Nb(a,b,c));this.mergeVertices()}function xa(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){var d=3*b;c.x=a[d+0];c.y=a[d+1];c.z=a[d+2]}function g(a,b,c,d){0>d&&1===a.x&&(k[b]=a.x-1);0===c.x&&0===c.z&&(k[b]=d/2/Math.PI+.5)}D.call(this);this.type="PolyhedronBufferGeometry";this.parameters=
13195 {vertices:a,indices:b,radius:c,detail:d};c=c||1;var h=[],k=[];(function(a){for(var c=new q,d=new q,g=new q,h=0;h<b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var k=c,l=d,F=g,t=Math.pow(2,a),v=[],M,z;for(M=0;M<=t;M++){v[M]=[];var A=k.clone().lerp(F,M/t),I=l.clone().lerp(F,M/t),E=t-M;for(z=0;z<=E;z++)v[M][z]=0===z&&M===t?A:A.clone().lerp(I,z/E)}for(M=0;M<t;M++)for(z=0;z<2*(t-M)-1;z++)k=Math.floor(z/2),0===z%2?(e(v[M][k+1]),e(v[M+1][k]),e(v[M][k])):(e(v[M][k+1]),e(v[M+1][k+1]),e(v[M+1][k]))}})(d||
13196 0);(function(a){for(var b=new q,c=0;c<h.length;c+=3)b.x=h[c+0],b.y=h[c+1],b.z=h[c+2],b.normalize().multiplyScalar(a),h[c+0]=b.x,h[c+1]=b.y,h[c+2]=b.z})(c);(function(){for(var a=new q,b=0;b<h.length;b+=3)a.x=h[b+0],a.y=h[b+1],a.z=h[b+2],k.push(Math.atan2(a.z,-a.x)/2/Math.PI+.5,1-(Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))/Math.PI+.5));for(var a=new q,b=new q,c=new q,d=new q,e=new C,f=new C,l=new C,F=0,t=0;F<h.length;F+=9,t+=6){a.set(h[F+0],h[F+1],h[F+2]);b.set(h[F+3],h[F+4],h[F+5]);c.set(h[F+6],h[F+
13197 7],h[F+8]);e.set(k[t+0],k[t+1]);f.set(k[t+2],k[t+3]);l.set(k[t+4],k[t+5]);d.copy(a).add(b).add(c).divideScalar(3);var v=Math.atan2(d.z,-d.x);g(e,t+0,a,v);g(f,t+2,b,v);g(l,t+4,c,v)}for(a=0;a<k.length;a+=6)b=k[a+0],c=k[a+2],d=k[a+4],e=Math.min(b,c,d),.9<Math.max(b,c,d)&&.1>e&&(.2>b&&(k[a+0]+=1),.2>c&&(k[a+2]+=1),.2>d&&(k[a+4]+=1))})();this.addAttribute("position",new X(h,3));this.addAttribute("normal",new X(h.slice(),3));this.addAttribute("uv",new X(k,2));this.normalizeNormals();this.boundingSphere=
13198 new Fa(new q,c)}function Ob(a,b){xa.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Ec(a,b){S.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ob(a,b));this.mergeVertices()}function lb(a,b){xa.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";
13199 this.parameters={radius:a,detail:b}}function Fc(a,b){S.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new lb(a,b));this.mergeVertices()}function Pb(a,b){var c=(1+Math.sqrt(5))/2;xa.call(this,[-1,c,0,1,c,0,-1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";
13200 this.parameters={radius:a,detail:b}}function Gc(a,b){S.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Pb(a,b));this.mergeVertices()}function Qb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;xa.call(this,[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,
13201 0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Hc(a,b){S.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Qb(a,b));this.mergeVertices()}function Ic(a,b,c,d){S.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,
13202 radius:c,detail:d};this.fromBufferGeometry(new xa(a,b,c,d));this.mergeVertices()}function Rb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(p=0;p<=d;p++){var x=p/d*Math.PI*2,l=Math.sin(x),x=-Math.cos(x);k.x=x*m.x+l*e.x;k.y=x*m.y+l*e.y;k.z=x*m.z+l*e.z;k.normalize();r.push(k.x,k.y,k.z);h.x=f.x+c*k.x;h.y=f.y+c*k.y;h.z=f.z+c*k.z;n.push(h.x,h.y,h.z)}}D.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};
13203 b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new q,k=new q,m=new C,x,p,n=[],r=[],l=[],u=[];for(x=0;x<b;x++)f(x);f(!1===e?b:0);for(x=0;x<=b;x++)for(p=0;p<=d;p++)m.x=x/b,m.y=p/d,l.push(m.x,m.y);(function(){for(p=1;p<=b;p++)for(x=1;x<=d;x++){var a=(d+1)*p+(x-1),c=(d+1)*p+x,e=(d+1)*(p-1)+x;u.push((d+1)*(p-1)+(x-1),a,e);u.push(a,c,e)}})();this.setIndex(new (65535<u.length?Ua:Ra)(u,1));this.addAttribute("position",
13204 new X(n,3));this.addAttribute("normal",new X(r,3));this.addAttribute("uv",new X(l,2))}function Jc(a,b,c,d,e,f){S.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Rb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Sb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);
13205 b=c/b*a;c=Math.cos(b);e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}D.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||100;b=b||40;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=(d+1)*(c+1),k=d*c*6,k=new y(new (65535<k?Uint32Array:Uint16Array)(k),1),m=new y(new Float32Array(3*h),3),x=new y(new Float32Array(3*h),3),h=new y(new Float32Array(2*h),2),p,n,r=0,l=0,u=new q,F=new q,t=new C,v=new q,
13206 M=new q,z=new q,A=new q,I=new q;for(p=0;p<=c;++p)for(n=p/c*e*Math.PI*2,g(n,e,f,a,v),g(n+.01,e,f,a,M),A.subVectors(M,v),I.addVectors(M,v),z.crossVectors(A,I),I.crossVectors(z,A),z.normalize(),I.normalize(),n=0;n<=d;++n){var E=n/d*Math.PI*2,K=-b*Math.cos(E),E=b*Math.sin(E);u.x=v.x+(K*I.x+E*z.x);u.y=v.y+(K*I.y+E*z.y);u.z=v.z+(K*I.z+E*z.z);m.setXYZ(r,u.x,u.y,u.z);F.subVectors(u,v).normalize();x.setXYZ(r,F.x,F.y,F.z);t.x=p/c;t.y=n/d;h.setXY(r,t.x,t.y);r++}for(n=1;n<=c;n++)for(p=1;p<=d;p++)a=(d+1)*n+(p-
13207 1),b=(d+1)*n+p,e=(d+1)*(n-1)+p,k.setX(l,(d+1)*(n-1)+(p-1)),l++,k.setX(l,a),l++,k.setX(l,e),l++,k.setX(l,a),l++,k.setX(l,b),l++,k.setX(l,e),l++;this.setIndex(k);this.addAttribute("position",m);this.addAttribute("normal",x);this.addAttribute("uv",h)}function Kc(a,b,c,d,e,f,g){S.call(this);this.type="TorusKnotGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};void 0!==g&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");
13208 this.fromBufferGeometry(new Sb(a,b,c,d,e,f));this.mergeVertices()}function Tb(a,b,c,d,e){D.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||100;b=b||40;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=(c+1)*(d+1),g=c*d*6,g=new (65535<g?Uint32Array:Uint16Array)(g),h=new Float32Array(3*f),k=new Float32Array(3*f),f=new Float32Array(2*f),m=0,x=0,p=0,n=new q,l=new q,w=new q,u,F;for(u=0;u<=c;u++)for(F=0;F<=d;F++){var t=
13209 F/d*e,v=u/c*Math.PI*2;l.x=(a+b*Math.cos(v))*Math.cos(t);l.y=(a+b*Math.cos(v))*Math.sin(t);l.z=b*Math.sin(v);h[m]=l.x;h[m+1]=l.y;h[m+2]=l.z;n.x=a*Math.cos(t);n.y=a*Math.sin(t);w.subVectors(l,n).normalize();k[m]=w.x;k[m+1]=w.y;k[m+2]=w.z;f[x]=F/d;f[x+1]=u/c;m+=3;x+=2}for(u=1;u<=c;u++)for(F=1;F<=d;F++)a=(d+1)*(u-1)+F-1,b=(d+1)*(u-1)+F,e=(d+1)*u+F,g[p]=(d+1)*u+F-1,g[p+1]=a,g[p+2]=e,g[p+3]=a,g[p+4]=b,g[p+5]=e,p+=6;this.setIndex(new y(g,1));this.addAttribute("position",new y(h,3));this.addAttribute("normal",
13210 new y(k,3));this.addAttribute("uv",new y(f,2))}function Lc(a,b,c,d,e){S.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Tb(a,b,c,d,e))}function La(a,b){"undefined"!==typeof a&&(S.call(this),this.type="ExtrudeGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeFaceNormals())}function Mc(a,b){b=b||{};var c=b.font;if(!1===(c&&c.isFont))return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),
13211 new S;c=c.generateShapes(a,b.size,b.curveSegments);b.amount=void 0!==b.height?b.height:50;void 0===b.bevelThickness&&(b.bevelThickness=10);void 0===b.bevelSize&&(b.bevelSize=8);void 0===b.bevelEnabled&&(b.bevelEnabled=!1);La.call(this,c,b);this.type="TextGeometry"}function mb(a,b,c,d,e,f,g){D.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||50;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||
13212 6);d=void 0!==d?d:0;e=void 0!==e?e:2*Math.PI;f=void 0!==f?f:0;g=void 0!==g?g:Math.PI;for(var h=f+g,k=(b+1)*(c+1),m=new y(new Float32Array(3*k),3),x=new y(new Float32Array(3*k),3),k=new y(new Float32Array(2*k),2),p=0,n=[],l=new q,w=0;w<=c;w++){for(var u=[],F=w/c,t=0;t<=b;t++){var v=t/b,M=-a*Math.cos(d+v*e)*Math.sin(f+F*g),z=a*Math.cos(f+F*g),A=a*Math.sin(d+v*e)*Math.sin(f+F*g);l.set(M,z,A).normalize();m.setXYZ(p,M,z,A);x.setXYZ(p,l.x,l.y,l.z);k.setXY(p,v,1-F);u.push(p);p++}n.push(u)}d=[];for(w=0;w<
13213 c;w++)for(t=0;t<b;t++)e=n[w][t+1],g=n[w][t],p=n[w+1][t],l=n[w+1][t+1],(0!==w||0<f)&&d.push(e,g,l),(w!==c-1||h<Math.PI)&&d.push(g,p,l);this.setIndex(new (65535<m.count?Ua:Ra)(d,1));this.addAttribute("position",m);this.addAttribute("normal",x);this.addAttribute("uv",k);this.boundingSphere=new Fa(new q,a)}function Nc(a,b,c,d,e,f,g){S.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new mb(a,
13214 b,c,d,e,f,g))}function Ub(a,b,c,d,e,f){D.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||20;b=b||50;e=void 0!==e?e:0;f=void 0!==f?f:2*Math.PI;c=void 0!==c?Math.max(3,c):8;d=void 0!==d?Math.max(1,d):1;var g=(c+1)*(d+1),h=c*d*6,h=new y(new (65535<h?Uint32Array:Uint16Array)(h),1),k=new y(new Float32Array(3*g),3),m=new y(new Float32Array(3*g),3),g=new y(new Float32Array(2*g),2),x=0,p=0,n,l=a,w=(b-a)/
13215 d,u=new q,F=new C,t;for(a=0;a<=d;a++){for(t=0;t<=c;t++)n=e+t/c*f,u.x=l*Math.cos(n),u.y=l*Math.sin(n),k.setXYZ(x,u.x,u.y,u.z),m.setXYZ(x,0,0,1),F.x=(u.x/b+1)/2,F.y=(u.y/b+1)/2,g.setXY(x,F.x,F.y),x++;l+=w}for(a=0;a<d;a++)for(b=a*(c+1),t=0;t<c;t++)e=n=t+b,f=n+c+1,x=n+c+2,n+=1,h.setX(p,e),p++,h.setX(p,f),p++,h.setX(p,x),p++,h.setX(p,e),p++,h.setX(p,x),p++,h.setX(p,n),p++;this.setIndex(h);this.addAttribute("position",k);this.addAttribute("normal",m);this.addAttribute("uv",g)}function Oc(a,b,c,d,e,f){S.call(this);
13216 this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Ub(a,b,c,d,e,f))}function Pc(a,b,c,d){S.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new ib(a,b,c,d))}function Vb(a,b,c,d){D.call(this);this.type="LatheBufferGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};b=Math.floor(b)||12;c=c||0;d=d||
13217 2*Math.PI;d=Q.clamp(d,0,2*Math.PI);for(var e=(b+1)*a.length,f=b*a.length*6,g=new y(new (65535<f?Uint32Array:Uint16Array)(f),1),h=new y(new Float32Array(3*e),3),k=new y(new Float32Array(2*e),2),m=0,x=0,p=1/b,n=new q,l=new C,e=0;e<=b;e++)for(var f=c+e*p*d,w=Math.sin(f),u=Math.cos(f),f=0;f<=a.length-1;f++)n.x=a[f].x*w,n.y=a[f].y,n.z=a[f].x*u,h.setXYZ(m,n.x,n.y,n.z),l.x=e/b,l.y=f/(a.length-1),k.setXY(m,l.x,l.y),m++;for(e=0;e<b;e++)for(f=0;f<a.length-1;f++)c=f+e*a.length,m=c+a.length,p=c+a.length+1,n=
13218 c+1,g.setX(x,c),x++,g.setX(x,m),x++,g.setX(x,n),x++,g.setX(x,m),x++,g.setX(x,p),x++,g.setX(x,n),x++;this.setIndex(g);this.addAttribute("position",h);this.addAttribute("uv",k);this.computeVertexNormals();if(d===2*Math.PI)for(d=this.attributes.normal.array,g=new q,h=new q,k=new q,c=b*a.length*3,f=e=0;e<a.length;e++,f+=3)g.x=d[f+0],g.y=d[f+1],g.z=d[f+2],h.x=d[c+f+0],h.y=d[c+f+1],h.z=d[c+f+2],k.addVectors(g,h).normalize(),d[f+0]=d[c+f+0]=k.x,d[f+1]=d[c+f+1]=k.y,d[f+2]=d[c+f+2]=k.z}function Qc(a,b,c,d){S.call(this);
13219 this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new Vb(a,b,c,d));this.mergeVertices()}function Wb(a,b){function c(a){var c,h,m=d.length/3;a=a.extractPoints(b);var l=a.shape,u=a.holes;if(!1===pa.isClockWise(l))for(l=l.reverse(),a=0,c=u.length;a<c;a++)h=u[a],!0===pa.isClockWise(h)&&(u[a]=h.reverse());var q=pa.triangulateShape(l,u);a=0;for(c=u.length;a<c;a++)h=u[a],l=l.concat(h);a=0;for(c=l.length;a<c;a++)h=l[a],d.push(h.x,h.y,0),e.push(0,
13220 0,1),f.push(h.x,h.y);a=0;for(c=q.length;a<c;a++)l=q[a],g.push(l[0]+m,l[1]+m,l[2]+m),k+=3}D.call(this);this.type="ShapeBufferGeometry";this.parameters={shapes:a,curveSegments:b};b=b||12;var d=[],e=[],f=[],g=[],h=0,k=0;if(!1===Array.isArray(a))c(a);else for(var m=0;m<a.length;m++)c(a[m]),this.addGroup(h,k,m),h+=k,k=0;this.setIndex(new (65535<g.length?Ua:Ra)(g,1));this.addAttribute("position",new X(d,3));this.addAttribute("normal",new X(e,3));this.addAttribute("uv",new X(f,2))}function Xb(a,b){S.call(this);
13221 this.type="ShapeGeometry";"object"===typeof b&&(console.warn("THREE.ShapeGeometry: Options parameter has been removed."),b=b.curveSegments);this.parameters={shapes:a,curveSegments:b};this.fromBufferGeometry(new Wb(a,b));this.mergeVertices()}function Yb(a,b){function c(a,b){return a-b}D.call(this);var d=Math.cos(Q.DEG2RAD*(void 0!==b?b:1)),e=[0,0],f={},g=["a","b","c"],h;a.isBufferGeometry?(h=new S,h.fromBufferGeometry(a)):h=a.clone();h.mergeVertices();h.computeFaceNormals();var k=h.vertices;h=h.faces;
13222 for(var m=0,l=h.length;m<l;m++)for(var p=h[m],n=0;3>n;n++){e[0]=p[g[n]];e[1]=p[g[(n+1)%3]];e.sort(c);var r=e.toString();void 0===f[r]?f[r]={vert1:e[0],vert2:e[1],face1:m,face2:void 0}:f[r].face2=m}e=[];for(r in f)if(g=f[r],void 0===g.face2||h[g.face1].normal.dot(h[g.face2].normal)<=d)m=k[g.vert1],e.push(m.x),e.push(m.y),e.push(m.z),m=k[g.vert2],e.push(m.x),e.push(m.y),e.push(m.z);this.addAttribute("position",new X(e,3))}function Wa(a,b,c,d,e,f,g,h){function k(c){var e,f,k,n=new C,p=new q,l=0,x=!0===
13223 c?a:b,M=!0===c?1:-1;f=t;for(e=1;e<=d;e++)w.setXYZ(t,0,z*M,0),u.setXYZ(t,0,M,0),n.x=.5,n.y=.5,F.setXY(t,n.x,n.y),t++;k=t;for(e=0;e<=d;e++){var y=e/d*h+g,D=Math.cos(y),y=Math.sin(y);p.x=x*y;p.y=z*M;p.z=x*D;w.setXYZ(t,p.x,p.y,p.z);u.setXYZ(t,0,M,0);n.x=.5*D+.5;n.y=.5*y*M+.5;F.setXY(t,n.x,n.y);t++}for(e=0;e<d;e++)n=f+e,p=k+e,!0===c?(r.setX(v,p),v++,r.setX(v,p+1)):(r.setX(v,p+1),v++,r.setX(v,p)),v++,r.setX(v,n),v++,l+=3;m.addGroup(A,l,!0===c?1:2);A+=l}D.call(this);this.type="CylinderBufferGeometry";this.parameters=
13224 {radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var m=this;a=void 0!==a?a:20;b=void 0!==b?b:20;c=void 0!==c?c:100;d=Math.floor(d)||8;e=Math.floor(e)||1;f=void 0!==f?f:!1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var l=0;!1===f&&(0<a&&l++,0<b&&l++);var p=function(){var a=(d+1)*(e+1);!1===f&&(a+=(d+1)*l+d*l);return a}(),n=function(){var a=d*e*6;!1===f&&(a+=d*l*3);return a}(),r=new y(new (65535<n?Uint32Array:Uint16Array)(n),1),w=new y(new Float32Array(3*
13225 p),3),u=new y(new Float32Array(3*p),3),F=new y(new Float32Array(2*p),2),t=0,v=0,M=[],z=c/2,A=0;(function(){var f,k,n=new q,p=new q,l=0,x=(b-a)/c;for(k=0;k<=e;k++){var y=[],C=k/e,D=C*(b-a)+a;for(f=0;f<=d;f++){var G=f/d,P=G*h+g,R=Math.sin(P),P=Math.cos(P);p.x=D*R;p.y=-C*c+z;p.z=D*P;w.setXYZ(t,p.x,p.y,p.z);n.set(R,x,P).normalize();u.setXYZ(t,n.x,n.y,n.z);F.setXY(t,G,1-C);y.push(t);t++}M.push(y)}for(f=0;f<d;f++)for(k=0;k<e;k++)n=M[k+1][f],p=M[k+1][f+1],x=M[k][f+1],r.setX(v,M[k][f]),v++,r.setX(v,n),v++,
13226 r.setX(v,x),v++,r.setX(v,n),v++,r.setX(v,p),v++,r.setX(v,x),v++,l+=6;m.addGroup(A,l,0);A+=l})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(r);this.addAttribute("position",w);this.addAttribute("normal",u);this.addAttribute("uv",F)}function nb(a,b,c,d,e,f,g,h){S.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};this.fromBufferGeometry(new Wa(a,b,c,d,e,f,g,h));this.mergeVertices()}
13227 function Rc(a,b,c,d,e,f,g){nb.call(this,0,a,b,c,d,e,f,g);this.type="ConeGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Sc(a,b,c,d,e,f,g){Wa.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Zb(a,b,c,d){D.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,
13228 thetaLength:d};a=a||50;b=void 0!==b?Math.max(3,b):8;c=void 0!==c?c:0;d=void 0!==d?d:2*Math.PI;var e=b+2,f=new Float32Array(3*e),g=new Float32Array(3*e),e=new Float32Array(2*e);g[2]=1;e[0]=.5;e[1]=.5;for(var h=0,k=3,m=2;h<=b;h++,k+=3,m+=2){var l=c+h/b*d;f[k]=a*Math.cos(l);f[k+1]=a*Math.sin(l);g[k+2]=1;e[m]=(f[k]/a+1)/2;e[m+1]=(f[k+1]/a+1)/2}c=[];for(k=1;k<=b;k++)c.push(k,k+1,0);this.setIndex(new y(new Uint16Array(c),1));this.addAttribute("position",new y(f,3));this.addAttribute("normal",new y(g,3));
13229 this.addAttribute("uv",new y(e,2));this.boundingSphere=new Fa(new q,a)}function Tc(a,b,c,d){S.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new Zb(a,b,c,d))}function $b(a,b,c,d,e,f){S.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new hb(a,b,c,d,e,f));this.mergeVertices()}function ac(){Ia.call(this,{uniforms:Ja.merge([U.lights,
13230 {opacity:{value:1}}]),vertexShader:Z.shadow_vert,fragmentShader:Z.shadow_frag});this.transparent=this.lights=!0;Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(a){this.uniforms.opacity.value=a}}})}function bc(a){Ia.call(this,a);this.type="RawShaderMaterial"}function Uc(a){this.uuid=Q.generateUUID();this.type="MultiMaterial";this.materials=Array.isArray(a)?a:[];this.visible=!0}function Pa(a){W.call(this);this.defines={STANDARD:""};
13231 this.type="MeshStandardMaterial";this.color=new N(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new N(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=
13232 .98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function ob(a){Pa.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Ca(a){W.call(this);this.type="MeshPhongMaterial";this.color=new N(16777215);this.specular=new N(1118481);this.shininess=30;this.lightMap=this.map=null;
13233 this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new N(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=
13234 this.morphTargets=this.skinning=!1;this.setValues(a)}function pb(a){Ca.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function qb(a){W.call(this,a);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=
13235 !1;this.setValues(a)}function rb(a){W.call(this);this.type="MeshLambertMaterial";this.color=new N(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new N(0);this.emissiveIntensity=1;this.envMap=this.alphaMap=this.specularMap=this.emissiveMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=
13236 this.skinning=!1;this.setValues(a)}function sb(a){W.call(this);this.type="LineDashedMaterial";this.color=new N(16777215);this.scale=this.linewidth=1;this.dashSize=3;this.gapSize=1;this.lights=!1;this.setValues(a)}function Pd(a,b,c){var d=this,e=!1,f=0,g=0;this.onStart=void 0;this.onLoad=a;this.onProgress=b;this.onError=c;this.itemStart=function(a){g++;if(!1===e&&void 0!==d.onStart)d.onStart(a,f,g);e=!0};this.itemEnd=function(a){f++;if(void 0!==d.onProgress)d.onProgress(a,f,g);if(f===g&&(e=!1,void 0!==
13237 d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)}}function Ma(a){this.manager=void 0!==a?a:va}function Ee(a){this.manager=void 0!==a?a:va;this._parser=null}function Qd(a){this.manager=void 0!==a?a:va;this._parser=null}function Vc(a){this.manager=void 0!==a?a:va}function Rd(a){this.manager=void 0!==a?a:va}function md(a){this.manager=void 0!==a?a:va}function na(a,b){G.call(this);this.type="Light";this.color=new N(a);this.intensity=void 0!==b?b:1;this.receiveShadow=
13238 void 0}function nd(a,b,c){na.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(G.DefaultUp);this.updateMatrix();this.groundColor=new N(b)}function tb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new C(512,512);this.map=null;this.matrix=new H}function od(){tb.call(this,new Ha(50,1,.5,500))}function pd(a,b,c,d,e,f){na.call(this,a,b);this.type="SpotLight";this.position.copy(G.DefaultUp);this.updateMatrix();this.target=new G;Object.defineProperty(this,"power",
13239 {get:function(){return this.intensity*Math.PI},set:function(a){this.intensity=a/Math.PI}});this.distance=void 0!==c?c:0;this.angle=void 0!==d?d:Math.PI/3;this.penumbra=void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=new od}function qd(a,b,c,d){na.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new tb(new Ha(90,
13240 1,.5,500))}function rd(a){tb.call(this,new Hb(-5,5,5,-5,.5,500))}function sd(a,b){na.call(this,a,b);this.type="DirectionalLight";this.position.copy(G.DefaultUp);this.updateMatrix();this.target=new G;this.shadow=new rd}function td(a,b){na.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function qa(a,b,c,d){this.parameterPositions=a;this._cachedIndex=0;this.resultBuffer=void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function ud(a,b,c,d){qa.call(this,a,b,c,d);this._offsetNext=
13241 this._weightNext=this._offsetPrev=this._weightPrev=-0}function Wc(a,b,c,d){qa.call(this,a,b,c,d)}function vd(a,b,c,d){qa.call(this,a,b,c,d)}function ub(a,b,c,d){if(void 0===a)throw Error("track name is undefined");if(void 0===b||0===b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=ba.convertArray(b,this.TimeBufferType);this.values=ba.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function cc(a,b,
13242 c,d){ub.call(this,a,b,c,d)}function wd(a,b,c,d){qa.call(this,a,b,c,d)}function Xc(a,b,c,d){ub.call(this,a,b,c,d)}function dc(a,b,c,d){ub.call(this,a,b,c,d)}function xd(a,b,c,d){ub.call(this,a,b,c,d)}function yd(a,b,c){ub.call(this,a,b,c)}function zd(a,b,c,d){ub.call(this,a,b,c,d)}function vb(a,b,c,d){ub.apply(this,arguments)}function ta(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=Q.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function Ad(a){this.manager=
13243 void 0!==a?a:va;this.textures={}}function Sd(a){this.manager=void 0!==a?a:va}function wb(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function Td(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:va;this.withCredentials=!1}function Fe(a){this.manager=void 0!==a?a:va;this.texturePath=""}function wa(){}function Qa(a,b){this.v1=a;this.v2=b}function Yc(){this.curves=
13244 [];this.autoClose=!1}function Xa(a,b,c,d,e,f,g,h){this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=e;this.aEndAngle=f;this.aClockwise=g;this.aRotation=h||0}function xb(a){this.points=void 0===a?[]:a}function yb(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d}function zb(a,b,c){this.v0=a;this.v1=b;this.v2=c}function Ab(){Zc.apply(this,arguments);this.holes=[]}function Zc(a){Yc.call(this);this.currentPoint=new C;a&&this.fromPoints(a)}function Ud(){this.subPaths=[];this.currentPath=
13245 null}function Vd(a){this.data=a}function Ge(a){this.manager=void 0!==a?a:va}function Wd(a){this.manager=void 0!==a?a:va}function Xd(a,b,c,d){na.call(this,a,b);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function He(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new Ha;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new Ha;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=
13246 !1}function Bd(a,b,c){G.call(this);this.type="CubeCamera";var d=new Ha(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new q(1,0,0));this.add(d);var e=new Ha(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new q(-1,0,0));this.add(e);var f=new Ha(90,1,a,b);f.up.set(0,0,1);f.lookAt(new q(0,1,0));this.add(f);var g=new Ha(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new q(0,-1,0));this.add(g);var h=new Ha(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new q(0,0,1));this.add(h);var k=new Ha(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new q(0,0,-1));this.add(k);
13247 this.renderTarget=new Eb(c,c,{format:1022,magFilter:1006,minFilter:1006});this.updateCubeMap=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,n=c.texture.generateMipmaps;c.texture.generateMipmaps=!1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=n;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)}}function Yd(){G.call(this);
13248 this.type="AudioListener";this.context=Zd.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function ec(a){G.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.buffer=null;this.loop=!1;this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function $d(a){ec.call(this,a);this.panner=
13249 this.context.createPanner();this.panner.connect(this.gain)}function ae(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);a.getOutput().connect(this.analyser)}function Cd(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=
13250 this.useCount=this.cumulativeWeight=0}function ka(a,b,c){this.path=b;this.parsedPath=c||ka.parseTrackName(b);this.node=ka.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function be(a){this.uuid=Q.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var b={};this._indicesByUUID=b;for(var c=0,d=arguments.length;c!==d;++c)b[arguments[c].uuid]=c;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var e=this;this.stats={objects:{get total(){return e._objects.length},
13251 get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}function ce(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop=
13252 2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function de(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Dd(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function Bb(){D.call(this);
13253 this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function ee(a,b,c,d){this.uuid=Q.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function fc(a,b){this.uuid=Q.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function gc(a,b,c){fc.call(this,a,b);this.meshPerAttribute=c||1}function hc(a,b,c){y.call(this,a,b);this.meshPerAttribute=
13254 c||1}function fe(a,b,c,d){this.ray=new bb(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function Ie(a,b){return a.distance-b.distance}function ge(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;d<e;d++)ge(a[d],b,c,!0)}}function he(a){this.autoStart=
13255 void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function ie(a,b,c){this.radius=void 0!==a?a:1;this.phi=void 0!==b?b:0;this.theta=void 0!==c?c:0;return this}function je(a,b,c){this.radius=void 0!==a?a:1;this.theta=void 0!==b?b:0;this.y=void 0!==c?c:0;return this}function ua(a,b){Ba.call(this,a,b);this.animationsMap={};this.animationsList=[];var c=this.geometry.morphTargets.length;this.createAnimation("__default",0,c-1,c/1);this.setAnimationWeight("__default",1)}function $c(a){G.call(this);
13256 this.material=a;this.render=function(a){}}function ad(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16711680;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=3*c.faces.length:c&&c.isBufferGeometry&&(b=c.attributes.normal.count);c=new D;b=new X(6*b,3);c.addAttribute("position",b);fa.call(this,c,new ia({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function ic(a){G.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=
13257 !1;a=new D;for(var b=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1],c=0,d=1;32>c;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new X(b,3));b=new ia({fog:!1});this.cone=new fa(a,b);this.add(this.cone);this.update()}function jc(a){this.bones=this.getBoneList(a);for(var b=new D,c=[],d=[],e=new N(0,0,1),f=new N(0,1,0),g=0;g<this.bones.length;g++){var h=this.bones[g];h.parent&&h.parent.isBone&&(c.push(0,
13258 0,0),c.push(0,0,0),d.push(e.r,e.g,e.b),d.push(f.r,f.g,f.b))}b.addAttribute("position",new X(c,3));b.addAttribute("color",new X(d,3));c=new ia({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});fa.call(this,b,c);this.root=a;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.update()}function kc(a,b){this.light=a;this.light.updateMatrixWorld();var c=new mb(b,4,2),d=new Ka({wireframe:!0,fog:!1});d.color.copy(this.light.color).multiplyScalar(this.light.intensity);Ba.call(this,c,d);this.matrix=
13259 this.light.matrixWorld;this.matrixAutoUpdate=!1}function lc(a){G.call(this);this.light=a;this.light.updateMatrixWorld();var b=new Ka({color:a.color,fog:!1});a=new Ka({color:a.color,fog:!1,wireframe:!0});var c=new D;c.addAttribute("position",new y(new Float32Array(18),3));this.add(new Ba(c,b));this.add(new Ba(c,a));this.update()}function mc(a,b){G.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;var c=new lb(b);c.rotateY(.5*Math.PI);var d=new Ka({vertexColors:2,
13260 wireframe:!0}),e=c.getAttribute("position"),e=new Float32Array(3*e.count);c.addAttribute("color",new y(e,3));this.add(new Ba(c,d));this.update()}function bd(a,b,c,d){a=a||10;b=b||10;c=new N(void 0!==c?c:4473924);d=new N(void 0!==d?d:8947848);for(var e=b/2,f=2*a/b,g=[],h=[],k=0,m=0,l=-a;k<=b;k++,l+=f){g.push(-a,0,l,a,0,l);g.push(l,0,-a,l,0,a);var p=k===e?c:d;p.toArray(h,m);m+=3;p.toArray(h,m);m+=3;p.toArray(h,m);m+=3;p.toArray(h,m);m+=3}a=new D;a.addAttribute("position",new X(g,3));a.addAttribute("color",
13261 new X(h,3));g=new ia({vertexColors:2});fa.call(this,a,g)}function Ed(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new N(void 0!==e?e:4473924);f=new N(void 0!==f?f:8947848);var g=[],h=[],k,m,l,p,n;for(l=0;l<=b;l++)m=l/b*2*Math.PI,k=Math.sin(m)*a,m=Math.cos(m)*a,g.push(0,0,0),g.push(k,0,m),n=l&1?e:f,h.push(n.r,n.g,n.b),h.push(n.r,n.g,n.b);for(l=0;l<=c;l++)for(n=l&1?e:f,p=a-a/c*l,b=0;b<d;b++)m=b/d*2*Math.PI,k=Math.sin(m)*p,m=Math.cos(m)*p,g.push(k,0,m),h.push(n.r,n.g,n.b),m=(b+1)/d*2*Math.PI,k=Math.sin(m)*
13262 p,m=Math.cos(m)*p,g.push(k,0,m),h.push(n.r,n.g,n.b);a=new D;a.addAttribute("position",new X(g,3));a.addAttribute("color",new X(h,3));g=new ia({vertexColors:2});fa.call(this,a,g)}function cd(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16776960;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=c.faces.length:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");c=new D;b=new X(6*b,3);c.addAttribute("position",
13263 b);fa.call(this,c,new ia({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function nc(a,b){G.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;void 0===b&&(b=1);var c=new D;c.addAttribute("position",new X([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));var d=new ia({fog:!1});this.add(new Va(c,d));c=new D;c.addAttribute("position",new X([0,0,0,0,0,1],3));this.add(new Va(c,d));this.update()}function dd(a){function b(a,b,d){c(a,d);c(b,d)}
13264 function c(a,b){f.push(0,0,0);g.push(b.r,b.g,b.b);void 0===h[a]&&(h[a]=[]);h[a].push(f.length/3-1)}var d=new D,e=new ia({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new N(16755200),m=new N(16711680),l=new N(43775),p=new N(16777215),n=new N(3355443);b("n1","n2",k);b("n2","n4",k);b("n4","n3",k);b("n3","n1",k);b("f1","f2",k);b("f2","f4",k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);b("n3","f3",k);b("n4","f4",k);b("p","n1",m);b("p","n2",m);b("p","n3",m);b("p","n4",m);b("u1","u2",
13265 l);b("u2","u3",l);b("u3","u1",l);b("c","t",p);b("p","c",n);b("cn1","cn2",n);b("cn3","cn4",n);b("cf1","cf2",n);b("cf3","cf4",n);d.addAttribute("position",new X(f,3));d.addAttribute("color",new X(g,3));fa.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function oc(a,b){void 0===b&&(b=16776960);var c=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),
13266 d=new Float32Array(24),e=new D;e.setIndex(new y(c,1));e.addAttribute("position",new y(d,3));fa.call(this,e,new ia({color:b}));void 0!==a&&this.update(a)}function Cb(a,b,c,d,e,f){G.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);this.position.copy(b);this.line=new Va(Je,new ia({color:d}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new Ba(Ke,new Ka({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,
13267 e,f)}function Fd(a){a=a||1;var b=[0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a];a=new D;a.addAttribute("position",new X(b,3));a.addAttribute("color",new X([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new ia({vertexColors:2});fa.call(this,a,b)}function Gd(a,b,c,d,e,f){Xa.call(this,a,b,c,c,d,e,f)}function Le(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ke.call(this,a);this.type="catmullrom";this.closed=!0}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,
13268 -52));void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0<a?1:+a});void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}});void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===a||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var d=arguments[c];if(void 0!==d&&null!==d)for(var e in d)Object.prototype.hasOwnProperty.call(d,
13269 e)&&(b[e]=d[e])}return b}}();Object.assign(oa.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]);-1===c[a].indexOf(b)&&c[a].push(b)},hasEventListener:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){if(void 0!==this._listeners){var c=this._listeners[a];if(void 0!==c){var d=c.indexOf(b);-1!==d&&c.splice(d,1)}}},dispatchEvent:function(a){if(void 0!==
13270 this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;var c=[],d,e=b.length;for(d=0;d<e;d++)c[d]=b[d];for(d=0;d<e;d++)c[d].call(this,a)}}}});var Me={NoBlending:0,NormalBlending:1,AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},Ne={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},
13271 le={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},me={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008},Q={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){var a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),b=Array(36),c=0,d;return function(){for(var e=0;36>e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":
13272 (2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+
13273 10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*Q.DEG2RAD},radToDeg:function(a){return a*Q.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}};C.prototype={constructor:C,
13274 isVector2:!0,get width(){return this.x},set width(a){this.x=a},get height(){return this.y},set height(a){this.y=a},set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;
13275 default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,
13276 b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a):this.y=this.x=0;
13277 return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new C,b=new C);a.set(c,
13278 c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);
13279 return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},
13280 distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+
13281 1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromAttribute().");this.x=a.getX(b);this.y=a.getY(b);return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}};var Oe=0;ea.DEFAULT_IMAGE=void 0;ea.DEFAULT_MAPPING=300;ea.prototype={constructor:ea,isTexture:!0,
13282 set needsUpdate(a){!0===a&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;
13283 this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){if(void 0!==a.textures[this.uuid])return a.textures[this.uuid];var b={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var c=
13284 this.image;void 0===c.uuid&&(c.uuid=Q.generateUUID());if(void 0===a.images[c.uuid]){var d=a.images,e=c.uuid,f=c.uuid,g;void 0!==c.toDataURL?g=c:(g=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),g.width=c.width,g.height=c.height,g.getContext("2d").drawImage(c,0,0,c.width,c.height));g=2048<g.width||2048<g.height?g.toDataURL("image/jpeg",.6):g.toDataURL("image/png");d[e]={uuid:f,url:g}}b.image=c.uuid}return a.textures[this.uuid]=b},dispose:function(){this.dispatchEvent({type:"dispose"})},
13285 transformUv:function(a){if(300===this.mapping){a.multiply(this.repeat);a.add(this.offset);if(0>a.x||1<a.x)switch(this.wrapS){case 1E3:a.x-=Math.floor(a.x);break;case 1001:a.x=0>a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)%2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>a.y||1<a.y)switch(this.wrapT){case 1E3:a.y-=Math.floor(a.y);break;case 1001:a.y=0>a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}};Object.assign(ea.prototype,
13286 oa.prototype);ga.prototype={constructor:ga,isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+
13287 a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,
13288 b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=
13289 a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a,this.w*=a):this.w=this.z=this.y=this.x=0;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=
13290 a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var m=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01>
13291 Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+m-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;m=(m+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>m?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b):h>m?.01>h?(b=.707106781,c=0,d=.707106781):(c=Math.sqrt(h),b=d/c,d=k/c):.01>m?(c=b=.707106781,d=0):(d=Math.sqrt(m),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/
13292 a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));
13293 this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new ga,b=new ga);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);
13294 this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*
13295 this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,
13296 b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromAttribute().");this.x=a.getX(b);
13297 this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}};Object.assign(Db.prototype,oa.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=
13298 a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Eb.prototype=Object.create(Db.prototype);Eb.prototype.constructor=Eb;Eb.prototype.isWebGLRenderTargetCube=!0;da.prototype={constructor:da,get x(){return this._x},set x(a){this._x=a;this.onChangeCallback()},get y(){return this._y},set y(a){this._y=a;this.onChangeCallback()},get z(){return this._z},set z(a){this._z=a;this.onChangeCallback()},get w(){return this._w},set w(a){this._w=
13299 a;this.onChangeCallback()},set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!1===(a&&a.isEuler))throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=Math.cos(a._x/2),d=Math.cos(a._y/
13300 2),e=Math.cos(a._z/2),f=Math.sin(a._x/2),g=Math.sin(a._y/2),h=Math.sin(a._z/2),k=a.order;"XYZ"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e-f*g*h):"YXZ"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e+f*g*h):"ZXY"===k?(this._x=f*d*e-c*g*h,this._y=c*g*e+f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e-f*g*h):"ZYX"===k?(this._x=f*d*e-c*g*h,this._y=c*g*e+f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e+f*g*h):"YZX"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e+
13301 f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e-f*g*h):"XZY"===k&&(this._x=f*d*e-c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e+f*g*h);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,b){var c=b/2,d=Math.sin(c);this._x=a.x*d;this._y=a.y*d;this._z=a.z*d;this._w=Math.cos(c);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],m=c+f+b;0<m?(c=.5/Math.sqrt(m+1),this._w=
13302 .25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a,b;return function(c,d){void 0===a&&(a=new q);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,
13303 c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+
13304 this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,
13305 b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,k=b._z,m=b._w;this._x=c*m+f*g+d*k-e*h;this._y=d*m+f*h+e*g-c*k;this._z=e*m+f*k+c*h-d*g;this._w=f*m-c*g-d*h-e*k;this.onChangeCallback();return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);
13306 if(.001>Math.abs(h))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b*k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];
13307 this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}};Object.assign(da,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var l=e[f+1],p=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==l||m!==p){f=1-g;var n=h*d+k*l+m*p+c*e,r=0<=
13308 n?1:-1,w=1-n*n;w>Number.EPSILON&&(w=Math.sqrt(w),n=Math.atan2(w,n*r),f=Math.sin(f*n)/w,g=Math.sin(g*n)/w);r*=g;h=h*f+d*r;k=k*f+l*r;m=m*f+p*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m*m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});q.prototype={constructor:q,isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=
13309 a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),
13310 this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;
13311 return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a):this.z=this.y=this.x=0;return this},multiplyVectors:function(a,
13312 b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a;return function(b){!1===(b&&b.isEuler)&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");void 0===a&&(a=new da);return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a;return function(b,c){void 0===a&&(a=new da);return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;
13313 a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12];this.y=a[1]*b+a[5]*c+a[9]*d+a[13];this.z=a[2]*b+a[6]*c+a[10]*d+a[14];return this},applyProjection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*
13314 c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,m=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b*-g+h*-f-k*-e;return this},project:function(){var a;return function(b){void 0===a&&(a=new H);a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyProjection(a)}}(),unproject:function(){var a;return function(b){void 0===a&&(a=new H);
13315 a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyProjection(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,
13316 a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new q,b=new q);a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,
13317 Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):
13318 Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/
13319 this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=
13320 a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=e*f-c*h;this.z=c*g-d*f;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a;return function(b){void 0===a&&(a=new q);a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a;return function(b){void 0===a&&(a=new q);return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*
13321 a.lengthSq());return Math.acos(Q.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=
13322 a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){return this.setFromMatrixColumn(a,3)},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){if("number"===typeof a){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var c=
13323 a;a=b;b=c}return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}};
13324 H.prototype={constructor:H,isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,l,p,n,r,w,u){var q=this.elements;q[0]=a;q[4]=b;q[8]=c;q[12]=d;q[1]=e;q[5]=f;q[9]=g;q[13]=h;q[2]=k;q[6]=m;q[10]=l;q[14]=p;q[3]=n;q[7]=r;q[11]=w;q[15]=u;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new H).fromArray(this.elements)},copy:function(a){this.elements.set(a.elements);return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=
13325 a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a;return function(b){void 0===a&&(a=new q);var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;
13326 c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){!1===(a&&a.isEuler)&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){a=f*h;var k=f*e,m=c*h,l=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-
13327 l*d;b[9]=-c*g;b[2]=l-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,l=d*e,b[0]=a+l*c,b[4]=m*c-k,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=l+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,l=d*e,b[0]=a-l*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=l-a*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,k=f*e,m=c*h,l=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*d+l,b[1]=g*e,b[5]=l*d+a,b[9]=k*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,k=f*d,m=c*g,l=c*d,b[0]=g*h,b[4]=l-
13328 a*e,b[8]=m*e+k,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=k*e+m,b[10]=a-l*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,l=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+l,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=l*e+a);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=this.elements,c=a.x,d=a.y,e=a.z,f=a.w,g=c+c,h=d+d,k=e+e;a=c*g;var m=c*h,c=c*k,l=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(l+e);b[4]=m-f;b[8]=c+h;b[1]=m+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-
13329 h;b[6]=d+g;b[10]=1-(a+l);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},lookAt:function(){var a,b,c;return function(d,e,f){void 0===a&&(a=new q,b=new q,c=new q);var g=this.elements;c.subVectors(d,e).normalize();0===c.lengthSq()&&(c.z=1);a.crossVectors(f,c).normalize();0===a.lengthSq()&&(c.z+=1E-4,a.crossVectors(f,c).normalize());b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==
13330 b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],k=c[12],m=c[1],l=c[5],p=c[9],n=c[13],r=c[2],w=c[6],u=c[10],q=c[14],t=c[3],v=c[7],M=c[11],c=c[15],z=d[0],A=d[4],I=d[8],E=d[12],K=d[1],y=d[5],J=d[9],C=d[13],D=d[2],G=d[6],
13331 H=d[10],O=d[14],P=d[3],R=d[7],T=d[11],d=d[15];e[0]=f*z+g*K+h*D+k*P;e[4]=f*A+g*y+h*G+k*R;e[8]=f*I+g*J+h*H+k*T;e[12]=f*E+g*C+h*O+k*d;e[1]=m*z+l*K+p*D+n*P;e[5]=m*A+l*y+p*G+n*R;e[9]=m*I+l*J+p*H+n*T;e[13]=m*E+l*C+p*O+n*d;e[2]=r*z+w*K+u*D+q*P;e[6]=r*A+w*y+u*G+q*R;e[10]=r*I+w*J+u*H+q*T;e[14]=r*E+w*C+u*O+q*d;e[3]=t*z+v*K+M*D+c*P;e[7]=t*A+v*y+M*G+c*R;e[11]=t*I+v*J+M*H+c*T;e[15]=t*E+v*C+M*O+c*d;return this},multiplyToArray:function(a,b,c){var d=this.elements;this.multiplyMatrices(a,b);c[0]=d[0];c[1]=d[1];c[2]=
13332 d[2];c[3]=d[3];c[4]=d[4];c[5]=d[5];c[6]=d[6];c[7]=d[7];c[8]=d[8];c[9]=d[9];c[10]=d[10];c[11]=d[11];c[12]=d[12];c[13]=d[13];c[14]=d[14];c[15]=d[15];return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToVector3Array:function(){var a;return function(b,c,d){void 0===a&&(a=new q);void 0===c&&(c=0);void 0===d&&(d=b.length);for(var e=0;e<d;e+=3,c+=
13333 3)a.fromArray(b,c),a.applyMatrix4(this),a.toArray(b,c);return b}}(),applyToBufferAttribute:function(){var a;return function(b){void 0===a&&(a=new q);for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix4(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),determinant:function(){var a=this.elements,b=a[0],c=a[4],d=a[8],e=a[12],f=a[1],g=a[5],h=a[9],k=a[13],m=a[2],l=a[6],p=a[10],n=a[14];return a[3]*(+e*h*l-d*k*l-e*g*p+c*k*p+d*g*n-c*h*n)+a[7]*(+b*h*n-b*k*p+e*f*p-d*f*n+d*k*m-e*h*
13334 m)+a[11]*(+b*k*l-b*g*n-e*f*l+c*f*n+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*l+b*g*p+d*f*l-c*f*p+c*h*m)},transpose:function(){var a=this.elements,b;b=a[1];a[1]=a[4];a[4]=b;b=a[2];a[2]=a[8];a[8]=b;b=a[6];a[6]=a[9];a[9]=b;b=a[3];a[3]=a[12];a[12]=b;b=a[7];a[7]=a[13];a[13]=b;b=a[11];a[11]=a[14];a[14]=b;return this},setPosition:function(a){var b=this.elements;b[12]=a.x;b[13]=a.y;b[14]=a.z;return this},getInverse:function(a,b){var c=this.elements,d=a.elements,e=d[0],f=d[1],g=d[2],h=d[3],k=d[4],m=d[5],l=d[6],p=d[7],
13335 n=d[8],r=d[9],w=d[10],u=d[11],q=d[12],t=d[13],v=d[14],d=d[15],M=r*v*p-t*w*p+t*l*u-m*v*u-r*l*d+m*w*d,z=q*w*p-n*v*p-q*l*u+k*v*u+n*l*d-k*w*d,A=n*t*p-q*r*p+q*m*u-k*t*u-n*m*d+k*r*d,I=q*r*l-n*t*l-q*m*w+k*t*w+n*m*v-k*r*v,E=e*M+f*z+g*A+h*I;if(0===E){if(!0===b)throw Error("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");return this.identity()}E=1/E;c[0]=M*E;c[1]=(t*w*h-r*v*h-t*g*u+f*v*u+r*g*d-f*w*d)*E;c[2]=
13336 (m*v*h-t*l*h+t*g*p-f*v*p-m*g*d+f*l*d)*E;c[3]=(r*l*h-m*w*h-r*g*p+f*w*p+m*g*u-f*l*u)*E;c[4]=z*E;c[5]=(n*v*h-q*w*h+q*g*u-e*v*u-n*g*d+e*w*d)*E;c[6]=(q*l*h-k*v*h-q*g*p+e*v*p+k*g*d-e*l*d)*E;c[7]=(k*w*h-n*l*h+n*g*p-e*w*p-k*g*u+e*l*u)*E;c[8]=A*E;c[9]=(q*r*h-n*t*h-q*f*u+e*t*u+n*f*d-e*r*d)*E;c[10]=(k*t*h-q*m*h+q*f*p-e*t*p-k*f*d+e*m*d)*E;c[11]=(n*m*h-k*r*h-n*f*p+e*r*p+k*f*u-e*m*u)*E;c[12]=I*E;c[13]=(n*t*g-q*r*g+q*f*w-e*t*w-n*f*v+e*r*v)*E;c[14]=(q*m*g-k*t*g-q*f*l+e*t*l+k*f*v-e*m*v)*E;c[15]=(k*r*g-n*m*g+n*f*l-
13337 e*r*l-k*f*w+e*m*w)*E;return this},scale:function(a){var b=this.elements,c=a.x,d=a.y;a=a.z;b[0]*=c;b[4]*=d;b[8]*=a;b[1]*=c;b[5]*=d;b[9]*=a;b[2]*=c;b[6]*=d;b[10]*=a;b[3]*=c;b[7]*=d;b[11]*=a;return this},getMaxScaleOnAxis:function(){var a=this.elements;return Math.sqrt(Math.max(a[0]*a[0]+a[1]*a[1]+a[2]*a[2],a[4]*a[4]+a[5]*a[5]+a[6]*a[6],a[8]*a[8]+a[9]*a[9]+a[10]*a[10]))},makeTranslation:function(a,b,c){this.set(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1);return this},makeRotationX:function(a){var b=Math.cos(a);
13338 a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=1-c,f=a.x,g=a.y,h=a.z,k=e*f,m=e*g;this.set(k*f+c,k*g-d*h,k*h+d*g,0,k*g+d*h,m*g+c,m*h-d*f,0,k*h-d*g,m*h+d*f,e*h*h+c,0,0,0,0,1);return this},
13339 makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},makeShear:function(a,b,c){this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1);return this},compose:function(a,b,c){this.makeRotationFromQuaternion(b);this.scale(c);this.setPosition(a);return this},decompose:function(){var a,b;return function(c,d,e){void 0===a&&(a=new q,b=new H);var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),k=a.set(f[8],f[9],f[10]).length();0>this.determinant()&&(g=-g);c.x=
13340 f[12];c.y=f[13];c.z=f[14];b.elements.set(this.elements);c=1/g;var f=1/h,m=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makeFrustum:function(a,b,c,d,e,f){var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(d-c);g[9]=(d+c)/(d-c);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=
13341 0;g[11]=-1;g[15]=0;return this},makePerspective:function(a,b,c,d){a=c*Math.tan(Q.DEG2RAD*a*.5);var e=-a;return this.makeFrustum(e*b,a*b,e,a,c,d)},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),m=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},
13342 fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}};Za.prototype=Object.create(ea.prototype);Za.prototype.constructor=Za;Za.prototype.isCubeTexture=!0;Object.defineProperty(Za.prototype,
13343 "images",{get:function(){return this.image},set:function(a){this.image=a}});var se=new ea,te=new Za,pe=[],re=[];xe.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var Id=/([\w\d_]+)(\])?(\[|\.)?/g;$a.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};$a.prototype.set=function(a,b,c){var d=this.map[c];void 0!==d&&d.setValue(a,b[c],this.renderer)};$a.prototype.setOptional=function(a,b,c){b=b[c];
13344 void 0!==b&&this.setValue(a,c,b)};$a.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};$a.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var Ja={merge:function(a){for(var b={},c=0;c<a.length;c++){var d=this.clone(a[c]),e;for(e in d)b[e]=d[e]}return b},clone:function(a){var b={},c;for(c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||
13345 e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},Z={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n",alphatest_fragment:"#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n",
13346 aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 ltcTextureCoords( const in GeometricContext geometry, const in float roughness ) {\n\tconst float LUT_SIZE  = 64.0;\n\tconst float LUT_SCALE = (LUT_SIZE - 1.0)/LUT_SIZE;\n\tconst float LUT_BIAS  = 0.5/LUT_SIZE;\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] =  L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3(   1,   0, t.y ),\n\t\tvec3(   0, t.z,   0 ),\n\t\tvec3( t.w,   0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n",
13347 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",
13348 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",
13349 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",
13350 color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n",
13351 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",
13352 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",
13353 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",
13354 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",
13355 envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n",
13356 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",
13357 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",
13358 gradientmap_pars_fragment:"#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n",
13359 lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n",
13360 lights_pars:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight  ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n",
13361 lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\n#if NUM_RECT_AREA_LIGHTS > 0\n    void RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n        vec3 matDiffColor = material.diffuseColor;\n        vec3 matSpecColor = material.specularColor;\n        vec3 lightColor   = rectAreaLight.color;\n        float roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n        vec3 spec = Rect_Area_Light_Specular_Reflectance(\n                geometry,\n                rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n                roughness,\n                ltcMat, ltcMag );\n        vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n                geometry,\n                rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n        reflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\n        reflectedLight.directDiffuse  += lightColor * matDiffColor * diff / PI2;\n    }\n#endif\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n",
13362 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",
13363 lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n    void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n        vec3 matDiffColor = material.diffuseColor;\n        vec3 matSpecColor = material.specularColor;\n        vec3 lightColor   = rectAreaLight.color;\n        float roughness = material.specularRoughness;\n        vec3 spec = Rect_Area_Light_Specular_Reflectance(\n                geometry,\n                rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n                roughness,\n                ltcMat, ltcMag );\n        vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n                geometry,\n                rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n        reflectedLight.directSpecular += lightColor * matSpecColor * spec;\n        reflectedLight.directDiffuse  += lightColor * matDiffColor * diff;\n    }\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material )   GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material )   GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n",
13364 lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",
13365 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",
13366 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",
13367 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",
13368 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",
13369 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",
13370 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",
13371 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",
13372 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",
13373 roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n    #if NUM_RECT_AREA_LIGHTS > 0\n    #endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n",
13374 shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n    #if NUM_RECT_AREA_LIGHTS > 0\n    #endif\n#endif\n",
13375 shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n    #if NUM_RECT_AREA_LIGHTS > 0\n    #endif\n#endif\n",
13376 shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
13377 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",
13378 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",
13379 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",
13380 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",
13381 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",
13382 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",
13383 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",
13384 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",
13385 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",
13386 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",
13387 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",
13388 linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
13389 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",
13390 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",
13391 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",
13392 meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
13393 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",
13394 meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
13395 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",
13396 normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED  ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#include <premultiplied_alpha_fragment>\n\t#include <encodings_fragment>\n}\n",
13397 normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED  ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED  ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n",
13398 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",
13399 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",
13400 shadow_frag:"uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0  - getShadowMask() ) );\n}\n",shadow_vert:"#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n"};N.prototype={constructor:N,
13401 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,
13402 c,d){b=Q.euclideanModulo(b,1);c=Q.clamp(c,0,1);d=Q.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=
13403 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])/
13404 360,e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0<a.length&&(c=Lf[a],void 0!==
13405 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=
13406 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):
13407 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+=
13408 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=
13409 0);this.r=a[b];this.g=a[b+1];this.b=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.r;a[b+1]=this.g;a[b+2]=this.b;return a},toJSON:function(){return this.getHex()}};var Lf={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,
13410 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,
13411 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,
13412 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,
13413 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,
13414 silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};db.prototype=Object.create(ea.prototype);db.prototype.constructor=db;db.prototype.isDataTexture=!0;var U={common:{diffuse:{value:new N(15658734)},opacity:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,
13415 0,1,1)},specularMap:{value:null},alphaMap:{value:null},envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new C(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},
13416 roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:2.5E-4},fogNear:{value:1},fogFar:{value:2E3},fogColor:{value:new N(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},
13417 direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},
13418 width:{},height:{}}}},points:{diffuse:{value:new N(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,0,1,1)}}},Gb={basic:{uniforms:Ja.merge([U.common,U.aomap,U.lightmap,U.fog]),vertexShader:Z.meshbasic_vert,fragmentShader:Z.meshbasic_frag},lambert:{uniforms:Ja.merge([U.common,U.aomap,U.lightmap,U.emissivemap,U.fog,U.lights,{emissive:{value:new N(0)}}]),vertexShader:Z.meshlambert_vert,fragmentShader:Z.meshlambert_frag},phong:{uniforms:Ja.merge([U.common,
13419 U.aomap,U.lightmap,U.emissivemap,U.bumpmap,U.normalmap,U.displacementmap,U.gradientmap,U.fog,U.lights,{emissive:{value:new N(0)},specular:{value:new N(1118481)},shininess:{value:30}}]),vertexShader:Z.meshphong_vert,fragmentShader:Z.meshphong_frag},standard:{uniforms:Ja.merge([U.common,U.aomap,U.lightmap,U.emissivemap,U.bumpmap,U.normalmap,U.displacementmap,U.roughnessmap,U.metalnessmap,U.fog,U.lights,{emissive:{value:new N(0)},roughness:{value:.5},metalness:{value:0},envMapIntensity:{value:1}}]),
13420 vertexShader:Z.meshphysical_vert,fragmentShader:Z.meshphysical_frag},points:{uniforms:Ja.merge([U.points,U.fog]),vertexShader:Z.points_vert,fragmentShader:Z.points_frag},dashed:{uniforms:Ja.merge([U.common,U.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Z.linedashed_vert,fragmentShader:Z.linedashed_frag},depth:{uniforms:Ja.merge([U.common,U.displacementmap]),vertexShader:Z.depth_vert,fragmentShader:Z.depth_frag},normal:{uniforms:Ja.merge([U.common,U.bumpmap,U.normalmap,
13421 U.displacementmap,{opacity:{value:1}}]),vertexShader:Z.normal_vert,fragmentShader:Z.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Z.cube_vert,fragmentShader:Z.cube_frag},equirect:{uniforms:{tEquirect:{value:null},tFlip:{value:-1}},vertexShader:Z.equirect_vert,fragmentShader:Z.equirect_frag},distanceRGBA:{uniforms:{lightPos:{value:new q}},vertexShader:Z.distanceRGBA_vert,fragmentShader:Z.distanceRGBA_frag}};Gb.physical={uniforms:Ja.merge([Gb.standard.uniforms,
13422 {clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:Z.meshphysical_vert,fragmentShader:Z.meshphysical_frag};pc.prototype={constructor:pc,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new C;return function(b,c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);return this}}(),clone:function(){return(new this.constructor).copy(this)},
13423 copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);
13424 return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y},getParameter:function(a,b){return(b||new C).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-
13425 this.min.y))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y?!1:!0},clampPoint:function(a,b){return(b||new C).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);
13426 this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};var pf=0;W.prototype={constructor:W,isMaterial:!0,get needsUpdate(){return this._needsUpdate},set needsUpdate(a){!0===a&&this.update();this._needsUpdate=a},setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+b+"' parameter is undefined.");else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):
13427 d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.4,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);
13428 void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=
13429 this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=
13430 this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);
13431 this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);2!==this.shading&&(d.shading=this.shading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;
13432 d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=this.premultipliedAlpha);!0===this.wireframe&&(d.wireframe=this.wireframe);1<this.wireframeLinewidth&&(d.wireframeLinewidth=this.wireframeLinewidth);"round"!==this.wireframeLinecap&&(d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin);d.skinning=this.skinning;d.morphTargets=this.morphTargets;
13433 c&&(c=b(a.textures),a=b(a.images),0<c.length&&(d.textures=c),0<a.length&&(d.images=a));return d},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.fog=a.fog;this.lights=a.lights;this.blending=a.blending;this.side=a.side;this.shading=a.shading;this.vertexColors=a.vertexColors;this.opacity=a.opacity;this.transparent=a.transparent;this.blendSrc=a.blendSrc;this.blendDst=a.blendDst;this.blendEquation=a.blendEquation;this.blendSrcAlpha=a.blendSrcAlpha;this.blendDstAlpha=
13434 a.blendDstAlpha;this.blendEquationAlpha=a.blendEquationAlpha;this.depthFunc=a.depthFunc;this.depthTest=a.depthTest;this.depthWrite=a.depthWrite;this.colorWrite=a.colorWrite;this.precision=a.precision;this.polygonOffset=a.polygonOffset;this.polygonOffsetFactor=a.polygonOffsetFactor;this.polygonOffsetUnits=a.polygonOffsetUnits;this.alphaTest=a.alphaTest;this.premultipliedAlpha=a.premultipliedAlpha;this.overdraw=a.overdraw;this.visible=a.visible;this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;
13435 a=a.clippingPlanes;var b=null;if(null!==a)for(var c=a.length,b=Array(c),d=0;d!==c;++d)b[d]=a[d].clone();this.clippingPlanes=b;return this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}};Object.assign(W.prototype,oa.prototype);Ia.prototype=Object.create(W.prototype);Ia.prototype.constructor=Ia;Ia.prototype.isShaderMaterial=!0;Ia.prototype.copy=function(a){W.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=
13436 a.vertexShader;this.uniforms=Ja.clone(a.uniforms);this.defines=a.defines;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.lights=a.lights;this.clipping=a.clipping;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;this.extensions=a.extensions;return this};Ia.prototype.toJSON=function(a){a=W.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};ab.prototype=
13437 Object.create(W.prototype);ab.prototype.constructor=ab;ab.prototype.isMeshDepthMaterial=!0;ab.prototype.copy=function(a){W.prototype.copy.call(this,a);this.depthPacking=a.depthPacking;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};ya.prototype=
13438 {constructor:ya,isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;h<k;h+=3){var m=a[h],l=a[h+1],p=a[h+2];m<b&&(b=m);l<c&&(c=l);p<d&&(d=p);m>e&&(e=m);l>f&&(f=l);p>g&&(g=p)}this.min.set(b,c,d);this.max.set(e,f,g)},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var m=a.getX(h),
13439 l=a.getY(h),p=a.getZ(h);m<b&&(b=m);l<c&&(c=l);p<d&&(d=p);m>e&&(e=m);l>f&&(f=l);p>g&&(g=p)}this.min.set(b,c,d);this.max.set(e,f,g)},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new q;return function(b,c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);return this}}(),setFromObject:function(){var a=new q;return function(b){var c=this;b.updateMatrixWorld(!0);this.makeEmpty();
13440 b.traverse(function(b){var e,f;e=b.geometry;if(void 0!==e)if(e.isGeometry){var g=e.vertices;e=0;for(f=g.length;e<f;e++)a.copy(g[e]),a.applyMatrix4(b.matrixWorld),c.expandByPoint(a)}else if(e.isBufferGeometry&&(g=e.attributes.position,void 0!==g))for(e=0,f=g.count;e<f;e++)a.fromAttribute(g,e).applyMatrix4(b.matrixWorld),c.expandByPoint(a)});return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=
13441 this.min.y=this.min.z=Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(a){a=a||new q;return this.isEmpty()?a.set(0,0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new q;return this.isEmpty()?a.set(0,0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);
13442 this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y||a.z<this.min.z||a.z>this.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z},getParameter:function(a,b){return(b||new q).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/
13443 (this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y||a.max.z<this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a;return function(b){void 0===a&&(a=new q);this.clampPoint(b.center,a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0<a.normal.x?(b=a.normal.x*this.min.x,c=a.normal.x*this.max.x):(b=a.normal.x*
13444 this.max.x,c=a.normal.x*this.min.x);0<a.normal.y?(b+=a.normal.y*this.min.y,c+=a.normal.y*this.max.y):(b+=a.normal.y*this.max.y,c+=a.normal.y*this.min.y);0<a.normal.z?(b+=a.normal.z*this.min.z,c+=a.normal.z*this.max.z):(b+=a.normal.z*this.max.z,c+=a.normal.z*this.min.z);return b<=a.constant&&c>=a.constant},clampPoint:function(a,b){return(b||new q).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new q;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),
13445 getBoundingSphere:function(){var a=new q;return function(b){b=b||new Fa;this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new q,new q,new q,new q,new q,new q,new q,new q];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);
13446 a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);
13447 return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};Fa.prototype={constructor:Fa,set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new ya;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=0,f=0,g=b.length;f<g;f++)e=Math.max(e,d.distanceToSquared(b[f]));this.radius=Math.sqrt(e);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.center.copy(a.center);
13448 this.radius=a.radius;return this},empty:function(){return 0>=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},
13449 clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new q;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a=a||new ya;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&
13450 a.radius===this.radius}};za.prototype={constructor:za,isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=k;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){a=a.elements;this.set(a[0],a[3],a[6],a[1],a[4],a[7],a[2],a[5],a[8]);return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],
13451 a[2],a[6],a[10]);return this},applyToVector3Array:function(){var a;return function(b,c,d){void 0===a&&(a=new q);void 0===c&&(c=0);void 0===d&&(d=b.length);for(var e=0;e<d;e+=3,c+=3)a.fromArray(b,c),a.applyMatrix3(this),a.toArray(b,c);return b}}(),applyToBufferAttribute:function(){var a;return function(b){void 0===a&&(a=new q);for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiplyScalar:function(a){var b=this.elements;
13452 b[0]*=a;b[3]*=a;b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=a;return this},determinant:function(){var a=this.elements,b=a[0],c=a[1],d=a[2],e=a[3],f=a[4],g=a[5],h=a[6],k=a[7],a=a[8];return b*f*a-b*g*k-c*e*a+c*g*h+d*e*k-d*f*h},getInverse:function(a,b){a&&a.isMatrix4&&console.error("THREE.Matrix3.getInverse no longer takes a Matrix4 argument.");var c=a.elements,d=this.elements,e=c[0],f=c[1],g=c[2],h=c[3],k=c[4],m=c[5],l=c[6],p=c[7],c=c[8],n=c*k-m*p,r=m*l-c*h,w=p*h-k*l,q=e*n+f*r+g*w;if(0===
13453 q){if(!0===b)throw Error("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");return this.identity()}q=1/q;d[0]=n*q;d[1]=(g*p-c*f)*q;d[2]=(m*f-g*k)*q;d[3]=r*q;d[4]=(c*e-g*l)*q;d[5]=(g*h-m*e)*q;d[6]=w*q;d[7]=(f*l-p*e)*q;d[8]=(k*e-f*h)*q;return this},transpose:function(){var a,b=this.elements;a=b[1];b[1]=b[3];b[3]=a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},
13454 transposeIntoArray:function(a){var b=this.elements;a[0]=b[0];a[1]=b[3];a[2]=b[6];a[3]=b[1];a[4]=b[4];a[5]=b[7];a[6]=b[2];a[7]=b[5];a[8]=b[8];return this},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}};ma.prototype={constructor:ma,set:function(a,b){this.normal.copy(a);
13455 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);
13456 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||
13457 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)},
13458 intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){return(a||new q).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new q,b=new za;return function(c,d){var e=this.coplanarPoint(a).applyMatrix4(c),f=d||b.getNormalMatrix(c),f=this.normal.applyMatrix3(f).normalize();this.constant=-e.dot(f);return this}}(),translate:function(a){this.constant-=a.dot(this.normal);return this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===
13459 this.constant}};qc.prototype={constructor:qc,set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],m=c[7],l=c[8],p=c[9],n=c[10],r=c[11],q=c[12],u=c[13],F=c[14],c=c[15];
13460 b[0].setComponents(f-a,m-g,r-l,c-q).normalize();b[1].setComponents(f+a,m+g,r+l,c+q).normalize();b[2].setComponents(f+d,m+h,r+p,c+u).normalize();b[3].setComponents(f-d,m-h,r-p,c-u).normalize();b[4].setComponents(f-e,m-k,r-n,c-F).normalize();b[5].setComponents(f+e,m+k,r+n,c+F).normalize();return this},intersectsObject:function(){var a=new Fa;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),
13461 intersectsSprite:function(){var a=new Fa;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)<a)return!1;return!0},intersectsBox:function(){var a=new q,b=new q;return function(c){for(var d=this.planes,e=0;6>e;e++){var f=d[e];a.x=0<f.normal.x?c.min.x:c.max.x;b.x=0<f.normal.x?c.max.x:c.min.x;a.y=0<f.normal.y?
13462 c.min.y:c.max.y;b.y=0<f.normal.y?c.max.y:c.min.y;a.z=0<f.normal.z?c.min.z:c.max.z;b.z=0<f.normal.z?c.max.z:c.min.z;var g=f.distanceToPoint(a),f=f.distanceToPoint(b);if(0>g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}};bb.prototype={constructor:bb,set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.origin.copy(a.origin);
13463 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)},
13464 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);
13465 var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),l=-c.dot(b),p=c.lengthSq(),n=Math.abs(1-k*k),r;0<n?(d=k*l-m,e=k*m-l,r=h*n,0<=d?e>=-r?e<=r?(h=1/n,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*l)+p):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+p):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+p):e<=-r?(d=Math.max(0,-(-k*h+m)),e=0<d?-h:Math.min(Math.max(-h,-l),h),k=-d*d+e*(e+2*l)+p):e<=r?(d=0,e=Math.min(Math.max(-h,-l),h),k=e*(e+2*l)+p):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,
13466 -l),h),k=-d*d+e*(e+2*l)+p)):(e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+p);f&&f.copy(this.direction).multiplyScalar(d).add(this.origin);g&&g.copy(b).multiplyScalar(e).add(a);return k}}(),intersectSphere:function(){var a=new q;return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d,f=b.radius*b.radius;if(e>f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=
13467 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;
13468 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=
13469 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);
13470 this.direction.sub(this.origin);this.direction.normalize();return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}};cb.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");cb.DefaultOrder="XYZ";cb.prototype={constructor:cb,isEuler:!0,get x(){return this._x},set x(a){this._x=a;this.onChangeCallback()},get y(){return this._y},set y(a){this._y=a;this.onChangeCallback()},get z(){return this._z},set z(a){this._z=a;this.onChangeCallback()},get order(){return this._order},
13471 set order(a){this._order=a;this.onChangeCallback()},set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=Q.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],l=e[2],p=e[6],e=e[10];b=b||
13472 this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-m,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(p,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-l,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(p,-1,1)),.99999>Math.abs(p)?(this._y=Math.atan2(-l,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(l,-1,1)),.99999>
13473 Math.abs(l)?(this._x=Math.atan2(p,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-l,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(p,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();
13474 return this},setFromQuaternion:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new da;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];
13475 this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new q(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}};gd.prototype={constructor:gd,set:function(a){this.mask=1<<a},enable:function(a){this.mask|=1<<a},toggle:function(a){this.mask^=
13476 1<<a},disable:function(a){this.mask&=~(1<<a)},test:function(a){return 0!==(this.mask&a.mask)}};var qf=0;G.DefaultUp=new q(0,1,0);G.DefaultMatrixAutoUpdate=!0;Object.assign(G.prototype,oa.prototype,{isObject3D:!0,applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,!0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},
13477 setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new da;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateX:function(){var a=new q(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=new q(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new q(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new q;
13478 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=
13479 new H;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new H;return function(b){a.lookAt(b,this.position,this.up);this.quaternion.setFromRotationMatrix(a)}}(),add:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.add(arguments[b]);return this}if(a===this)return console.error("THREE.Object3D.add: object can't be added as a child of itself.",a),this;a&&a.isObject3D?(null!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),
13480 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]===
13481 b)return this;for(var c=0,d=this.children.length;c<d;c++){var e=this.children[c].getObjectByProperty(a,b);if(void 0!==e)return e}},getWorldPosition:function(a){a=a||new q;this.updateMatrixWorld(!0);return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new q,b=new q;return function(c){c=c||new da;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new da;return function(b){b=b||new cb;this.getWorldQuaternion(a);
13482 return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new q,b=new da;return function(c){c=c||new q;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new da;return function(b){b=b||new q;this.getWorldQuaternion(a);return b.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);
13483 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,
13484 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=
13485 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=
13486 [];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);
13487 this.matrix.copy(a.matrix);this.matrixWorld.copy(a.matrixWorld);this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate;this.layers.mask=a.layers.mask;this.visible=a.visible;this.castShadow=a.castShadow;this.receiveShadow=a.receiveShadow;this.frustumCulled=a.frustumCulled;this.renderOrder=a.renderOrder;this.userData=JSON.parse(JSON.stringify(a.userData));if(!0===b)for(var c=0;c<a.children.length;c++)this.add(a.children[c].clone());return this}});gb.prototype=
13488 {constructor:gb,set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},getCenter:function(a){return(a||new q).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new q).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},
13489 at:function(a,b){var c=b||new q;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new q,b=new q;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);var e=b.dot(b),e=b.dot(a)/e;d&&(e=Q.clamp(e,0,1));return e}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new q;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);this.end.applyMatrix4(a);
13490 return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}};Aa.normal=function(){var a=new q;return function(b,c,d,e){e=e||new q;e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0<b?e.multiplyScalar(1/Math.sqrt(b)):e.set(0,0,0)}}();Aa.barycoordFromPoint=function(){var a=new q,b=new q,c=new q;return function(d,e,f,g,h){a.subVectors(g,e);b.subVectors(f,e);c.subVectors(d,e);d=a.dot(a);e=a.dot(b);f=a.dot(c);var k=b.dot(b);g=b.dot(c);var m=d*k-e*e;h=
13491 h||new q;if(0===m)return h.set(-2,-1,-1);m=1/m;k=(k*f-e*g)*m;d=(d*g-e*f)*m;return h.set(1-k-d,d,k)}}();Aa.containsPoint=function(){var a=new q;return function(b,c,d,e){b=Aa.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}();Aa.prototype={constructor:Aa,set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},
13492 copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new q,b=new q;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new q).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Aa.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new ma).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Aa.barycoordFromPoint(a,
13493 this.a,this.b,this.c,b)},containsPoint:function(a){return Aa.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a,b,c,d;return function(e,f){void 0===a&&(a=new ma,b=[new gb,new gb,new gb],c=new q,d=new q);var g=f||new q,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;k<b.length;k++){b[k].closestPointToPoint(c,!0,d);var m=
13494 c.distanceToSquared(d);m<h&&(h=m,g.copy(d))}}return g}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}};ha.prototype={constructor:ha,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=
13495 a.vertexColors[b].clone();return this}};Ka.prototype=Object.create(W.prototype);Ka.prototype.constructor=Ka;Ka.prototype.isMeshBasicMaterial=!0;Ka.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;
13496 this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;return this};y.prototype={constructor:y,isBufferAttribute:!0,set needsUpdate(a){!0===a&&this.version++},setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/
13497 this.itemSize:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.itemSize=a.itemSize;this.count=a.count;this.normalized=a.normalized;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.itemSize;c*=b.itemSize;for(var d=0,e=this.itemSize;d<e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<
13498 e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new N);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];b[c++]=f.a;b[c++]=f.b;b[c++]=f.c}return this},copyVector2sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",d),f=new C);b[c++]=f.x;
13499 b[c++]=f.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),f=new q);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z}return this},copyVector4sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",d),f=new ga);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z;b[c++]=f.w}return this},
13500 set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*this.itemSize]},setX:function(a,b){this.array[a*this.itemSize]=b;return this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){this.array[a*this.itemSize+1]=b;return this},getZ:function(a){return this.array[a*this.itemSize+2]},setZ:function(a,b){this.array[a*this.itemSize+2]=b;return this},getW:function(a){return this.array[a*this.itemSize+3]},setW:function(a,b){this.array[a*
13501 this.itemSize+3]=b;return this},setXY:function(a,b,c){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;this.array[a+3]=e;return this},onUpload:function(a){this.onUploadCallback=a;return this},clone:function(){return(new this.constructor).copy(this)}};rc.prototype=Object.create(y.prototype);
13502 rc.prototype.constructor=rc;sc.prototype=Object.create(y.prototype);sc.prototype.constructor=sc;tc.prototype=Object.create(y.prototype);tc.prototype.constructor=tc;uc.prototype=Object.create(y.prototype);uc.prototype.constructor=uc;Ra.prototype=Object.create(y.prototype);Ra.prototype.constructor=Ra;vc.prototype=Object.create(y.prototype);vc.prototype.constructor=vc;Ua.prototype=Object.create(y.prototype);Ua.prototype.constructor=Ua;X.prototype=Object.create(y.prototype);X.prototype.constructor=X;
13503 wc.prototype=Object.create(y.prototype);wc.prototype.constructor=wc;Object.assign(ze.prototype,{computeGroups:function(a){var b,c=[],d=void 0;a=a.faces;for(var e=0;e<a.length;e++){var f=a[e];f.materialIndex!==d&&(d=f.materialIndex,void 0!==b&&(b.count=3*e-b.start,c.push(b)),b={start:3*e,materialIndex:d})}void 0!==b&&(b.count=3*e-b.start,c.push(b));this.groups=c},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length,
13504 k;if(0<h){k=[];for(var m=0;m<h;m++)k[m]=[];this.morphTargets.position=k}var l=a.morphNormals,p=l.length,n;if(0<p){n=[];for(m=0;m<p;m++)n[m]=[];this.morphTargets.normal=n}for(var r=a.skinIndices,q=a.skinWeights,u=r.length===c.length,F=q.length===c.length,m=0;m<b.length;m++){var t=b[m];this.vertices.push(c[t.a],c[t.b],c[t.c]);var v=t.vertexNormals;3===v.length?this.normals.push(v[0],v[1],v[2]):(v=t.normal,this.normals.push(v,v,v));v=t.vertexColors;3===v.length?this.colors.push(v[0],v[1],v[2]):(v=t.color,
13505 this.colors.push(v,v,v));!0===e&&(v=d[0][m],void 0!==v?this.uvs.push(v[0],v[1],v[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",m),this.uvs.push(new C,new C,new C)));!0===f&&(v=d[1][m],void 0!==v?this.uvs2.push(v[0],v[1],v[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",m),this.uvs2.push(new C,new C,new C)));for(v=0;v<h;v++){var M=g[v].vertices;k[v].push(M[t.a],M[t.b],M[t.c])}for(v=0;v<p;v++)M=l[v].vertexNormals[m],n[v].push(M.a,M.b,M.c);
13506 u&&this.skinIndices.push(r[t.a],r[t.b],r[t.c]);F&&this.skinWeights.push(q[t.a],q[t.b],q[t.c])}this.computeGroups(a);this.verticesNeedUpdate=a.verticesNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this}});Object.assign(S.prototype,oa.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=(new za).getNormalMatrix(a),c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);
13507 c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<f;e++)a.vertexNormals[e].applyMatrix3(b).normalize()}null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();this.normalsNeedUpdate=this.verticesNeedUpdate=!0;return this},rotateX:function(){var a;return function(b){void 0===a&&(a=new H);a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a;return function(b){void 0===
13508 a&&(a=new H);a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a;return function(b){void 0===a&&(a=new H);a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a;return function(b){void 0===a&&(a=
13509 new G);a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=void 0!==g?[l[a].clone(),l[b].clone(),l[d].clone()]:[],r=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new ha(a,b,d,f,r,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([p[a].clone(),p[b].clone(),p[d].clone()]);void 0!==m&&c.faceVertexUvs[1].push([n[a].clone(),n[b].clone(),n[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=
13510 a.attributes,f=e.position.array,g=void 0!==e.normal?e.normal.array:void 0,h=void 0!==e.color?e.color.array:void 0,k=void 0!==e.uv?e.uv.array:void 0,m=void 0!==e.uv2?e.uv2.array:void 0;void 0!==m&&(this.faceVertexUvs[1]=[]);for(var l=[],p=[],n=[],r=e=0;e<f.length;e+=3,r+=2)c.vertices.push(new q(f[e],f[e+1],f[e+2])),void 0!==g&&l.push(new q(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new N(h[e],h[e+1],h[e+2])),void 0!==k&&p.push(new C(k[r],k[r+1])),void 0!==m&&n.push(new C(m[r],m[r+1]));if(void 0!==
13511 d)if(f=a.groups,0<f.length)for(e=0;e<f.length;e++)for(var w=f[e],u=w.start,F=w.count,r=u,u=u+F;r<u;r+=3)b(d[r],d[r+1],d[r+2],w.materialIndex);else for(e=0;e<d.length;e+=3)b(d[e],d[e+1],d[e+2]);else for(e=0;e<f.length/3;e+=3)b(e,e+1,e+2);this.computeFaceNormals();null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());return this},center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,
13512 a.y,a.z);return a},normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius,b=0===b?1:1/b,c=new H;c.set(b,0,0,-b*a.x,0,b,0,-b*a.y,0,0,b,-b*a.z,0,0,0,1);this.applyMatrix(c);return this},computeFaceNormals:function(){for(var a=new q,b=new q,c=0,d=this.faces.length;c<d;c++){var e=this.faces[c],f=this.vertices[e.a],g=this.vertices[e.b];a.subVectors(this.vertices[e.c],g);b.subVectors(f,g);a.cross(b);a.normalize();e.normal.copy(a)}},computeVertexNormals:function(a){void 0===
13513 a&&(a=!0);var b,c,d;d=Array(this.vertices.length);b=0;for(c=this.vertices.length;b<c;b++)d[b]=new q;if(a){var e,f,g,h=new q,k=new q;a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=this.vertices[c.a],f=this.vertices[c.b],g=this.vertices[c.c],h.subVectors(g,f),k.subVectors(e,f),h.cross(k),d[c.a].add(h),d[c.b].add(h),d[c.c].add(h)}else for(this.computeFaceNormals(),a=0,b=this.faces.length;a<b;a++)c=this.faces[a],d[c.a].add(c.normal),d[c.b].add(c.normal),d[c.c].add(c.normal);b=0;for(c=this.vertices.length;b<
13514 c;b++)d[b].normalize();a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=c.vertexNormals,3===e.length?(e[0].copy(d[c.a]),e[1].copy(d[c.b]),e[2].copy(d[c.c])):(e[0]=d[c.a].clone(),e[1]=d[c.b].clone(),e[2]=d[c.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a,b,c;this.computeFaceNormals();a=0;for(b=this.faces.length;a<b;a++){c=this.faces[a];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),d[1].copy(c.normal),d[2].copy(c.normal)):(d[0]=
13515 c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var a,b,c,d,e;c=0;for(d=this.faces.length;c<d;c++)for(e=this.faces[c],e.__originalFaceNormal?e.__originalFaceNormal.copy(e.normal):e.__originalFaceNormal=e.normal.clone(),e.__originalVertexNormals||(e.__originalVertexNormals=[]),a=0,b=e.vertexNormals.length;a<b;a++)e.__originalVertexNormals[a]?e.__originalVertexNormals[a].copy(e.vertexNormals[a]):e.__originalVertexNormals[a]=
13516 e.vertexNormals[a].clone();var f=new S;f.faces=this.faces;a=0;for(b=this.morphTargets.length;a<b;a++){if(!this.morphNormals[a]){this.morphNormals[a]={};this.morphNormals[a].faceNormals=[];this.morphNormals[a].vertexNormals=[];e=this.morphNormals[a].faceNormals;var g=this.morphNormals[a].vertexNormals,h,k;c=0;for(d=this.faces.length;c<d;c++)h=new q,k={a:new q,b:new q,c:new q},e.push(h),g.push(k)}g=this.morphNormals[a];f.vertices=this.morphTargets[a].vertices;f.computeFaceNormals();f.computeVertexNormals();
13517 c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(e.normal),k.a.copy(e.vertexNormals[0]),k.b.copy(e.vertexNormals[1]),k.c.copy(e.vertexNormals[2])}c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],e.normal=e.__originalFaceNormal,e.vertexNormals=e.__originalVertexNormals},computeLineDistances:function(){for(var a=0,b=this.vertices,c=0,d=b.length;c<d;c++)0<c&&(a+=b[c].distanceTo(b[c-1])),this.lineDistances[c]=a},computeBoundingBox:function(){null===
13518 this.boundingBox&&(this.boundingBox=new ya);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Fa);this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(!1===(a&&a.isGeometry))console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a);else{var d,e=this.vertices.length,f=this.vertices,g=a.vertices,h=this.faces,k=a.faces,m=this.faceVertexUvs[0],l=a.faceVertexUvs[0],p=this.colors,
13519 n=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new za).getNormalMatrix(b));a=0;for(var r=g.length;a<r;a++){var q=g[a].clone();void 0!==b&&q.applyMatrix4(b);f.push(q)}a=0;for(r=n.length;a<r;a++)p.push(n[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],u=g.vertexNormals,n=g.vertexColors,p=new ha(g.a+e,g.b+e,g.c+e);p.normal.copy(g.normal);void 0!==d&&p.normal.applyMatrix3(d).normalize();b=0;for(f=u.length;b<f;b++)q=u[b].clone(),void 0!==d&&q.applyMatrix3(d).normalize(),p.vertexNormals.push(q);p.color.copy(g.color);
13520 b=0;for(f=n.length;b<f;b++)q=n[b],p.vertexColors.push(q.clone());p.materialIndex=g.materialIndex+c;h.push(p)}a=0;for(r=l.length;a<r;a++)if(c=l[a],d=[],void 0!==c){b=0;for(f=c.length;b<f;b++)d.push(c[b].clone());m.push(d)}}},mergeMesh:function(a){!1===(a&&a.isMesh)?console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",a):(a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix))},mergeVertices:function(){var a={},b=[],c=[],d,e=Math.pow(10,4),f,g;f=0;for(g=this.vertices.length;f<
13521 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=
13522 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()+
13523 a.z.toString();if(void 0!==m[b])return m[b];m[b]=k.length/3;k.push(a.x,a.y,a.z);return m[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==p[b])return p[b];p[b]=l.length;l.push(a.getHex());return p[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==r[b])return r[b];r[b]=n.length/2;n.push(a.x,a.y);return r[b]}var e={metadata:{version:4.4,type:"Geometry",generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==
13524 this.parameters){var f=this.parameters,g;for(g in f)void 0!==f[g]&&(e[g]=f[g]);return e}f=[];for(g=0;g<this.vertices.length;g++){var h=this.vertices[g];f.push(h.x,h.y,h.z)}var h=[],k=[],m={},l=[],p={},n=[],r={};for(g=0;g<this.faces.length;g++){var q=this.faces[g],u=void 0!==this.faceVertexUvs[0][g],F=0<q.normal.length(),t=0<q.vertexNormals.length,v=1!==q.color.r||1!==q.color.g||1!==q.color.b,M=0<q.vertexColors.length,z=0,z=a(z,0,0),z=a(z,1,!0),z=a(z,2,!1),z=a(z,3,u),z=a(z,4,F),z=a(z,5,t),z=a(z,6,
13525 v),z=a(z,7,M);h.push(z);h.push(q.a,q.b,q.c);h.push(q.materialIndex);u&&(u=this.faceVertexUvs[0][g],h.push(d(u[0]),d(u[1]),d(u[2])));F&&h.push(b(q.normal));t&&(F=q.vertexNormals,h.push(b(F[0]),b(F[1]),b(F[2])));v&&h.push(c(q.color));M&&(q=q.vertexColors,h.push(c(q[0]),c(q[1]),c(q[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<l.length&&(e.data.colors=l);0<n.length&&(e.data.uvs=[n]);e.data.faces=h;return e},clone:function(){return(new S).copy(this)},copy:function(a){this.vertices=[];this.faces=
13526 [];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},
13527 dispose:function(){this.dispatchEvent({type:"dispose"})}});var Kd=0;Object.assign(D.prototype,oa.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){this.index=a},addAttribute:function(a,b,c){if(!1===(b&&b.isBufferAttribute)&&!1===(b&&b.isInterleavedBufferAttribute))console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.addAttribute(a,new y(b,c));else if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),
13528 this.setIndex(b);else return this.attributes[a]=b,this},getAttribute:function(a){return this.attributes[a]},removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==c?c:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(a,b){this.drawRange.start=a;this.drawRange.count=b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToVector3Array(b.array),b.needsUpdate=!0);b=this.attributes.normal;
13529 void 0!==b&&((new za).getNormalMatrix(a).applyToVector3Array(b.array),b.needsUpdate=!0);null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a;return function(b){void 0===a&&(a=new H);a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a;return function(b){void 0===a&&(a=new H);a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a;return function(b){void 0===
13530 a&&(a=new H);a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a;return function(b){void 0===a&&(a=new G);a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();
13531 this.translate(a.x,a.y,a.z);return a},setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new X(3*b.vertices.length,3);var c=new X(3*b.colors.length,3);this.addAttribute("position",a.copyVector3sArray(b.vertices));this.addAttribute("color",c.copyColorsArray(b.colors));b.lineDistances&&b.lineDistances.length===b.vertices.length&&(a=new X(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());
13532 null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},updateFromObject:function(a){var b=a.geometry;if(a.isMesh){var c=b.__directGeometry;!0===b.elementsNeedUpdate&&(c=void 0,b.elementsNeedUpdate=!1);if(void 0===c)return this.fromGeometry(b);c.verticesNeedUpdate=b.verticesNeedUpdate;c.normalsNeedUpdate=b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;c.groupsNeedUpdate=b.groupsNeedUpdate;
13533 b.verticesNeedUpdate=!1;b.normalsNeedUpdate=!1;b.colorsNeedUpdate=!1;b.uvsNeedUpdate=!1;b.groupsNeedUpdate=!1;b=c}!0===b.verticesNeedUpdate&&(c=this.attributes.position,void 0!==c&&(c.copyVector3sArray(b.vertices),c.needsUpdate=!0),b.verticesNeedUpdate=!1);!0===b.normalsNeedUpdate&&(c=this.attributes.normal,void 0!==c&&(c.copyVector3sArray(b.normals),c.needsUpdate=!0),b.normalsNeedUpdate=!1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),c.needsUpdate=!0),
13534 b.colorsNeedUpdate=!1);b.uvsNeedUpdate&&(c=this.attributes.uv,void 0!==c&&(c.copyVector2sArray(b.uvs),c.needsUpdate=!0),b.uvsNeedUpdate=!1);b.lineDistancesNeedUpdate&&(c=this.attributes.lineDistance,void 0!==c&&(c.copyArray(b.lineDistances),c.needsUpdate=!0),b.lineDistancesNeedUpdate=!1);b.groupsNeedUpdate&&(b.computeGroups(a.geometry),this.groups=b.groups,b.groupsNeedUpdate=!1);return this},fromGeometry:function(a){a.__directGeometry=(new ze).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},
13535 fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new y(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new y(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new y(b,3)).copyColorsArray(a.colors)));0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new y(b,2)).copyVector2sArray(a.uvs)));
13536 0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new y(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<a.vertices.length?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new y(b,1)).copyIndicesArray(a.indices)));this.groups=a.groups;for(var c in a.morphTargets){for(var b=[],d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],h=new X(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new X(4*
13537 a.skinIndices.length,4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new X(4*a.skinWeights.length,4),this.addAttribute("skinWeight",c.copyVector4sArray(a.skinWeights)));null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());return this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new ya);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):
13538 this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var a=new ya,b=new q;return function(){null===this.boundingSphere&&(this.boundingSphere=new Fa);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);
13539 a.getCenter(d);for(var e=0,f=0,g=c.count;f<g;f++)b.x=c.getX(f),b.y=c.getY(f),b.z=c.getZ(f),e=Math.max(e,d.distanceToSquared(b));this.boundingSphere.radius=Math.sqrt(e);isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;
13540 if(void 0===b.normal)this.addAttribute("normal",new y(new Float32Array(d.length),3));else for(var e=b.normal.array,f=0,g=e.length;f<g;f++)e[f]=0;var e=b.normal.array,h,k,m,l=new q,p=new q,n=new q,r=new q,w=new q;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var u=0,F=c.length;u<F;++u)for(f=c[u],g=f.start,h=f.count,f=g,g+=h;f<g;f+=3)h=3*a[f+0],k=3*a[f+1],m=3*a[f+2],l.fromArray(d,h),p.fromArray(d,k),n.fromArray(d,m),r.subVectors(n,p),w.subVectors(l,p),r.cross(w),e[h]+=r.x,e[h+1]+=r.y,
13541 e[h+2]+=r.z,e[k]+=r.x,e[k+1]+=r.y,e[k+2]+=r.z,e[m]+=r.x,e[m+1]+=r.y,e[m+2]+=r.z}else for(f=0,g=d.length;f<g;f+=9)l.fromArray(d,f),p.fromArray(d,f+3),n.fromArray(d,f+6),r.subVectors(n,p),w.subVectors(l,p),r.cross(w),e[f]=r.x,e[f+1]=r.y,e[f+2]=r.z,e[f+3]=r.x,e[f+4]=r.y,e[f+5]=r.z,e[f+6]=r.x,e[f+7]=r.y,e[f+8]=r.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,b){if(!1===(a&&a.isBufferGeometry))console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",
13542 a);else{void 0===b&&(b=0);var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d])for(var e=c[d].array,f=a.attributes[d],g=f.array,h=0,f=f.itemSize*b;h<g.length;h++,f++)e[f]=g[h];return this}},normalizeNormals:function(){for(var a=this.attributes.normal.array,b,c,d,e=0,f=a.length;e<f;e+=3)b=a[e],c=a[e+1],d=a[e+2],b=1/Math.sqrt(b*b+c*c+d*d),a[e]*=b,a[e+1]*=b,a[e+2]*=b},toNonIndexed:function(){if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),
13543 this;var a=new D,b=this.index.array,c=this.attributes,d;for(d in c){for(var e=c[d],f=e.array,e=e.itemSize,g=new f.constructor(b.length*e),h,k=0,m=0,l=b.length;m<l;m++){h=b[m]*e;for(var p=0;p<e;p++)g[k++]=f[h++]}a.addAttribute(d,new y(g,e))}return a},toJSON:function(){var a={metadata:{version:4.4,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};a.uuid=this.uuid;a.type=this.type;""!==this.name&&(a.name=this.name);if(void 0!==this.parameters){var b=this.parameters,c;for(c in b)void 0!==b[c]&&
13544 (a[c]=b[c]);return a}a.data={attributes:{}};var d=this.index;null!==d&&(b=Array.prototype.slice.call(d.array),a.data.index={type:d.array.constructor.name,array:b});d=this.attributes;for(c in d){var e=d[c],b=Array.prototype.slice.call(e.array);a.data.attributes[c]={itemSize:e.itemSize,type:e.array.constructor.name,array:b,normalized:e.normalized}}c=this.groups;0<c.length&&(a.data.groups=JSON.parse(JSON.stringify(c)));c=this.boundingSphere;null!==c&&(a.data.boundingSphere={center:c.center.toArray(),
13545 radius:c.radius});return a},clone:function(){return(new D).copy(this)},copy:function(a){var b=a.index;null!==b&&this.setIndex(b.clone());var b=a.attributes,c;for(c in b)this.addAttribute(c,b[c].clone());a=a.groups;c=0;for(b=a.length;c<b;c++){var d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});D.MaxIndex=65535;Ba.prototype=Object.assign(Object.create(G.prototype),{constructor:Ba,isMesh:!0,setDrawMode:function(a){this.drawMode=
13546 a},copy:function(a){G.prototype.copy.call(this,a);this.drawMode=a.drawMode;return this},updateMorphTargets:function(){var a=this.geometry.morphTargets;if(void 0!==a&&0<a.length){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var b=0,c=a.length;b<c;b++)this.morphTargetInfluences.push(0),this.morphTargetDictionary[a[b].name]=b}},raycast:function(){function a(a,b,c,d,e,f,g){Aa.barycoordFromPoint(a,b,c,d,u);e.multiplyScalar(u.x);f.multiplyScalar(u.y);g.multiplyScalar(u.z);e.add(f).add(g);
13547 return e.clone()}function b(a,b,c,d,e,f,g){var h=a.material;if(null===(1===h.side?c.intersectTriangle(f,e,d,!0,g):c.intersectTriangle(d,e,f,2!==h.side,g)))return null;t.copy(g);t.applyMatrix4(a.matrixWorld);c=b.ray.origin.distanceTo(t);return c<b.near||c>b.far?null:{distance:c,point:t.clone(),object:a}}function c(c,d,e,f,m,l,p,q){g.fromArray(f,3*l);h.fromArray(f,3*p);k.fromArray(f,3*q);if(c=b(c,d,e,g,h,k,F))m&&(n.fromArray(m,2*l),r.fromArray(m,2*p),w.fromArray(m,2*q),c.uv=a(F,g,h,k,n,r,w)),c.face=
13548 new ha(l,p,q,Aa.normal(g,h,k)),c.faceIndex=l;return c}var d=new H,e=new bb,f=new Fa,g=new q,h=new q,k=new q,m=new q,l=new q,p=new q,n=new C,r=new C,w=new C,u=new q,F=new q,t=new q;return function(q,u){var t=this.geometry,A=this.material,I=this.matrixWorld;if(void 0!==A&&(null===t.boundingSphere&&t.computeBoundingSphere(),f.copy(t.boundingSphere),f.applyMatrix4(I),!1!==q.ray.intersectsSphere(f)&&(d.getInverse(I),e.copy(q.ray).applyMatrix4(d),null===t.boundingBox||!1!==e.intersectsBox(t.boundingBox)))){var E,
13549 K;if(t.isBufferGeometry){var y,J,A=t.index,I=t.attributes,t=I.position.array;void 0!==I.uv&&(E=I.uv.array);if(null!==A)for(var I=A.array,C=0,D=I.length;C<D;C+=3){if(A=I[C],y=I[C+1],J=I[C+2],K=c(this,q,e,t,E,A,y,J))K.faceIndex=Math.floor(C/3),u.push(K)}else for(C=0,D=t.length;C<D;C+=9)if(A=C/3,y=A+1,J=A+2,K=c(this,q,e,t,E,A,y,J))K.index=A,u.push(K)}else if(t.isGeometry){var G,H,I=A&&A.isMultiMaterial,C=!0===I?A.materials:null,D=t.vertices;y=t.faces;J=t.faceVertexUvs[0];0<J.length&&(E=J);for(var O=
13550 0,P=y.length;O<P;O++){var R=y[O];K=!0===I?C[R.materialIndex]:A;if(void 0!==K){J=D[R.a];G=D[R.b];H=D[R.c];if(!0===K.morphTargets){K=t.morphTargets;var T=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var N=0,V=K.length;N<V;N++){var S=T[N];if(0!==S){var L=K[N].vertices;g.addScaledVector(m.subVectors(L[R.a],J),S);h.addScaledVector(l.subVectors(L[R.b],G),S);k.addScaledVector(p.subVectors(L[R.c],H),S)}}g.add(J);h.add(G);k.add(H);J=g;G=h;H=k}if(K=b(this,q,e,J,G,H,F))E&&(T=E[O],n.copy(T[0]),
13551 r.copy(T[1]),w.copy(T[2]),K.uv=a(F,J,G,H,n,r,w)),K.face=R,K.faceIndex=O,u.push(K)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});hb.prototype=Object.create(D.prototype);hb.prototype.constructor=hb;ib.prototype=Object.create(D.prototype);ib.prototype.constructor=ib;sa.prototype=Object.create(G.prototype);sa.prototype.constructor=sa;sa.prototype.isCamera=!0;sa.prototype.getWorldDirection=function(){var a=new da;return function(b){b=b||new q;this.getWorldQuaternion(a);
13552 return b.set(0,0,-1).applyQuaternion(a)}}();sa.prototype.lookAt=function(){var a=new H;return function(b){a.lookAt(this.position,b,this.up);this.quaternion.setFromRotationMatrix(a)}}();sa.prototype.clone=function(){return(new this.constructor).copy(this)};sa.prototype.copy=function(a){G.prototype.copy.call(this,a);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);return this};Ha.prototype=Object.assign(Object.create(sa.prototype),{constructor:Ha,isPerspectiveCamera:!0,
13553 copy:function(a){sa.prototype.copy.call(this,a);this.fov=a.fov;this.zoom=a.zoom;this.near=a.near;this.far=a.far;this.focus=a.focus;this.aspect=a.aspect;this.view=null===a.view?null:Object.assign({},a.view);this.filmGauge=a.filmGauge;this.filmOffset=a.filmOffset;return this},setFocalLength:function(a){a=.5*this.getFilmHeight()/a;this.fov=2*Q.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*Q.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*
13554 Q.RAD2DEG*Math.atan(Math.tan(.5*Q.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b;this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*
13555 Q.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==f)var g=f.fullWidth,h=f.fullHeight,e=e+f.offsetX*d/g,b=b-f.offsetY*c/h,d=f.width/g*d,c=f.height/h*c;f=this.filmOffset;0!==f&&(e+=a*f/this.getFilmWidth());this.projectionMatrix.makeFrustum(e,e+d,b-c,b,a,this.far)},toJSON:function(a){a=G.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==
13556 this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});Hb.prototype=Object.assign(Object.create(sa.prototype),{constructor:Hb,isOrthographicCamera:!0,copy:function(a){sa.prototype.copy.call(this,a);this.left=a.left;this.right=a.right;this.top=a.top;this.bottom=a.bottom;this.near=a.near;this.far=a.far;this.zoom=a.zoom;this.view=null===a.view?null:Object.assign({},a.view);return this},setViewOffset:function(a,b,c,d,e,
13557 f){this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=(this.right-this.left)/(2*this.zoom),b=(this.top-this.bottom)/(2*this.zoom),c=(this.right+this.left)/2,d=(this.top+this.bottom)/2,e=c-a,c=c+a,a=d+b,b=d-b;if(null!==this.view)var c=this.zoom/(this.view.width/this.view.fullWidth),b=this.zoom/(this.view.height/this.view.fullHeight),
13558 f=(this.right-this.left)/this.view.width,d=(this.top-this.bottom)/this.view.height,e=e+this.view.offsetX/c*f,c=e+this.view.width/c*f,a=a-this.view.offsetY/b*d,b=a-this.view.height/b*d;this.projectionMatrix.makeOrthographic(e,c,a,b,this.near,this.far)},toJSON:function(a){a=G.prototype.toJSON.call(this,a);a.object.zoom=this.zoom;a.object.left=this.left;a.object.right=this.right;a.object.top=this.top;a.object.bottom=this.bottom;a.object.near=this.near;a.object.far=this.far;null!==this.view&&(a.object.view=
13559 Object.assign({},this.view));return a}});var Af=0;Ib.prototype.isFogExp2=!0;Ib.prototype.clone=function(){return new Ib(this.color.getHex(),this.density)};Ib.prototype.toJSON=function(a){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};Jb.prototype.isFog=!0;Jb.prototype.clone=function(){return new Jb(this.color.getHex(),this.near,this.far)};Jb.prototype.toJSON=function(a){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};jb.prototype=Object.create(G.prototype);
13560 jb.prototype.constructor=jb;jb.prototype.copy=function(a,b){G.prototype.copy.call(this,a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=a.overrideMaterial.clone());this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this};jb.prototype.toJSON=function(a){var b=G.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));null!==
13561 this.fog&&(b.object.fog=this.fog.toJSON());return b};Od.prototype=Object.assign(Object.create(G.prototype),{constructor:Od,isLensFlare:!0,copy:function(a){G.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=a.customUpdateCallback;for(var b=0,c=a.lensFlares.length;b<c;b++)this.lensFlares.push(a.lensFlares[b]);return this},add:function(a,b,c,d,e,f){void 0===b&&(b=-1);void 0===c&&(c=0);void 0===f&&(f=1);void 0===e&&(e=new N(16777215));void 0===d&&(d=1);
13562 c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:0,opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c,d=2*-this.positionScreen.x,e=2*-this.positionScreen.y;for(a=0;a<b;a++)c=this.lensFlares[a],c.x=this.positionScreen.x+d*c.distance,c.y=this.positionScreen.y+e*c.distance,c.wantedRotation=c.x*Math.PI*.25,c.rotation+=.25*(c.wantedRotation-c.rotation)}});kb.prototype=Object.create(W.prototype);kb.prototype.constructor=
13563 kb;kb.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};zc.prototype=Object.assign(Object.create(G.prototype),{constructor:zc,isSprite:!0,raycast:function(){var a=new q;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=b.ray.distanceSqToPoint(a);d>this.scale.x*this.scale.y/4||c.push({distance:Math.sqrt(d),point:this.position,face:null,object:this})}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});
13564 Ac.prototype=Object.assign(Object.create(G.prototype),{constructor:Ac,copy:function(a){G.prototype.copy.call(this,a,!1);a=a.levels;for(var b=0,c=a.length;b<c;b++){var d=a[b];this.addLevel(d.object.clone(),d.distance)}return this},addLevel:function(a,b){void 0===b&&(b=0);b=Math.abs(b);for(var c=this.levels,d=0;d<c.length&&!(b<c[d].distance);d++);c.splice(d,0,{distance:b,object:a});this.add(a)},getObjectForDistance:function(a){for(var b=this.levels,c=1,d=b.length;c<d&&!(a<b[c].distance);c++);return b[c-
13565 1].object},raycast:function(){var a=new q;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=b.ray.origin.distanceTo(a);this.getObjectForDistance(d).raycast(b,c)}}(),update:function(){var a=new q,b=new q;return function(c){var d=this.levels;if(1<d.length){a.setFromMatrixPosition(c.matrixWorld);b.setFromMatrixPosition(this.matrixWorld);c=a.distanceTo(b);d[0].object.visible=!0;for(var e=1,f=d.length;e<f;e++)if(c>=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;
13566 for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=G.prototype.toJSON.call(this,a);a.object.levels=[];for(var b=this.levels,c=0,d=b.length;c<d;c++){var e=b[c];a.object.levels.push({object:e.object.uuid,distance:e.distance})}return a}});Object.assign(hd.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new H;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){for(var a,b=0,c=this.bones.length;b<
13567 c;b++)(a=this.bones[b])&&a.matrixWorld.getInverse(this.boneInverses[b]);b=0;for(c=this.bones.length;b<c;b++)if(a=this.bones[b])a.parent&&a.parent.isBone?(a.matrix.getInverse(a.parent.matrixWorld),a.matrix.multiply(a.matrixWorld)):a.matrix.copy(a.matrixWorld),a.matrix.decompose(a.position,a.quaternion,a.scale)},update:function(){var a=new H;return function(){for(var b=0,c=this.bones.length;b<c;b++)a.multiplyMatrices(this.bones[b]?this.bones[b].matrixWorld:this.identityMatrix,this.boneInverses[b]),
13568 a.toArray(this.boneMatrices,16*b);this.useVertexTexture&&(this.boneTexture.needsUpdate=!0)}}(),clone:function(){return new hd(this.bones,this.boneInverses,this.useVertexTexture)}});id.prototype=Object.assign(Object.create(G.prototype),{constructor:id,isBone:!0});jd.prototype=Object.assign(Object.create(Ba.prototype),{constructor:jd,isSkinnedMesh:!0,bind:function(a,b){this.skeleton=a;void 0===b&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),b=this.matrixWorld);this.bindMatrix.copy(b);
13569 this.bindMatrixInverse.getInverse(b)},pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){if(this.geometry&&this.geometry.isGeometry)for(var a=0;a<this.geometry.skinWeights.length;a++){var b=this.geometry.skinWeights[a],c=1/b.lengthManhattan();Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry)for(var b=new ga,d=this.geometry.attributes.skinWeight,a=0;a<d.count;a++)b.x=d.getX(a),b.y=d.getY(a),b.z=d.getZ(a),b.w=d.getW(a),c=1/b.lengthManhattan(),
13570 Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0),d.setXYZW(a,b.x,b.y,b.z,b.w)},updateMatrixWorld:function(a){Ba.prototype.updateMatrixWorld.call(this,!0);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):"detached"===this.bindMode?this.bindMatrixInverse.getInverse(this.bindMatrix):console.warn("THREE.SkinnedMesh unrecognized bindMode: "+this.bindMode)},clone:function(){return(new this.constructor(this.geometry,this.material,this.skeleton.useVertexTexture)).copy(this)}});
13571 ia.prototype=Object.create(W.prototype);ia.prototype.constructor=ia;ia.prototype.isLineBasicMaterial=!0;ia.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};Va.prototype=Object.assign(Object.create(G.prototype),{constructor:Va,isLine:!0,raycast:function(){var a=new H,b=new bb,c=new Fa;return function(d,e){var f=d.linePrecision,f=f*f,g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&
13572 g.computeBoundingSphere();c.copy(g.boundingSphere);c.applyMatrix4(h);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(h);b.copy(d.ray).applyMatrix4(a);var k=new q,m=new q,h=new q,l=new q,p=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var n=g.index,r=g.attributes.position.array;if(null!==n)for(var n=n.array,g=0,w=n.length-1;g<w;g+=p){var u=n[g+1];k.fromArray(r,3*n[g]);m.fromArray(r,3*u);u=b.distanceSqToSegment(k,m,l,h);u>f||(l.applyMatrix4(this.matrixWorld),u=d.ray.origin.distanceTo(l),u<d.near||
13573 u>d.far||e.push({distance:u,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,w=r.length/3-1;g<w;g+=p)k.fromArray(r,3*g),m.fromArray(r,3*g+3),u=b.distanceSqToSegment(k,m,l,h),u>f||(l.applyMatrix4(this.matrixWorld),u=d.ray.origin.distanceTo(l),u<d.near||u>d.far||e.push({distance:u,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,m=k.length,g=0;g<m-1;g+=p)u=b.distanceSqToSegment(k[g],
13574 k[g+1],l,h),u>f||(l.applyMatrix4(this.matrixWorld),u=d.ray.origin.distanceTo(l),u<d.near||u>d.far||e.push({distance:u,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});fa.prototype=Object.assign(Object.create(Va.prototype),{constructor:fa,isLineSegments:!0});Oa.prototype=Object.create(W.prototype);Oa.prototype.constructor=Oa;Oa.prototype.isPointsMaterial=!0;Oa.prototype.copy=
13575 function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Kb.prototype=Object.assign(Object.create(G.prototype),{constructor:Kb,isPoints:!0,raycast:function(){var a=new H,b=new bb,c=new Fa;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(f<l){var h=b.closestPointToPoint(a);h.applyMatrix4(k);var m=d.ray.origin.distanceTo(h);m<d.near||m>d.far||e.push({distance:m,distanceToRay:Math.sqrt(f),
13576 point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var m=m/((this.scale.x+this.scale.y+this.scale.z)/3),l=m*m,m=new q;if(h.isBufferGeometry){var p=h.index,h=h.attributes.position.array;if(null!==p)for(var n=p.array,p=0,r=n.length;p<r;p++){var w=n[p];m.fromArray(h,
13577 3*w);f(m,w)}else for(p=0,n=h.length/3;p<n;p++)m.fromArray(h,3*p),f(m,p)}else for(m=h.vertices,p=0,n=m.length;p<n;p++)f(m[p],p)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});Bc.prototype=Object.assign(Object.create(G.prototype),{constructor:Bc});kd.prototype=Object.create(ea.prototype);kd.prototype.constructor=kd;Lb.prototype=Object.create(ea.prototype);Lb.prototype.constructor=Lb;Lb.prototype.isCompressedTexture=!0;ld.prototype=Object.create(ea.prototype);
13578 ld.prototype.constructor=ld;Cc.prototype=Object.create(ea.prototype);Cc.prototype.constructor=Cc;Cc.prototype.isDepthTexture=!0;Mb.prototype=Object.create(D.prototype);Mb.prototype.constructor=Mb;Nb.prototype=Object.create(D.prototype);Nb.prototype.constructor=Nb;Dc.prototype=Object.create(S.prototype);Dc.prototype.constructor=Dc;xa.prototype=Object.create(D.prototype);xa.prototype.constructor=xa;Ob.prototype=Object.create(xa.prototype);Ob.prototype.constructor=Ob;Ec.prototype=Object.create(S.prototype);
13579 Ec.prototype.constructor=Ec;lb.prototype=Object.create(xa.prototype);lb.prototype.constructor=lb;Fc.prototype=Object.create(S.prototype);Fc.prototype.constructor=Fc;Pb.prototype=Object.create(xa.prototype);Pb.prototype.constructor=Pb;Gc.prototype=Object.create(S.prototype);Gc.prototype.constructor=Gc;Qb.prototype=Object.create(xa.prototype);Qb.prototype.constructor=Qb;Hc.prototype=Object.create(S.prototype);Hc.prototype.constructor=Hc;Ic.prototype=Object.create(S.prototype);Ic.prototype.constructor=
13580 Ic;Rb.prototype=Object.create(D.prototype);Rb.prototype.constructor=Rb;Jc.prototype=Object.create(S.prototype);Jc.prototype.constructor=Jc;Sb.prototype=Object.create(D.prototype);Sb.prototype.constructor=Sb;Kc.prototype=Object.create(S.prototype);Kc.prototype.constructor=Kc;Tb.prototype=Object.create(D.prototype);Tb.prototype.constructor=Tb;Lc.prototype=Object.create(S.prototype);Lc.prototype.constructor=Lc;var pa={area:function(a){for(var b=a.length,c=0,d=b-1,e=0;e<b;d=e++)c+=a[d].x*a[e].y-a[e].x*
13581 a[d].y;return.5*c},triangulate:function(){return function(a,b){var c=a.length;if(3>c)return null;var d=[],e=[],f=[],g,h,k;if(0<pa.area(a))for(h=0;h<c;h++)e[h]=h;else for(h=0;h<c;h++)e[h]=c-1-h;var m=2*c;for(h=c-1;2<c;){if(0>=m--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var l;a:{var p,n,r,q,u,F,t,v;p=a[e[g]].x;n=a[e[g]].y;r=a[e[h]].x;q=a[e[h]].y;u=a[e[k]].x;F=a[e[k]].y;if(0>=(r-p)*(F-n)-(q-n)*(u-p))l=
13582 !1;else{var M,z,A,I,E,K,y,C,D,G;M=u-r;z=F-q;A=p-u;I=n-F;E=r-p;K=q-n;for(l=0;l<c;l++)if(t=a[e[l]].x,v=a[e[l]].y,!(t===p&&v===n||t===r&&v===q||t===u&&v===F)&&(y=t-p,C=v-n,D=t-r,G=v-q,t-=u,v-=F,D=M*G-z*D,y=E*C-K*y,C=A*v-I*t,D>=-Number.EPSILON&&C>=-Number.EPSILON&&y>=-Number.EPSILON)){l=!1;break a}l=!0}}if(l){d.push([a[e[g]],a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;k<c;g++,k++)e[g]=e[k];c--;m=2*c}}return b?f:d}}(),triangulateShape:function(a,b){function c(a){var b=a.length;2<b&&a[b-1].equals(a[0])&&
13583 a.pop()}function d(a,b,c){return a.x!==b.x?a.x<b.x?a.x<=c.x&&c.x<=b.x:b.x<=c.x&&c.x<=a.x:a.y<b.y?a.y<=c.y&&c.y<=b.y:b.y<=c.y&&c.y<=a.y}function e(a,b,c,e,f){var g=b.x-a.x,h=b.y-a.y,k=e.x-c.x,m=e.y-c.y,l=a.x-c.x,n=a.y-c.y,p=h*k-g*m,q=h*l-g*n;if(Math.abs(p)>Number.EPSILON){if(0<p){if(0>q||q>p)return[];k=m*l-k*n;if(0>k||k>p)return[]}else{if(0<q||q<p)return[];k=m*l-k*n;if(0<k||k<p)return[]}if(0===k)return!f||0!==q&&q!==p?[a]:[];if(k===p)return!f||0!==q&&q!==p?[b]:[];if(0===q)return[c];if(q===p)return[e];
13584 f=k/p;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==q||m*l!==k*n)return[];h=0===g&&0===h;k=0===k&&0===m;if(h&&k)return a.x!==c.x||a.y!==c.y?[]:[a];if(h)return d(c,e,a)?[a]:[];if(k)return d(a,b,c)?[c]:[];0!==g?(a.x<b.x?(g=a,k=a.x,h=b,a=b.x):(g=b,k=b.x,h=a,a=a.x),c.x<e.x?(b=c,p=c.x,m=e,c=e.x):(b=e,p=e.x,m=c,c=c.x)):(a.y<b.y?(g=a,k=a.y,h=b,a=b.y):(g=b,k=b.y,h=a,a=a.y),c.y<e.y?(b=c,p=c.y,m=e,c=e.y):(b=e,p=e.y,m=c,c=c.y));return k<=p?a<p?[]:a===p?f?[]:[b]:a<=c?[b,h]:[b,m]:k>c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,m]}
13585 function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0<a?0<=e&&0<=b:0<=e||0<=b):0<e}c(a);b.forEach(c);var g,h,k,m,l,p={};k=a.concat();g=0;for(h=b.length;g<h;g++)Array.prototype.push.apply(k,b[g]);g=0;for(h=k.length;g<h;g++)l=k[g].x+":"+k[g].y,void 0!==p[l]&&console.warn("THREE.ShapeUtils: Duplicate point",l,g),p[l]=g;g=function(a,b){function c(a,b){var d=h.length-1,e=a-1;0>e&&(e=d);var g=a+1;g>d&&(g=
13586 0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;c<h.length;c++)if(f=c+1,f%=h.length,f=e(a,b,h[c],h[f],!0),0<f.length)return!0;return!1}function g(a,c){var d,f,h,k;for(d=0;d<m.length;d++)for(f=b[m[d]],h=0;h<f.length;h++)if(k=h+1,k%=f.length,k=e(a,c,f[h],f[k],!0),0<k.length)return!0;return!1}var h=a.concat(),k,m=[],l,n,p,q,x,y=[],C,D,G,H=0;for(l=b.length;H<l;H++)m.push(H);C=0;for(var O=2*
13587 m.length;0<m.length;){O--;if(0>O){console.log("Infinite Loop! Holes left:"+m.length+", Probably Hole outside Shape!");break}for(n=C;n<h.length;n++){p=h[n];l=-1;for(H=0;H<m.length;H++)if(q=m[H],x=p.x+":"+p.y+":"+q,void 0===y[x]){k=b[q];for(D=0;D<k.length;D++)if(q=k[D],c(n,D)&&!d(p,q)&&!g(p,q)){l=D;m.splice(H,1);C=h.slice(0,n+1);q=h.slice(n);D=k.slice(l);G=k.slice(0,l+1);h=C.concat(D).concat(G).concat(q);C=n;break}if(0<=l)break;y[x]=!0}if(0<=l)break}}return h}(a,b);var n=pa.triangulate(g,!1);g=0;for(h=
13588 n.length;g<h;g++)for(m=n[g],k=0;3>k;k++)l=m[k].x+":"+m[k].y,l=p[l],void 0!==l&&(m[k]=l);return n.concat()},isClockWise:function(a){return 0>pa.area(a)},b2:function(){return function(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}}(),b3:function(){return function(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}}()};La.prototype=Object.create(S.prototype);La.prototype.constructor=La;La.prototype.addShapeList=function(a,b){for(var c=a.length,d=0;d<c;d++)this.addShape(a[d],
13589 b)};La.prototype.addShape=function(a,b){function c(a,b,c){b||console.error("THREE.ExtrudeGeometry: vec does not exist");return b.clone().multiplyScalar(c).add(a)}function d(a,b,c){var d,e,f;e=a.x-b.x;f=a.y-b.y;d=c.x-a.x;var g=c.y-a.y,h=e*e+f*f;if(Math.abs(e*g-f*d)>Number.EPSILON){var k=Math.sqrt(h),m=Math.sqrt(d*d+g*g),h=b.x-f/k;b=b.y+e/k;g=((c.x-g/m-h)*g-(c.y+d/m-b)*d)/(e*g-f*d);d=h+e*g-a.x;e=b+f*g-a.y;f=d*d+e*e;if(2>=f)return new C(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&&
13590 (a=!0):e<-Number.EPSILON?d<-Number.EPSILON&&(a=!0):Math.sign(f)===Math.sign(g)&&(a=!0),a?(d=-f,f=Math.sqrt(h)):(d=e,e=f,f=Math.sqrt(h/2));return new C(d/f,e/f)}function e(a,b){var c,d;for(L=a.length;0<=--L;){c=L;d=L-1;0>d&&(d=a.length-1);var e,f=r+2*l;for(e=0;e<f;e++){var g=U*e,h=U*(e+1),k=b+c+g,g=b+d+g,m=b+d+h,h=b+c+h,k=k+J,g=g+J,m=m+J,h=h+J;G.faces.push(new ha(k,g,h,null,null,1));G.faces.push(new ha(g,m,h,null,null,1));k=t.generateSideWallUV(G,k,g,m,h);G.faceVertexUvs[0].push([k[0],k[1],k[3]]);
13591 G.faceVertexUvs[0].push([k[1],k[2],k[3]])}}}function f(a,b,c){G.vertices.push(new q(a,b,c))}function g(a,b,c){a+=J;b+=J;c+=J;G.faces.push(new ha(a,b,c,null,null,0));a=t.generateTopUV(G,a,b,c);G.faceVertexUvs[0].push(a)}var h=void 0!==b.amount?b.amount:100,k=void 0!==b.bevelThickness?b.bevelThickness:6,m=void 0!==b.bevelSize?b.bevelSize:k-2,l=void 0!==b.bevelSegments?b.bevelSegments:3,p=void 0!==b.bevelEnabled?b.bevelEnabled:!0,n=void 0!==b.curveSegments?b.curveSegments:12,r=void 0!==b.steps?b.steps:
13592 1,w=b.extrudePath,u,F=!1,t=void 0!==b.UVGenerator?b.UVGenerator:La.WorldUVGenerator,v,y,z,A;w&&(u=w.getSpacedPoints(r),F=!0,p=!1,v=void 0!==b.frames?b.frames:w.computeFrenetFrames(r,!1),y=new q,z=new q,A=new q);p||(m=k=l=0);var I,E,D,G=this,J=this.vertices.length,w=a.extractPoints(n),n=w.shape,H=w.holes;if(w=!pa.isClockWise(n)){n=n.reverse();E=0;for(D=H.length;E<D;E++)I=H[E],pa.isClockWise(I)&&(H[E]=I.reverse());w=!1}var N=pa.triangulateShape(n,H),S=n;E=0;for(D=H.length;E<D;E++)I=H[E],n=n.concat(I);
13593 var Q,O,P,R,T,U=n.length,V,W=N.length,w=[],L=0;P=S.length;Q=P-1;for(O=L+1;L<P;L++,Q++,O++)Q===P&&(Q=0),O===P&&(O=0),w[L]=d(S[L],S[Q],S[O]);var X=[],Z,ba=w.concat();E=0;for(D=H.length;E<D;E++){I=H[E];Z=[];L=0;P=I.length;Q=P-1;for(O=L+1;L<P;L++,Q++,O++)Q===P&&(Q=0),O===P&&(O=0),Z[L]=d(I[L],I[Q],I[O]);X.push(Z);ba=ba.concat(Z)}for(Q=0;Q<l;Q++){P=Q/l;R=k*Math.cos(P*Math.PI/2);O=m*Math.sin(P*Math.PI/2);L=0;for(P=S.length;L<P;L++)T=c(S[L],w[L],O),f(T.x,T.y,-R);E=0;for(D=H.length;E<D;E++)for(I=H[E],Z=X[E],
13594 L=0,P=I.length;L<P;L++)T=c(I[L],Z[L],O),f(T.x,T.y,-R)}O=m;for(L=0;L<U;L++)T=p?c(n[L],ba[L],O):n[L],F?(z.copy(v.normals[0]).multiplyScalar(T.x),y.copy(v.binormals[0]).multiplyScalar(T.y),A.copy(u[0]).add(z).add(y),f(A.x,A.y,A.z)):f(T.x,T.y,0);for(P=1;P<=r;P++)for(L=0;L<U;L++)T=p?c(n[L],ba[L],O):n[L],F?(z.copy(v.normals[P]).multiplyScalar(T.x),y.copy(v.binormals[P]).multiplyScalar(T.y),A.copy(u[P]).add(z).add(y),f(A.x,A.y,A.z)):f(T.x,T.y,h/r*P);for(Q=l-1;0<=Q;Q--){P=Q/l;R=k*Math.cos(P*Math.PI/2);O=
13595 m*Math.sin(P*Math.PI/2);L=0;for(P=S.length;L<P;L++)T=c(S[L],w[L],O),f(T.x,T.y,h+R);E=0;for(D=H.length;E<D;E++)for(I=H[E],Z=X[E],L=0,P=I.length;L<P;L++)T=c(I[L],Z[L],O),F?f(T.x,T.y+u[r-1].y,u[r-1].x+R):f(T.x,T.y,h+R)}(function(){if(p){var a=0*U;for(L=0;L<W;L++)V=N[L],g(V[2]+a,V[1]+a,V[0]+a);a=U*(r+2*l);for(L=0;L<W;L++)V=N[L],g(V[0]+a,V[1]+a,V[2]+a)}else{for(L=0;L<W;L++)V=N[L],g(V[2],V[1],V[0]);for(L=0;L<W;L++)V=N[L],g(V[0]+U*r,V[1]+U*r,V[2]+U*r)}})();(function(){var a=0;e(S,a);a+=S.length;E=0;for(D=
13596 H.length;E<D;E++)I=H[E],e(I,a),a+=I.length})()};La.WorldUVGenerator={generateTopUV:function(a,b,c,d){a=a.vertices;b=a[b];c=a[c];d=a[d];return[new C(b.x,b.y),new C(c.x,c.y),new C(d.x,d.y)]},generateSideWallUV:function(a,b,c,d,e){a=a.vertices;b=a[b];c=a[c];d=a[d];e=a[e];return.01>Math.abs(b.y-c.y)?[new C(b.x,1-b.z),new C(c.x,1-c.z),new C(d.x,1-d.z),new C(e.x,1-e.z)]:[new C(b.y,1-b.z),new C(c.y,1-c.z),new C(d.y,1-d.z),new C(e.y,1-e.z)]}};Mc.prototype=Object.create(La.prototype);Mc.prototype.constructor=
13597 Mc;mb.prototype=Object.create(D.prototype);mb.prototype.constructor=mb;Nc.prototype=Object.create(S.prototype);Nc.prototype.constructor=Nc;Ub.prototype=Object.create(D.prototype);Ub.prototype.constructor=Ub;Oc.prototype=Object.create(S.prototype);Oc.prototype.constructor=Oc;Pc.prototype=Object.create(S.prototype);Pc.prototype.constructor=Pc;Vb.prototype=Object.create(D.prototype);Vb.prototype.constructor=Vb;Qc.prototype=Object.create(S.prototype);Qc.prototype.constructor=Qc;Wb.prototype=Object.create(D.prototype);
13598 Wb.prototype.constructor=Wb;Xb.prototype=Object.create(S.prototype);Xb.prototype.constructor=Xb;Yb.prototype=Object.create(D.prototype);Yb.prototype.constructor=Yb;Wa.prototype=Object.create(D.prototype);Wa.prototype.constructor=Wa;nb.prototype=Object.create(S.prototype);nb.prototype.constructor=nb;Rc.prototype=Object.create(nb.prototype);Rc.prototype.constructor=Rc;Sc.prototype=Object.create(Wa.prototype);Sc.prototype.constructor=Sc;Zb.prototype=Object.create(D.prototype);Zb.prototype.constructor=
13599 Zb;Tc.prototype=Object.create(S.prototype);Tc.prototype.constructor=Tc;$b.prototype=Object.create(S.prototype);$b.prototype.constructor=$b;var Ea=Object.freeze({WireframeGeometry:Mb,ParametricGeometry:Dc,ParametricBufferGeometry:Nb,TetrahedronGeometry:Ec,TetrahedronBufferGeometry:Ob,OctahedronGeometry:Fc,OctahedronBufferGeometry:lb,IcosahedronGeometry:Gc,IcosahedronBufferGeometry:Pb,DodecahedronGeometry:Hc,DodecahedronBufferGeometry:Qb,PolyhedronGeometry:Ic,PolyhedronBufferGeometry:xa,TubeGeometry:Jc,
13600 TubeBufferGeometry:Rb,TorusKnotGeometry:Kc,TorusKnotBufferGeometry:Sb,TorusGeometry:Lc,TorusBufferGeometry:Tb,TextGeometry:Mc,SphereBufferGeometry:mb,SphereGeometry:Nc,RingGeometry:Oc,RingBufferGeometry:Ub,PlaneBufferGeometry:ib,PlaneGeometry:Pc,LatheGeometry:Qc,LatheBufferGeometry:Vb,ShapeGeometry:Xb,ShapeBufferGeometry:Wb,ExtrudeGeometry:La,EdgesGeometry:Yb,ConeGeometry:Rc,ConeBufferGeometry:Sc,CylinderGeometry:nb,CylinderBufferGeometry:Wa,CircleBufferGeometry:Zb,CircleGeometry:Tc,BoxBufferGeometry:hb,
13601 BoxGeometry:$b});ac.prototype=Object.create(Ia.prototype);ac.prototype.constructor=ac;ac.prototype.isShadowMaterial=!0;bc.prototype=Object.create(Ia.prototype);bc.prototype.constructor=bc;bc.prototype.isRawShaderMaterial=!0;Uc.prototype={constructor:Uc,isMultiMaterial:!0,toJSON:function(a){for(var b={metadata:{version:4.2,type:"material",generator:"MaterialExporter"},uuid:this.uuid,type:this.type,materials:[]},c=this.materials,d=0,e=c.length;d<e;d++){var f=c[d].toJSON(a);delete f.metadata;b.materials.push(f)}b.visible=
13602 this.visible;return b},clone:function(){for(var a=new this.constructor,b=0;b<this.materials.length;b++)a.materials.push(this.materials[b].clone());a.visible=this.visible;return a}};Pa.prototype=Object.create(W.prototype);Pa.prototype.constructor=Pa;Pa.prototype.isMeshStandardMaterial=!0;Pa.prototype.copy=function(a){W.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=
13603 a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;
13604 this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};ob.prototype=Object.create(Pa.prototype);ob.prototype.constructor=ob;ob.prototype.isMeshPhysicalMaterial=!0;ob.prototype.copy=function(a){Pa.prototype.copy.call(this,
13605 a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ca.prototype=Object.create(W.prototype);Ca.prototype.constructor=Ca;Ca.prototype.isMeshPhongMaterial=!0;Ca.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=
13606 a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=
13607 a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};pb.prototype=Object.create(Ca.prototype);pb.prototype.constructor=pb;pb.prototype.isMeshToonMaterial=!0;pb.prototype.copy=function(a){Ca.prototype.copy.call(this,a);this.gradientMap=a.gradientMap;return this};qb.prototype=Object.create(W.prototype);
13608 qb.prototype.constructor=qb;qb.prototype.isMeshNormalMaterial=!0;qb.prototype.copy=function(a){W.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=
13609 a.morphNormals;return this};rb.prototype=Object.create(W.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshLambertMaterial=!0;rb.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=
13610 a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};sb.prototype=Object.create(W.prototype);sb.prototype.constructor=sb;sb.prototype.isLineDashedMaterial=!0;sb.prototype.copy=
13611 function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var Mf=Object.freeze({ShadowMaterial:ac,SpriteMaterial:kb,RawShaderMaterial:bc,ShaderMaterial:Ia,PointsMaterial:Oa,MultiMaterial:Uc,MeshPhysicalMaterial:ob,MeshStandardMaterial:Pa,MeshPhongMaterial:Ca,MeshToonMaterial:pb,MeshNormalMaterial:qb,MeshLambertMaterial:rb,MeshDepthMaterial:ab,MeshBasicMaterial:Ka,LineDashedMaterial:sb,
13612 LineBasicMaterial:ia,Material:W}),ne={enabled:!1,files:{},add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},va=new Pd;Object.assign(Ma.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=ne.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);
13613 if(g){var h=g[1],k=!!g[2],g=g[3],g=window.decodeURIComponent(g);k&&(g=window.atob(g));try{var m,l=(this.responseType||"").toLowerCase();switch(l){case "arraybuffer":case "blob":m=new ArrayBuffer(g.length);for(var p=new Uint8Array(m),k=0;k<g.length;k++)p[k]=g.charCodeAt(k);"blob"===l&&(m=new Blob([m],{type:h}));break;case "document":m=(new DOMParser).parseFromString(g,h);break;case "json":m=JSON.parse(g);break;default:m=g}window.setTimeout(function(){b&&b(m);e.manager.itemEnd(a)},0)}catch(q){window.setTimeout(function(){d&&
13614 d(q);e.manager.itemError(a)},0)}}else{var n=new XMLHttpRequest;n.open("GET",a,!0);n.addEventListener("load",function(c){var f=c.target.response;ne.add(a,f);200===this.status?(b&&b(f),e.manager.itemEnd(a)):0===this.status?(console.warn("THREE.FileLoader: HTTP Status 0 received."),b&&b(f),e.manager.itemEnd(a)):(d&&d(c),e.manager.itemError(a))},!1);void 0!==c&&n.addEventListener("progress",function(a){c(a)},!1);n.addEventListener("error",function(b){d&&d(b);e.manager.itemError(a)},!1);void 0!==this.responseType&&
13615 (n.responseType=this.responseType);void 0!==this.withCredentials&&(n.withCredentials=this.withCredentials);n.overrideMimeType&&n.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");n.send(null)}e.manager.itemStart(a);return n},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setMimeType:function(a){this.mimeType=a;return this}});Object.assign(Ee.prototype,{load:function(a,
13616 b,c,d){function e(e){k.load(a[e],function(a){a=f._parser(a,!0);g[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};m+=1;6===m&&(1===a.mipmapCount&&(h.minFilter=1006),h.format=a.format,h.needsUpdate=!0,b&&b(h))},c,d)}var f=this,g=[],h=new Lb;h.image=g;var k=new Ma(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");if(Array.isArray(a))for(var m=0,l=0,p=a.length;l<p;++l)e(l);else k.load(a,function(a){a=f._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,
13617 d=0;d<c;d++){g[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)g[d].mipmaps.push(a.mipmaps[d*a.mipmapCount+e]),g[d].format=a.format,g[d].width=a.width,g[d].height=a.height}else h.image.width=a.width,h.image.height=a.height,h.mipmaps=a.mipmaps;1===a.mipmapCount&&(h.minFilter=1006);h.format=a.format;h.needsUpdate=!0;b&&b(h)},c,d);return h},setPath:function(a){this.path=a;return this}});Object.assign(Qd.prototype,{load:function(a,b,c,d){var e=this,f=new db,g=new Ma(this.manager);g.setResponseType("arraybuffer");
13618 g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?a.anisotropy:1,void 0!==a.format&&(f.format=a.format),void 0!==a.type&&(f.type=a.type),void 0!==a.mipmaps&&(f.mipmaps=a.mipmaps),1===
13619 a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Vc.prototype,{load:function(a,b,c,d){var e=this,f=document.createElementNS("http://www.w3.org/1999/xhtml","img");f.onload=function(){f.onload=null;URL.revokeObjectURL(f.src);b&&b(f);e.manager.itemEnd(a)};f.onerror=d;if(0===a.indexOf("data:"))f.src=a;else if(void 0!==this.crossOrigin)f.crossOrigin=this.crossOrigin,f.src=a;else{var g=new Ma;g.setPath(this.path);g.setResponseType("blob");g.setWithCredentials(this.withCredentials);
13620 g.load(a,function(a){f.src=URL.createObjectURL(a)},c,d)}e.manager.itemStart(a);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(Rd.prototype,{load:function(a,b,c,d){function e(c){g.load(a[c],function(a){f.images[c]=a;h++;6===h&&(f.needsUpdate=!0,b&&b(f))},void 0,d)}var f=new Za,g=new Vc(this.manager);g.setCrossOrigin(this.crossOrigin);g.setPath(this.path);
13621 var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(md.prototype,{load:function(a,b,c,d){var e=new ea,f=new Vc(this.manager);f.setCrossOrigin(this.crossOrigin);f.setWithCredentials(this.withCredentials);f.setPath(this.path);f.load(a,function(c){var d=0<a.search(/\.(jpg|jpeg)$/)||0===a.search(/^data\:image\/jpeg/);e.format=d?1022:1023;e.image=c;e.needsUpdate=!0;void 0!==b&&b(e)},c,d);return e},
13622 setCrossOrigin:function(a){this.crossOrigin=a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setPath:function(a){this.path=a;return this}});na.prototype=Object.assign(Object.create(G.prototype),{constructor:na,isLight:!0,copy:function(a){G.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=G.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=this.intensity;void 0!==this.groundColor&&
13623 (a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&(a.object.shadow=this.shadow.toJSON());return a}});nd.prototype=Object.assign(Object.create(na.prototype),{constructor:nd,isHemisphereLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.groundColor.copy(a.groundColor);
13624 return this}});Object.assign(tb.prototype,{copy:function(a){this.camera=a.camera.clone();this.bias=a.bias;this.radius=a.radius;this.mapSize.copy(a.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var a={};0!==this.bias&&(a.bias=this.bias);1!==this.radius&&(a.radius=this.radius);if(512!==this.mapSize.x||512!==this.mapSize.y)a.mapSize=this.mapSize.toArray();a.camera=this.camera.toJSON(!1).object;delete a.camera.matrix;return a}});od.prototype=Object.assign(Object.create(tb.prototype),
13625 {constructor:od,isSpotLightShadow:!0,update:function(a){var b=2*Q.RAD2DEG*a.angle,c=this.mapSize.width/this.mapSize.height;a=a.distance||500;var d=this.camera;if(b!==d.fov||c!==d.aspect||a!==d.far)d.fov=b,d.aspect=c,d.far=a,d.updateProjectionMatrix()}});pd.prototype=Object.assign(Object.create(na.prototype),{constructor:pd,isSpotLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=a.penumbra;this.decay=a.decay;this.target=a.target.clone();
13626 this.shadow=a.shadow.clone();return this}});qd.prototype=Object.assign(Object.create(na.prototype),{constructor:qd,isPointLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();return this}});rd.prototype=Object.assign(Object.create(tb.prototype),{constructor:rd});sd.prototype=Object.assign(Object.create(na.prototype),{constructor:sd,isDirectionalLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.target=a.target.clone();
13627 this.shadow=a.shadow.clone();return this}});td.prototype=Object.assign(Object.create(na.prototype),{constructor:td,isAmbientLight:!0});var ba={arraySlice:function(a,b,c){return ba.isTypedArray(a)?new a.constructor(a.subarray(b,c)):a.slice(b,c)},convertArray:function(a,b,c){return!a||!c&&a.constructor===b?a:"number"===typeof b.BYTES_PER_ELEMENT?new b(a):Array.prototype.slice.call(a)},isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof DataView)},getKeyframeOrder:function(a){for(var b=
13628 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],
13629 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&&
13630 (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||
13631 this.DefaultSettings_},copySampleValue_:function(a){var b=this.resultBuffer,c=this.sampleValues,d=this.valueSize;a*=d;for(var e=0;e!==d;++e)b[e]=c[a+e];return b},interpolate_:function(a,b,c,d){throw Error("call to abstract method");},intervalChanged_:function(a,b,c){}};Object.assign(qa.prototype,{beforeStart_:qa.prototype.copySampleValue_,afterEnd_:qa.prototype.copySampleValue_});ud.prototype=Object.assign(Object.create(qa.prototype),{constructor:ud,DefaultSettings_:{endingStart:2400,endingEnd:2400},
13632 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,
13633 b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,m=this._offsetNext,l=this._weightPrev,p=this._weightNext,n=(c-b)/(d-b);c=n*n;d=c*n;b=-l*d+2*l*c-l*n;l=(1+l)*d+(-1.5-2*l)*c+(-.5+l)*n+1;n=(-1-p)*d+(1.5+p)*c+.5*n;p=p*d-p*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+l*f[h+c]+n*f[a+c]+p*f[m+c];return e}});Wc.prototype=Object.assign(Object.create(qa.prototype),{constructor:Wc,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;
13634 a*=g;var h=a-g;b=(c-b)/(d-b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});vd.prototype=Object.assign(Object.create(qa.prototype),{constructor:vd,interpolate_:function(a,b,c,d){return this.copySampleValue_(a-1)}});var Ya;Ya={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new vd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Wc(this.times,this.values,
13635 this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new ud(this.times,this.values,this.getValueSize(),a)},setInterpolation:function(a){var b;switch(a){case 2300:b=this.InterpolantFactoryMethodDiscrete;break;case 2301:b=this.InterpolantFactoryMethodLinear;break;case 2302:b=this.InterpolantFactoryMethodSmooth}if(void 0===b){b="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant)if(a!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);
13636 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=
13637 0,d=b.length;c!==d;++c)b[c]*=a;return this},trim:function(a,b){for(var c=this.times,d=c.length,e=0,f=d-1;e!==d&&c[e]<a;)++e;for(;-1!==f&&c[f]>b;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),d=this.getValueSize(),this.times=ba.arraySlice(c,e,f),this.values=ba.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("invalid value size in track",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("track is empty",
13638 this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("time is not a valid number",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("out of order keys",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&ba.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("value is not a valid number",this,f,d);a=!1;break}return a},optimize:function(){for(var a=this.times,b=this.values,c=this.getValueSize(),d=2302===this.getInterpolation(),e=1,
13639 f=a.length-1,g=1;g<f;++g){var h=!1,k=a[g];if(k!==a[g+1]&&(1!==g||k!==k[0]))if(d)h=!0;else for(var m=g*c,l=m-c,p=m+c,k=0;k!==c;++k){var n=b[m+k];if(n!==b[l+k]||n!==b[p+k]){h=!0;break}}if(h){if(g!==e)for(a[e]=a[g],h=g*c,m=e*c,k=0;k!==c;++k)b[m+k]=b[h+k];++e}}if(0<f){a[e]=a[f];h=f*c;m=e*c;for(k=0;k!==c;++k)b[m+k]=b[h+k];++e}e!==a.length&&(this.times=ba.arraySlice(a,0,e),this.values=ba.arraySlice(b,0,e*c));return this}};cc.prototype=Object.assign(Object.create(Ya),{constructor:cc,ValueTypeName:"vector"});
13640 wd.prototype=Object.assign(Object.create(qa.prototype),{constructor:wd,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;b=(c-b)/(d-b);for(c=a+g;a!==c;a+=4)da.slerpFlat(e,0,f,a-g,f,a,b);return e}});Xc.prototype=Object.assign(Object.create(Ya),{constructor:Xc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new wd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});
13641 dc.prototype=Object.assign(Object.create(Ya),{constructor:dc,ValueTypeName:"number"});xd.prototype=Object.assign(Object.create(Ya),{constructor:xd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});yd.prototype=Object.assign(Object.create(Ya),{constructor:yd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});
13642 zd.prototype=Object.assign(Object.create(Ya),{constructor:zd,ValueTypeName:"color"});vb.prototype=Ya;Ya.constructor=vb;Object.assign(vb,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=vb._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];ba.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=
13643 b.toJSON(a);else{var b={name:a.name,times:ba.convertArray(a.times,Array),values:ba.convertArray(a.values,Array)},c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b},_getTrackTypeForValueTypeName:function(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return dc;case "vector":case "vector2":case "vector3":case "vector4":return cc;case "color":return zd;case "quaternion":return Xc;case "bool":case "boolean":return yd;
13644 case "string":return xd}throw Error("Unsupported typeName: "+a);}});ta.prototype={constructor:ta,resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==c;++b)var d=this.tracks[b],a=Math.max(a,d.times[d.times.length-1]);this.duration=a},trim:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].trim(0,this.duration);return this},optimize:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].optimize();return this}};Object.assign(ta,{parse:function(a){for(var b=[],c=a.tracks,
13645 d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(vb.parse(c[e]).scale(d));return new ta(a.name,a.duration,b)},toJSON:function(a){var b=[],c=a.tracks;a={name:a.name,duration:a.duration,tracks:b};for(var d=0,e=c.length;d!==e;++d)b.push(vb.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,b,c,d){for(var e=b.length,f=[],g=0;g<e;g++){var h=[],k=[];h.push((g+e-1)%e,g,(g+1)%e);k.push(0,1,0);var m=ba.getKeyframeOrder(h),h=ba.sortedArray(h,1,m),k=ba.sortedArray(k,1,m);d||0!==h[0]||(h.push(e),
13646 k.push(k[0]));f.push((new dc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new ta(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(var d=0;d<c.length;d++)if(c[d].name===b)return c[d];return null},CreateClipsFromMorphTargetSequences:function(a,b,c){for(var d={},e=/^([\w-]*?)([\d]+)$/,f=0,g=a.length;f<g;f++){var h=a[f],k=h.name.match(e);if(k&&1<k.length){var m=k[1];(k=d[m])||(d[m]=k=[]);k.push(h)}}a=[];for(m in d)a.push(ta.CreateFromMorphTargetSequence(m,
13647 d[m],b,c));return a},parseAnimation:function(a,b){if(!a)return console.error("  no animation in JSONLoader data"),null;for(var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];ba.flattenJSON(c,f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||-1,g=a.fps||30,h=a.hierarchy||[],k=0;k<h.length;k++){var m=h[k].keys;if(m&&0!==m.length)if(m[0].morphTargets){for(var f={},l=0;l<m.length;l++)if(m[l].morphTargets)for(var p=0;p<m[l].morphTargets.length;p++)f[m[l].morphTargets[p]]=
13648 -1;for(var n in f){for(var q=[],w=[],p=0;p!==m[l].morphTargets.length;++p){var u=m[l];q.push(u.time);w.push(u.morphTarget===n?1:0)}d.push(new dc(".morphTargetInfluence["+n+"]",q,w))}f=f.length*(g||1)}else l=".bones["+b[k].name+"]",c(cc,l+".position",m,"pos",d),c(Xc,l+".quaternion",m,"rot",d),c(cc,l+".scale",m,"scl",d)}return 0===d.length?null:new ta(e,f,d)}});Object.assign(Ad.prototype,{load:function(a,b,c,d){var e=this;(new Ma(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=
13649 a},parse:function(a){function b(a){void 0===c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new Mf[a.type];void 0!==a.uuid&&(d.uuid=a.uuid);void 0!==a.name&&(d.name=a.name);void 0!==a.color&&d.color.setHex(a.color);void 0!==a.roughness&&(d.roughness=a.roughness);void 0!==a.metalness&&(d.metalness=a.metalness);void 0!==a.emissive&&d.emissive.setHex(a.emissive);void 0!==a.specular&&d.specular.setHex(a.specular);void 0!==a.shininess&&(d.shininess=a.shininess);
13650 void 0!==a.clearCoat&&(d.clearCoat=a.clearCoat);void 0!==a.clearCoatRoughness&&(d.clearCoatRoughness=a.clearCoatRoughness);void 0!==a.uniforms&&(d.uniforms=a.uniforms);void 0!==a.vertexShader&&(d.vertexShader=a.vertexShader);void 0!==a.fragmentShader&&(d.fragmentShader=a.fragmentShader);void 0!==a.vertexColors&&(d.vertexColors=a.vertexColors);void 0!==a.fog&&(d.fog=a.fog);void 0!==a.shading&&(d.shading=a.shading);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==
13651 a.opacity&&(d.opacity=a.opacity);void 0!==a.transparent&&(d.transparent=a.transparent);void 0!==a.alphaTest&&(d.alphaTest=a.alphaTest);void 0!==a.depthTest&&(d.depthTest=a.depthTest);void 0!==a.depthWrite&&(d.depthWrite=a.depthWrite);void 0!==a.colorWrite&&(d.colorWrite=a.colorWrite);void 0!==a.wireframe&&(d.wireframe=a.wireframe);void 0!==a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&
13652 (d.wireframeLinejoin=a.wireframeLinejoin);void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&(d.morphTargets=a.morphTargets);void 0!==a.size&&(d.size=a.size);void 0!==a.sizeAttenuation&&(d.sizeAttenuation=a.sizeAttenuation);void 0!==a.map&&(d.map=b(a.map));void 0!==a.alphaMap&&(d.alphaMap=b(a.alphaMap),d.transparent=!0);void 0!==a.bumpMap&&(d.bumpMap=b(a.bumpMap));void 0!==a.bumpScale&&(d.bumpScale=a.bumpScale);void 0!==a.normalMap&&(d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=
13653 a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new C).fromArray(e)}void 0!==a.displacementMap&&(d.displacementMap=b(a.displacementMap));void 0!==a.displacementScale&&(d.displacementScale=a.displacementScale);void 0!==a.displacementBias&&(d.displacementBias=a.displacementBias);void 0!==a.roughnessMap&&(d.roughnessMap=b(a.roughnessMap));void 0!==a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=
13654 a.emissiveIntensity);void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));void 0!==a.reflectivity&&(d.reflectivity=a.reflectivity);void 0!==a.lightMap&&(d.lightMap=b(a.lightMap));void 0!==a.lightMapIntensity&&(d.lightMapIntensity=a.lightMapIntensity);void 0!==a.aoMap&&(d.aoMap=b(a.aoMap));void 0!==a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=b(a.gradientMap));if(void 0!==a.materials)for(var e=0,f=a.materials.length;e<
13655 f;e++)d.materials.push(this.parse(a.materials[e]));return d}});Object.assign(Sd.prototype,{load:function(a,b,c,d){var e=this;(new Ma(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new D,c=a.data.index,d={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};void 0!==c&&(c=new d[c.type](c.array),
13656 b.setIndex(new y(c,1)));var e=a.data.attributes,f;for(f in e){var g=e[f],c=new d[g.type](g.array);b.addAttribute(f,new y(c,g.itemSize,g.normalized))}d=a.data.groups||a.data.drawcalls||a.data.offsets;if(void 0!==d)for(f=0,c=d.length;f!==c;++f)e=d[f],b.addGroup(e.start,e.count,e.materialIndex);a=a.data.boundingSphere;void 0!==a&&(d=new q,void 0!==a.center&&d.fromArray(a.center),b.boundingSphere=new Fa(d,a.radius));return b}});wb.prototype={constructor:wb,crossOrigin:void 0,extractUrlBase:function(a){a=
13657 a.split("/");if(1===a.length)return"./";a.pop();return a.join("/")+"/"},initMaterials:function(a,b,c){for(var d=[],e=0;e<a.length;++e)d[e]=this.createMaterial(a[e],b,c);return d},createMaterial:function(){var a,b,c;return function(d,e,f){function g(a,c,d,g,k){a=e+a;var m=wb.Handlers.get(a);null!==m?a=m.load(a):(b.setCrossOrigin(f),a=b.load(a));void 0!==c&&(a.repeat.fromArray(c),1!==c[0]&&(a.wrapS=1E3),1!==c[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==g&&("repeat"===g[0]&&(a.wrapS=
13658 1E3),"mirror"===g[0]&&(a.wrapS=1002),"repeat"===g[1]&&(a.wrapT=1E3),"mirror"===g[1]&&(a.wrapT=1002));void 0!==k&&(a.anisotropy=k);c=Q.generateUUID();h[c]=a;return c}void 0===a&&(a=new N);void 0===b&&(b=new md);void 0===c&&(c=new Ad);var h={},k={uuid:Q.generateUUID(),type:"MeshLambertMaterial"},m;for(m in d){var l=d[m];switch(m){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":k.name=l;break;case "blending":k.blending=Me[l];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",
13659 m,"is no longer supported.");break;case "colorDiffuse":k.color=a.fromArray(l).getHex();break;case "colorSpecular":k.specular=a.fromArray(l).getHex();break;case "colorEmissive":k.emissive=a.fromArray(l).getHex();break;case "specularCoef":k.shininess=l;break;case "shading":"basic"===l.toLowerCase()&&(k.type="MeshBasicMaterial");"phong"===l.toLowerCase()&&(k.type="MeshPhongMaterial");"standard"===l.toLowerCase()&&(k.type="MeshStandardMaterial");break;case "mapDiffuse":k.map=g(l,d.mapDiffuseRepeat,d.mapDiffuseOffset,
13660 d.mapDiffuseWrap,d.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":k.emissiveMap=g(l,d.mapEmissiveRepeat,d.mapEmissiveOffset,d.mapEmissiveWrap,d.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":k.lightMap=g(l,d.mapLightRepeat,d.mapLightOffset,d.mapLightWrap,d.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;
13661 case "mapAO":k.aoMap=g(l,d.mapAORepeat,d.mapAOOffset,d.mapAOWrap,d.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;case "mapBump":k.bumpMap=g(l,d.mapBumpRepeat,d.mapBumpOffset,d.mapBumpWrap,d.mapBumpAnisotropy);break;case "mapBumpScale":k.bumpScale=l;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":k.normalMap=g(l,d.mapNormalRepeat,d.mapNormalOffset,d.mapNormalWrap,d.mapNormalAnisotropy);
13662 break;case "mapNormalFactor":k.normalScale=[l,l];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":k.specularMap=g(l,d.mapSpecularRepeat,d.mapSpecularOffset,d.mapSpecularWrap,d.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":k.metalnessMap=g(l,d.mapMetalnessRepeat,d.mapMetalnessOffset,d.mapMetalnessWrap,d.mapMetalnessAnisotropy);
13663 break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":k.roughnessMap=g(l,d.mapRoughnessRepeat,d.mapRoughnessOffset,d.mapRoughnessWrap,d.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":k.alphaMap=g(l,d.mapAlphaRepeat,d.mapAlphaOffset,d.mapAlphaWrap,d.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;
13664 case "flipSided":k.side=1;break;case "doubleSided":k.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");k.opacity=l;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":k[m]=l;break;case "vertexColors":!0===l&&(k.vertexColors=2);"face"===l&&(k.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",m,l)}}"MeshBasicMaterial"===
13665 k.type&&delete k.emissive;"MeshPhongMaterial"!==k.type&&delete k.specular;1>k.opacity&&(k.transparent=!0);c.setTextures(h);return c.parse(k)}}()};wb.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;c<d;c+=2){var e=b[c+1];if(b[c].test(a))return e}return null}};Object.assign(Td.prototype,{load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:wb.prototype.extractUrlBase(a),g=new Ma(this.manager);
13666 g.setWithCredentials(this.withCredentials);g.load(a,function(c){c=JSON.parse(c);var d=c.metadata;if(void 0!==d&&(d=d.type,void 0!==d)){if("object"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}if("scene"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.SceneLoader instead.");return}}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setTexturePath:function(a){this.texturePath=a},parse:function(a,
13667 b){var c=new S,d=void 0!==a.scale?1/a.scale:1;(function(b){var d,g,h,k,m,l,p,n,r,w,u,F,t,v=a.faces;l=a.vertices;var y=a.normals,z=a.colors,A=0;if(void 0!==a.uvs){for(d=0;d<a.uvs.length;d++)a.uvs[d].length&&A++;for(d=0;d<A;d++)c.faceVertexUvs[d]=[]}k=0;for(m=l.length;k<m;)d=new q,d.x=l[k++]*b,d.y=l[k++]*b,d.z=l[k++]*b,c.vertices.push(d);k=0;for(m=v.length;k<m;)if(b=v[k++],r=b&1,h=b&2,d=b&8,p=b&16,w=b&32,l=b&64,b&=128,r){r=new ha;r.a=v[k];r.b=v[k+1];r.c=v[k+3];u=new ha;u.a=v[k+1];u.b=v[k+2];u.c=v[k+
13668 3];k+=4;h&&(h=v[k++],r.materialIndex=h,u.materialIndex=h);h=c.faces.length;if(d)for(d=0;d<A;d++)for(F=a.uvs[d],c.faceVertexUvs[d][h]=[],c.faceVertexUvs[d][h+1]=[],g=0;4>g;g++)n=v[k++],t=F[2*n],n=F[2*n+1],t=new C(t,n),2!==g&&c.faceVertexUvs[d][h].push(t),0!==g&&c.faceVertexUvs[d][h+1].push(t);p&&(p=3*v[k++],r.normal.set(y[p++],y[p++],y[p]),u.normal.copy(r.normal));if(w)for(d=0;4>d;d++)p=3*v[k++],w=new q(y[p++],y[p++],y[p]),2!==d&&r.vertexNormals.push(w),0!==d&&u.vertexNormals.push(w);l&&(l=v[k++],
13669 l=z[l],r.color.setHex(l),u.color.setHex(l));if(b)for(d=0;4>d;d++)l=v[k++],l=z[l],2!==d&&r.vertexColors.push(new N(l)),0!==d&&u.vertexColors.push(new N(l));c.faces.push(r);c.faces.push(u)}else{r=new ha;r.a=v[k++];r.b=v[k++];r.c=v[k++];h&&(h=v[k++],r.materialIndex=h);h=c.faces.length;if(d)for(d=0;d<A;d++)for(F=a.uvs[d],c.faceVertexUvs[d][h]=[],g=0;3>g;g++)n=v[k++],t=F[2*n],n=F[2*n+1],t=new C(t,n),c.faceVertexUvs[d][h].push(t);p&&(p=3*v[k++],r.normal.set(y[p++],y[p++],y[p]));if(w)for(d=0;3>d;d++)p=3*
13670 v[k++],w=new q(y[p++],y[p++],y[p]),r.vertexNormals.push(w);l&&(l=v[k++],r.color.setHex(z[l]));if(b)for(d=0;3>d;d++)l=v[k++],r.vertexColors.push(new N(z[l]));c.faces.push(r)}})(d);(function(){var b=void 0!==a.influencesPerVertex?a.influencesPerVertex:2;if(a.skinWeights)for(var d=0,g=a.skinWeights.length;d<g;d+=b)c.skinWeights.push(new ga(a.skinWeights[d],1<b?a.skinWeights[d+1]:0,2<b?a.skinWeights[d+2]:0,3<b?a.skinWeights[d+3]:0));if(a.skinIndices)for(d=0,g=a.skinIndices.length;d<g;d+=b)c.skinIndices.push(new ga(a.skinIndices[d],
13671 1<b?a.skinIndices[d+1]:0,2<b?a.skinIndices[d+2]:0,3<b?a.skinIndices[d+3]:0));c.bones=a.bones;c.bones&&0<c.bones.length&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+c.skinWeights.length+") should match.")})();(function(b){if(void 0!==a.morphTargets)for(var d=0,g=a.morphTargets.length;d<g;d++){c.morphTargets[d]={};c.morphTargets[d].name=
13672 a.morphTargets[d].name;c.morphTargets[d].vertices=[];for(var h=c.morphTargets[d].vertices,k=a.morphTargets[d].vertices,m=0,l=k.length;m<l;m+=3){var p=new q;p.x=k[m]*b;p.y=k[m+1]*b;p.z=k[m+2]*b;h.push(p)}}if(void 0!==a.morphColors&&0<a.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),b=c.faces,h=a.morphColors[0].colors,d=0,g=b.length;d<g;d++)b[d].color.fromArray(h,3*d)})(d);(function(){var b=[],d=[];void 0!==a.animation&&d.push(a.animation);
13673 void 0!==a.animations&&(a.animations.length?d=d.concat(a.animations):d.push(a.animations));for(var g=0;g<d.length;g++){var h=ta.parseAnimation(d[g],c.bones);h&&b.push(h)}c.morphTargets&&(d=ta.CreateClipsFromMorphTargetSequences(c.morphTargets,10),b=b.concat(d));0<b.length&&(c.animations=b)})();c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===a.materials.length)return{geometry:c};d=wb.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:d}}});
13674 Object.assign(Fe.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ma(e.manager)).load(a,function(c){var d=null;try{d=JSON.parse(c)}catch(h){console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=d.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?console.error("THREE.ObjectLoader: Can't load "+a+". Use THREE.JSONLoader instead."):e.parse(d,b)},c,d)},setTexturePath:function(a){this.texturePath=
13675 a},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a,b){var c=this.parseGeometries(a.geometries),d=this.parseImages(a.images,function(){void 0!==b&&b(e)}),d=this.parseTextures(a.textures,d),d=this.parseMaterials(a.materials,d),e=this.parseObject(a.object,c,d);a.animations&&(e.animations=this.parseAnimations(a.animations));void 0!==a.images&&0!==a.images.length||void 0===b||b(e);return e},parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new Td,d=new Sd,e=0,f=a.length;e<f;e++){var g,
13676 h=a[e];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":g=new Ea[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":g=new Ea[h.type](h.width,h.height,h.depth,h.widthSegments,h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":g=new Ea[h.type](h.radius,h.segments,h.thetaStart,h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":g=new Ea[h.type](h.radiusTop,
13677 h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":g=new Ea[h.type](h.radius,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":g=new Ea[h.type](h.radius,h.widthSegments,h.heightSegments,h.phiStart,h.phiLength,h.thetaStart,h.thetaLength);break;case "DodecahedronGeometry":case "IcosahedronGeometry":case "OctahedronGeometry":case "TetrahedronGeometry":g=
13678 new Ea[h.type](h.radius,h.detail);break;case "RingGeometry":case "RingBufferGeometry":g=new Ea[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":g=new Ea[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":g=new Ea[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":g=
13679 new Ea[h.type](h.points,h.segments,h.phiStart,h.phiLength);break;case "BufferGeometry":g=d.parse(h);break;case "Geometry":g=c.parse(h.data,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+h.type+'"');continue}g.uuid=h.uuid;void 0!==h.name&&(g.name=h.name);b[h.uuid]=g}return b},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Ad;d.setTextures(b);for(var e=0,f=a.length;e<f;e++){var g=d.parse(a[e]);c[g.uuid]=g}}return c},parseAnimations:function(a){for(var b=
13680 [],c=0;c<a.length;c++){var d=ta.parse(a[c]);b.push(d)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return g.load(a,function(){d.manager.itemEnd(a)},void 0,function(){d.manager.itemError(a)})}var d=this,e={};if(void 0!==a&&0<a.length){var f=new Pd(b),g=new Vc(f);g.setCrossOrigin(this.crossOrigin);for(var f=0,h=a.length;f<h;f++){var k=a[f],m=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(k.url)?k.url:d.texturePath+k.url;e[k.uuid]=c(m)}}return e},parseTextures:function(a,b){function c(a,
13681 b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",a);return b[a]}var d={};if(void 0!==a)for(var e=0,f=a.length;e<f;e++){var g=a[e];void 0===g.image&&console.warn('THREE.ObjectLoader: No "image" specified for',g.uuid);void 0===b[g.image]&&console.warn("THREE.ObjectLoader: Undefined image",g.image);var h=new ea(b[g.image]);h.needsUpdate=!0;h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,Ne));
13682 void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);void 0!==g.wrap&&(h.wrapS=c(g.wrap[0],le),h.wrapT=c(g.wrap[1],le));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,me));void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,me));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(){var a=new H;return function(b,c,d){function e(a){void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",
13683 a);return c[a]}function f(a){if(void 0!==a)return void 0===d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a),d[a]}var g;switch(b.type){case "Scene":g=new jb;void 0!==b.background&&Number.isInteger(b.background)&&(g.background=new N(b.background));void 0!==b.fog&&("Fog"===b.fog.type?g.fog=new Jb(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Ib(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new Ha(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=
13684 b.focus);void 0!==b.zoom&&(g.zoom=b.zoom);void 0!==b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=Object.assign({},b.view));break;case "OrthographicCamera":g=new Hb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new td(b.color,b.intensity);break;case "DirectionalLight":g=new sd(b.color,b.intensity);break;case "PointLight":g=new qd(b.color,b.intensity,b.distance,b.decay);break;case "SpotLight":g=new pd(b.color,
13685 b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new nd(b.color,b.groundColor,b.intensity);break;case "Mesh":g=e(b.geometry);var h=f(b.material);g=g.bones&&0<g.bones.length?new jd(g,h):new Ba(g,h);break;case "LOD":g=new Ac;break;case "Line":g=new Va(e(b.geometry),f(b.material),b.mode);break;case "LineSegments":g=new fa(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Kb(e(b.geometry),f(b.material));break;case "Sprite":g=new zc(f(b.material));
13686 break;case "Group":g=new Bc;break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh type. Instantiates Object3D instead.");default:g=new G}g.uuid=b.uuid;void 0!==b.name&&(g.name=b.name);void 0!==b.matrix?(a.fromArray(b.matrix),a.decompose(g.position,g.quaternion,g.scale)):(void 0!==b.position&&g.position.fromArray(b.position),void 0!==b.rotation&&g.rotation.fromArray(b.rotation),void 0!==b.quaternion&&g.quaternion.fromArray(b.quaternion),void 0!==b.scale&&
13687 g.scale.fromArray(b.scale));void 0!==b.castShadow&&(g.castShadow=b.castShadow);void 0!==b.receiveShadow&&(g.receiveShadow=b.receiveShadow);b.shadow&&(void 0!==b.shadow.bias&&(g.shadow.bias=b.shadow.bias),void 0!==b.shadow.radius&&(g.shadow.radius=b.shadow.radius),void 0!==b.shadow.mapSize&&g.shadow.mapSize.fromArray(b.shadow.mapSize),void 0!==b.shadow.camera&&(g.shadow.camera=this.parseObject(b.shadow.camera)));void 0!==b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=b.userData);
13688 if(void 0!==b.children)for(var k in b.children)g.add(this.parseObject(b.children[k],c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var m=b[h];k=g.getObjectByProperty("uuid",m.object);void 0!==k&&g.addLevel(k,m.distance)}return g}}()});wa.prototype={constructor:wa,getPoint:function(a){console.warn("THREE.Curve: Warning, getPoint() not implemented!");return null},getPointAt:function(a){a=this.getUtoTmapping(a);return this.getPoint(a)},getPoints:function(a){a||(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/
13689 a));return b},getSpacedPoints:function(a){a||(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/a));return b},getLength:function(){var a=this.getLengths();return a[a.length-1]},getLengths:function(a){a||(a=this.__arcLengthDivisions?this.__arcLengthDivisions:200);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b=[],c,d=this.getPoint(0),e,f=0;b.push(0);for(e=1;e<=a;e++)c=this.getPoint(e/a),f+=c.distanceTo(d),b.push(f),
13690 d=c;return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,b){var c=this.getLengths(),d,e=c.length,f;f=b?b:a*c[e-1];for(var g=0,h=e-1,k;g<=h;)if(d=Math.floor(g+(h-g)/2),k=c[d]-f,0>k)g=d+1;else if(0<k)h=d-1;else{h=d;break}d=h;if(c[d]===f)return d/(e-1);g=c[d];return(d+(f-g)/(c[d+1]-g))/(e-1)},getTangent:function(a){var b=a-1E-4;a+=1E-4;0>b&&(b=0);1<a&&(a=1);b=this.getPoint(b);return this.getPoint(a).clone().sub(b).normalize()},getTangentAt:function(a){a=
13691 this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new q,d=[],e=[],f=[],g=new q,h=new H,k,m;for(k=0;k<=a;k++)m=k/a,d[k]=this.getTangentAt(m),d[k].normalize();e[0]=new q;f[0]=new q;k=Number.MAX_VALUE;m=Math.abs(d[0].x);var l=Math.abs(d[0].y),p=Math.abs(d[0].z);m<=k&&(k=m,c.set(1,0,0));l<=k&&(k=l,c.set(0,1,0));p<=k&&c.set(0,0,1);g.crossVectors(d[0],c).normalize();e[0].crossVectors(d[0],g);f[0].crossVectors(d[0],e[0]);for(k=1;k<=a;k++)e[k]=e[k-1].clone(),f[k]=f[k-
13692 1].clone(),g.crossVectors(d[k-1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(Q.clamp(d[k-1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(Q.clamp(e[0].dot(e[a]),-1,1)),c/=a,0<d[0].dot(g.crossVectors(e[0],e[a]))&&(c=-c),k=1;k<=a;k++)e[k].applyMatrix4(h.makeRotationAxis(d[k],c*k)),f[k].crossVectors(d[k],e[k]);return{tangents:d,normals:e,binormals:f}}};wa.create=function(a,b){a.prototype=Object.create(wa.prototype);
13693 a.prototype.constructor=a;a.prototype.getPoint=b;return a};Qa.prototype=Object.create(wa.prototype);Qa.prototype.constructor=Qa;Qa.prototype.isLineCurve=!0;Qa.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=this.v2.clone().sub(this.v1);b.multiplyScalar(a).add(this.v1);return b};Qa.prototype.getPointAt=function(a){return this.getPoint(a)};Qa.prototype.getTangent=function(a){return this.v2.clone().sub(this.v1).normalize()};Yc.prototype=Object.assign(Object.create(wa.prototype),
13694 {constructor:Yc,add:function(a){this.curves.push(a)},closePath:function(){var a=this.curves[0].getPoint(0),b=this.curves[this.curves.length-1].getPoint(1);a.equals(b)||this.curves.push(new Qa(b,a))},getPoint:function(a){var b=a*this.getLength(),c=this.getCurveLengths();for(a=0;a<c.length;){if(c[a]>=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=
13695 !0;this.cacheLengths=null;this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;c<d;c++)b+=this.curves[c].getLength(),a.push(b);return this.cacheLengths=a},getSpacedPoints:function(a){a||(a=40);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));this.autoClose&&b.push(b[0]);return b},getPoints:function(a){a=a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++)for(var f=
13696 e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length:a),g=0;g<f.length;g++){var h=f[g];c&&c.equals(h)||(b.push(h),c=h)}this.autoClose&&1<b.length&&!b[b.length-1].equals(b[0])&&b.push(b[0]);return b},createPointsGeometry:function(a){a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){for(var b=new S,c=0,d=a.length;c<d;c++){var e=a[c];
13697 b.vertices.push(new q(e.x,e.y,e.z||0))}return b}});Xa.prototype=Object.create(wa.prototype);Xa.prototype.constructor=Xa;Xa.prototype.isEllipseCurve=!0;Xa.prototype.getPoint=function(a){for(var b=2*Math.PI,c=this.aEndAngle-this.aStartAngle,d=Math.abs(c)<Number.EPSILON;0>c;)c+=b;for(;c>b;)c-=b;c<Number.EPSILON&&(c=d?0:b);!0!==this.aClockwise||d||(c=c===b?-b:c-b);b=this.aStartAngle+a*c;a=this.aX+this.xRadius*Math.cos(b);var e=this.aY+this.yRadius*Math.sin(b);0!==this.aRotation&&(b=Math.cos(this.aRotation),
13698 c=Math.sin(this.aRotation),d=a-this.aX,e-=this.aY,a=d*b-e*c+this.aX,e=d*c+e*b+this.aY);return new C(a,e)};var ed={tangentQuadraticBezier:function(a,b,c,d){return 2*(1-a)*(c-b)+2*a*(d-c)},tangentCubicBezier:function(a,b,c,d,e){return-3*b*(1-a)*(1-a)+3*c*(1-a)*(1-a)-6*a*c*(1-a)+6*a*d*(1-a)-3*a*a*d+3*a*a*e},tangentSpline:function(a,b,c,d,e){return 6*a*a-6*a+(3*a*a-4*a+1)+(-6*a*a+6*a)+(3*a*a-2*a)},interpolate:function(a,b,c,d,e){a=.5*(c-a);d=.5*(d-b);var f=e*e;return(2*b-2*c+a+d)*e*f+(-3*b+3*c-2*a-d)*
13699 f+a*e+b}};xb.prototype=Object.create(wa.prototype);xb.prototype.constructor=xb;xb.prototype.isSplineCurve=!0;xb.prototype.getPoint=function(a){var b=this.points;a*=b.length-1;var c=Math.floor(a);a-=c;var d=b[0===c?c:c-1],e=b[c],f=b[c>b.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=ed.interpolate;return new C(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a))};yb.prototype=Object.create(wa.prototype);yb.prototype.constructor=yb;yb.prototype.getPoint=function(a){var b=pa.b3;return new C(b(a,this.v0.x,
13700 this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y))};yb.prototype.getTangent=function(a){var b=ed.tangentCubicBezier;return(new C(b(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y))).normalize()};zb.prototype=Object.create(wa.prototype);zb.prototype.constructor=zb;zb.prototype.getPoint=function(a){var b=pa.b2;return new C(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y))};zb.prototype.getTangent=function(a){var b=
13701 ed.tangentQuadraticBezier;return(new C(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y))).normalize()};var oe=Object.assign(Object.create(Yc.prototype),{fromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;b<c;b++)this.lineTo(a[b].x,a[b].y)},moveTo:function(a,b){this.currentPoint.set(a,b)},lineTo:function(a,b){var c=new Qa(this.currentPoint.clone(),new C(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new zb(this.currentPoint.clone(),
13702 new C(a,b),new C(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new yb(this.currentPoint.clone(),new C(a,b),new C(c,d),new C(e,f));this.curves.push(a);this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a),b=new xb(b);this.curves.push(b);this.currentPoint.copy(a[a.length-1])},arc:function(a,b,c,d,e,f){this.absarc(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f)},absarc:function(a,b,c,d,e,f){this.absellipse(a,
13703 b,c,c,d,e,f)},ellipse:function(a,b,c,d,e,f,g,h){this.absellipse(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f,g,h)},absellipse:function(a,b,c,d,e,f,g,h){a=new Xa(a,b,c,d,e,f,g,h);0<this.curves.length&&(b=a.getPoint(0),b.equals(this.currentPoint)||this.lineTo(b.x,b.y));this.curves.push(a);a=a.getPoint(1);this.currentPoint.copy(a)}});Ab.prototype=Object.assign(Object.create(oe),{constructor:Ab,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);
13704 return b},extractAllPoints:function(a){return{shape:this.getPoints(a),holes:this.getPointsHoles(a)}},extractPoints:function(a){return this.extractAllPoints(a)}});Zc.prototype=oe;oe.constructor=Zc;Ud.prototype={moveTo:function(a,b){this.currentPath=new Zc;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,b)},lineTo:function(a,b){this.currentPath.lineTo(a,b)},quadraticCurveTo:function(a,b,c,d){this.currentPath.quadraticCurveTo(a,b,c,d)},bezierCurveTo:function(a,b,c,d,e,f){this.currentPath.bezierCurveTo(a,
13705 b,c,d,e,f)},splineThru:function(a){this.currentPath.splineThru(a)},toShapes:function(a,b){function c(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=new Ab;f.curves=e.curves;b.push(f)}return b}function d(a,b){for(var c=b.length,d=!1,e=c-1,f=0;f<c;e=f++){var g=b[e],h=b[f],k=h.x-g.x,m=h.y-g.y;if(Math.abs(m)>Number.EPSILON){if(0>m&&(g=b[f],k=-k,h=b[e],m=-m),!(a.y<g.y||a.y>h.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=m*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=
13706 a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=pa.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,m=[];if(1===f.length)return h=f[0],k=new Ab,k.curves=h.curves,m.push(k),m;var l=!e(f[0].getPoints()),l=a?!l:l;k=[];var p=[],n=[],q=0,w;p[q]=void 0;n[q]=[];for(var u=0,y=f.length;u<y;u++)h=f[u],w=h.getPoints(),g=e(w),(g=a?!g:g)?(!l&&p[q]&&q++,p[q]={s:new Ab,p:w},p[q].s.curves=h.curves,l&&q++,n[q]=[]):n[q].push({h:h,p:w[0]});if(!p[0])return c(f);if(1<p.length){u=
13707 !1;h=[];e=0;for(f=p.length;e<f;e++)k[e]=[];e=0;for(f=p.length;e<f;e++)for(g=n[e],l=0;l<g.length;l++){q=g[l];w=!0;for(y=0;y<p.length;y++)d(q.p,p[y].p)&&(e!==y&&h.push({froms:e,tos:y,hole:l}),w?(w=!1,k[y].push(q)):u=!0);w&&k[e].push(q)}0<h.length&&(u||(n=k))}u=0;for(e=p.length;u<e;u++)for(k=p[u].s,m.push(k),h=n[u],f=0,g=h.length;f<g;f++)k.holes.push(h[f].h);return m}};Object.assign(Vd.prototype,{isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=100);void 0===c&&(c=4);var d=this.data;a=String(a).split("");
13708 var e=b/d.resolution,f=0;b=[];for(var g=0;g<a.length;g++){var h;h=e;var k=f,m=d.glyphs[a[g]]||d.glyphs["?"];if(m){var l=new Ud,p=[],n=pa.b2,q=pa.b3,w,u,y,t,v,D,z,A;if(m.o)for(var C=m._cachedOutline||(m._cachedOutline=m.o.split(" ")),E=0,G=C.length;E<G;)switch(C[E++]){case "m":w=C[E++]*h+k;u=C[E++]*h;l.moveTo(w,u);break;case "l":w=C[E++]*h+k;u=C[E++]*h;l.lineTo(w,u);break;case "q":w=C[E++]*h+k;u=C[E++]*h;v=C[E++]*h+k;D=C[E++]*h;l.quadraticCurveTo(v,D,w,u);if(t=p[p.length-1]){y=t.x;t=t.y;for(var H=
13709 1;H<=c;H++){var J=H/c;n(J,y,v,w);n(J,t,D,u)}}break;case "b":if(w=C[E++]*h+k,u=C[E++]*h,v=C[E++]*h+k,D=C[E++]*h,z=C[E++]*h+k,A=C[E++]*h,l.bezierCurveTo(v,D,z,A,w,u),t=p[p.length-1])for(y=t.x,t=t.y,H=1;H<=c;H++)J=H/c,q(J,y,v,z,w),q(J,t,D,A,u)}h={offset:m.ha*h,path:l}}else h=void 0;f+=h.offset;b.push(h.path)}c=[];d=0;for(a=b.length;d<a;d++)Array.prototype.push.apply(c,b[d].toShapes());return c}});Object.assign(Ge.prototype,{load:function(a,b,c,d){var e=this;(new Ma(this.manager)).load(a,function(a){var c;
13710 try{c=JSON.parse(a)}catch(d){console.warn("THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead."),c=JSON.parse(a.substring(65,a.length-2))}a=e.parse(c);b&&b(a)},c,d)},parse:function(a){return new Vd(a)}});var Hd,Zd={getContext:function(){void 0===Hd&&(Hd=new (window.AudioContext||window.webkitAudioContext));return Hd},setContext:function(a){Hd=a}};Object.assign(Wd.prototype,{load:function(a,b,c,d){var e=new Ma(this.manager);e.setResponseType("arraybuffer");e.load(a,
13711 function(a){Zd.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Xd.prototype=Object.assign(Object.create(na.prototype),{constructor:Xd,isRectAreaLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.width=a.width;this.height=a.height;return this}});Object.assign(He.prototype,{update:function(){var a,b,c,d,e,f,g,h=new H,k=new H;return function(m){if(a!==this||b!==m.focus||c!==m.fov||d!==m.aspect*this.aspect||e!==m.near||f!==m.far||g!==m.zoom){a=this;b=m.focus;c=m.fov;d=m.aspect*this.aspect;
13712 e=m.near;f=m.far;g=m.zoom;var l=m.projectionMatrix.clone(),p=this.eyeSep/2,n=p*e/b,q=e*Math.tan(Q.DEG2RAD*c*.5)/g,w;k.elements[12]=-p;h.elements[12]=p;p=-q*d+n;w=q*d+n;l.elements[0]=2*e/(w-p);l.elements[8]=(w+p)/(w-p);this.cameraL.projectionMatrix.copy(l);p=-q*d-n;w=q*d-n;l.elements[0]=2*e/(w-p);l.elements[8]=(w+p)/(w-p);this.cameraR.projectionMatrix.copy(l)}this.cameraL.matrixWorld.copy(m.matrixWorld).multiply(k);this.cameraR.matrixWorld.copy(m.matrixWorld).multiply(h)}}()});Bd.prototype=Object.create(G.prototype);
13713 Bd.prototype.constructor=Bd;Yd.prototype=Object.assign(Object.create(G.prototype),{constructor:Yd,getInput:function(){return this.gain},removeFilter:function(){null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null)},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination);
13714 this.filter=a;this.gain.connect(this.filter);this.filter.connect(this.context.destination)},getMasterVolume:function(){return this.gain.gain.value},setMasterVolume:function(a){this.gain.gain.value=a},updateMatrixWorld:function(){var a=new q,b=new da,c=new q,d=new q;return function(e){G.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,this.context.currentTime),
13715 e.positionY.setValueAtTime(a.y,this.context.currentTime),e.positionZ.setValueAtTime(a.z,this.context.currentTime),e.forwardX.setValueAtTime(d.x,this.context.currentTime),e.forwardY.setValueAtTime(d.y,this.context.currentTime),e.forwardZ.setValueAtTime(d.z,this.context.currentTime),e.upX.setValueAtTime(f.x,this.context.currentTime),e.upY.setValueAtTime(f.y,this.context.currentTime),e.upZ.setValueAtTime(f.z,this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,d.y,d.z,f.x,f.y,
13716 f.z))}}()});ec.prototype=Object.assign(Object.create(G.prototype),{constructor:ec,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
13717 else{var a=this.context.createBufferSource();a.buffer=this.buffer;a.loop=this.loop;a.onended=this.onEnded.bind(this);a.playbackRate.setValueAtTime(this.playbackRate,this.startTime);a.start(0,this.startTime);this.isPlaying=!0;this.source=a;return this.connect()}},pause:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.startTime=this.context.currentTime,this.isPlaying=!1,this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
13718 else return this.source.stop(),this.startTime=0,this.isPlaying=!1,this},connect:function(){if(0<this.filters.length){this.source.connect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].connect(this.filters[a]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this},disconnect:function(){if(0<this.filters.length){this.source.disconnect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-
13719 1].disconnect(this.filters[a]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this},getFilters:function(){return this.filters},setFilters:function(a){a||(a=[]);!0===this.isPlaying?(this.disconnect(),this.filters=a,this.connect()):this.filters=a;return this},getFilter:function(){return this.getFilters()[0]},setFilter:function(a){return this.setFilters(a?[a]:[])},setPlaybackRate:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
13720 else return this.playbackRate=a,!0===this.isPlaying&&this.source.playbackRate.setValueAtTime(this.playbackRate,this.context.currentTime),this},getPlaybackRate:function(){return this.playbackRate},onEnded:function(){this.isPlaying=!1},getLoop:function(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop},setLoop:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.loop=
13721 a,!0===this.isPlaying&&(this.source.loop=this.loop),this},getVolume:function(){return this.gain.gain.value},setVolume:function(a){this.gain.gain.value=a;return this}});$d.prototype=Object.assign(Object.create(ec.prototype),{constructor:$d,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=a},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(a){this.panner.rolloffFactor=
13722 a},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=a},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a},updateMatrixWorld:function(){var a=new q;return function(b){G.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,a.y,a.z)}}()});Object.assign(ae.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);
13723 return this.data},getAverageFrequency:function(){for(var a=0,b=this.getFrequencyData(),c=0;c<b.length;c++)a+=b[c];return a/b.length}});Cd.prototype={constructor:Cd,accumulate:function(a,b){var c=this.buffer,d=this.valueSize,e=a*d+d,f=this.cumulativeWeight;if(0===f){for(f=0;f!==d;++f)c[e+f]=c[f];f=b}else f+=b,this._mixBufferRegion(c,e,0,b/f,d);this.cumulativeWeight=f},apply:function(a){var b=this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&
13724 this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d,e){da.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=
13725 1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}};ka.prototype={constructor:ka,getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=ka.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error("  can not bind to material as node does not have a material",
13726 this);return}if(!a.material.materials){console.error("  can not bind to material.materials as node.material does not have a materials array",this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error("  can not bind to bones as node does not have a skeleton",this);return}a=a.skeleton.bones;for(c=0;c<a.length;c++)if(a[c].name===f){f=c;break}break;default:if(void 0===a[c]){console.error("  can not bind to objectName of node, undefined",this);return}a=a[c]}if(void 0!==f){if(void 0===
13727 a[f]){console.error("  trying to bind to objectIndex of objectName, but is undefined:",this,a);return}a=a[f]}}f=a[d];if(void 0===f)console.error("  trying to update property for track: "+b.nodeName+"."+d+" but it wasn't found.",a);else{b=this.Versioning.None;void 0!==a.needsUpdate?(b=this.Versioning.NeedsUpdate,this.targetObject=a):void 0!==a.matrixWorldNeedsUpdate&&(b=this.Versioning.MatrixWorldNeedsUpdate,this.targetObject=a);c=this.BindingType.Direct;if(void 0!==e){if("morphTargetInfluences"===
13728 d){if(!a.geometry){console.error("  can not bind to morphTargetInfluences becasuse node does not have a geometry",this);return}if(!a.geometry.morphTargets){console.error("  can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets",this);return}for(c=0;c<this.node.geometry.morphTargets.length;c++)if(a.geometry.morphTargets[c].name===e){e=c;break}}c=this.BindingType.ArrayElement;this.resolvedProperty=f;this.propertyIndex=e}else void 0!==f.fromArray&&void 0!==f.toArray?
13729 (c=this.BindingType.HasFromToArray,this.resolvedProperty=f):void 0!==f.length?(c=this.BindingType.EntireArray,this.resolvedProperty=f):this.propertyName=d;this.getValue=this.GetterByBindingType[c];this.setValue=this.SetterByBindingTypeAndVersioning[c][b]}}else console.error("  trying to update node for track: "+this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}};Object.assign(ka.prototype,{_getValue_unavailable:function(){},
13730 _setValue_unavailable:function(){},_getValue_unbound:ka.prototype.getValue,_setValue_unbound:ka.prototype.setValue,BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,b){a[b]=this.node[this.propertyName]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,
13731 b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.node[this.propertyName]=a[b]},function(a,b){this.node[this.propertyName]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.node[this.propertyName]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,
13732 d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,
13733 b);this.targetObject.matrixWorldNeedsUpdate=!0}]]});ka.Composite=function(a,b,c){c=c||ka.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)};ka.Composite.prototype={constructor:ka.Composite,getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,
13734 c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].unbind()}};ka.create=function(a,b,c){return a&&a.isAnimationObjectGroup?new ka.Composite(a,b,c):new ka(a,b,c)};ka.parseTrackName=function(a){var b=/^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/.exec(a);if(!b)throw Error("cannot parse trackName at all: "+a);b={nodeName:b[2],objectName:b[3],objectIndex:b[4],propertyName:b[5],propertyIndex:b[6]};
13735 if(null===b.propertyName||0===b.propertyName.length)throw Error("can not parse propertyName from trackName: "+a);return b};ka.findNode=function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;if(a.skeleton){var c=function(a){for(var c=0;c<a.bones.length;c++){var d=a.bones[c];if(d.name===b)return d}return null}(a.skeleton);if(c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var g=a[c];if(g.name===b||g.uuid===b||(g=d(g.children)))return g}return null};
13736 if(c=d(a.children))return c}return null};be.prototype={constructor:be,isAnimationObjectGroup:!0,add:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._paths,g=this._parsedPaths,h=this._bindings,k=h.length,l=0,q=arguments.length;l!==q;++l){var p=arguments[l],n=p.uuid,r=e[n];if(void 0===r){r=c++;e[n]=r;b.push(p);for(var n=0,w=k;n!==w;++n)h[n].push(new ka(p,f[n],g[n]))}else if(r<d){var u=--d,w=b[u];e[w.uuid]=r;b[r]=w;e[n]=u;b[u]=p;n=0;for(w=k;n!==w;++n){var y=
13737 h[n],t=y[r];y[r]=y[u];void 0===t&&(t=new ka(p,f[n],g[n]));y[u]=t}}else void 0!==b[r]&&console.error("Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes...")}this.nCachedObjects_=d},remove:function(a){for(var b=this._objects,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._bindings,f=e.length,g=0,h=arguments.length;g!==h;++g){var k=arguments[g],l=k.uuid,q=d[l];if(void 0!==q&&q>=c){var p=c++,n=b[p];d[n.uuid]=q;b[q]=n;d[l]=p;b[p]=
13738 k;k=0;for(l=f;k!==l;++k){var n=e[k],r=n[q];n[q]=n[p];n[p]=r}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,q=e[l];if(void 0!==q)if(delete e[l],q<d){var l=--d,p=b[l],n=--c,r=b[n];e[p.uuid]=q;b[q]=p;e[r.uuid]=l;b[l]=r;b.pop();p=0;for(r=g;p!==r;++p){var w=f[p],u=w[n];w[q]=w[l];w[l]=u;w.pop()}}else for(n=--c,r=b[n],e[r.uuid]=q,b[q]=r,b.pop(),
13739 p=0,r=g;p!==r;++p)w=f[p],w[q]=w[n],w.pop()}this.nCachedObjects_=d},subscribe_:function(a,b){var c=this._bindingsIndicesByPath,d=c[a],e=this._bindings;if(void 0!==d)return e[d];var f=this._paths,g=this._parsedPaths,h=this._objects,k=this.nCachedObjects_,l=Array(h.length),d=e.length;c[a]=d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new ka(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=
13740 this._bindings,g=f.length-1,h=f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}};ce.prototype={constructor:ce,play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=!1;this.enabled=!0;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&
13741 this._mixer._isActiveAction(this)},isScheduled:function(){return this._mixer._isActiveAction(this)},startAt:function(a){this._startTime=a;return this},setLoop:function(a,b){this.loop=a;this.repetitions=b;return this},setEffectiveWeight:function(a){this.weight=a;this._effectiveWeight=this.enabled?a:0;return this.stopFading()},getEffectiveWeight:function(){return this._effectiveWeight},fadeIn:function(a){return this._scheduleFading(a,0,1)},fadeOut:function(a){return this._scheduleFading(a,1,0)},crossFadeFrom:function(a,
13742 b,c){a.fadeOut(b);this.fadeIn(b);if(c){c=this._clip.duration;var d=a._clip.duration,e=c/d;a.warp(1,d/c,b);this.warp(e,1,b)}return this},crossFadeTo:function(a,b,c){return a.crossFadeFrom(this,b,c)},stopFading:function(){var a=this._weightInterpolant;null!==a&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},setEffectiveTimeScale:function(a){this.timeScale=a;this._effectiveTimeScale=this.paused?0:a;return this.stopWarping()},getEffectiveTimeScale:function(){return this._effectiveTimeScale},
13743 setDuration:function(a){this.timeScale=this._clip.duration/a;return this.stopWarping()},syncWith:function(a){this.time=a.time;this.timeScale=a.timeScale;return this.stopWarping()},halt:function(a){return this.warp(this._effectiveTimeScale,0,a)},warp:function(a,b,c){var d=this._mixer,e=d.time,f=this._timeScaleInterpolant,g=this.timeScale;null===f&&(this._timeScaleInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;d[1]=e+c;f[0]=a/g;f[1]=b/g;return this},stopWarping:function(){var a=
13744 this._timeScaleInterpolant;null!==a&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},getMixer:function(){return this._mixer},getClip:function(){return this._clip},getRoot:function(){return this._localRoot||this._mixer._root},_update:function(a,b,c,d){var e=this._startTime;if(null!==e){b=(a-e)*c;if(0>b||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0<a){b=this._interpolants;for(var e=this._propertyBindings,
13745 f=0,g=b.length;f!==g;++f)b[f].evaluate(c),e[f].accumulate(d,a)}},_updateWeight:function(a){var b=0;if(this.enabled){var b=this.weight,c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===
13746 b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,
13747 d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0<a?c:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:0<a?1:-1})):(0===g?(a=0>a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,
13748 b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}};Object.assign(de.prototype,oa.prototype,{clipAction:function(a,b){var c=b||this._root,
13749 d=c.uuid,e="string"===typeof a?ta.findByName(c,a):a,c=null!==e?e.uuid:a,f=this._actionsByClip[c],g=null;if(void 0!==f){g=f.actionByRoot[d];if(void 0!==g)return g;g=f.knownActions[0];null===e&&(e=g._clip)}if(null===e)return null;e=new ce(this,e,b);this._bindAction(e,g);this._addInactiveAction(e,c,d);return e},existingAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?ta.findByName(c,a):a,c=this._actionsByClip[c?c.uuid:a];return void 0!==c?c.actionByRoot[d]||null:null},stopAllAction:function(){for(var a=
13750 this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=0;return this},update:function(a){a*=this.timeScale;for(var b=this._actions,c=this._nActiveActions,d=this.time+=a,e=Math.sign(a),f=this._accuIndex^=1,g=0;g!==c;++g){var h=b[g];h.enabled&&h._update(d,a,e,f)}a=this._bindings;b=this._nActiveBindings;for(g=0;g!==b;++g)a[g].apply(f);return this},getRoot:function(){return this._root},
13751 uncacheClip:function(a){var b=this._actions;a=a.uuid;var c=this._actionsByClip,d=c[a];if(void 0!==d){for(var d=d.knownActions,e=0,f=d.length;e!==f;++e){var g=d[e];this._deactivateAction(g);var h=g._cacheIndex,k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=this._actionsByClip,c;for(c in b){var d=b[c].actionByRoot[a];void 0!==d&&(this._deactivateAction(d),this._removeInactiveAction(d))}c=
13752 this._bindingsByRootAndName[a];if(void 0!==c)for(var e in c)a=c[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){var c=this.existingAction(a,b);null!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}});Object.assign(de.prototype,{_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings,g=a._interpolants,h=c.uuid,k=this._bindingsByRootAndName,l=k[h];void 0===l&&(l={},k[h]=l);for(k=0;k!==e;++k){var q=
13753 d[k],p=q.name,n=l[p];if(void 0===n){n=f[k];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,h,p));continue}n=new Cd(ka.create(c,p,b&&b._propertyBindings[k].binding.parsedPath),q.ValueTypeName,q.getValueSize());++n.referenceCount;this._addInactiveBinding(n,h,p)}f[k]=n;g[k].resultBuffer=n.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,
13754 d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip=
13755 {};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;
13756 return null!==a&&a<this._nActiveActions},_addInactiveAction:function(a,b,c){var d=this._actions,e=this._actionsByClip,f=e[b];void 0===f?(f={knownActions:[a],actionByRoot:{}},a._byClipCacheIndex=0,e[b]=f):(b=f.knownActions,a._byClipCacheIndex=b.length,b.push(a));a._cacheIndex=d.length;d.push(a);f.actionByRoot[c]=a},_removeInactiveAction:function(a){var b=this._actions,c=b[b.length-1],d=a._cacheIndex;c._cacheIndex=d;b[d]=c;b.pop();a._cacheIndex=null;var c=a._clip.uuid,d=this._actionsByClip,e=d[c],f=
13757 e.knownActions,g=f[f.length-1],h=a._byClipCacheIndex;g._byClipCacheIndex=h;f[h]=g;f.pop();a._byClipCacheIndex=null;delete e.actionByRoot[(b._localRoot||this._root).uuid];0===f.length&&delete d[c];this._removeInactiveBindingsForAction(a)},_removeInactiveBindingsForAction:function(a){a=a._propertyBindings;for(var b=0,c=a.length;b!==c;++b){var d=a[b];0===--d.referenceCount&&this._removeInactiveBinding(d)}},_lendAction:function(a){var b=this._actions,c=a._cacheIndex,d=this._nActiveActions++,e=b[d];a._cacheIndex=
13758 d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=this._actions,c=a._cacheIndex,d=--this._nActiveActions,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_addInactiveBinding:function(a,b,c){var d=this._bindingsByRootAndName,e=d[b],f=this._bindings;void 0===e&&(e={},d[b]=e);e[c]=a;a._cacheIndex=f.length;f.push(a)},_removeInactiveBinding:function(a){var b=this._bindings,c=a.binding,d=c.rootNode.uuid,c=c.path,e=this._bindingsByRootAndName,f=e[d],g=b[b.length-1];a=a._cacheIndex;
13759 g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;delete e[d]}},_lendBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=this._nActiveBindings++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=--this._nActiveBindings,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_lendControlInterpolant:function(){var a=this._controlInterpolants,b=this._nActiveControlInterpolants++,c=a[b];void 0===c&&(c=new Wc(new Float32Array(2),
13760 new Float32Array(2),1,this._controlInterpolantsResultBuffer),c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=d;b[d]=a;e.__cacheIndex=c;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1)});Dd.prototype.clone=function(){return new Dd(void 0===this.value.clone?this.value:this.value.clone())};Bb.prototype=Object.create(D.prototype);Bb.prototype.constructor=Bb;
13761 Bb.prototype.isInstancedBufferGeometry=!0;Bb.prototype.addGroup=function(a,b,c){this.groups.push({start:a,count:b,materialIndex:c})};Bb.prototype.copy=function(a){var b=a.index;null!==b&&this.setIndex(b.clone());var b=a.attributes,c;for(c in b)this.addAttribute(c,b[c].clone());a=a.groups;c=0;for(b=a.length;c<b;c++){var d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}return this};ee.prototype={constructor:ee,isInterleavedBufferAttribute:!0,get count(){return this.data.count},get array(){return this.data.array},
13762 setX:function(a,b){this.data.array[a*this.data.stride+this.offset]=b;return this},setY:function(a,b){this.data.array[a*this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+this.offset+2]=b;return this},setW:function(a,b){this.data.array[a*this.data.stride+this.offset+3]=b;return this},getX:function(a){return this.data.array[a*this.data.stride+this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*
13763 this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;this.data.array[a+
13764 3]=e;return this}};fc.prototype={constructor:fc,isInterleavedBuffer:!0,set needsUpdate(a){!0===a&&this.version++},setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.stride:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=
13765 this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(a){this.onUploadCallback=a;return this}};gc.prototype=Object.create(fc.prototype);gc.prototype.constructor=gc;gc.prototype.isInstancedInterleavedBuffer=!0;gc.prototype.copy=function(a){fc.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;
13766 return this};hc.prototype=Object.create(y.prototype);hc.prototype.constructor=hc;hc.prototype.isInstancedBufferAttribute=!0;hc.prototype.copy=function(a){y.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this};fe.prototype={constructor:fe,linePrecision:1,set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):
13767 b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];ge(a,this,c,b);c.sort(Ie);return c},intersectObjects:function(a,b){var c=[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),c;for(var d=0,e=a.length;d<e;d++)ge(a[d],this,c,b);c.sort(Ie);
13768 return c}};he.prototype={constructor:he,start:function(){this.oldTime=this.startTime=(performance||Date).now();this.elapsedTime=0;this.running=!0},stop:function(){this.getElapsedTime();this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=0;this.autoStart&&!this.running&&this.start();if(this.running){var b=(performance||Date).now(),a=(b-this.oldTime)/1E3;this.oldTime=b;this.elapsedTime+=a}return a}};ie.prototype={constructor:ie,set:function(a,
13769 b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=Math.max(1E-6,Math.min(Math.PI-1E-6,this.phi));return this},setFromVector3:function(a){this.radius=a.length();0===this.radius?this.phi=this.theta=0:(this.theta=Math.atan2(a.x,a.z),this.phi=Math.acos(Q.clamp(a.y/this.radius,-1,1)));return this}};je.prototype={constructor:je,
13770 set:function(a,b,c){this.radius=a;this.theta=b;this.y=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.theta=a.theta;this.y=a.y;return this},setFromVector3:function(a){this.radius=Math.sqrt(a.x*a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}};ua.prototype=Object.create(Ba.prototype);ua.prototype.constructor=ua;ua.prototype.createAnimation=function(a,b,c,d){b={start:b,end:c,length:c-b+1,fps:d,duration:(c-b)/d,lastFrame:0,
13771 currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[a]=b;this.animationsList.push(b)};ua.prototype.autoCreateAnimations=function(a){for(var b=/([a-z]+)_?(\d+)/i,c,d={},e=this.geometry,f=0,g=e.morphTargets.length;f<g;f++){var h=e.morphTargets[f].name.match(b);if(h&&1<h.length){var k=h[1];d[k]||(d[k]={start:Infinity,end:-Infinity});h=d[k];f<h.start&&(h.start=f);f>h.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,
13772 a);this.firstAnimation=c};ua.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};ua.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};ua.prototype.setAnimationFPS=function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};ua.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/
13773 c.duration)};ua.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};ua.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};ua.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b};ua.prototype.getAnimationDuration=function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};ua.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+
13774 a+"] undefined in .playAnimation()")};ua.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};ua.prototype.update=function(a){for(var b=0,c=this.animationsList.length;b<c;b++){var d=this.animationsList[b];if(d.active){var e=d.duration/d.length;d.time+=d.direction*a;if(d.mirroredLoop){if(d.time>d.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=
13775 d.duration);var f=d.start+Q.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&&(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!==d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};$c.prototype=Object.create(G.prototype);
13776 $c.prototype.constructor=$c;$c.prototype.isImmediateRenderObject=!0;ad.prototype=Object.create(fa.prototype);ad.prototype.constructor=ad;ad.prototype.update=function(){var a=new q,b=new q,c=new za;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,l=g=0,q=k.length;l<q;l++)for(var p=k[l],n=0,r=p.vertexNormals.length;n<
13777 r;n++){var w=p.vertexNormals[n];a.copy(h[p[d[n]]]).applyMatrix4(e);b.copy(w).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);f.setXYZ(g,a.x,a.y,a.z);g+=1;f.setXYZ(g,b.x,b.y,b.z);g+=1}else if(g&&g.isBufferGeometry)for(d=g.attributes.position,h=g.attributes.normal,n=g=0,r=d.count;n<r;n++)a.set(d.getX(n),d.getY(n),d.getZ(n)).applyMatrix4(e),b.set(h.getX(n),h.getY(n),h.getZ(n)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),f.setXYZ(g,a.x,a.y,a.z),g+=1,f.setXYZ(g,b.x,b.y,
13778 b.z),g+=1;f.needsUpdate=!0;return this}}();ic.prototype=Object.create(G.prototype);ic.prototype.constructor=ic;ic.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};ic.prototype.update=function(){var a=new q,b=new q;return function(){var c=this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));
13779 this.cone.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}}();jc.prototype=Object.create(fa.prototype);jc.prototype.constructor=jc;jc.prototype.getBoneList=function(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,this.getBoneList(a.children[c]));return b};jc.prototype.update=function(){var a=new q,b=new H,c=new H;return function(){var d=this.geometry,e=d.getAttribute("position");c.getInverse(this.root.matrixWorld);for(var f=0,g=0;f<
13780 this.bones.length;f++){var h=this.bones[f];h.parent&&h.parent.isBone&&(b.multiplyMatrices(c,h.matrixWorld),a.setFromMatrixPosition(b),e.setXYZ(g,a.x,a.y,a.z),b.multiplyMatrices(c,h.parent.matrixWorld),a.setFromMatrixPosition(b),e.setXYZ(g+1,a.x,a.y,a.z),g+=2)}d.getAttribute("position").needsUpdate=!0}}();kc.prototype=Object.create(Ba.prototype);kc.prototype.constructor=kc;kc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};kc.prototype.update=function(){this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)};
13781 lc.prototype=Object.create(G.prototype);lc.prototype.constructor=lc;lc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose();this.children[1].geometry.dispose();this.children[1].material.dispose()};lc.prototype.update=function(){var a=new q,b=new q;return function(){var c=this.children[0],d=this.children[1];if(this.light.target){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);var e=b.clone().sub(a);
13782 c.lookAt(e);d.lookAt(e)}c.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);d.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);var d=.5*this.light.width,e=.5*this.light.height,c=c.geometry.getAttribute("position"),f=c.array;f[0]=d;f[1]=-e;f[2]=0;f[3]=d;f[4]=e;f[5]=0;f[6]=-d;f[7]=e;f[8]=0;f[9]=-d;f[10]=e;f[11]=0;f[12]=-d;f[13]=-e;f[14]=0;f[15]=d;f[16]=-e;f[17]=0;c.needsUpdate=!0}}();mc.prototype=Object.create(G.prototype);mc.prototype.constructor=
13783 mc;mc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};mc.prototype.update=function(){var a=new q,b=new N,c=new N;return function(){var d=this.children[0],e=d.geometry.getAttribute("color");b.copy(this.light.color).multiplyScalar(this.light.intensity);c.copy(this.light.groundColor).multiplyScalar(this.light.intensity);for(var f=0,g=e.count;f<g;f++){var h=f<g/2?b:c;e.setXYZ(f,h.r,h.g,h.b)}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate());
13784 e.needsUpdate=!0}}();bd.prototype=Object.create(fa.prototype);bd.prototype.constructor=bd;Ed.prototype=Object.create(fa.prototype);Ed.prototype.constructor=Ed;cd.prototype=Object.create(fa.prototype);cd.prototype.constructor=cd;cd.prototype.update=function(){var a=new q,b=new q,c=new za;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);for(var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices,f=f.faces,h=
13785 0,k=0,l=f.length;k<l;k++){var q=f[k],p=q.normal;a.copy(g[q.a]).add(g[q.b]).add(g[q.c]).divideScalar(3).applyMatrix4(d);b.copy(p).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);e.setXYZ(h,a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0;return this}}();nc.prototype=Object.create(G.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){var a=this.children[0],b=this.children[1];a.geometry.dispose();a.material.dispose();b.geometry.dispose();b.material.dispose()};
13786 nc.prototype.update=function(){var a=new q,b=new q,c=new q;return function(){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);c.subVectors(b,a);var d=this.children[0],e=this.children[1];d.lookAt(c);d.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);e.lookAt(c);e.scale.z=c.length()}}();dd.prototype=Object.create(fa.prototype);dd.prototype.constructor=dd;dd.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);
13787 a=c[a];if(void 0!==a)for(g=b.getAttribute("position"),h=0,k=a.length;h<k;h++)g.setXYZ(a[h],d.x,d.y,d.z)}var b,c,d=new q,e=new sa;return function(){b=this.geometry;c=this.pointMap;e.projectionMatrix.copy(this.camera.projectionMatrix);a("c",0,0,-1);a("t",0,0,1);a("n1",-1,-1,-1);a("n2",1,-1,-1);a("n3",-1,1,-1);a("n4",1,1,-1);a("f1",-1,-1,1);a("f2",1,-1,1);a("f3",-1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",
13788 -1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",0,1,-1);b.getAttribute("position").needsUpdate=!0}}();oc.prototype=Object.create(fa.prototype);oc.prototype.constructor=oc;oc.prototype.update=function(){var a=new ya;return function(b){b&&b.isBox3?a.copy(b):a.setFromObject(b);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=
13789 b.x;e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}();var Je=new D;Je.addAttribute("position",new X([0,0,0,0,1,0],3));var Ke=new Wa(0,.5,1,5,1);Ke.translate(0,-.5,0);Cb.prototype=Object.create(G.prototype);Cb.prototype.constructor=Cb;Cb.prototype.setDirection=function(){var a=new q,b;return function(c){.99999<c.y?this.quaternion.set(0,0,0,1):-.99999>c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),
13790 b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Cb.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Cb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};Fd.prototype=Object.create(fa.prototype);Fd.prototype.constructor=Fd;var ke=function(){function a(){}var b=new q,c=new a,
13791 d=new a,e=new a;a.prototype.init=function(a,b,c,d){this.c0=a;this.c1=c;this.c2=-3*a+3*b-2*c-d;this.c3=2*a-2*b+c+d};a.prototype.initNonuniformCatmullRom=function(a,b,c,d,e,l,p){this.init(b,c,((b-a)/e-(c-a)/(e+l)+(c-b)/l)*l,((c-b)/l-(d-b)/(l+p)+(d-c)/p)*l)};a.prototype.initCatmullRom=function(a,b,c,d,e){this.init(b,c,e*(c-a),e*(d-b))};a.prototype.calc=function(a){var b=a*a;return this.c0+this.c1*a+this.c2*b+this.c3*b*a};return wa.create(function(a){this.points=a||[];this.closed=!1},function(a){var g=
13792 this.points,h,k;k=g.length;2>k&&console.log("duh, you need at least 2 points");a*=k-(this.closed?0:1);h=Math.floor(a);a-=h;this.closed?h+=0<h?0:(Math.floor(Math.abs(h)/g.length)+1)*g.length:0===a&&h===k-1&&(h=k-2,a=1);var l,x,p;this.closed||0<h?l=g[(h-1)%k]:(b.subVectors(g[0],g[1]).add(g[0]),l=b);x=g[h%k];p=g[(h+1)%k];this.closed||h+2<k?g=g[(h+2)%k]:(b.subVectors(g[k-1],g[k-2]).add(g[k-1]),g=b);if(void 0===this.type||"centripetal"===this.type||"chordal"===this.type){var n="chordal"===this.type?.5:
13793 .25;k=Math.pow(l.distanceToSquared(x),n);h=Math.pow(x.distanceToSquared(p),n);n=Math.pow(p.distanceToSquared(g),n);1E-4>h&&(h=1);1E-4>k&&(k=h);1E-4>n&&(n=h);c.initNonuniformCatmullRom(l.x,x.x,p.x,g.x,k,h,n);d.initNonuniformCatmullRom(l.y,x.y,p.y,g.y,k,h,n);e.initNonuniformCatmullRom(l.z,x.z,p.z,g.z,k,h,n)}else"catmullrom"===this.type&&(k=void 0!==this.tension?this.tension:.5,c.initCatmullRom(l.x,x.x,p.x,g.x,k),d.initCatmullRom(l.y,x.y,p.y,g.y,k),e.initCatmullRom(l.z,x.z,p.z,g.z,k));return new q(c.calc(a),
13794 d.calc(a),e.calc(a))})}(),Nf=wa.create(function(a){console.warn("THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3");this.points=void 0===a?[]:a},function(a){var b=this.points;a*=b.length-1;var c=Math.floor(a);a-=c;var d=b[0==c?c:c-1],e=b[c],f=b[c>b.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=ed.interpolate;return new q(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a),c(d.z,e.z,f.z,b.z,a))}),Of=wa.create(function(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d},function(a){var b=
13795 pa.b3;return new q(b(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y),b(a,this.v0.z,this.v1.z,this.v2.z,this.v3.z))}),Pf=wa.create(function(a,b,c){this.v0=a;this.v1=b;this.v2=c},function(a){var b=pa.b2;return new q(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y),b(a,this.v0.z,this.v1.z,this.v2.z))}),Qf=wa.create(function(a,b){this.v1=a;this.v2=b},function(a){if(1===a)return this.v2.clone();var b=new q;b.subVectors(this.v2,this.v1);b.multiplyScalar(a);
13796 b.add(this.v1);return b});Gd.prototype=Object.create(Xa.prototype);Gd.prototype.constructor=Gd;Le.prototype=Object.create(ke.prototype);bd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};Object.assign(pc.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");
13797 return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(a)}});Object.assign(ya.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");
13798 return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(a)}});gb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");
13799 return this.getCenter(a)};Q.random16=function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()};Object.assign(za.prototype,{flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},
13800 multiplyVector3Array:function(a){console.warn("THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");return this.applyToVector3Array(a)},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)}});Object.assign(H.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");
13801 return this.copyPosition(a)},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;return function(){void 0===a&&(a=new q);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");return a.setFromMatrixColumn(this,3)}}(),setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");
13802 return this.makeRotationFromQuaternion(a)},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.");return a.applyProjection(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector3Array:function(a){console.warn("THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");
13803 return this.applyToVector3Array(a)},rotateAxis:function(a){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.");a.transformDirection(this)},crossVector:function(a){console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},
13804 rotateY:function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},rotateByAxis:function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)}});ma.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");
13805 return this.intersectsLine(a)};da.prototype.multiplyVector3=function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)};Object.assign(bb.prototype,{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");
13806 return this.intersectsPlane(a)},isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(Ab.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new La(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new Xb(this,a)}});Object.assign(q.prototype,
13807 {setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},getPositionFromMatrix:function(a){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");return this.setFromMatrixPosition(a)},getScaleFromMatrix:function(a){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");
13808 return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b,a)}});S.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(G.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");return this.getObjectByName(a)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},
13809 translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(G.prototype,{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},
13810 set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(Ac.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Ha.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(na.prototype,
13811 {onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");
13812 this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");this.shadow.camera.bottom=a}},shadowCameraNear:{set:function(a){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near.");this.shadow.camera.near=a}},shadowCameraFar:{set:function(a){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far.");this.shadow.camera.far=a}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},
13813 shadowBias:{set:function(a){console.warn("THREE.Light: .shadowBias is now .shadow.bias.");this.shadow.bias=a}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(a){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.");this.shadow.mapSize.width=a}},shadowMapHeight:{set:function(a){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.");this.shadow.mapSize.height=a}}});Object.defineProperties(y.prototype,
13814 {length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(D.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,b,c){void 0!==c&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.");console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(a,
13815 b)},clearDrawCalls:function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().");this.clearGroups()},computeTangents:function(){console.warn("THREE.BufferGeometry: .computeTangents() has been removed.")},computeOffsets:function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")}});Object.defineProperties(D.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");
13816 return this.groups}}});Object.defineProperties(Dd.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.");return this}}});Object.defineProperties(W.prototype,{wrapAround:{get:function(){console.warn("THREE."+this.type+": .wrapAround has been removed.")},set:function(){console.warn("THREE."+this.type+
13817 ": .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE."+this.type+": .wrapRGB has been removed.");return new N}}});Object.defineProperties(Ca.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});Object.defineProperties(Ia.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");
13818 return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});oa.prototype=Object.assign(Object.create({constructor:oa,apply:function(a){console.warn("THREE.EventDispatcher: .apply is deprecated, just inherit or Object.assign the prototype to mix-in.");Object.assign(a,this)}}),oa.prototype);Object.assign(Nd.prototype,{supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");
13819 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' ).");
13820 return this.extensions.get("WEBGL_compressed_texture_s3tc")},supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},supportsBlendMinMax:function(){console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' ).");return this.extensions.get("EXT_blend_minmax")},supportsVertexTextures:function(){console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.");
13821 return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(a){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(a)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},
13822 addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(Nd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");
13823 this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");this.shadowMap.cullFace=a}}});Object.defineProperties(ye.prototype,{cullFace:{get:function(){return this.renderReverseSided?2:1},set:function(a){a=1!==a;console.warn("WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to "+a+".");this.renderReverseSided=a}}});Object.defineProperties(Db.prototype,
13824 {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.");
13825 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.");
13826 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},
13827 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.");
13828 this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});ec.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new Wd).load(a,function(a){b.setBuffer(a)});return this};
13829 ae.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};l.WebGLRenderTargetCube=Eb;l.WebGLRenderTarget=Db;l.WebGLRenderer=Nd;l.ShaderLib=Gb;l.UniformsLib=U;l.UniformsUtils=Ja;l.ShaderChunk=Z;l.FogExp2=Ib;l.Fog=Jb;l.Scene=jb;l.LensFlare=Od;l.Sprite=zc;l.LOD=Ac;l.SkinnedMesh=jd;l.Skeleton=hd;l.Bone=id;l.Mesh=Ba;l.LineSegments=fa;l.Line=Va;l.Points=Kb;l.Group=Bc;l.VideoTexture=kd;l.DataTexture=db;l.CompressedTexture=
13830 Lb;l.CubeTexture=Za;l.CanvasTexture=ld;l.DepthTexture=Cc;l.Texture=ea;l.CompressedTextureLoader=Ee;l.BinaryTextureLoader=Qd;l.DataTextureLoader=Qd;l.CubeTextureLoader=Rd;l.TextureLoader=md;l.ObjectLoader=Fe;l.MaterialLoader=Ad;l.BufferGeometryLoader=Sd;l.DefaultLoadingManager=va;l.LoadingManager=Pd;l.JSONLoader=Td;l.ImageLoader=Vc;l.FontLoader=Ge;l.FileLoader=Ma;l.Loader=wb;l.Cache=ne;l.AudioLoader=Wd;l.SpotLightShadow=od;l.SpotLight=pd;l.PointLight=qd;l.RectAreaLight=Xd;l.HemisphereLight=nd;l.DirectionalLightShadow=
13831 rd;l.DirectionalLight=sd;l.AmbientLight=td;l.LightShadow=tb;l.Light=na;l.StereoCamera=He;l.PerspectiveCamera=Ha;l.OrthographicCamera=Hb;l.CubeCamera=Bd;l.Camera=sa;l.AudioListener=Yd;l.PositionalAudio=$d;l.AudioContext=Zd;l.AudioAnalyser=ae;l.Audio=ec;l.VectorKeyframeTrack=cc;l.StringKeyframeTrack=xd;l.QuaternionKeyframeTrack=Xc;l.NumberKeyframeTrack=dc;l.ColorKeyframeTrack=zd;l.BooleanKeyframeTrack=yd;l.PropertyMixer=Cd;l.PropertyBinding=ka;l.KeyframeTrack=vb;l.AnimationUtils=ba;l.AnimationObjectGroup=
13832 be;l.AnimationMixer=de;l.AnimationClip=ta;l.Uniform=Dd;l.InstancedBufferGeometry=Bb;l.BufferGeometry=D;l.GeometryIdCount=function(){return Kd++};l.Geometry=S;l.InterleavedBufferAttribute=ee;l.InstancedInterleavedBuffer=gc;l.InterleavedBuffer=fc;l.InstancedBufferAttribute=hc;l.Face3=ha;l.Object3D=G;l.Raycaster=fe;l.Layers=gd;l.EventDispatcher=oa;l.Clock=he;l.QuaternionLinearInterpolant=wd;l.LinearInterpolant=Wc;l.DiscreteInterpolant=vd;l.CubicInterpolant=ud;l.Interpolant=qa;l.Triangle=Aa;l.Spline=
13833 function(a){function b(a,b,c,d,e,f,g){a=.5*(c-a);d=.5*(d-b);return(2*(b-c)+a+d)*g+(-3*(b-c)-2*a-d)*f+a*e+b}this.points=a;var c=[],d={x:0,y:0,z:0},e,f,g,h,k,l,x,p,n;this.initFromArray=function(a){this.points=[];for(var b=0;b<a.length;b++)this.points[b]={x:a[b][0],y:a[b][1],z:a[b][2]}};this.getPoint=function(a){e=(this.points.length-1)*a;f=Math.floor(e);g=e-f;c[0]=0===f?f:f-1;c[1]=f;c[2]=f>this.points.length-2?this.points.length-1:f+1;c[3]=f>this.points.length-3?this.points.length-1:f+2;l=this.points[c[0]];
13834 x=this.points[c[1]];p=this.points[c[2]];n=this.points[c[3]];h=g*g;k=g*h;d.x=b(l.x,x.x,p.x,n.x,g,h,k);d.y=b(l.y,x.y,p.y,n.y,g,h,k);d.z=b(l.z,x.z,p.z,n.z,g,h,k);return d};this.getControlPointsArray=function(){var a,b,c=this.points.length,d=[];for(a=0;a<c;a++)b=this.points[a],d[a]=[b.x,b.y,b.z];return d};this.getLength=function(a){var b,c,d,e=0,f=new q,g=new q,h=[],k=0;h[0]=0;a||(a=100);c=this.points.length*a;f.copy(this.points[0]);for(a=1;a<c;a++)b=a/c,d=this.getPoint(b),g.copy(d),k+=g.distanceTo(f),
13835 f.copy(d),b*=this.points.length-1,b=Math.floor(b),b!==e&&(h[b]=k,e=b);h[h.length]=k;return{chunks:h,total:k}};this.reparametrizeByArcLength=function(a){var b,c,d,e,f,g,h=[],k=new q,l=this.getLength();h.push(k.copy(this.points[0]).clone());for(b=1;b<this.points.length;b++){c=l.chunks[b]-l.chunks[b-1];g=Math.ceil(a*c/l.total);e=(b-1)/(this.points.length-1);f=b/(this.points.length-1);for(c=1;c<g-1;c++)d=e+1/g*c*(f-e),d=this.getPoint(d),h.push(k.copy(d).clone());h.push(k.copy(this.points[b]).clone())}this.points=
13836 h}};l.Math=Q;l.Spherical=ie;l.Cylindrical=je;l.Plane=ma;l.Frustum=qc;l.Sphere=Fa;l.Ray=bb;l.Matrix4=H;l.Matrix3=za;l.Box3=ya;l.Box2=pc;l.Line3=gb;l.Euler=cb;l.Vector4=ga;l.Vector3=q;l.Vector2=C;l.Quaternion=da;l.Color=N;l.MorphBlendMesh=ua;l.ImmediateRenderObject=$c;l.VertexNormalsHelper=ad;l.SpotLightHelper=ic;l.SkeletonHelper=jc;l.PointLightHelper=kc;l.RectAreaLightHelper=lc;l.HemisphereLightHelper=mc;l.GridHelper=bd;l.PolarGridHelper=Ed;l.FaceNormalsHelper=cd;l.DirectionalLightHelper=nc;l.CameraHelper=
13837 dd;l.BoxHelper=oc;l.ArrowHelper=Cb;l.AxisHelper=Fd;l.CatmullRomCurve3=ke;l.SplineCurve3=Nf;l.CubicBezierCurve3=Of;l.QuadraticBezierCurve3=Pf;l.LineCurve3=Qf;l.ArcCurve=Gd;l.EllipseCurve=Xa;l.SplineCurve=xb;l.CubicBezierCurve=yb;l.QuadraticBezierCurve=zb;l.LineCurve=Qa;l.Shape=Ab;l.ShapePath=Ud;l.Path=Zc;l.Font=Vd;l.CurvePath=Yc;l.Curve=wa;l.ShapeUtils=pa;l.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=new Bc,d=0,e=b.length;d<e;d++)c.add(new Ba(a,b[d]));return c},detach:function(a,
13838 b,c){a.applyMatrix(b.matrixWorld);b.remove(a);c.add(a)},attach:function(a,b,c){var d=new H;d.getInverse(c.matrixWorld);a.applyMatrix(d);b.remove(a);c.add(a)}};l.CurveUtils=ed;l.WireframeGeometry=Mb;l.ParametricGeometry=Dc;l.ParametricBufferGeometry=Nb;l.TetrahedronGeometry=Ec;l.TetrahedronBufferGeometry=Ob;l.OctahedronGeometry=Fc;l.OctahedronBufferGeometry=lb;l.IcosahedronGeometry=Gc;l.IcosahedronBufferGeometry=Pb;l.DodecahedronGeometry=Hc;l.DodecahedronBufferGeometry=Qb;l.PolyhedronGeometry=Ic;l.PolyhedronBufferGeometry=
13839 xa;l.TubeGeometry=Jc;l.TubeBufferGeometry=Rb;l.TorusKnotGeometry=Kc;l.TorusKnotBufferGeometry=Sb;l.TorusGeometry=Lc;l.TorusBufferGeometry=Tb;l.TextGeometry=Mc;l.SphereBufferGeometry=mb;l.SphereGeometry=Nc;l.RingGeometry=Oc;l.RingBufferGeometry=Ub;l.PlaneBufferGeometry=ib;l.PlaneGeometry=Pc;l.LatheGeometry=Qc;l.LatheBufferGeometry=Vb;l.ShapeGeometry=Xb;l.ShapeBufferGeometry=Wb;l.ExtrudeGeometry=La;l.EdgesGeometry=Yb;l.ConeGeometry=Rc;l.ConeBufferGeometry=Sc;l.CylinderGeometry=nb;l.CylinderBufferGeometry=
13840 Wa;l.CircleBufferGeometry=Zb;l.CircleGeometry=Tc;l.BoxBufferGeometry=hb;l.BoxGeometry=$b;l.ShadowMaterial=ac;l.SpriteMaterial=kb;l.RawShaderMaterial=bc;l.ShaderMaterial=Ia;l.PointsMaterial=Oa;l.MultiMaterial=Uc;l.MeshPhysicalMaterial=ob;l.MeshStandardMaterial=Pa;l.MeshPhongMaterial=Ca;l.MeshToonMaterial=pb;l.MeshNormalMaterial=qb;l.MeshLambertMaterial=rb;l.MeshDepthMaterial=ab;l.MeshBasicMaterial=Ka;l.LineDashedMaterial=sb;l.LineBasicMaterial=ia;l.Material=W;l.Float64BufferAttribute=wc;l.Float32BufferAttribute=
13841 X;l.Uint32BufferAttribute=Ua;l.Int32BufferAttribute=vc;l.Uint16BufferAttribute=Ra;l.Int16BufferAttribute=uc;l.Uint8ClampedBufferAttribute=tc;l.Uint8BufferAttribute=sc;l.Int8BufferAttribute=rc;l.BufferAttribute=y;l.REVISION="83";l.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};l.CullFaceNone=0;l.CullFaceBack=1;l.CullFaceFront=2;l.CullFaceFrontBack=3;l.FrontFaceDirectionCW=0;l.FrontFaceDirectionCCW=1;l.BasicShadowMap=0;l.PCFShadowMap=1;l.PCFSoftShadowMap=2;l.FrontSide=0;l.BackSide=1;l.DoubleSide=2;l.FlatShading=1;
13842 l.SmoothShading=2;l.NoColors=0;l.FaceColors=1;l.VertexColors=2;l.NoBlending=0;l.NormalBlending=1;l.AdditiveBlending=2;l.SubtractiveBlending=3;l.MultiplyBlending=4;l.CustomBlending=5;l.BlendingMode=Me;l.AddEquation=100;l.SubtractEquation=101;l.ReverseSubtractEquation=102;l.MinEquation=103;l.MaxEquation=104;l.ZeroFactor=200;l.OneFactor=201;l.SrcColorFactor=202;l.OneMinusSrcColorFactor=203;l.SrcAlphaFactor=204;l.OneMinusSrcAlphaFactor=205;l.DstAlphaFactor=206;l.OneMinusDstAlphaFactor=207;l.DstColorFactor=
13843 208;l.OneMinusDstColorFactor=209;l.SrcAlphaSaturateFactor=210;l.NeverDepth=0;l.AlwaysDepth=1;l.LessDepth=2;l.LessEqualDepth=3;l.EqualDepth=4;l.GreaterEqualDepth=5;l.GreaterDepth=6;l.NotEqualDepth=7;l.MultiplyOperation=0;l.MixOperation=1;l.AddOperation=2;l.NoToneMapping=0;l.LinearToneMapping=1;l.ReinhardToneMapping=2;l.Uncharted2ToneMapping=3;l.CineonToneMapping=4;l.UVMapping=300;l.CubeReflectionMapping=301;l.CubeRefractionMapping=302;l.EquirectangularReflectionMapping=303;l.EquirectangularRefractionMapping=
13844 304;l.SphericalReflectionMapping=305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=307;l.TextureMapping=Ne;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.TextureWrapping=le;l.NearestFilter=1003;l.NearestMipMapNearestFilter=1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.TextureFilter=me;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;
13845 l.UnsignedIntType=1014;l.FloatType=1015;l.HalfFloatType=1016;l.UnsignedShort4444Type=1017;l.UnsignedShort5551Type=1018;l.UnsignedShort565Type=1019;l.UnsignedInt248Type=1020;l.AlphaFormat=1021;l.RGBFormat=1022;l.RGBAFormat=1023;l.LuminanceFormat=1024;l.LuminanceAlphaFormat=1025;l.RGBEFormat=1023;l.DepthFormat=1026;l.DepthStencilFormat=1027;l.RGB_S3TC_DXT1_Format=2001;l.RGBA_S3TC_DXT1_Format=2002;l.RGBA_S3TC_DXT3_Format=2003;l.RGBA_S3TC_DXT5_Format=2004;l.RGB_PVRTC_4BPPV1_Format=2100;l.RGB_PVRTC_2BPPV1_Format=
13846 2101;l.RGBA_PVRTC_4BPPV1_Format=2102;l.RGBA_PVRTC_2BPPV1_Format=2103;l.RGB_ETC1_Format=2151;l.LoopOnce=2200;l.LoopRepeat=2201;l.LoopPingPong=2202;l.InterpolateDiscrete=2300;l.InterpolateLinear=2301;l.InterpolateSmooth=2302;l.ZeroCurvatureEnding=2400;l.ZeroSlopeEnding=2401;l.WrapAroundEnding=2402;l.TrianglesDrawMode=0;l.TriangleStripDrawMode=1;l.TriangleFanDrawMode=2;l.LinearEncoding=3E3;l.sRGBEncoding=3001;l.GammaEncoding=3007;l.RGBEEncoding=3002;l.LogLuvEncoding=3003;l.RGBM7Encoding=3004;l.RGBM16Encoding=
13847 3005;l.RGBDEncoding=3006;l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.CubeGeometry=$b;l.Face4=function(a,b,c,d,e,f,g){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");return new ha(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=function(a){console.warn("THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.");return new Uc(a)};l.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Kb(a,
13848 b)};l.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new zc(a)};l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Kb(a,b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};
13849 l.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new q(a,b,c)};l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return(new y(a,b)).setDynamic(!0)};l.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");
13850 return new rc(a,b)};l.Uint8Attribute=function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new sc(a,b)};l.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new tc(a,b)};l.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new uc(a,b)};l.Uint16Attribute=
13851 function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new Ra(a,b)};l.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new vc(a,b)};l.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");return new Ua(a,b)};l.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");
13852 return new X(a,b)};l.Float64Attribute=function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new wc(a,b)};l.ClosedSplineCurve3=Le;l.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new oc(a,b)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new fa(new Yb(a.geometry),new ia({color:void 0!==
13853 b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new fa(new Mb(a.geometry),new ia({color:void 0!==b?b:16777215}))};l.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ma(a)};l.GeometryUtils={merge:function(a,b,c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");
13854 var d;b.isMesh&&(b.matrixAutoUpdate&&b.updateMatrix(),d=b.matrix,b=b.geometry);a.merge(b,d,c)},center:function(a){console.warn("THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.");return a.center()}};l.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");var e=new md;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},
13855 loadTextureCube:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");var e=new Rd;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadCompressedTexture:function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},loadCompressedTextureCube:function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")}};
13856 l.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=function(a,b){console.warn("THREE.Projector: .projectVector() is now vector.project().");a.project(b)};this.unprojectVector=function(a,b){console.warn("THREE.Projector: .unprojectVector() is now vector.unproject().");a.unproject(b)};this.pickingRay=function(){console.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}};l.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");
13857 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})});
13858
13859 },{}],175:[function(require,module,exports){
13860 //     Underscore.js 1.8.3
13861 //     http://underscorejs.org
13862 //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
13863 //     Underscore may be freely distributed under the MIT license.
13864
13865 (function() {
13866
13867   // Baseline setup
13868   // --------------
13869
13870   // Establish the root object, `window` in the browser, or `exports` on the server.
13871   var root = this;
13872
13873   // Save the previous value of the `_` variable.
13874   var previousUnderscore = root._;
13875
13876   // Save bytes in the minified (but not gzipped) version:
13877   var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
13878
13879   // Create quick reference variables for speed access to core prototypes.
13880   var
13881     push             = ArrayProto.push,
13882     slice            = ArrayProto.slice,
13883     toString         = ObjProto.toString,
13884     hasOwnProperty   = ObjProto.hasOwnProperty;
13885
13886   // All **ECMAScript 5** native function implementations that we hope to use
13887   // are declared here.
13888   var
13889     nativeIsArray      = Array.isArray,
13890     nativeKeys         = Object.keys,
13891     nativeBind         = FuncProto.bind,
13892     nativeCreate       = Object.create;
13893
13894   // Naked function reference for surrogate-prototype-swapping.
13895   var Ctor = function(){};
13896
13897   // Create a safe reference to the Underscore object for use below.
13898   var _ = function(obj) {
13899     if (obj instanceof _) return obj;
13900     if (!(this instanceof _)) return new _(obj);
13901     this._wrapped = obj;
13902   };
13903
13904   // Export the Underscore object for **Node.js**, with
13905   // backwards-compatibility for the old `require()` API. If we're in
13906   // the browser, add `_` as a global object.
13907   if (typeof exports !== 'undefined') {
13908     if (typeof module !== 'undefined' && module.exports) {
13909       exports = module.exports = _;
13910     }
13911     exports._ = _;
13912   } else {
13913     root._ = _;
13914   }
13915
13916   // Current version.
13917   _.VERSION = '1.8.3';
13918
13919   // Internal function that returns an efficient (for current engines) version
13920   // of the passed-in callback, to be repeatedly applied in other Underscore
13921   // functions.
13922   var optimizeCb = function(func, context, argCount) {
13923     if (context === void 0) return func;
13924     switch (argCount == null ? 3 : argCount) {
13925       case 1: return function(value) {
13926         return func.call(context, value);
13927       };
13928       case 2: return function(value, other) {
13929         return func.call(context, value, other);
13930       };
13931       case 3: return function(value, index, collection) {
13932         return func.call(context, value, index, collection);
13933       };
13934       case 4: return function(accumulator, value, index, collection) {
13935         return func.call(context, accumulator, value, index, collection);
13936       };
13937     }
13938     return function() {
13939       return func.apply(context, arguments);
13940     };
13941   };
13942
13943   // A mostly-internal function to generate callbacks that can be applied
13944   // to each element in a collection, returning the desired result — either
13945   // identity, an arbitrary callback, a property matcher, or a property accessor.
13946   var cb = function(value, context, argCount) {
13947     if (value == null) return _.identity;
13948     if (_.isFunction(value)) return optimizeCb(value, context, argCount);
13949     if (_.isObject(value)) return _.matcher(value);
13950     return _.property(value);
13951   };
13952   _.iteratee = function(value, context) {
13953     return cb(value, context, Infinity);
13954   };
13955
13956   // An internal function for creating assigner functions.
13957   var createAssigner = function(keysFunc, undefinedOnly) {
13958     return function(obj) {
13959       var length = arguments.length;
13960       if (length < 2 || obj == null) return obj;
13961       for (var index = 1; index < length; index++) {
13962         var source = arguments[index],
13963             keys = keysFunc(source),
13964             l = keys.length;
13965         for (var i = 0; i < l; i++) {
13966           var key = keys[i];
13967           if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
13968         }
13969       }
13970       return obj;
13971     };
13972   };
13973
13974   // An internal function for creating a new object that inherits from another.
13975   var baseCreate = function(prototype) {
13976     if (!_.isObject(prototype)) return {};
13977     if (nativeCreate) return nativeCreate(prototype);
13978     Ctor.prototype = prototype;
13979     var result = new Ctor;
13980     Ctor.prototype = null;
13981     return result;
13982   };
13983
13984   var property = function(key) {
13985     return function(obj) {
13986       return obj == null ? void 0 : obj[key];
13987     };
13988   };
13989
13990   // Helper for collection methods to determine whether a collection
13991   // should be iterated as an array or as an object
13992   // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
13993   // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
13994   var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
13995   var getLength = property('length');
13996   var isArrayLike = function(collection) {
13997     var length = getLength(collection);
13998     return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
13999   };
14000
14001   // Collection Functions
14002   // --------------------
14003
14004   // The cornerstone, an `each` implementation, aka `forEach`.
14005   // Handles raw objects in addition to array-likes. Treats all
14006   // sparse array-likes as if they were dense.
14007   _.each = _.forEach = function(obj, iteratee, context) {
14008     iteratee = optimizeCb(iteratee, context);
14009     var i, length;
14010     if (isArrayLike(obj)) {
14011       for (i = 0, length = obj.length; i < length; i++) {
14012         iteratee(obj[i], i, obj);
14013       }
14014     } else {
14015       var keys = _.keys(obj);
14016       for (i = 0, length = keys.length; i < length; i++) {
14017         iteratee(obj[keys[i]], keys[i], obj);
14018       }
14019     }
14020     return obj;
14021   };
14022
14023   // Return the results of applying the iteratee to each element.
14024   _.map = _.collect = function(obj, iteratee, context) {
14025     iteratee = cb(iteratee, context);
14026     var keys = !isArrayLike(obj) && _.keys(obj),
14027         length = (keys || obj).length,
14028         results = Array(length);
14029     for (var index = 0; index < length; index++) {
14030       var currentKey = keys ? keys[index] : index;
14031       results[index] = iteratee(obj[currentKey], currentKey, obj);
14032     }
14033     return results;
14034   };
14035
14036   // Create a reducing function iterating left or right.
14037   function createReduce(dir) {
14038     // Optimized iterator function as using arguments.length
14039     // in the main function will deoptimize the, see #1991.
14040     function iterator(obj, iteratee, memo, keys, index, length) {
14041       for (; index >= 0 && index < length; index += dir) {
14042         var currentKey = keys ? keys[index] : index;
14043         memo = iteratee(memo, obj[currentKey], currentKey, obj);
14044       }
14045       return memo;
14046     }
14047
14048     return function(obj, iteratee, memo, context) {
14049       iteratee = optimizeCb(iteratee, context, 4);
14050       var keys = !isArrayLike(obj) && _.keys(obj),
14051           length = (keys || obj).length,
14052           index = dir > 0 ? 0 : length - 1;
14053       // Determine the initial value if none is provided.
14054       if (arguments.length < 3) {
14055         memo = obj[keys ? keys[index] : index];
14056         index += dir;
14057       }
14058       return iterator(obj, iteratee, memo, keys, index, length);
14059     };
14060   }
14061
14062   // **Reduce** builds up a single result from a list of values, aka `inject`,
14063   // or `foldl`.
14064   _.reduce = _.foldl = _.inject = createReduce(1);
14065
14066   // The right-associative version of reduce, also known as `foldr`.
14067   _.reduceRight = _.foldr = createReduce(-1);
14068
14069   // Return the first value which passes a truth test. Aliased as `detect`.
14070   _.find = _.detect = function(obj, predicate, context) {
14071     var key;
14072     if (isArrayLike(obj)) {
14073       key = _.findIndex(obj, predicate, context);
14074     } else {
14075       key = _.findKey(obj, predicate, context);
14076     }
14077     if (key !== void 0 && key !== -1) return obj[key];
14078   };
14079
14080   // Return all the elements that pass a truth test.
14081   // Aliased as `select`.
14082   _.filter = _.select = function(obj, predicate, context) {
14083     var results = [];
14084     predicate = cb(predicate, context);
14085     _.each(obj, function(value, index, list) {
14086       if (predicate(value, index, list)) results.push(value);
14087     });
14088     return results;
14089   };
14090
14091   // Return all the elements for which a truth test fails.
14092   _.reject = function(obj, predicate, context) {
14093     return _.filter(obj, _.negate(cb(predicate)), context);
14094   };
14095
14096   // Determine whether all of the elements match a truth test.
14097   // Aliased as `all`.
14098   _.every = _.all = function(obj, predicate, context) {
14099     predicate = cb(predicate, context);
14100     var keys = !isArrayLike(obj) && _.keys(obj),
14101         length = (keys || obj).length;
14102     for (var index = 0; index < length; index++) {
14103       var currentKey = keys ? keys[index] : index;
14104       if (!predicate(obj[currentKey], currentKey, obj)) return false;
14105     }
14106     return true;
14107   };
14108
14109   // Determine if at least one element in the object matches a truth test.
14110   // Aliased as `any`.
14111   _.some = _.any = function(obj, predicate, context) {
14112     predicate = cb(predicate, context);
14113     var keys = !isArrayLike(obj) && _.keys(obj),
14114         length = (keys || obj).length;
14115     for (var index = 0; index < length; index++) {
14116       var currentKey = keys ? keys[index] : index;
14117       if (predicate(obj[currentKey], currentKey, obj)) return true;
14118     }
14119     return false;
14120   };
14121
14122   // Determine if the array or object contains a given item (using `===`).
14123   // Aliased as `includes` and `include`.
14124   _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
14125     if (!isArrayLike(obj)) obj = _.values(obj);
14126     if (typeof fromIndex != 'number' || guard) fromIndex = 0;
14127     return _.indexOf(obj, item, fromIndex) >= 0;
14128   };
14129
14130   // Invoke a method (with arguments) on every item in a collection.
14131   _.invoke = function(obj, method) {
14132     var args = slice.call(arguments, 2);
14133     var isFunc = _.isFunction(method);
14134     return _.map(obj, function(value) {
14135       var func = isFunc ? method : value[method];
14136       return func == null ? func : func.apply(value, args);
14137     });
14138   };
14139
14140   // Convenience version of a common use case of `map`: fetching a property.
14141   _.pluck = function(obj, key) {
14142     return _.map(obj, _.property(key));
14143   };
14144
14145   // Convenience version of a common use case of `filter`: selecting only objects
14146   // containing specific `key:value` pairs.
14147   _.where = function(obj, attrs) {
14148     return _.filter(obj, _.matcher(attrs));
14149   };
14150
14151   // Convenience version of a common use case of `find`: getting the first object
14152   // containing specific `key:value` pairs.
14153   _.findWhere = function(obj, attrs) {
14154     return _.find(obj, _.matcher(attrs));
14155   };
14156
14157   // Return the maximum element (or element-based computation).
14158   _.max = function(obj, iteratee, context) {
14159     var result = -Infinity, lastComputed = -Infinity,
14160         value, computed;
14161     if (iteratee == null && obj != null) {
14162       obj = isArrayLike(obj) ? obj : _.values(obj);
14163       for (var i = 0, length = obj.length; i < length; i++) {
14164         value = obj[i];
14165         if (value > result) {
14166           result = value;
14167         }
14168       }
14169     } else {
14170       iteratee = cb(iteratee, context);
14171       _.each(obj, function(value, index, list) {
14172         computed = iteratee(value, index, list);
14173         if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
14174           result = value;
14175           lastComputed = computed;
14176         }
14177       });
14178     }
14179     return result;
14180   };
14181
14182   // Return the minimum element (or element-based computation).
14183   _.min = function(obj, iteratee, context) {
14184     var result = Infinity, lastComputed = Infinity,
14185         value, computed;
14186     if (iteratee == null && obj != null) {
14187       obj = isArrayLike(obj) ? obj : _.values(obj);
14188       for (var i = 0, length = obj.length; i < length; i++) {
14189         value = obj[i];
14190         if (value < result) {
14191           result = value;
14192         }
14193       }
14194     } else {
14195       iteratee = cb(iteratee, context);
14196       _.each(obj, function(value, index, list) {
14197         computed = iteratee(value, index, list);
14198         if (computed < lastComputed || computed === Infinity && result === Infinity) {
14199           result = value;
14200           lastComputed = computed;
14201         }
14202       });
14203     }
14204     return result;
14205   };
14206
14207   // Shuffle a collection, using the modern version of the
14208   // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
14209   _.shuffle = function(obj) {
14210     var set = isArrayLike(obj) ? obj : _.values(obj);
14211     var length = set.length;
14212     var shuffled = Array(length);
14213     for (var index = 0, rand; index < length; index++) {
14214       rand = _.random(0, index);
14215       if (rand !== index) shuffled[index] = shuffled[rand];
14216       shuffled[rand] = set[index];
14217     }
14218     return shuffled;
14219   };
14220
14221   // Sample **n** random values from a collection.
14222   // If **n** is not specified, returns a single random element.
14223   // The internal `guard` argument allows it to work with `map`.
14224   _.sample = function(obj, n, guard) {
14225     if (n == null || guard) {
14226       if (!isArrayLike(obj)) obj = _.values(obj);
14227       return obj[_.random(obj.length - 1)];
14228     }
14229     return _.shuffle(obj).slice(0, Math.max(0, n));
14230   };
14231
14232   // Sort the object's values by a criterion produced by an iteratee.
14233   _.sortBy = function(obj, iteratee, context) {
14234     iteratee = cb(iteratee, context);
14235     return _.pluck(_.map(obj, function(value, index, list) {
14236       return {
14237         value: value,
14238         index: index,
14239         criteria: iteratee(value, index, list)
14240       };
14241     }).sort(function(left, right) {
14242       var a = left.criteria;
14243       var b = right.criteria;
14244       if (a !== b) {
14245         if (a > b || a === void 0) return 1;
14246         if (a < b || b === void 0) return -1;
14247       }
14248       return left.index - right.index;
14249     }), 'value');
14250   };
14251
14252   // An internal function used for aggregate "group by" operations.
14253   var group = function(behavior) {
14254     return function(obj, iteratee, context) {
14255       var result = {};
14256       iteratee = cb(iteratee, context);
14257       _.each(obj, function(value, index) {
14258         var key = iteratee(value, index, obj);
14259         behavior(result, value, key);
14260       });
14261       return result;
14262     };
14263   };
14264
14265   // Groups the object's values by a criterion. Pass either a string attribute
14266   // to group by, or a function that returns the criterion.
14267   _.groupBy = group(function(result, value, key) {
14268     if (_.has(result, key)) result[key].push(value); else result[key] = [value];
14269   });
14270
14271   // Indexes the object's values by a criterion, similar to `groupBy`, but for
14272   // when you know that your index values will be unique.
14273   _.indexBy = group(function(result, value, key) {
14274     result[key] = value;
14275   });
14276
14277   // Counts instances of an object that group by a certain criterion. Pass
14278   // either a string attribute to count by, or a function that returns the
14279   // criterion.
14280   _.countBy = group(function(result, value, key) {
14281     if (_.has(result, key)) result[key]++; else result[key] = 1;
14282   });
14283
14284   // Safely create a real, live array from anything iterable.
14285   _.toArray = function(obj) {
14286     if (!obj) return [];
14287     if (_.isArray(obj)) return slice.call(obj);
14288     if (isArrayLike(obj)) return _.map(obj, _.identity);
14289     return _.values(obj);
14290   };
14291
14292   // Return the number of elements in an object.
14293   _.size = function(obj) {
14294     if (obj == null) return 0;
14295     return isArrayLike(obj) ? obj.length : _.keys(obj).length;
14296   };
14297
14298   // Split a collection into two arrays: one whose elements all satisfy the given
14299   // predicate, and one whose elements all do not satisfy the predicate.
14300   _.partition = function(obj, predicate, context) {
14301     predicate = cb(predicate, context);
14302     var pass = [], fail = [];
14303     _.each(obj, function(value, key, obj) {
14304       (predicate(value, key, obj) ? pass : fail).push(value);
14305     });
14306     return [pass, fail];
14307   };
14308
14309   // Array Functions
14310   // ---------------
14311
14312   // Get the first element of an array. Passing **n** will return the first N
14313   // values in the array. Aliased as `head` and `take`. The **guard** check
14314   // allows it to work with `_.map`.
14315   _.first = _.head = _.take = function(array, n, guard) {
14316     if (array == null) return void 0;
14317     if (n == null || guard) return array[0];
14318     return _.initial(array, array.length - n);
14319   };
14320
14321   // Returns everything but the last entry of the array. Especially useful on
14322   // the arguments object. Passing **n** will return all the values in
14323   // the array, excluding the last N.
14324   _.initial = function(array, n, guard) {
14325     return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
14326   };
14327
14328   // Get the last element of an array. Passing **n** will return the last N
14329   // values in the array.
14330   _.last = function(array, n, guard) {
14331     if (array == null) return void 0;
14332     if (n == null || guard) return array[array.length - 1];
14333     return _.rest(array, Math.max(0, array.length - n));
14334   };
14335
14336   // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
14337   // Especially useful on the arguments object. Passing an **n** will return
14338   // the rest N values in the array.
14339   _.rest = _.tail = _.drop = function(array, n, guard) {
14340     return slice.call(array, n == null || guard ? 1 : n);
14341   };
14342
14343   // Trim out all falsy values from an array.
14344   _.compact = function(array) {
14345     return _.filter(array, _.identity);
14346   };
14347
14348   // Internal implementation of a recursive `flatten` function.
14349   var flatten = function(input, shallow, strict, startIndex) {
14350     var output = [], idx = 0;
14351     for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
14352       var value = input[i];
14353       if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
14354         //flatten current level of array or arguments object
14355         if (!shallow) value = flatten(value, shallow, strict);
14356         var j = 0, len = value.length;
14357         output.length += len;
14358         while (j < len) {
14359           output[idx++] = value[j++];
14360         }
14361       } else if (!strict) {
14362         output[idx++] = value;
14363       }
14364     }
14365     return output;
14366   };
14367
14368   // Flatten out an array, either recursively (by default), or just one level.
14369   _.flatten = function(array, shallow) {
14370     return flatten(array, shallow, false);
14371   };
14372
14373   // Return a version of the array that does not contain the specified value(s).
14374   _.without = function(array) {
14375     return _.difference(array, slice.call(arguments, 1));
14376   };
14377
14378   // Produce a duplicate-free version of the array. If the array has already
14379   // been sorted, you have the option of using a faster algorithm.
14380   // Aliased as `unique`.
14381   _.uniq = _.unique = function(array, isSorted, iteratee, context) {
14382     if (!_.isBoolean(isSorted)) {
14383       context = iteratee;
14384       iteratee = isSorted;
14385       isSorted = false;
14386     }
14387     if (iteratee != null) iteratee = cb(iteratee, context);
14388     var result = [];
14389     var seen = [];
14390     for (var i = 0, length = getLength(array); i < length; i++) {
14391       var value = array[i],
14392           computed = iteratee ? iteratee(value, i, array) : value;
14393       if (isSorted) {
14394         if (!i || seen !== computed) result.push(value);
14395         seen = computed;
14396       } else if (iteratee) {
14397         if (!_.contains(seen, computed)) {
14398           seen.push(computed);
14399           result.push(value);
14400         }
14401       } else if (!_.contains(result, value)) {
14402         result.push(value);
14403       }
14404     }
14405     return result;
14406   };
14407
14408   // Produce an array that contains the union: each distinct element from all of
14409   // the passed-in arrays.
14410   _.union = function() {
14411     return _.uniq(flatten(arguments, true, true));
14412   };
14413
14414   // Produce an array that contains every item shared between all the
14415   // passed-in arrays.
14416   _.intersection = function(array) {
14417     var result = [];
14418     var argsLength = arguments.length;
14419     for (var i = 0, length = getLength(array); i < length; i++) {
14420       var item = array[i];
14421       if (_.contains(result, item)) continue;
14422       for (var j = 1; j < argsLength; j++) {
14423         if (!_.contains(arguments[j], item)) break;
14424       }
14425       if (j === argsLength) result.push(item);
14426     }
14427     return result;
14428   };
14429
14430   // Take the difference between one array and a number of other arrays.
14431   // Only the elements present in just the first array will remain.
14432   _.difference = function(array) {
14433     var rest = flatten(arguments, true, true, 1);
14434     return _.filter(array, function(value){
14435       return !_.contains(rest, value);
14436     });
14437   };
14438
14439   // Zip together multiple lists into a single array -- elements that share
14440   // an index go together.
14441   _.zip = function() {
14442     return _.unzip(arguments);
14443   };
14444
14445   // Complement of _.zip. Unzip accepts an array of arrays and groups
14446   // each array's elements on shared indices
14447   _.unzip = function(array) {
14448     var length = array && _.max(array, getLength).length || 0;
14449     var result = Array(length);
14450
14451     for (var index = 0; index < length; index++) {
14452       result[index] = _.pluck(array, index);
14453     }
14454     return result;
14455   };
14456
14457   // Converts lists into objects. Pass either a single array of `[key, value]`
14458   // pairs, or two parallel arrays of the same length -- one of keys, and one of
14459   // the corresponding values.
14460   _.object = function(list, values) {
14461     var result = {};
14462     for (var i = 0, length = getLength(list); i < length; i++) {
14463       if (values) {
14464         result[list[i]] = values[i];
14465       } else {
14466         result[list[i][0]] = list[i][1];
14467       }
14468     }
14469     return result;
14470   };
14471
14472   // Generator function to create the findIndex and findLastIndex functions
14473   function createPredicateIndexFinder(dir) {
14474     return function(array, predicate, context) {
14475       predicate = cb(predicate, context);
14476       var length = getLength(array);
14477       var index = dir > 0 ? 0 : length - 1;
14478       for (; index >= 0 && index < length; index += dir) {
14479         if (predicate(array[index], index, array)) return index;
14480       }
14481       return -1;
14482     };
14483   }
14484
14485   // Returns the first index on an array-like that passes a predicate test
14486   _.findIndex = createPredicateIndexFinder(1);
14487   _.findLastIndex = createPredicateIndexFinder(-1);
14488
14489   // Use a comparator function to figure out the smallest index at which
14490   // an object should be inserted so as to maintain order. Uses binary search.
14491   _.sortedIndex = function(array, obj, iteratee, context) {
14492     iteratee = cb(iteratee, context, 1);
14493     var value = iteratee(obj);
14494     var low = 0, high = getLength(array);
14495     while (low < high) {
14496       var mid = Math.floor((low + high) / 2);
14497       if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
14498     }
14499     return low;
14500   };
14501
14502   // Generator function to create the indexOf and lastIndexOf functions
14503   function createIndexFinder(dir, predicateFind, sortedIndex) {
14504     return function(array, item, idx) {
14505       var i = 0, length = getLength(array);
14506       if (typeof idx == 'number') {
14507         if (dir > 0) {
14508             i = idx >= 0 ? idx : Math.max(idx + length, i);
14509         } else {
14510             length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
14511         }
14512       } else if (sortedIndex && idx && length) {
14513         idx = sortedIndex(array, item);
14514         return array[idx] === item ? idx : -1;
14515       }
14516       if (item !== item) {
14517         idx = predicateFind(slice.call(array, i, length), _.isNaN);
14518         return idx >= 0 ? idx + i : -1;
14519       }
14520       for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
14521         if (array[idx] === item) return idx;
14522       }
14523       return -1;
14524     };
14525   }
14526
14527   // Return the position of the first occurrence of an item in an array,
14528   // or -1 if the item is not included in the array.
14529   // If the array is large and already in sort order, pass `true`
14530   // for **isSorted** to use binary search.
14531   _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
14532   _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
14533
14534   // Generate an integer Array containing an arithmetic progression. A port of
14535   // the native Python `range()` function. See
14536   // [the Python documentation](http://docs.python.org/library/functions.html#range).
14537   _.range = function(start, stop, step) {
14538     if (stop == null) {
14539       stop = start || 0;
14540       start = 0;
14541     }
14542     step = step || 1;
14543
14544     var length = Math.max(Math.ceil((stop - start) / step), 0);
14545     var range = Array(length);
14546
14547     for (var idx = 0; idx < length; idx++, start += step) {
14548       range[idx] = start;
14549     }
14550
14551     return range;
14552   };
14553
14554   // Function (ahem) Functions
14555   // ------------------
14556
14557   // Determines whether to execute a function as a constructor
14558   // or a normal function with the provided arguments
14559   var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
14560     if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
14561     var self = baseCreate(sourceFunc.prototype);
14562     var result = sourceFunc.apply(self, args);
14563     if (_.isObject(result)) return result;
14564     return self;
14565   };
14566
14567   // Create a function bound to a given object (assigning `this`, and arguments,
14568   // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
14569   // available.
14570   _.bind = function(func, context) {
14571     if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
14572     if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
14573     var args = slice.call(arguments, 2);
14574     var bound = function() {
14575       return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
14576     };
14577     return bound;
14578   };
14579
14580   // Partially apply a function by creating a version that has had some of its
14581   // arguments pre-filled, without changing its dynamic `this` context. _ acts
14582   // as a placeholder, allowing any combination of arguments to be pre-filled.
14583   _.partial = function(func) {
14584     var boundArgs = slice.call(arguments, 1);
14585     var bound = function() {
14586       var position = 0, length = boundArgs.length;
14587       var args = Array(length);
14588       for (var i = 0; i < length; i++) {
14589         args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
14590       }
14591       while (position < arguments.length) args.push(arguments[position++]);
14592       return executeBound(func, bound, this, this, args);
14593     };
14594     return bound;
14595   };
14596
14597   // Bind a number of an object's methods to that object. Remaining arguments
14598   // are the method names to be bound. Useful for ensuring that all callbacks
14599   // defined on an object belong to it.
14600   _.bindAll = function(obj) {
14601     var i, length = arguments.length, key;
14602     if (length <= 1) throw new Error('bindAll must be passed function names');
14603     for (i = 1; i < length; i++) {
14604       key = arguments[i];
14605       obj[key] = _.bind(obj[key], obj);
14606     }
14607     return obj;
14608   };
14609
14610   // Memoize an expensive function by storing its results.
14611   _.memoize = function(func, hasher) {
14612     var memoize = function(key) {
14613       var cache = memoize.cache;
14614       var address = '' + (hasher ? hasher.apply(this, arguments) : key);
14615       if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
14616       return cache[address];
14617     };
14618     memoize.cache = {};
14619     return memoize;
14620   };
14621
14622   // Delays a function for the given number of milliseconds, and then calls
14623   // it with the arguments supplied.
14624   _.delay = function(func, wait) {
14625     var args = slice.call(arguments, 2);
14626     return setTimeout(function(){
14627       return func.apply(null, args);
14628     }, wait);
14629   };
14630
14631   // Defers a function, scheduling it to run after the current call stack has
14632   // cleared.
14633   _.defer = _.partial(_.delay, _, 1);
14634
14635   // Returns a function, that, when invoked, will only be triggered at most once
14636   // during a given window of time. Normally, the throttled function will run
14637   // as much as it can, without ever going more than once per `wait` duration;
14638   // but if you'd like to disable the execution on the leading edge, pass
14639   // `{leading: false}`. To disable execution on the trailing edge, ditto.
14640   _.throttle = function(func, wait, options) {
14641     var context, args, result;
14642     var timeout = null;
14643     var previous = 0;
14644     if (!options) options = {};
14645     var later = function() {
14646       previous = options.leading === false ? 0 : _.now();
14647       timeout = null;
14648       result = func.apply(context, args);
14649       if (!timeout) context = args = null;
14650     };
14651     return function() {
14652       var now = _.now();
14653       if (!previous && options.leading === false) previous = now;
14654       var remaining = wait - (now - previous);
14655       context = this;
14656       args = arguments;
14657       if (remaining <= 0 || remaining > wait) {
14658         if (timeout) {
14659           clearTimeout(timeout);
14660           timeout = null;
14661         }
14662         previous = now;
14663         result = func.apply(context, args);
14664         if (!timeout) context = args = null;
14665       } else if (!timeout && options.trailing !== false) {
14666         timeout = setTimeout(later, remaining);
14667       }
14668       return result;
14669     };
14670   };
14671
14672   // Returns a function, that, as long as it continues to be invoked, will not
14673   // be triggered. The function will be called after it stops being called for
14674   // N milliseconds. If `immediate` is passed, trigger the function on the
14675   // leading edge, instead of the trailing.
14676   _.debounce = function(func, wait, immediate) {
14677     var timeout, args, context, timestamp, result;
14678
14679     var later = function() {
14680       var last = _.now() - timestamp;
14681
14682       if (last < wait && last >= 0) {
14683         timeout = setTimeout(later, wait - last);
14684       } else {
14685         timeout = null;
14686         if (!immediate) {
14687           result = func.apply(context, args);
14688           if (!timeout) context = args = null;
14689         }
14690       }
14691     };
14692
14693     return function() {
14694       context = this;
14695       args = arguments;
14696       timestamp = _.now();
14697       var callNow = immediate && !timeout;
14698       if (!timeout) timeout = setTimeout(later, wait);
14699       if (callNow) {
14700         result = func.apply(context, args);
14701         context = args = null;
14702       }
14703
14704       return result;
14705     };
14706   };
14707
14708   // Returns the first function passed as an argument to the second,
14709   // allowing you to adjust arguments, run code before and after, and
14710   // conditionally execute the original function.
14711   _.wrap = function(func, wrapper) {
14712     return _.partial(wrapper, func);
14713   };
14714
14715   // Returns a negated version of the passed-in predicate.
14716   _.negate = function(predicate) {
14717     return function() {
14718       return !predicate.apply(this, arguments);
14719     };
14720   };
14721
14722   // Returns a function that is the composition of a list of functions, each
14723   // consuming the return value of the function that follows.
14724   _.compose = function() {
14725     var args = arguments;
14726     var start = args.length - 1;
14727     return function() {
14728       var i = start;
14729       var result = args[start].apply(this, arguments);
14730       while (i--) result = args[i].call(this, result);
14731       return result;
14732     };
14733   };
14734
14735   // Returns a function that will only be executed on and after the Nth call.
14736   _.after = function(times, func) {
14737     return function() {
14738       if (--times < 1) {
14739         return func.apply(this, arguments);
14740       }
14741     };
14742   };
14743
14744   // Returns a function that will only be executed up to (but not including) the Nth call.
14745   _.before = function(times, func) {
14746     var memo;
14747     return function() {
14748       if (--times > 0) {
14749         memo = func.apply(this, arguments);
14750       }
14751       if (times <= 1) func = null;
14752       return memo;
14753     };
14754   };
14755
14756   // Returns a function that will be executed at most one time, no matter how
14757   // often you call it. Useful for lazy initialization.
14758   _.once = _.partial(_.before, 2);
14759
14760   // Object Functions
14761   // ----------------
14762
14763   // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
14764   var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
14765   var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
14766                       'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
14767
14768   function collectNonEnumProps(obj, keys) {
14769     var nonEnumIdx = nonEnumerableProps.length;
14770     var constructor = obj.constructor;
14771     var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
14772
14773     // Constructor is a special case.
14774     var prop = 'constructor';
14775     if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
14776
14777     while (nonEnumIdx--) {
14778       prop = nonEnumerableProps[nonEnumIdx];
14779       if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
14780         keys.push(prop);
14781       }
14782     }
14783   }
14784
14785   // Retrieve the names of an object's own properties.
14786   // Delegates to **ECMAScript 5**'s native `Object.keys`
14787   _.keys = function(obj) {
14788     if (!_.isObject(obj)) return [];
14789     if (nativeKeys) return nativeKeys(obj);
14790     var keys = [];
14791     for (var key in obj) if (_.has(obj, key)) keys.push(key);
14792     // Ahem, IE < 9.
14793     if (hasEnumBug) collectNonEnumProps(obj, keys);
14794     return keys;
14795   };
14796
14797   // Retrieve all the property names of an object.
14798   _.allKeys = function(obj) {
14799     if (!_.isObject(obj)) return [];
14800     var keys = [];
14801     for (var key in obj) keys.push(key);
14802     // Ahem, IE < 9.
14803     if (hasEnumBug) collectNonEnumProps(obj, keys);
14804     return keys;
14805   };
14806
14807   // Retrieve the values of an object's properties.
14808   _.values = function(obj) {
14809     var keys = _.keys(obj);
14810     var length = keys.length;
14811     var values = Array(length);
14812     for (var i = 0; i < length; i++) {
14813       values[i] = obj[keys[i]];
14814     }
14815     return values;
14816   };
14817
14818   // Returns the results of applying the iteratee to each element of the object
14819   // In contrast to _.map it returns an object
14820   _.mapObject = function(obj, iteratee, context) {
14821     iteratee = cb(iteratee, context);
14822     var keys =  _.keys(obj),
14823           length = keys.length,
14824           results = {},
14825           currentKey;
14826       for (var index = 0; index < length; index++) {
14827         currentKey = keys[index];
14828         results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
14829       }
14830       return results;
14831   };
14832
14833   // Convert an object into a list of `[key, value]` pairs.
14834   _.pairs = function(obj) {
14835     var keys = _.keys(obj);
14836     var length = keys.length;
14837     var pairs = Array(length);
14838     for (var i = 0; i < length; i++) {
14839       pairs[i] = [keys[i], obj[keys[i]]];
14840     }
14841     return pairs;
14842   };
14843
14844   // Invert the keys and values of an object. The values must be serializable.
14845   _.invert = function(obj) {
14846     var result = {};
14847     var keys = _.keys(obj);
14848     for (var i = 0, length = keys.length; i < length; i++) {
14849       result[obj[keys[i]]] = keys[i];
14850     }
14851     return result;
14852   };
14853
14854   // Return a sorted list of the function names available on the object.
14855   // Aliased as `methods`
14856   _.functions = _.methods = function(obj) {
14857     var names = [];
14858     for (var key in obj) {
14859       if (_.isFunction(obj[key])) names.push(key);
14860     }
14861     return names.sort();
14862   };
14863
14864   // Extend a given object with all the properties in passed-in object(s).
14865   _.extend = createAssigner(_.allKeys);
14866
14867   // Assigns a given object with all the own properties in the passed-in object(s)
14868   // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
14869   _.extendOwn = _.assign = createAssigner(_.keys);
14870
14871   // Returns the first key on an object that passes a predicate test
14872   _.findKey = function(obj, predicate, context) {
14873     predicate = cb(predicate, context);
14874     var keys = _.keys(obj), key;
14875     for (var i = 0, length = keys.length; i < length; i++) {
14876       key = keys[i];
14877       if (predicate(obj[key], key, obj)) return key;
14878     }
14879   };
14880
14881   // Return a copy of the object only containing the whitelisted properties.
14882   _.pick = function(object, oiteratee, context) {
14883     var result = {}, obj = object, iteratee, keys;
14884     if (obj == null) return result;
14885     if (_.isFunction(oiteratee)) {
14886       keys = _.allKeys(obj);
14887       iteratee = optimizeCb(oiteratee, context);
14888     } else {
14889       keys = flatten(arguments, false, false, 1);
14890       iteratee = function(value, key, obj) { return key in obj; };
14891       obj = Object(obj);
14892     }
14893     for (var i = 0, length = keys.length; i < length; i++) {
14894       var key = keys[i];
14895       var value = obj[key];
14896       if (iteratee(value, key, obj)) result[key] = value;
14897     }
14898     return result;
14899   };
14900
14901    // Return a copy of the object without the blacklisted properties.
14902   _.omit = function(obj, iteratee, context) {
14903     if (_.isFunction(iteratee)) {
14904       iteratee = _.negate(iteratee);
14905     } else {
14906       var keys = _.map(flatten(arguments, false, false, 1), String);
14907       iteratee = function(value, key) {
14908         return !_.contains(keys, key);
14909       };
14910     }
14911     return _.pick(obj, iteratee, context);
14912   };
14913
14914   // Fill in a given object with default properties.
14915   _.defaults = createAssigner(_.allKeys, true);
14916
14917   // Creates an object that inherits from the given prototype object.
14918   // If additional properties are provided then they will be added to the
14919   // created object.
14920   _.create = function(prototype, props) {
14921     var result = baseCreate(prototype);
14922     if (props) _.extendOwn(result, props);
14923     return result;
14924   };
14925
14926   // Create a (shallow-cloned) duplicate of an object.
14927   _.clone = function(obj) {
14928     if (!_.isObject(obj)) return obj;
14929     return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
14930   };
14931
14932   // Invokes interceptor with the obj, and then returns obj.
14933   // The primary purpose of this method is to "tap into" a method chain, in
14934   // order to perform operations on intermediate results within the chain.
14935   _.tap = function(obj, interceptor) {
14936     interceptor(obj);
14937     return obj;
14938   };
14939
14940   // Returns whether an object has a given set of `key:value` pairs.
14941   _.isMatch = function(object, attrs) {
14942     var keys = _.keys(attrs), length = keys.length;
14943     if (object == null) return !length;
14944     var obj = Object(object);
14945     for (var i = 0; i < length; i++) {
14946       var key = keys[i];
14947       if (attrs[key] !== obj[key] || !(key in obj)) return false;
14948     }
14949     return true;
14950   };
14951
14952
14953   // Internal recursive comparison function for `isEqual`.
14954   var eq = function(a, b, aStack, bStack) {
14955     // Identical objects are equal. `0 === -0`, but they aren't identical.
14956     // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
14957     if (a === b) return a !== 0 || 1 / a === 1 / b;
14958     // A strict comparison is necessary because `null == undefined`.
14959     if (a == null || b == null) return a === b;
14960     // Unwrap any wrapped objects.
14961     if (a instanceof _) a = a._wrapped;
14962     if (b instanceof _) b = b._wrapped;
14963     // Compare `[[Class]]` names.
14964     var className = toString.call(a);
14965     if (className !== toString.call(b)) return false;
14966     switch (className) {
14967       // Strings, numbers, regular expressions, dates, and booleans are compared by value.
14968       case '[object RegExp]':
14969       // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
14970       case '[object String]':
14971         // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
14972         // equivalent to `new String("5")`.
14973         return '' + a === '' + b;
14974       case '[object Number]':
14975         // `NaN`s are equivalent, but non-reflexive.
14976         // Object(NaN) is equivalent to NaN
14977         if (+a !== +a) return +b !== +b;
14978         // An `egal` comparison is performed for other numeric values.
14979         return +a === 0 ? 1 / +a === 1 / b : +a === +b;
14980       case '[object Date]':
14981       case '[object Boolean]':
14982         // Coerce dates and booleans to numeric primitive values. Dates are compared by their
14983         // millisecond representations. Note that invalid dates with millisecond representations
14984         // of `NaN` are not equivalent.
14985         return +a === +b;
14986     }
14987
14988     var areArrays = className === '[object Array]';
14989     if (!areArrays) {
14990       if (typeof a != 'object' || typeof b != 'object') return false;
14991
14992       // Objects with different constructors are not equivalent, but `Object`s or `Array`s
14993       // from different frames are.
14994       var aCtor = a.constructor, bCtor = b.constructor;
14995       if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
14996                                _.isFunction(bCtor) && bCtor instanceof bCtor)
14997                           && ('constructor' in a && 'constructor' in b)) {
14998         return false;
14999       }
15000     }
15001     // Assume equality for cyclic structures. The algorithm for detecting cyclic
15002     // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
15003
15004     // Initializing stack of traversed objects.
15005     // It's done here since we only need them for objects and arrays comparison.
15006     aStack = aStack || [];
15007     bStack = bStack || [];
15008     var length = aStack.length;
15009     while (length--) {
15010       // Linear search. Performance is inversely proportional to the number of
15011       // unique nested structures.
15012       if (aStack[length] === a) return bStack[length] === b;
15013     }
15014
15015     // Add the first object to the stack of traversed objects.
15016     aStack.push(a);
15017     bStack.push(b);
15018
15019     // Recursively compare objects and arrays.
15020     if (areArrays) {
15021       // Compare array lengths to determine if a deep comparison is necessary.
15022       length = a.length;
15023       if (length !== b.length) return false;
15024       // Deep compare the contents, ignoring non-numeric properties.
15025       while (length--) {
15026         if (!eq(a[length], b[length], aStack, bStack)) return false;
15027       }
15028     } else {
15029       // Deep compare objects.
15030       var keys = _.keys(a), key;
15031       length = keys.length;
15032       // Ensure that both objects contain the same number of properties before comparing deep equality.
15033       if (_.keys(b).length !== length) return false;
15034       while (length--) {
15035         // Deep compare each member
15036         key = keys[length];
15037         if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
15038       }
15039     }
15040     // Remove the first object from the stack of traversed objects.
15041     aStack.pop();
15042     bStack.pop();
15043     return true;
15044   };
15045
15046   // Perform a deep comparison to check if two objects are equal.
15047   _.isEqual = function(a, b) {
15048     return eq(a, b);
15049   };
15050
15051   // Is a given array, string, or object empty?
15052   // An "empty" object has no enumerable own-properties.
15053   _.isEmpty = function(obj) {
15054     if (obj == null) return true;
15055     if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
15056     return _.keys(obj).length === 0;
15057   };
15058
15059   // Is a given value a DOM element?
15060   _.isElement = function(obj) {
15061     return !!(obj && obj.nodeType === 1);
15062   };
15063
15064   // Is a given value an array?
15065   // Delegates to ECMA5's native Array.isArray
15066   _.isArray = nativeIsArray || function(obj) {
15067     return toString.call(obj) === '[object Array]';
15068   };
15069
15070   // Is a given variable an object?
15071   _.isObject = function(obj) {
15072     var type = typeof obj;
15073     return type === 'function' || type === 'object' && !!obj;
15074   };
15075
15076   // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
15077   _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
15078     _['is' + name] = function(obj) {
15079       return toString.call(obj) === '[object ' + name + ']';
15080     };
15081   });
15082
15083   // Define a fallback version of the method in browsers (ahem, IE < 9), where
15084   // there isn't any inspectable "Arguments" type.
15085   if (!_.isArguments(arguments)) {
15086     _.isArguments = function(obj) {
15087       return _.has(obj, 'callee');
15088     };
15089   }
15090
15091   // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
15092   // IE 11 (#1621), and in Safari 8 (#1929).
15093   if (typeof /./ != 'function' && typeof Int8Array != 'object') {
15094     _.isFunction = function(obj) {
15095       return typeof obj == 'function' || false;
15096     };
15097   }
15098
15099   // Is a given object a finite number?
15100   _.isFinite = function(obj) {
15101     return isFinite(obj) && !isNaN(parseFloat(obj));
15102   };
15103
15104   // Is the given value `NaN`? (NaN is the only number which does not equal itself).
15105   _.isNaN = function(obj) {
15106     return _.isNumber(obj) && obj !== +obj;
15107   };
15108
15109   // Is a given value a boolean?
15110   _.isBoolean = function(obj) {
15111     return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
15112   };
15113
15114   // Is a given value equal to null?
15115   _.isNull = function(obj) {
15116     return obj === null;
15117   };
15118
15119   // Is a given variable undefined?
15120   _.isUndefined = function(obj) {
15121     return obj === void 0;
15122   };
15123
15124   // Shortcut function for checking if an object has a given property directly
15125   // on itself (in other words, not on a prototype).
15126   _.has = function(obj, key) {
15127     return obj != null && hasOwnProperty.call(obj, key);
15128   };
15129
15130   // Utility Functions
15131   // -----------------
15132
15133   // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
15134   // previous owner. Returns a reference to the Underscore object.
15135   _.noConflict = function() {
15136     root._ = previousUnderscore;
15137     return this;
15138   };
15139
15140   // Keep the identity function around for default iteratees.
15141   _.identity = function(value) {
15142     return value;
15143   };
15144
15145   // Predicate-generating functions. Often useful outside of Underscore.
15146   _.constant = function(value) {
15147     return function() {
15148       return value;
15149     };
15150   };
15151
15152   _.noop = function(){};
15153
15154   _.property = property;
15155
15156   // Generates a function for a given object that returns a given property.
15157   _.propertyOf = function(obj) {
15158     return obj == null ? function(){} : function(key) {
15159       return obj[key];
15160     };
15161   };
15162
15163   // Returns a predicate for checking whether an object has a given set of
15164   // `key:value` pairs.
15165   _.matcher = _.matches = function(attrs) {
15166     attrs = _.extendOwn({}, attrs);
15167     return function(obj) {
15168       return _.isMatch(obj, attrs);
15169     };
15170   };
15171
15172   // Run a function **n** times.
15173   _.times = function(n, iteratee, context) {
15174     var accum = Array(Math.max(0, n));
15175     iteratee = optimizeCb(iteratee, context, 1);
15176     for (var i = 0; i < n; i++) accum[i] = iteratee(i);
15177     return accum;
15178   };
15179
15180   // Return a random integer between min and max (inclusive).
15181   _.random = function(min, max) {
15182     if (max == null) {
15183       max = min;
15184       min = 0;
15185     }
15186     return min + Math.floor(Math.random() * (max - min + 1));
15187   };
15188
15189   // A (possibly faster) way to get the current timestamp as an integer.
15190   _.now = Date.now || function() {
15191     return new Date().getTime();
15192   };
15193
15194    // List of HTML entities for escaping.
15195   var escapeMap = {
15196     '&': '&amp;',
15197     '<': '&lt;',
15198     '>': '&gt;',
15199     '"': '&quot;',
15200     "'": '&#x27;',
15201     '`': '&#x60;'
15202   };
15203   var unescapeMap = _.invert(escapeMap);
15204
15205   // Functions for escaping and unescaping strings to/from HTML interpolation.
15206   var createEscaper = function(map) {
15207     var escaper = function(match) {
15208       return map[match];
15209     };
15210     // Regexes for identifying a key that needs to be escaped
15211     var source = '(?:' + _.keys(map).join('|') + ')';
15212     var testRegexp = RegExp(source);
15213     var replaceRegexp = RegExp(source, 'g');
15214     return function(string) {
15215       string = string == null ? '' : '' + string;
15216       return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
15217     };
15218   };
15219   _.escape = createEscaper(escapeMap);
15220   _.unescape = createEscaper(unescapeMap);
15221
15222   // If the value of the named `property` is a function then invoke it with the
15223   // `object` as context; otherwise, return it.
15224   _.result = function(object, property, fallback) {
15225     var value = object == null ? void 0 : object[property];
15226     if (value === void 0) {
15227       value = fallback;
15228     }
15229     return _.isFunction(value) ? value.call(object) : value;
15230   };
15231
15232   // Generate a unique integer id (unique within the entire client session).
15233   // Useful for temporary DOM ids.
15234   var idCounter = 0;
15235   _.uniqueId = function(prefix) {
15236     var id = ++idCounter + '';
15237     return prefix ? prefix + id : id;
15238   };
15239
15240   // By default, Underscore uses ERB-style template delimiters, change the
15241   // following template settings to use alternative delimiters.
15242   _.templateSettings = {
15243     evaluate    : /<%([\s\S]+?)%>/g,
15244     interpolate : /<%=([\s\S]+?)%>/g,
15245     escape      : /<%-([\s\S]+?)%>/g
15246   };
15247
15248   // When customizing `templateSettings`, if you don't want to define an
15249   // interpolation, evaluation or escaping regex, we need one that is
15250   // guaranteed not to match.
15251   var noMatch = /(.)^/;
15252
15253   // Certain characters need to be escaped so that they can be put into a
15254   // string literal.
15255   var escapes = {
15256     "'":      "'",
15257     '\\':     '\\',
15258     '\r':     'r',
15259     '\n':     'n',
15260     '\u2028': 'u2028',
15261     '\u2029': 'u2029'
15262   };
15263
15264   var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
15265
15266   var escapeChar = function(match) {
15267     return '\\' + escapes[match];
15268   };
15269
15270   // JavaScript micro-templating, similar to John Resig's implementation.
15271   // Underscore templating handles arbitrary delimiters, preserves whitespace,
15272   // and correctly escapes quotes within interpolated code.
15273   // NB: `oldSettings` only exists for backwards compatibility.
15274   _.template = function(text, settings, oldSettings) {
15275     if (!settings && oldSettings) settings = oldSettings;
15276     settings = _.defaults({}, settings, _.templateSettings);
15277
15278     // Combine delimiters into one regular expression via alternation.
15279     var matcher = RegExp([
15280       (settings.escape || noMatch).source,
15281       (settings.interpolate || noMatch).source,
15282       (settings.evaluate || noMatch).source
15283     ].join('|') + '|$', 'g');
15284
15285     // Compile the template source, escaping string literals appropriately.
15286     var index = 0;
15287     var source = "__p+='";
15288     text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
15289       source += text.slice(index, offset).replace(escaper, escapeChar);
15290       index = offset + match.length;
15291
15292       if (escape) {
15293         source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
15294       } else if (interpolate) {
15295         source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
15296       } else if (evaluate) {
15297         source += "';\n" + evaluate + "\n__p+='";
15298       }
15299
15300       // Adobe VMs need the match returned to produce the correct offest.
15301       return match;
15302     });
15303     source += "';\n";
15304
15305     // If a variable is not specified, place data values in local scope.
15306     if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
15307
15308     source = "var __t,__p='',__j=Array.prototype.join," +
15309       "print=function(){__p+=__j.call(arguments,'');};\n" +
15310       source + 'return __p;\n';
15311
15312     try {
15313       var render = new Function(settings.variable || 'obj', '_', source);
15314     } catch (e) {
15315       e.source = source;
15316       throw e;
15317     }
15318
15319     var template = function(data) {
15320       return render.call(this, data, _);
15321     };
15322
15323     // Provide the compiled source as a convenience for precompilation.
15324     var argument = settings.variable || 'obj';
15325     template.source = 'function(' + argument + '){\n' + source + '}';
15326
15327     return template;
15328   };
15329
15330   // Add a "chain" function. Start chaining a wrapped Underscore object.
15331   _.chain = function(obj) {
15332     var instance = _(obj);
15333     instance._chain = true;
15334     return instance;
15335   };
15336
15337   // OOP
15338   // ---------------
15339   // If Underscore is called as a function, it returns a wrapped object that
15340   // can be used OO-style. This wrapper holds altered versions of all the
15341   // underscore functions. Wrapped objects may be chained.
15342
15343   // Helper function to continue chaining intermediate results.
15344   var result = function(instance, obj) {
15345     return instance._chain ? _(obj).chain() : obj;
15346   };
15347
15348   // Add your own custom functions to the Underscore object.
15349   _.mixin = function(obj) {
15350     _.each(_.functions(obj), function(name) {
15351       var func = _[name] = obj[name];
15352       _.prototype[name] = function() {
15353         var args = [this._wrapped];
15354         push.apply(args, arguments);
15355         return result(this, func.apply(_, args));
15356       };
15357     });
15358   };
15359
15360   // Add all of the Underscore functions to the wrapper object.
15361   _.mixin(_);
15362
15363   // Add all mutator Array functions to the wrapper.
15364   _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
15365     var method = ArrayProto[name];
15366     _.prototype[name] = function() {
15367       var obj = this._wrapped;
15368       method.apply(obj, arguments);
15369       if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
15370       return result(this, obj);
15371     };
15372   });
15373
15374   // Add all accessor Array functions to the wrapper.
15375   _.each(['concat', 'join', 'slice'], function(name) {
15376     var method = ArrayProto[name];
15377     _.prototype[name] = function() {
15378       return result(this, method.apply(this._wrapped, arguments));
15379     };
15380   });
15381
15382   // Extracts the result from a wrapped and chained object.
15383   _.prototype.value = function() {
15384     return this._wrapped;
15385   };
15386
15387   // Provide unwrapping proxy for some methods used in engine operations
15388   // such as arithmetic and JSON stringification.
15389   _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
15390
15391   _.prototype.toString = function() {
15392     return '' + this._wrapped;
15393   };
15394
15395   // AMD registration happens at the end for compatibility with AMD loaders
15396   // that may not enforce next-turn semantics on modules. Even though general
15397   // practice for AMD registration is to be anonymous, underscore registers
15398   // as a named module because, like jQuery, it is a base library that is
15399   // popular enough to be bundled in a third party lib, but not be part of
15400   // an AMD load request. Those cases could generate an error when an
15401   // anonymous define() is called outside of a loader request.
15402   if (typeof define === 'function' && define.amd) {
15403     define('underscore', [], function() {
15404       return _;
15405     });
15406   }
15407 }.call(this));
15408
15409 },{}],176:[function(require,module,exports){
15410 /*
15411  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
15412  *
15413  * Redistribution and use in source and binary forms, with or without
15414  * modification, are permitted provided that the following conditions
15415  * are met:
15416  * 1. Redistributions of source code must retain the above copyright
15417  *    notice, this list of conditions and the following disclaimer.
15418  * 2. Redistributions in binary form must reproduce the above copyright
15419  *    notice, this list of conditions and the following disclaimer in the
15420  *    documentation and/or other materials provided with the distribution.
15421  *
15422  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15423  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15424  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
15425  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
15426  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
15427  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
15428  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
15429  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
15430  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15431  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15432  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15433  *
15434  * Ported from Webkit
15435  * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
15436  */
15437
15438 module.exports = UnitBezier;
15439
15440 function UnitBezier(p1x, p1y, p2x, p2y) {
15441     // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
15442     this.cx = 3.0 * p1x;
15443     this.bx = 3.0 * (p2x - p1x) - this.cx;
15444     this.ax = 1.0 - this.cx - this.bx;
15445
15446     this.cy = 3.0 * p1y;
15447     this.by = 3.0 * (p2y - p1y) - this.cy;
15448     this.ay = 1.0 - this.cy - this.by;
15449
15450     this.p1x = p1x;
15451     this.p1y = p2y;
15452     this.p2x = p2x;
15453     this.p2y = p2y;
15454 }
15455
15456 UnitBezier.prototype.sampleCurveX = function(t) {
15457     // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
15458     return ((this.ax * t + this.bx) * t + this.cx) * t;
15459 };
15460
15461 UnitBezier.prototype.sampleCurveY = function(t) {
15462     return ((this.ay * t + this.by) * t + this.cy) * t;
15463 };
15464
15465 UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
15466     return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
15467 };
15468
15469 UnitBezier.prototype.solveCurveX = function(x, epsilon) {
15470     if (typeof epsilon === 'undefined') epsilon = 1e-6;
15471
15472     var t0, t1, t2, x2, i;
15473
15474     // First try a few iterations of Newton's method -- normally very fast.
15475     for (t2 = x, i = 0; i < 8; i++) {
15476
15477         x2 = this.sampleCurveX(t2) - x;
15478         if (Math.abs(x2) < epsilon) return t2;
15479
15480         var d2 = this.sampleCurveDerivativeX(t2);
15481         if (Math.abs(d2) < 1e-6) break;
15482
15483         t2 = t2 - x2 / d2;
15484     }
15485
15486     // Fall back to the bisection method for reliability.
15487     t0 = 0.0;
15488     t1 = 1.0;
15489     t2 = x;
15490
15491     if (t2 < t0) return t0;
15492     if (t2 > t1) return t1;
15493
15494     while (t0 < t1) {
15495
15496         x2 = this.sampleCurveX(t2);
15497         if (Math.abs(x2 - x) < epsilon) return t2;
15498
15499         if (x > x2) {
15500             t0 = t2;
15501         } else {
15502             t1 = t2;
15503         }
15504
15505         t2 = (t1 - t0) * 0.5 + t0;
15506     }
15507
15508     // Failure.
15509     return t2;
15510 };
15511
15512 UnitBezier.prototype.solve = function(x, epsilon) {
15513     return this.sampleCurveY(this.solveCurveX(x, epsilon));
15514 };
15515
15516 },{}],177:[function(require,module,exports){
15517 var createElement = require("./vdom/create-element.js")
15518
15519 module.exports = createElement
15520
15521 },{"./vdom/create-element.js":183}],178:[function(require,module,exports){
15522 var diff = require("./vtree/diff.js")
15523
15524 module.exports = diff
15525
15526 },{"./vtree/diff.js":203}],179:[function(require,module,exports){
15527 var h = require("./virtual-hyperscript/index.js")
15528
15529 module.exports = h
15530
15531 },{"./virtual-hyperscript/index.js":190}],180:[function(require,module,exports){
15532 var diff = require("./diff.js")
15533 var patch = require("./patch.js")
15534 var h = require("./h.js")
15535 var create = require("./create-element.js")
15536 var VNode = require('./vnode/vnode.js')
15537 var VText = require('./vnode/vtext.js')
15538
15539 module.exports = {
15540     diff: diff,
15541     patch: patch,
15542     h: h,
15543     create: create,
15544     VNode: VNode,
15545     VText: VText
15546 }
15547
15548 },{"./create-element.js":177,"./diff.js":178,"./h.js":179,"./patch.js":181,"./vnode/vnode.js":199,"./vnode/vtext.js":201}],181:[function(require,module,exports){
15549 var patch = require("./vdom/patch.js")
15550
15551 module.exports = patch
15552
15553 },{"./vdom/patch.js":186}],182:[function(require,module,exports){
15554 var isObject = require("is-object")
15555 var isHook = require("../vnode/is-vhook.js")
15556
15557 module.exports = applyProperties
15558
15559 function applyProperties(node, props, previous) {
15560     for (var propName in props) {
15561         var propValue = props[propName]
15562
15563         if (propValue === undefined) {
15564             removeProperty(node, propName, propValue, previous);
15565         } else if (isHook(propValue)) {
15566             removeProperty(node, propName, propValue, previous)
15567             if (propValue.hook) {
15568                 propValue.hook(node,
15569                     propName,
15570                     previous ? previous[propName] : undefined)
15571             }
15572         } else {
15573             if (isObject(propValue)) {
15574                 patchObject(node, props, previous, propName, propValue);
15575             } else {
15576                 node[propName] = propValue
15577             }
15578         }
15579     }
15580 }
15581
15582 function removeProperty(node, propName, propValue, previous) {
15583     if (previous) {
15584         var previousValue = previous[propName]
15585
15586         if (!isHook(previousValue)) {
15587             if (propName === "attributes") {
15588                 for (var attrName in previousValue) {
15589                     node.removeAttribute(attrName)
15590                 }
15591             } else if (propName === "style") {
15592                 for (var i in previousValue) {
15593                     node.style[i] = ""
15594                 }
15595             } else if (typeof previousValue === "string") {
15596                 node[propName] = ""
15597             } else {
15598                 node[propName] = null
15599             }
15600         } else if (previousValue.unhook) {
15601             previousValue.unhook(node, propName, propValue)
15602         }
15603     }
15604 }
15605
15606 function patchObject(node, props, previous, propName, propValue) {
15607     var previousValue = previous ? previous[propName] : undefined
15608
15609     // Set attributes
15610     if (propName === "attributes") {
15611         for (var attrName in propValue) {
15612             var attrValue = propValue[attrName]
15613
15614             if (attrValue === undefined) {
15615                 node.removeAttribute(attrName)
15616             } else {
15617                 node.setAttribute(attrName, attrValue)
15618             }
15619         }
15620
15621         return
15622     }
15623
15624     if(previousValue && isObject(previousValue) &&
15625         getPrototype(previousValue) !== getPrototype(propValue)) {
15626         node[propName] = propValue
15627         return
15628     }
15629
15630     if (!isObject(node[propName])) {
15631         node[propName] = {}
15632     }
15633
15634     var replacer = propName === "style" ? "" : undefined
15635
15636     for (var k in propValue) {
15637         var value = propValue[k]
15638         node[propName][k] = (value === undefined) ? replacer : value
15639     }
15640 }
15641
15642 function getPrototype(value) {
15643     if (Object.getPrototypeOf) {
15644         return Object.getPrototypeOf(value)
15645     } else if (value.__proto__) {
15646         return value.__proto__
15647     } else if (value.constructor) {
15648         return value.constructor.prototype
15649     }
15650 }
15651
15652 },{"../vnode/is-vhook.js":194,"is-object":18}],183:[function(require,module,exports){
15653 var document = require("global/document")
15654
15655 var applyProperties = require("./apply-properties")
15656
15657 var isVNode = require("../vnode/is-vnode.js")
15658 var isVText = require("../vnode/is-vtext.js")
15659 var isWidget = require("../vnode/is-widget.js")
15660 var handleThunk = require("../vnode/handle-thunk.js")
15661
15662 module.exports = createElement
15663
15664 function createElement(vnode, opts) {
15665     var doc = opts ? opts.document || document : document
15666     var warn = opts ? opts.warn : null
15667
15668     vnode = handleThunk(vnode).a
15669
15670     if (isWidget(vnode)) {
15671         return vnode.init()
15672     } else if (isVText(vnode)) {
15673         return doc.createTextNode(vnode.text)
15674     } else if (!isVNode(vnode)) {
15675         if (warn) {
15676             warn("Item is not a valid virtual dom node", vnode)
15677         }
15678         return null
15679     }
15680
15681     var node = (vnode.namespace === null) ?
15682         doc.createElement(vnode.tagName) :
15683         doc.createElementNS(vnode.namespace, vnode.tagName)
15684
15685     var props = vnode.properties
15686     applyProperties(node, props)
15687
15688     var children = vnode.children
15689
15690     for (var i = 0; i < children.length; i++) {
15691         var childNode = createElement(children[i], opts)
15692         if (childNode) {
15693             node.appendChild(childNode)
15694         }
15695     }
15696
15697     return node
15698 }
15699
15700 },{"../vnode/handle-thunk.js":192,"../vnode/is-vnode.js":195,"../vnode/is-vtext.js":196,"../vnode/is-widget.js":197,"./apply-properties":182,"global/document":14}],184:[function(require,module,exports){
15701 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
15702 // We don't want to read all of the DOM nodes in the tree so we use
15703 // the in-order tree indexing to eliminate recursion down certain branches.
15704 // We only recurse into a DOM node if we know that it contains a child of
15705 // interest.
15706
15707 var noChild = {}
15708
15709 module.exports = domIndex
15710
15711 function domIndex(rootNode, tree, indices, nodes) {
15712     if (!indices || indices.length === 0) {
15713         return {}
15714     } else {
15715         indices.sort(ascending)
15716         return recurse(rootNode, tree, indices, nodes, 0)
15717     }
15718 }
15719
15720 function recurse(rootNode, tree, indices, nodes, rootIndex) {
15721     nodes = nodes || {}
15722
15723
15724     if (rootNode) {
15725         if (indexInRange(indices, rootIndex, rootIndex)) {
15726             nodes[rootIndex] = rootNode
15727         }
15728
15729         var vChildren = tree.children
15730
15731         if (vChildren) {
15732
15733             var childNodes = rootNode.childNodes
15734
15735             for (var i = 0; i < tree.children.length; i++) {
15736                 rootIndex += 1
15737
15738                 var vChild = vChildren[i] || noChild
15739                 var nextIndex = rootIndex + (vChild.count || 0)
15740
15741                 // skip recursion down the tree if there are no nodes down here
15742                 if (indexInRange(indices, rootIndex, nextIndex)) {
15743                     recurse(childNodes[i], vChild, indices, nodes, rootIndex)
15744                 }
15745
15746                 rootIndex = nextIndex
15747             }
15748         }
15749     }
15750
15751     return nodes
15752 }
15753
15754 // Binary search for an index in the interval [left, right]
15755 function indexInRange(indices, left, right) {
15756     if (indices.length === 0) {
15757         return false
15758     }
15759
15760     var minIndex = 0
15761     var maxIndex = indices.length - 1
15762     var currentIndex
15763     var currentItem
15764
15765     while (minIndex <= maxIndex) {
15766         currentIndex = ((maxIndex + minIndex) / 2) >> 0
15767         currentItem = indices[currentIndex]
15768
15769         if (minIndex === maxIndex) {
15770             return currentItem >= left && currentItem <= right
15771         } else if (currentItem < left) {
15772             minIndex = currentIndex + 1
15773         } else  if (currentItem > right) {
15774             maxIndex = currentIndex - 1
15775         } else {
15776             return true
15777         }
15778     }
15779
15780     return false;
15781 }
15782
15783 function ascending(a, b) {
15784     return a > b ? 1 : -1
15785 }
15786
15787 },{}],185:[function(require,module,exports){
15788 var applyProperties = require("./apply-properties")
15789
15790 var isWidget = require("../vnode/is-widget.js")
15791 var VPatch = require("../vnode/vpatch.js")
15792
15793 var updateWidget = require("./update-widget")
15794
15795 module.exports = applyPatch
15796
15797 function applyPatch(vpatch, domNode, renderOptions) {
15798     var type = vpatch.type
15799     var vNode = vpatch.vNode
15800     var patch = vpatch.patch
15801
15802     switch (type) {
15803         case VPatch.REMOVE:
15804             return removeNode(domNode, vNode)
15805         case VPatch.INSERT:
15806             return insertNode(domNode, patch, renderOptions)
15807         case VPatch.VTEXT:
15808             return stringPatch(domNode, vNode, patch, renderOptions)
15809         case VPatch.WIDGET:
15810             return widgetPatch(domNode, vNode, patch, renderOptions)
15811         case VPatch.VNODE:
15812             return vNodePatch(domNode, vNode, patch, renderOptions)
15813         case VPatch.ORDER:
15814             reorderChildren(domNode, patch)
15815             return domNode
15816         case VPatch.PROPS:
15817             applyProperties(domNode, patch, vNode.properties)
15818             return domNode
15819         case VPatch.THUNK:
15820             return replaceRoot(domNode,
15821                 renderOptions.patch(domNode, patch, renderOptions))
15822         default:
15823             return domNode
15824     }
15825 }
15826
15827 function removeNode(domNode, vNode) {
15828     var parentNode = domNode.parentNode
15829
15830     if (parentNode) {
15831         parentNode.removeChild(domNode)
15832     }
15833
15834     destroyWidget(domNode, vNode);
15835
15836     return null
15837 }
15838
15839 function insertNode(parentNode, vNode, renderOptions) {
15840     var newNode = renderOptions.render(vNode, renderOptions)
15841
15842     if (parentNode) {
15843         parentNode.appendChild(newNode)
15844     }
15845
15846     return parentNode
15847 }
15848
15849 function stringPatch(domNode, leftVNode, vText, renderOptions) {
15850     var newNode
15851
15852     if (domNode.nodeType === 3) {
15853         domNode.replaceData(0, domNode.length, vText.text)
15854         newNode = domNode
15855     } else {
15856         var parentNode = domNode.parentNode
15857         newNode = renderOptions.render(vText, renderOptions)
15858
15859         if (parentNode && newNode !== domNode) {
15860             parentNode.replaceChild(newNode, domNode)
15861         }
15862     }
15863
15864     return newNode
15865 }
15866
15867 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
15868     var updating = updateWidget(leftVNode, widget)
15869     var newNode
15870
15871     if (updating) {
15872         newNode = widget.update(leftVNode, domNode) || domNode
15873     } else {
15874         newNode = renderOptions.render(widget, renderOptions)
15875     }
15876
15877     var parentNode = domNode.parentNode
15878
15879     if (parentNode && newNode !== domNode) {
15880         parentNode.replaceChild(newNode, domNode)
15881     }
15882
15883     if (!updating) {
15884         destroyWidget(domNode, leftVNode)
15885     }
15886
15887     return newNode
15888 }
15889
15890 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
15891     var parentNode = domNode.parentNode
15892     var newNode = renderOptions.render(vNode, renderOptions)
15893
15894     if (parentNode && newNode !== domNode) {
15895         parentNode.replaceChild(newNode, domNode)
15896     }
15897
15898     return newNode
15899 }
15900
15901 function destroyWidget(domNode, w) {
15902     if (typeof w.destroy === "function" && isWidget(w)) {
15903         w.destroy(domNode)
15904     }
15905 }
15906
15907 function reorderChildren(domNode, moves) {
15908     var childNodes = domNode.childNodes
15909     var keyMap = {}
15910     var node
15911     var remove
15912     var insert
15913
15914     for (var i = 0; i < moves.removes.length; i++) {
15915         remove = moves.removes[i]
15916         node = childNodes[remove.from]
15917         if (remove.key) {
15918             keyMap[remove.key] = node
15919         }
15920         domNode.removeChild(node)
15921     }
15922
15923     var length = childNodes.length
15924     for (var j = 0; j < moves.inserts.length; j++) {
15925         insert = moves.inserts[j]
15926         node = keyMap[insert.key]
15927         // this is the weirdest bug i've ever seen in webkit
15928         domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
15929     }
15930 }
15931
15932 function replaceRoot(oldRoot, newRoot) {
15933     if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
15934         oldRoot.parentNode.replaceChild(newRoot, oldRoot)
15935     }
15936
15937     return newRoot;
15938 }
15939
15940 },{"../vnode/is-widget.js":197,"../vnode/vpatch.js":200,"./apply-properties":182,"./update-widget":187}],186:[function(require,module,exports){
15941 var document = require("global/document")
15942 var isArray = require("x-is-array")
15943
15944 var render = require("./create-element")
15945 var domIndex = require("./dom-index")
15946 var patchOp = require("./patch-op")
15947 module.exports = patch
15948
15949 function patch(rootNode, patches, renderOptions) {
15950     renderOptions = renderOptions || {}
15951     renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
15952         ? renderOptions.patch
15953         : patchRecursive
15954     renderOptions.render = renderOptions.render || render
15955
15956     return renderOptions.patch(rootNode, patches, renderOptions)
15957 }
15958
15959 function patchRecursive(rootNode, patches, renderOptions) {
15960     var indices = patchIndices(patches)
15961
15962     if (indices.length === 0) {
15963         return rootNode
15964     }
15965
15966     var index = domIndex(rootNode, patches.a, indices)
15967     var ownerDocument = rootNode.ownerDocument
15968
15969     if (!renderOptions.document && ownerDocument !== document) {
15970         renderOptions.document = ownerDocument
15971     }
15972
15973     for (var i = 0; i < indices.length; i++) {
15974         var nodeIndex = indices[i]
15975         rootNode = applyPatch(rootNode,
15976             index[nodeIndex],
15977             patches[nodeIndex],
15978             renderOptions)
15979     }
15980
15981     return rootNode
15982 }
15983
15984 function applyPatch(rootNode, domNode, patchList, renderOptions) {
15985     if (!domNode) {
15986         return rootNode
15987     }
15988
15989     var newNode
15990
15991     if (isArray(patchList)) {
15992         for (var i = 0; i < patchList.length; i++) {
15993             newNode = patchOp(patchList[i], domNode, renderOptions)
15994
15995             if (domNode === rootNode) {
15996                 rootNode = newNode
15997             }
15998         }
15999     } else {
16000         newNode = patchOp(patchList, domNode, renderOptions)
16001
16002         if (domNode === rootNode) {
16003             rootNode = newNode
16004         }
16005     }
16006
16007     return rootNode
16008 }
16009
16010 function patchIndices(patches) {
16011     var indices = []
16012
16013     for (var key in patches) {
16014         if (key !== "a") {
16015             indices.push(Number(key))
16016         }
16017     }
16018
16019     return indices
16020 }
16021
16022 },{"./create-element":183,"./dom-index":184,"./patch-op":185,"global/document":14,"x-is-array":222}],187:[function(require,module,exports){
16023 var isWidget = require("../vnode/is-widget.js")
16024
16025 module.exports = updateWidget
16026
16027 function updateWidget(a, b) {
16028     if (isWidget(a) && isWidget(b)) {
16029         if ("name" in a && "name" in b) {
16030             return a.id === b.id
16031         } else {
16032             return a.init === b.init
16033         }
16034     }
16035
16036     return false
16037 }
16038
16039 },{"../vnode/is-widget.js":197}],188:[function(require,module,exports){
16040 'use strict';
16041
16042 var EvStore = require('ev-store');
16043
16044 module.exports = EvHook;
16045
16046 function EvHook(value) {
16047     if (!(this instanceof EvHook)) {
16048         return new EvHook(value);
16049     }
16050
16051     this.value = value;
16052 }
16053
16054 EvHook.prototype.hook = function (node, propertyName) {
16055     var es = EvStore(node);
16056     var propName = propertyName.substr(3);
16057
16058     es[propName] = this.value;
16059 };
16060
16061 EvHook.prototype.unhook = function(node, propertyName) {
16062     var es = EvStore(node);
16063     var propName = propertyName.substr(3);
16064
16065     es[propName] = undefined;
16066 };
16067
16068 },{"ev-store":7}],189:[function(require,module,exports){
16069 'use strict';
16070
16071 module.exports = SoftSetHook;
16072
16073 function SoftSetHook(value) {
16074     if (!(this instanceof SoftSetHook)) {
16075         return new SoftSetHook(value);
16076     }
16077
16078     this.value = value;
16079 }
16080
16081 SoftSetHook.prototype.hook = function (node, propertyName) {
16082     if (node[propertyName] !== this.value) {
16083         node[propertyName] = this.value;
16084     }
16085 };
16086
16087 },{}],190:[function(require,module,exports){
16088 'use strict';
16089
16090 var isArray = require('x-is-array');
16091
16092 var VNode = require('../vnode/vnode.js');
16093 var VText = require('../vnode/vtext.js');
16094 var isVNode = require('../vnode/is-vnode');
16095 var isVText = require('../vnode/is-vtext');
16096 var isWidget = require('../vnode/is-widget');
16097 var isHook = require('../vnode/is-vhook');
16098 var isVThunk = require('../vnode/is-thunk');
16099
16100 var parseTag = require('./parse-tag.js');
16101 var softSetHook = require('./hooks/soft-set-hook.js');
16102 var evHook = require('./hooks/ev-hook.js');
16103
16104 module.exports = h;
16105
16106 function h(tagName, properties, children) {
16107     var childNodes = [];
16108     var tag, props, key, namespace;
16109
16110     if (!children && isChildren(properties)) {
16111         children = properties;
16112         props = {};
16113     }
16114
16115     props = props || properties || {};
16116     tag = parseTag(tagName, props);
16117
16118     // support keys
16119     if (props.hasOwnProperty('key')) {
16120         key = props.key;
16121         props.key = undefined;
16122     }
16123
16124     // support namespace
16125     if (props.hasOwnProperty('namespace')) {
16126         namespace = props.namespace;
16127         props.namespace = undefined;
16128     }
16129
16130     // fix cursor bug
16131     if (tag === 'INPUT' &&
16132         !namespace &&
16133         props.hasOwnProperty('value') &&
16134         props.value !== undefined &&
16135         !isHook(props.value)
16136     ) {
16137         props.value = softSetHook(props.value);
16138     }
16139
16140     transformProperties(props);
16141
16142     if (children !== undefined && children !== null) {
16143         addChild(children, childNodes, tag, props);
16144     }
16145
16146
16147     return new VNode(tag, props, childNodes, key, namespace);
16148 }
16149
16150 function addChild(c, childNodes, tag, props) {
16151     if (typeof c === 'string') {
16152         childNodes.push(new VText(c));
16153     } else if (typeof c === 'number') {
16154         childNodes.push(new VText(String(c)));
16155     } else if (isChild(c)) {
16156         childNodes.push(c);
16157     } else if (isArray(c)) {
16158         for (var i = 0; i < c.length; i++) {
16159             addChild(c[i], childNodes, tag, props);
16160         }
16161     } else if (c === null || c === undefined) {
16162         return;
16163     } else {
16164         throw UnexpectedVirtualElement({
16165             foreignObject: c,
16166             parentVnode: {
16167                 tagName: tag,
16168                 properties: props
16169             }
16170         });
16171     }
16172 }
16173
16174 function transformProperties(props) {
16175     for (var propName in props) {
16176         if (props.hasOwnProperty(propName)) {
16177             var value = props[propName];
16178
16179             if (isHook(value)) {
16180                 continue;
16181             }
16182
16183             if (propName.substr(0, 3) === 'ev-') {
16184                 // add ev-foo support
16185                 props[propName] = evHook(value);
16186             }
16187         }
16188     }
16189 }
16190
16191 function isChild(x) {
16192     return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
16193 }
16194
16195 function isChildren(x) {
16196     return typeof x === 'string' || isArray(x) || isChild(x);
16197 }
16198
16199 function UnexpectedVirtualElement(data) {
16200     var err = new Error();
16201
16202     err.type = 'virtual-hyperscript.unexpected.virtual-element';
16203     err.message = 'Unexpected virtual child passed to h().\n' +
16204         'Expected a VNode / Vthunk / VWidget / string but:\n' +
16205         'got:\n' +
16206         errorString(data.foreignObject) +
16207         '.\n' +
16208         'The parent vnode is:\n' +
16209         errorString(data.parentVnode)
16210         '\n' +
16211         'Suggested fix: change your `h(..., [ ... ])` callsite.';
16212     err.foreignObject = data.foreignObject;
16213     err.parentVnode = data.parentVnode;
16214
16215     return err;
16216 }
16217
16218 function errorString(obj) {
16219     try {
16220         return JSON.stringify(obj, null, '    ');
16221     } catch (e) {
16222         return String(obj);
16223     }
16224 }
16225
16226 },{"../vnode/is-thunk":193,"../vnode/is-vhook":194,"../vnode/is-vnode":195,"../vnode/is-vtext":196,"../vnode/is-widget":197,"../vnode/vnode.js":199,"../vnode/vtext.js":201,"./hooks/ev-hook.js":188,"./hooks/soft-set-hook.js":189,"./parse-tag.js":191,"x-is-array":222}],191:[function(require,module,exports){
16227 'use strict';
16228
16229 var split = require('browser-split');
16230
16231 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
16232 var notClassId = /^\.|#/;
16233
16234 module.exports = parseTag;
16235
16236 function parseTag(tag, props) {
16237     if (!tag) {
16238         return 'DIV';
16239     }
16240
16241     var noId = !(props.hasOwnProperty('id'));
16242
16243     var tagParts = split(tag, classIdSplit);
16244     var tagName = null;
16245
16246     if (notClassId.test(tagParts[1])) {
16247         tagName = 'DIV';
16248     }
16249
16250     var classes, part, type, i;
16251
16252     for (i = 0; i < tagParts.length; i++) {
16253         part = tagParts[i];
16254
16255         if (!part) {
16256             continue;
16257         }
16258
16259         type = part.charAt(0);
16260
16261         if (!tagName) {
16262             tagName = part;
16263         } else if (type === '.') {
16264             classes = classes || [];
16265             classes.push(part.substring(1, part.length));
16266         } else if (type === '#' && noId) {
16267             props.id = part.substring(1, part.length);
16268         }
16269     }
16270
16271     if (classes) {
16272         if (props.className) {
16273             classes.push(props.className);
16274         }
16275
16276         props.className = classes.join(' ');
16277     }
16278
16279     return props.namespace ? tagName : tagName.toUpperCase();
16280 }
16281
16282 },{"browser-split":3}],192:[function(require,module,exports){
16283 var isVNode = require("./is-vnode")
16284 var isVText = require("./is-vtext")
16285 var isWidget = require("./is-widget")
16286 var isThunk = require("./is-thunk")
16287
16288 module.exports = handleThunk
16289
16290 function handleThunk(a, b) {
16291     var renderedA = a
16292     var renderedB = b
16293
16294     if (isThunk(b)) {
16295         renderedB = renderThunk(b, a)
16296     }
16297
16298     if (isThunk(a)) {
16299         renderedA = renderThunk(a, null)
16300     }
16301
16302     return {
16303         a: renderedA,
16304         b: renderedB
16305     }
16306 }
16307
16308 function renderThunk(thunk, previous) {
16309     var renderedThunk = thunk.vnode
16310
16311     if (!renderedThunk) {
16312         renderedThunk = thunk.vnode = thunk.render(previous)
16313     }
16314
16315     if (!(isVNode(renderedThunk) ||
16316             isVText(renderedThunk) ||
16317             isWidget(renderedThunk))) {
16318         throw new Error("thunk did not return a valid node");
16319     }
16320
16321     return renderedThunk
16322 }
16323
16324 },{"./is-thunk":193,"./is-vnode":195,"./is-vtext":196,"./is-widget":197}],193:[function(require,module,exports){
16325 module.exports = isThunk
16326
16327 function isThunk(t) {
16328     return t && t.type === "Thunk"
16329 }
16330
16331 },{}],194:[function(require,module,exports){
16332 module.exports = isHook
16333
16334 function isHook(hook) {
16335     return hook &&
16336       (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
16337        typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
16338 }
16339
16340 },{}],195:[function(require,module,exports){
16341 var version = require("./version")
16342
16343 module.exports = isVirtualNode
16344
16345 function isVirtualNode(x) {
16346     return x && x.type === "VirtualNode" && x.version === version
16347 }
16348
16349 },{"./version":198}],196:[function(require,module,exports){
16350 var version = require("./version")
16351
16352 module.exports = isVirtualText
16353
16354 function isVirtualText(x) {
16355     return x && x.type === "VirtualText" && x.version === version
16356 }
16357
16358 },{"./version":198}],197:[function(require,module,exports){
16359 module.exports = isWidget
16360
16361 function isWidget(w) {
16362     return w && w.type === "Widget"
16363 }
16364
16365 },{}],198:[function(require,module,exports){
16366 module.exports = "2"
16367
16368 },{}],199:[function(require,module,exports){
16369 var version = require("./version")
16370 var isVNode = require("./is-vnode")
16371 var isWidget = require("./is-widget")
16372 var isThunk = require("./is-thunk")
16373 var isVHook = require("./is-vhook")
16374
16375 module.exports = VirtualNode
16376
16377 var noProperties = {}
16378 var noChildren = []
16379
16380 function VirtualNode(tagName, properties, children, key, namespace) {
16381     this.tagName = tagName
16382     this.properties = properties || noProperties
16383     this.children = children || noChildren
16384     this.key = key != null ? String(key) : undefined
16385     this.namespace = (typeof namespace === "string") ? namespace : null
16386
16387     var count = (children && children.length) || 0
16388     var descendants = 0
16389     var hasWidgets = false
16390     var hasThunks = false
16391     var descendantHooks = false
16392     var hooks
16393
16394     for (var propName in properties) {
16395         if (properties.hasOwnProperty(propName)) {
16396             var property = properties[propName]
16397             if (isVHook(property) && property.unhook) {
16398                 if (!hooks) {
16399                     hooks = {}
16400                 }
16401
16402                 hooks[propName] = property
16403             }
16404         }
16405     }
16406
16407     for (var i = 0; i < count; i++) {
16408         var child = children[i]
16409         if (isVNode(child)) {
16410             descendants += child.count || 0
16411
16412             if (!hasWidgets && child.hasWidgets) {
16413                 hasWidgets = true
16414             }
16415
16416             if (!hasThunks && child.hasThunks) {
16417                 hasThunks = true
16418             }
16419
16420             if (!descendantHooks && (child.hooks || child.descendantHooks)) {
16421                 descendantHooks = true
16422             }
16423         } else if (!hasWidgets && isWidget(child)) {
16424             if (typeof child.destroy === "function") {
16425                 hasWidgets = true
16426             }
16427         } else if (!hasThunks && isThunk(child)) {
16428             hasThunks = true;
16429         }
16430     }
16431
16432     this.count = count + descendants
16433     this.hasWidgets = hasWidgets
16434     this.hasThunks = hasThunks
16435     this.hooks = hooks
16436     this.descendantHooks = descendantHooks
16437 }
16438
16439 VirtualNode.prototype.version = version
16440 VirtualNode.prototype.type = "VirtualNode"
16441
16442 },{"./is-thunk":193,"./is-vhook":194,"./is-vnode":195,"./is-widget":197,"./version":198}],200:[function(require,module,exports){
16443 var version = require("./version")
16444
16445 VirtualPatch.NONE = 0
16446 VirtualPatch.VTEXT = 1
16447 VirtualPatch.VNODE = 2
16448 VirtualPatch.WIDGET = 3
16449 VirtualPatch.PROPS = 4
16450 VirtualPatch.ORDER = 5
16451 VirtualPatch.INSERT = 6
16452 VirtualPatch.REMOVE = 7
16453 VirtualPatch.THUNK = 8
16454
16455 module.exports = VirtualPatch
16456
16457 function VirtualPatch(type, vNode, patch) {
16458     this.type = Number(type)
16459     this.vNode = vNode
16460     this.patch = patch
16461 }
16462
16463 VirtualPatch.prototype.version = version
16464 VirtualPatch.prototype.type = "VirtualPatch"
16465
16466 },{"./version":198}],201:[function(require,module,exports){
16467 var version = require("./version")
16468
16469 module.exports = VirtualText
16470
16471 function VirtualText(text) {
16472     this.text = String(text)
16473 }
16474
16475 VirtualText.prototype.version = version
16476 VirtualText.prototype.type = "VirtualText"
16477
16478 },{"./version":198}],202:[function(require,module,exports){
16479 var isObject = require("is-object")
16480 var isHook = require("../vnode/is-vhook")
16481
16482 module.exports = diffProps
16483
16484 function diffProps(a, b) {
16485     var diff
16486
16487     for (var aKey in a) {
16488         if (!(aKey in b)) {
16489             diff = diff || {}
16490             diff[aKey] = undefined
16491         }
16492
16493         var aValue = a[aKey]
16494         var bValue = b[aKey]
16495
16496         if (aValue === bValue) {
16497             continue
16498         } else if (isObject(aValue) && isObject(bValue)) {
16499             if (getPrototype(bValue) !== getPrototype(aValue)) {
16500                 diff = diff || {}
16501                 diff[aKey] = bValue
16502             } else if (isHook(bValue)) {
16503                  diff = diff || {}
16504                  diff[aKey] = bValue
16505             } else {
16506                 var objectDiff = diffProps(aValue, bValue)
16507                 if (objectDiff) {
16508                     diff = diff || {}
16509                     diff[aKey] = objectDiff
16510                 }
16511             }
16512         } else {
16513             diff = diff || {}
16514             diff[aKey] = bValue
16515         }
16516     }
16517
16518     for (var bKey in b) {
16519         if (!(bKey in a)) {
16520             diff = diff || {}
16521             diff[bKey] = b[bKey]
16522         }
16523     }
16524
16525     return diff
16526 }
16527
16528 function getPrototype(value) {
16529   if (Object.getPrototypeOf) {
16530     return Object.getPrototypeOf(value)
16531   } else if (value.__proto__) {
16532     return value.__proto__
16533   } else if (value.constructor) {
16534     return value.constructor.prototype
16535   }
16536 }
16537
16538 },{"../vnode/is-vhook":194,"is-object":18}],203:[function(require,module,exports){
16539 var isArray = require("x-is-array")
16540
16541 var VPatch = require("../vnode/vpatch")
16542 var isVNode = require("../vnode/is-vnode")
16543 var isVText = require("../vnode/is-vtext")
16544 var isWidget = require("../vnode/is-widget")
16545 var isThunk = require("../vnode/is-thunk")
16546 var handleThunk = require("../vnode/handle-thunk")
16547
16548 var diffProps = require("./diff-props")
16549
16550 module.exports = diff
16551
16552 function diff(a, b) {
16553     var patch = { a: a }
16554     walk(a, b, patch, 0)
16555     return patch
16556 }
16557
16558 function walk(a, b, patch, index) {
16559     if (a === b) {
16560         return
16561     }
16562
16563     var apply = patch[index]
16564     var applyClear = false
16565
16566     if (isThunk(a) || isThunk(b)) {
16567         thunks(a, b, patch, index)
16568     } else if (b == null) {
16569
16570         // If a is a widget we will add a remove patch for it
16571         // Otherwise any child widgets/hooks must be destroyed.
16572         // This prevents adding two remove patches for a widget.
16573         if (!isWidget(a)) {
16574             clearState(a, patch, index)
16575             apply = patch[index]
16576         }
16577
16578         apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
16579     } else if (isVNode(b)) {
16580         if (isVNode(a)) {
16581             if (a.tagName === b.tagName &&
16582                 a.namespace === b.namespace &&
16583                 a.key === b.key) {
16584                 var propsPatch = diffProps(a.properties, b.properties)
16585                 if (propsPatch) {
16586                     apply = appendPatch(apply,
16587                         new VPatch(VPatch.PROPS, a, propsPatch))
16588                 }
16589                 apply = diffChildren(a, b, patch, apply, index)
16590             } else {
16591                 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
16592                 applyClear = true
16593             }
16594         } else {
16595             apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
16596             applyClear = true
16597         }
16598     } else if (isVText(b)) {
16599         if (!isVText(a)) {
16600             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
16601             applyClear = true
16602         } else if (a.text !== b.text) {
16603             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
16604         }
16605     } else if (isWidget(b)) {
16606         if (!isWidget(a)) {
16607             applyClear = true
16608         }
16609
16610         apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
16611     }
16612
16613     if (apply) {
16614         patch[index] = apply
16615     }
16616
16617     if (applyClear) {
16618         clearState(a, patch, index)
16619     }
16620 }
16621
16622 function diffChildren(a, b, patch, apply, index) {
16623     var aChildren = a.children
16624     var orderedSet = reorder(aChildren, b.children)
16625     var bChildren = orderedSet.children
16626
16627     var aLen = aChildren.length
16628     var bLen = bChildren.length
16629     var len = aLen > bLen ? aLen : bLen
16630
16631     for (var i = 0; i < len; i++) {
16632         var leftNode = aChildren[i]
16633         var rightNode = bChildren[i]
16634         index += 1
16635
16636         if (!leftNode) {
16637             if (rightNode) {
16638                 // Excess nodes in b need to be added
16639                 apply = appendPatch(apply,
16640                     new VPatch(VPatch.INSERT, null, rightNode))
16641             }
16642         } else {
16643             walk(leftNode, rightNode, patch, index)
16644         }
16645
16646         if (isVNode(leftNode) && leftNode.count) {
16647             index += leftNode.count
16648         }
16649     }
16650
16651     if (orderedSet.moves) {
16652         // Reorder nodes last
16653         apply = appendPatch(apply, new VPatch(
16654             VPatch.ORDER,
16655             a,
16656             orderedSet.moves
16657         ))
16658     }
16659
16660     return apply
16661 }
16662
16663 function clearState(vNode, patch, index) {
16664     // TODO: Make this a single walk, not two
16665     unhook(vNode, patch, index)
16666     destroyWidgets(vNode, patch, index)
16667 }
16668
16669 // Patch records for all destroyed widgets must be added because we need
16670 // a DOM node reference for the destroy function
16671 function destroyWidgets(vNode, patch, index) {
16672     if (isWidget(vNode)) {
16673         if (typeof vNode.destroy === "function") {
16674             patch[index] = appendPatch(
16675                 patch[index],
16676                 new VPatch(VPatch.REMOVE, vNode, null)
16677             )
16678         }
16679     } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
16680         var children = vNode.children
16681         var len = children.length
16682         for (var i = 0; i < len; i++) {
16683             var child = children[i]
16684             index += 1
16685
16686             destroyWidgets(child, patch, index)
16687
16688             if (isVNode(child) && child.count) {
16689                 index += child.count
16690             }
16691         }
16692     } else if (isThunk(vNode)) {
16693         thunks(vNode, null, patch, index)
16694     }
16695 }
16696
16697 // Create a sub-patch for thunks
16698 function thunks(a, b, patch, index) {
16699     var nodes = handleThunk(a, b)
16700     var thunkPatch = diff(nodes.a, nodes.b)
16701     if (hasPatches(thunkPatch)) {
16702         patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
16703     }
16704 }
16705
16706 function hasPatches(patch) {
16707     for (var index in patch) {
16708         if (index !== "a") {
16709             return true
16710         }
16711     }
16712
16713     return false
16714 }
16715
16716 // Execute hooks when two nodes are identical
16717 function unhook(vNode, patch, index) {
16718     if (isVNode(vNode)) {
16719         if (vNode.hooks) {
16720             patch[index] = appendPatch(
16721                 patch[index],
16722                 new VPatch(
16723                     VPatch.PROPS,
16724                     vNode,
16725                     undefinedKeys(vNode.hooks)
16726                 )
16727             )
16728         }
16729
16730         if (vNode.descendantHooks || vNode.hasThunks) {
16731             var children = vNode.children
16732             var len = children.length
16733             for (var i = 0; i < len; i++) {
16734                 var child = children[i]
16735                 index += 1
16736
16737                 unhook(child, patch, index)
16738
16739                 if (isVNode(child) && child.count) {
16740                     index += child.count
16741                 }
16742             }
16743         }
16744     } else if (isThunk(vNode)) {
16745         thunks(vNode, null, patch, index)
16746     }
16747 }
16748
16749 function undefinedKeys(obj) {
16750     var result = {}
16751
16752     for (var key in obj) {
16753         result[key] = undefined
16754     }
16755
16756     return result
16757 }
16758
16759 // List diff, naive left to right reordering
16760 function reorder(aChildren, bChildren) {
16761     // O(M) time, O(M) memory
16762     var bChildIndex = keyIndex(bChildren)
16763     var bKeys = bChildIndex.keys
16764     var bFree = bChildIndex.free
16765
16766     if (bFree.length === bChildren.length) {
16767         return {
16768             children: bChildren,
16769             moves: null
16770         }
16771     }
16772
16773     // O(N) time, O(N) memory
16774     var aChildIndex = keyIndex(aChildren)
16775     var aKeys = aChildIndex.keys
16776     var aFree = aChildIndex.free
16777
16778     if (aFree.length === aChildren.length) {
16779         return {
16780             children: bChildren,
16781             moves: null
16782         }
16783     }
16784
16785     // O(MAX(N, M)) memory
16786     var newChildren = []
16787
16788     var freeIndex = 0
16789     var freeCount = bFree.length
16790     var deletedItems = 0
16791
16792     // Iterate through a and match a node in b
16793     // O(N) time,
16794     for (var i = 0 ; i < aChildren.length; i++) {
16795         var aItem = aChildren[i]
16796         var itemIndex
16797
16798         if (aItem.key) {
16799             if (bKeys.hasOwnProperty(aItem.key)) {
16800                 // Match up the old keys
16801                 itemIndex = bKeys[aItem.key]
16802                 newChildren.push(bChildren[itemIndex])
16803
16804             } else {
16805                 // Remove old keyed items
16806                 itemIndex = i - deletedItems++
16807                 newChildren.push(null)
16808             }
16809         } else {
16810             // Match the item in a with the next free item in b
16811             if (freeIndex < freeCount) {
16812                 itemIndex = bFree[freeIndex++]
16813                 newChildren.push(bChildren[itemIndex])
16814             } else {
16815                 // There are no free items in b to match with
16816                 // the free items in a, so the extra free nodes
16817                 // are deleted.
16818                 itemIndex = i - deletedItems++
16819                 newChildren.push(null)
16820             }
16821         }
16822     }
16823
16824     var lastFreeIndex = freeIndex >= bFree.length ?
16825         bChildren.length :
16826         bFree[freeIndex]
16827
16828     // Iterate through b and append any new keys
16829     // O(M) time
16830     for (var j = 0; j < bChildren.length; j++) {
16831         var newItem = bChildren[j]
16832
16833         if (newItem.key) {
16834             if (!aKeys.hasOwnProperty(newItem.key)) {
16835                 // Add any new keyed items
16836                 // We are adding new items to the end and then sorting them
16837                 // in place. In future we should insert new items in place.
16838                 newChildren.push(newItem)
16839             }
16840         } else if (j >= lastFreeIndex) {
16841             // Add any leftover non-keyed items
16842             newChildren.push(newItem)
16843         }
16844     }
16845
16846     var simulate = newChildren.slice()
16847     var simulateIndex = 0
16848     var removes = []
16849     var inserts = []
16850     var simulateItem
16851
16852     for (var k = 0; k < bChildren.length;) {
16853         var wantedItem = bChildren[k]
16854         simulateItem = simulate[simulateIndex]
16855
16856         // remove items
16857         while (simulateItem === null && simulate.length) {
16858             removes.push(remove(simulate, simulateIndex, null))
16859             simulateItem = simulate[simulateIndex]
16860         }
16861
16862         if (!simulateItem || simulateItem.key !== wantedItem.key) {
16863             // if we need a key in this position...
16864             if (wantedItem.key) {
16865                 if (simulateItem && simulateItem.key) {
16866                     // if an insert doesn't put this key in place, it needs to move
16867                     if (bKeys[simulateItem.key] !== k + 1) {
16868                         removes.push(remove(simulate, simulateIndex, simulateItem.key))
16869                         simulateItem = simulate[simulateIndex]
16870                         // if the remove didn't put the wanted item in place, we need to insert it
16871                         if (!simulateItem || simulateItem.key !== wantedItem.key) {
16872                             inserts.push({key: wantedItem.key, to: k})
16873                         }
16874                         // items are matching, so skip ahead
16875                         else {
16876                             simulateIndex++
16877                         }
16878                     }
16879                     else {
16880                         inserts.push({key: wantedItem.key, to: k})
16881                     }
16882                 }
16883                 else {
16884                     inserts.push({key: wantedItem.key, to: k})
16885                 }
16886                 k++
16887             }
16888             // a key in simulate has no matching wanted key, remove it
16889             else if (simulateItem && simulateItem.key) {
16890                 removes.push(remove(simulate, simulateIndex, simulateItem.key))
16891             }
16892         }
16893         else {
16894             simulateIndex++
16895             k++
16896         }
16897     }
16898
16899     // remove all the remaining nodes from simulate
16900     while(simulateIndex < simulate.length) {
16901         simulateItem = simulate[simulateIndex]
16902         removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
16903     }
16904
16905     // If the only moves we have are deletes then we can just
16906     // let the delete patch remove these items.
16907     if (removes.length === deletedItems && !inserts.length) {
16908         return {
16909             children: newChildren,
16910             moves: null
16911         }
16912     }
16913
16914     return {
16915         children: newChildren,
16916         moves: {
16917             removes: removes,
16918             inserts: inserts
16919         }
16920     }
16921 }
16922
16923 function remove(arr, index, key) {
16924     arr.splice(index, 1)
16925
16926     return {
16927         from: index,
16928         key: key
16929     }
16930 }
16931
16932 function keyIndex(children) {
16933     var keys = {}
16934     var free = []
16935     var length = children.length
16936
16937     for (var i = 0; i < length; i++) {
16938         var child = children[i]
16939
16940         if (child.key) {
16941             keys[child.key] = i
16942         } else {
16943             free.push(i)
16944         }
16945     }
16946
16947     return {
16948         keys: keys,     // A hash of key name to index
16949         free: free      // An array of unkeyed item indices
16950     }
16951 }
16952
16953 function appendPatch(apply, patch) {
16954     if (apply) {
16955         if (isArray(apply)) {
16956             apply.push(patch)
16957         } else {
16958             apply = [apply, patch]
16959         }
16960
16961         return apply
16962     } else {
16963         return patch
16964     }
16965 }
16966
16967 },{"../vnode/handle-thunk":192,"../vnode/is-thunk":193,"../vnode/is-vnode":195,"../vnode/is-vtext":196,"../vnode/is-widget":197,"../vnode/vpatch":200,"./diff-props":202,"x-is-array":222}],204:[function(require,module,exports){
16968 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16969 /** @author Brian Cavalier */
16970 /** @author John Hann */
16971
16972 (function(define) { 'use strict';
16973 define(function (require) {
16974
16975         var makePromise = require('./makePromise');
16976         var Scheduler = require('./Scheduler');
16977         var async = require('./env').asap;
16978
16979         return makePromise({
16980                 scheduler: new Scheduler(async)
16981         });
16982
16983 });
16984 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
16985
16986 },{"./Scheduler":205,"./env":217,"./makePromise":219}],205:[function(require,module,exports){
16987 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16988 /** @author Brian Cavalier */
16989 /** @author John Hann */
16990
16991 (function(define) { 'use strict';
16992 define(function() {
16993
16994         // Credit to Twisol (https://github.com/Twisol) for suggesting
16995         // this type of extensible queue + trampoline approach for next-tick conflation.
16996
16997         /**
16998          * Async task scheduler
16999          * @param {function} async function to schedule a single async function
17000          * @constructor
17001          */
17002         function Scheduler(async) {
17003                 this._async = async;
17004                 this._running = false;
17005
17006                 this._queue = this;
17007                 this._queueLen = 0;
17008                 this._afterQueue = {};
17009                 this._afterQueueLen = 0;
17010
17011                 var self = this;
17012                 this.drain = function() {
17013                         self._drain();
17014                 };
17015         }
17016
17017         /**
17018          * Enqueue a task
17019          * @param {{ run:function }} task
17020          */
17021         Scheduler.prototype.enqueue = function(task) {
17022                 this._queue[this._queueLen++] = task;
17023                 this.run();
17024         };
17025
17026         /**
17027          * Enqueue a task to run after the main task queue
17028          * @param {{ run:function }} task
17029          */
17030         Scheduler.prototype.afterQueue = function(task) {
17031                 this._afterQueue[this._afterQueueLen++] = task;
17032                 this.run();
17033         };
17034
17035         Scheduler.prototype.run = function() {
17036                 if (!this._running) {
17037                         this._running = true;
17038                         this._async(this.drain);
17039                 }
17040         };
17041
17042         /**
17043          * Drain the handler queue entirely, and then the after queue
17044          */
17045         Scheduler.prototype._drain = function() {
17046                 var i = 0;
17047                 for (; i < this._queueLen; ++i) {
17048                         this._queue[i].run();
17049                         this._queue[i] = void 0;
17050                 }
17051
17052                 this._queueLen = 0;
17053                 this._running = false;
17054
17055                 for (i = 0; i < this._afterQueueLen; ++i) {
17056                         this._afterQueue[i].run();
17057                         this._afterQueue[i] = void 0;
17058                 }
17059
17060                 this._afterQueueLen = 0;
17061         };
17062
17063         return Scheduler;
17064
17065 });
17066 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17067
17068 },{}],206:[function(require,module,exports){
17069 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17070 /** @author Brian Cavalier */
17071 /** @author John Hann */
17072
17073 (function(define) { 'use strict';
17074 define(function() {
17075
17076         /**
17077          * Custom error type for promises rejected by promise.timeout
17078          * @param {string} message
17079          * @constructor
17080          */
17081         function TimeoutError (message) {
17082                 Error.call(this);
17083                 this.message = message;
17084                 this.name = TimeoutError.name;
17085                 if (typeof Error.captureStackTrace === 'function') {
17086                         Error.captureStackTrace(this, TimeoutError);
17087                 }
17088         }
17089
17090         TimeoutError.prototype = Object.create(Error.prototype);
17091         TimeoutError.prototype.constructor = TimeoutError;
17092
17093         return TimeoutError;
17094 });
17095 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17096 },{}],207:[function(require,module,exports){
17097 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17098 /** @author Brian Cavalier */
17099 /** @author John Hann */
17100
17101 (function(define) { 'use strict';
17102 define(function() {
17103
17104         makeApply.tryCatchResolve = tryCatchResolve;
17105
17106         return makeApply;
17107
17108         function makeApply(Promise, call) {
17109                 if(arguments.length < 2) {
17110                         call = tryCatchResolve;
17111                 }
17112
17113                 return apply;
17114
17115                 function apply(f, thisArg, args) {
17116                         var p = Promise._defer();
17117                         var l = args.length;
17118                         var params = new Array(l);
17119                         callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
17120
17121                         return p;
17122                 }
17123
17124                 function callAndResolve(c, h) {
17125                         if(c.i < 0) {
17126                                 return call(c.f, c.thisArg, c.params, h);
17127                         }
17128
17129                         var handler = Promise._handler(c.args[c.i]);
17130                         handler.fold(callAndResolveNext, c, void 0, h);
17131                 }
17132
17133                 function callAndResolveNext(c, x, h) {
17134                         c.params[c.i] = x;
17135                         c.i -= 1;
17136                         callAndResolve(c, h);
17137                 }
17138         }
17139
17140         function tryCatchResolve(f, thisArg, args, resolver) {
17141                 try {
17142                         resolver.resolve(f.apply(thisArg, args));
17143                 } catch(e) {
17144                         resolver.reject(e);
17145                 }
17146         }
17147
17148 });
17149 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17150
17151
17152
17153 },{}],208:[function(require,module,exports){
17154 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17155 /** @author Brian Cavalier */
17156 /** @author John Hann */
17157
17158 (function(define) { 'use strict';
17159 define(function(require) {
17160
17161         var state = require('../state');
17162         var applier = require('../apply');
17163
17164         return function array(Promise) {
17165
17166                 var applyFold = applier(Promise);
17167                 var toPromise = Promise.resolve;
17168                 var all = Promise.all;
17169
17170                 var ar = Array.prototype.reduce;
17171                 var arr = Array.prototype.reduceRight;
17172                 var slice = Array.prototype.slice;
17173
17174                 // Additional array combinators
17175
17176                 Promise.any = any;
17177                 Promise.some = some;
17178                 Promise.settle = settle;
17179
17180                 Promise.map = map;
17181                 Promise.filter = filter;
17182                 Promise.reduce = reduce;
17183                 Promise.reduceRight = reduceRight;
17184
17185                 /**
17186                  * When this promise fulfills with an array, do
17187                  * onFulfilled.apply(void 0, array)
17188                  * @param {function} onFulfilled function to apply
17189                  * @returns {Promise} promise for the result of applying onFulfilled
17190                  */
17191                 Promise.prototype.spread = function(onFulfilled) {
17192                         return this.then(all).then(function(array) {
17193                                 return onFulfilled.apply(this, array);
17194                         });
17195                 };
17196
17197                 return Promise;
17198
17199                 /**
17200                  * One-winner competitive race.
17201                  * Return a promise that will fulfill when one of the promises
17202                  * in the input array fulfills, or will reject when all promises
17203                  * have rejected.
17204                  * @param {array} promises
17205                  * @returns {Promise} promise for the first fulfilled value
17206                  */
17207                 function any(promises) {
17208                         var p = Promise._defer();
17209                         var resolver = p._handler;
17210                         var l = promises.length>>>0;
17211
17212                         var pending = l;
17213                         var errors = [];
17214
17215                         for (var h, x, i = 0; i < l; ++i) {
17216                                 x = promises[i];
17217                                 if(x === void 0 && !(i in promises)) {
17218                                         --pending;
17219                                         continue;
17220                                 }
17221
17222                                 h = Promise._handler(x);
17223                                 if(h.state() > 0) {
17224                                         resolver.become(h);
17225                                         Promise._visitRemaining(promises, i, h);
17226                                         break;
17227                                 } else {
17228                                         h.visit(resolver, handleFulfill, handleReject);
17229                                 }
17230                         }
17231
17232                         if(pending === 0) {
17233                                 resolver.reject(new RangeError('any(): array must not be empty'));
17234                         }
17235
17236                         return p;
17237
17238                         function handleFulfill(x) {
17239                                 /*jshint validthis:true*/
17240                                 errors = null;
17241                                 this.resolve(x); // this === resolver
17242                         }
17243
17244                         function handleReject(e) {
17245                                 /*jshint validthis:true*/
17246                                 if(this.resolved) { // this === resolver
17247                                         return;
17248                                 }
17249
17250                                 errors.push(e);
17251                                 if(--pending === 0) {
17252                                         this.reject(errors);
17253                                 }
17254                         }
17255                 }
17256
17257                 /**
17258                  * N-winner competitive race
17259                  * Return a promise that will fulfill when n input promises have
17260                  * fulfilled, or will reject when it becomes impossible for n
17261                  * input promises to fulfill (ie when promises.length - n + 1
17262                  * have rejected)
17263                  * @param {array} promises
17264                  * @param {number} n
17265                  * @returns {Promise} promise for the earliest n fulfillment values
17266                  *
17267                  * @deprecated
17268                  */
17269                 function some(promises, n) {
17270                         /*jshint maxcomplexity:7*/
17271                         var p = Promise._defer();
17272                         var resolver = p._handler;
17273
17274                         var results = [];
17275                         var errors = [];
17276
17277                         var l = promises.length>>>0;
17278                         var nFulfill = 0;
17279                         var nReject;
17280                         var x, i; // reused in both for() loops
17281
17282                         // First pass: count actual array items
17283                         for(i=0; i<l; ++i) {
17284                                 x = promises[i];
17285                                 if(x === void 0 && !(i in promises)) {
17286                                         continue;
17287                                 }
17288                                 ++nFulfill;
17289                         }
17290
17291                         // Compute actual goals
17292                         n = Math.max(n, 0);
17293                         nReject = (nFulfill - n + 1);
17294                         nFulfill = Math.min(n, nFulfill);
17295
17296                         if(n > nFulfill) {
17297                                 resolver.reject(new RangeError('some(): array must contain at least '
17298                                 + n + ' item(s), but had ' + nFulfill));
17299                         } else if(nFulfill === 0) {
17300                                 resolver.resolve(results);
17301                         }
17302
17303                         // Second pass: observe each array item, make progress toward goals
17304                         for(i=0; i<l; ++i) {
17305                                 x = promises[i];
17306                                 if(x === void 0 && !(i in promises)) {
17307                                         continue;
17308                                 }
17309
17310                                 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
17311                         }
17312
17313                         return p;
17314
17315                         function fulfill(x) {
17316                                 /*jshint validthis:true*/
17317                                 if(this.resolved) { // this === resolver
17318                                         return;
17319                                 }
17320
17321                                 results.push(x);
17322                                 if(--nFulfill === 0) {
17323                                         errors = null;
17324                                         this.resolve(results);
17325                                 }
17326                         }
17327
17328                         function reject(e) {
17329                                 /*jshint validthis:true*/
17330                                 if(this.resolved) { // this === resolver
17331                                         return;
17332                                 }
17333
17334                                 errors.push(e);
17335                                 if(--nReject === 0) {
17336                                         results = null;
17337                                         this.reject(errors);
17338                                 }
17339                         }
17340                 }
17341
17342                 /**
17343                  * Apply f to the value of each promise in a list of promises
17344                  * and return a new list containing the results.
17345                  * @param {array} promises
17346                  * @param {function(x:*, index:Number):*} f mapping function
17347                  * @returns {Promise}
17348                  */
17349                 function map(promises, f) {
17350                         return Promise._traverse(f, promises);
17351                 }
17352
17353                 /**
17354                  * Filter the provided array of promises using the provided predicate.  Input may
17355                  * contain promises and values
17356                  * @param {Array} promises array of promises and values
17357                  * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
17358                  *  Must return truthy (or promise for truthy) for items to retain.
17359                  * @returns {Promise} promise that will fulfill with an array containing all items
17360                  *  for which predicate returned truthy.
17361                  */
17362                 function filter(promises, predicate) {
17363                         var a = slice.call(promises);
17364                         return Promise._traverse(predicate, a).then(function(keep) {
17365                                 return filterSync(a, keep);
17366                         });
17367                 }
17368
17369                 function filterSync(promises, keep) {
17370                         // Safe because we know all promises have fulfilled if we've made it this far
17371                         var l = keep.length;
17372                         var filtered = new Array(l);
17373                         for(var i=0, j=0; i<l; ++i) {
17374                                 if(keep[i]) {
17375                                         filtered[j++] = Promise._handler(promises[i]).value;
17376                                 }
17377                         }
17378                         filtered.length = j;
17379                         return filtered;
17380
17381                 }
17382
17383                 /**
17384                  * Return a promise that will always fulfill with an array containing
17385                  * the outcome states of all input promises.  The returned promise
17386                  * will never reject.
17387                  * @param {Array} promises
17388                  * @returns {Promise} promise for array of settled state descriptors
17389                  */
17390                 function settle(promises) {
17391                         return all(promises.map(settleOne));
17392                 }
17393
17394                 function settleOne(p) {
17395                         // Optimize the case where we get an already-resolved when.js promise
17396                         //  by extracting its state:
17397                         var handler;
17398                         if (p instanceof Promise) {
17399                                 // This is our own Promise type and we can reach its handler internals:
17400                                 handler = p._handler.join();
17401                         }
17402                         if((handler && handler.state() === 0) || !handler) {
17403                                 // Either still pending, or not a Promise at all:
17404                                 return toPromise(p).then(state.fulfilled, state.rejected);
17405                         }
17406
17407                         // The promise is our own, but it is already resolved. Take a shortcut.
17408                         // Since we're not actually handling the resolution, we need to disable
17409                         // rejection reporting.
17410                         handler._unreport();
17411                         return state.inspect(handler);
17412                 }
17413
17414                 /**
17415                  * Traditional reduce function, similar to `Array.prototype.reduce()`, but
17416                  * input may contain promises and/or values, and reduceFunc
17417                  * may return either a value or a promise, *and* initialValue may
17418                  * be a promise for the starting value.
17419                  * @param {Array|Promise} promises array or promise for an array of anything,
17420                  *      may contain a mix of promises and values.
17421                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
17422                  * @returns {Promise} that will resolve to the final reduced value
17423                  */
17424                 function reduce(promises, f /*, initialValue */) {
17425                         return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
17426                                         : ar.call(promises, liftCombine(f));
17427                 }
17428
17429                 /**
17430                  * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
17431                  * input may contain promises and/or values, and reduceFunc
17432                  * may return either a value or a promise, *and* initialValue may
17433                  * be a promise for the starting value.
17434                  * @param {Array|Promise} promises array or promise for an array of anything,
17435                  *      may contain a mix of promises and values.
17436                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
17437                  * @returns {Promise} that will resolve to the final reduced value
17438                  */
17439                 function reduceRight(promises, f /*, initialValue */) {
17440                         return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
17441                                         : arr.call(promises, liftCombine(f));
17442                 }
17443
17444                 function liftCombine(f) {
17445                         return function(z, x, i) {
17446                                 return applyFold(f, void 0, [z,x,i]);
17447                         };
17448                 }
17449         };
17450
17451 });
17452 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17453
17454 },{"../apply":207,"../state":220}],209:[function(require,module,exports){
17455 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17456 /** @author Brian Cavalier */
17457 /** @author John Hann */
17458
17459 (function(define) { 'use strict';
17460 define(function() {
17461
17462         return function flow(Promise) {
17463
17464                 var resolve = Promise.resolve;
17465                 var reject = Promise.reject;
17466                 var origCatch = Promise.prototype['catch'];
17467
17468                 /**
17469                  * Handle the ultimate fulfillment value or rejection reason, and assume
17470                  * responsibility for all errors.  If an error propagates out of result
17471                  * or handleFatalError, it will be rethrown to the host, resulting in a
17472                  * loud stack track on most platforms and a crash on some.
17473                  * @param {function?} onResult
17474                  * @param {function?} onError
17475                  * @returns {undefined}
17476                  */
17477                 Promise.prototype.done = function(onResult, onError) {
17478                         this._handler.visit(this._handler.receiver, onResult, onError);
17479                 };
17480
17481                 /**
17482                  * Add Error-type and predicate matching to catch.  Examples:
17483                  * promise.catch(TypeError, handleTypeError)
17484                  *   .catch(predicate, handleMatchedErrors)
17485                  *   .catch(handleRemainingErrors)
17486                  * @param onRejected
17487                  * @returns {*}
17488                  */
17489                 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
17490                         if (arguments.length < 2) {
17491                                 return origCatch.call(this, onRejected);
17492                         }
17493
17494                         if(typeof onRejected !== 'function') {
17495                                 return this.ensure(rejectInvalidPredicate);
17496                         }
17497
17498                         return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
17499                 };
17500
17501                 /**
17502                  * Wraps the provided catch handler, so that it will only be called
17503                  * if the predicate evaluates truthy
17504                  * @param {?function} handler
17505                  * @param {function} predicate
17506                  * @returns {function} conditional catch handler
17507                  */
17508                 function createCatchFilter(handler, predicate) {
17509                         return function(e) {
17510                                 return evaluatePredicate(e, predicate)
17511                                         ? handler.call(this, e)
17512                                         : reject(e);
17513                         };
17514                 }
17515
17516                 /**
17517                  * Ensures that onFulfilledOrRejected will be called regardless of whether
17518                  * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
17519                  * receive the promises' value or reason.  Any returned value will be disregarded.
17520                  * onFulfilledOrRejected may throw or return a rejected promise to signal
17521                  * an additional error.
17522                  * @param {function} handler handler to be called regardless of
17523                  *  fulfillment or rejection
17524                  * @returns {Promise}
17525                  */
17526                 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
17527                         if(typeof handler !== 'function') {
17528                                 return this;
17529                         }
17530
17531                         return this.then(function(x) {
17532                                 return runSideEffect(handler, this, identity, x);
17533                         }, function(e) {
17534                                 return runSideEffect(handler, this, reject, e);
17535                         });
17536                 };
17537
17538                 function runSideEffect (handler, thisArg, propagate, value) {
17539                         var result = handler.call(thisArg);
17540                         return maybeThenable(result)
17541                                 ? propagateValue(result, propagate, value)
17542                                 : propagate(value);
17543                 }
17544
17545                 function propagateValue (result, propagate, x) {
17546                         return resolve(result).then(function () {
17547                                 return propagate(x);
17548                         });
17549                 }
17550
17551                 /**
17552                  * Recover from a failure by returning a defaultValue.  If defaultValue
17553                  * is a promise, it's fulfillment value will be used.  If defaultValue is
17554                  * a promise that rejects, the returned promise will reject with the
17555                  * same reason.
17556                  * @param {*} defaultValue
17557                  * @returns {Promise} new promise
17558                  */
17559                 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
17560                         return this.then(void 0, function() {
17561                                 return defaultValue;
17562                         });
17563                 };
17564
17565                 /**
17566                  * Shortcut for .then(function() { return value; })
17567                  * @param  {*} value
17568                  * @return {Promise} a promise that:
17569                  *  - is fulfilled if value is not a promise, or
17570                  *  - if value is a promise, will fulfill with its value, or reject
17571                  *    with its reason.
17572                  */
17573                 Promise.prototype['yield'] = function(value) {
17574                         return this.then(function() {
17575                                 return value;
17576                         });
17577                 };
17578
17579                 /**
17580                  * Runs a side effect when this promise fulfills, without changing the
17581                  * fulfillment value.
17582                  * @param {function} onFulfilledSideEffect
17583                  * @returns {Promise}
17584                  */
17585                 Promise.prototype.tap = function(onFulfilledSideEffect) {
17586                         return this.then(onFulfilledSideEffect)['yield'](this);
17587                 };
17588
17589                 return Promise;
17590         };
17591
17592         function rejectInvalidPredicate() {
17593                 throw new TypeError('catch predicate must be a function');
17594         }
17595
17596         function evaluatePredicate(e, predicate) {
17597                 return isError(predicate) ? e instanceof predicate : predicate(e);
17598         }
17599
17600         function isError(predicate) {
17601                 return predicate === Error
17602                         || (predicate != null && predicate.prototype instanceof Error);
17603         }
17604
17605         function maybeThenable(x) {
17606                 return (typeof x === 'object' || typeof x === 'function') && x !== null;
17607         }
17608
17609         function identity(x) {
17610                 return x;
17611         }
17612
17613 });
17614 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17615
17616 },{}],210:[function(require,module,exports){
17617 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17618 /** @author Brian Cavalier */
17619 /** @author John Hann */
17620 /** @author Jeff Escalante */
17621
17622 (function(define) { 'use strict';
17623 define(function() {
17624
17625         return function fold(Promise) {
17626
17627                 Promise.prototype.fold = function(f, z) {
17628                         var promise = this._beget();
17629
17630                         this._handler.fold(function(z, x, to) {
17631                                 Promise._handler(z).fold(function(x, z, to) {
17632                                         to.resolve(f.call(this, z, x));
17633                                 }, x, this, to);
17634                         }, z, promise._handler.receiver, promise._handler);
17635
17636                         return promise;
17637                 };
17638
17639                 return Promise;
17640         };
17641
17642 });
17643 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17644
17645 },{}],211:[function(require,module,exports){
17646 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17647 /** @author Brian Cavalier */
17648 /** @author John Hann */
17649
17650 (function(define) { 'use strict';
17651 define(function(require) {
17652
17653         var inspect = require('../state').inspect;
17654
17655         return function inspection(Promise) {
17656
17657                 Promise.prototype.inspect = function() {
17658                         return inspect(Promise._handler(this));
17659                 };
17660
17661                 return Promise;
17662         };
17663
17664 });
17665 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17666
17667 },{"../state":220}],212:[function(require,module,exports){
17668 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17669 /** @author Brian Cavalier */
17670 /** @author John Hann */
17671
17672 (function(define) { 'use strict';
17673 define(function() {
17674
17675         return function generate(Promise) {
17676
17677                 var resolve = Promise.resolve;
17678
17679                 Promise.iterate = iterate;
17680                 Promise.unfold = unfold;
17681
17682                 return Promise;
17683
17684                 /**
17685                  * @deprecated Use github.com/cujojs/most streams and most.iterate
17686                  * Generate a (potentially infinite) stream of promised values:
17687                  * x, f(x), f(f(x)), etc. until condition(x) returns true
17688                  * @param {function} f function to generate a new x from the previous x
17689                  * @param {function} condition function that, given the current x, returns
17690                  *  truthy when the iterate should stop
17691                  * @param {function} handler function to handle the value produced by f
17692                  * @param {*|Promise} x starting value, may be a promise
17693                  * @return {Promise} the result of the last call to f before
17694                  *  condition returns true
17695                  */
17696                 function iterate(f, condition, handler, x) {
17697                         return unfold(function(x) {
17698                                 return [x, f(x)];
17699                         }, condition, handler, x);
17700                 }
17701
17702                 /**
17703                  * @deprecated Use github.com/cujojs/most streams and most.unfold
17704                  * Generate a (potentially infinite) stream of promised values
17705                  * by applying handler(generator(seed)) iteratively until
17706                  * condition(seed) returns true.
17707                  * @param {function} unspool function that generates a [value, newSeed]
17708                  *  given a seed.
17709                  * @param {function} condition function that, given the current seed, returns
17710                  *  truthy when the unfold should stop
17711                  * @param {function} handler function to handle the value produced by unspool
17712                  * @param x {*|Promise} starting value, may be a promise
17713                  * @return {Promise} the result of the last value produced by unspool before
17714                  *  condition returns true
17715                  */
17716                 function unfold(unspool, condition, handler, x) {
17717                         return resolve(x).then(function(seed) {
17718                                 return resolve(condition(seed)).then(function(done) {
17719                                         return done ? seed : resolve(unspool(seed)).spread(next);
17720                                 });
17721                         });
17722
17723                         function next(item, newSeed) {
17724                                 return resolve(handler(item)).then(function() {
17725                                         return unfold(unspool, condition, handler, newSeed);
17726                                 });
17727                         }
17728                 }
17729         };
17730
17731 });
17732 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17733
17734 },{}],213:[function(require,module,exports){
17735 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17736 /** @author Brian Cavalier */
17737 /** @author John Hann */
17738
17739 (function(define) { 'use strict';
17740 define(function() {
17741
17742         return function progress(Promise) {
17743
17744                 /**
17745                  * @deprecated
17746                  * Register a progress handler for this promise
17747                  * @param {function} onProgress
17748                  * @returns {Promise}
17749                  */
17750                 Promise.prototype.progress = function(onProgress) {
17751                         return this.then(void 0, void 0, onProgress);
17752                 };
17753
17754                 return Promise;
17755         };
17756
17757 });
17758 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17759
17760 },{}],214:[function(require,module,exports){
17761 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17762 /** @author Brian Cavalier */
17763 /** @author John Hann */
17764
17765 (function(define) { 'use strict';
17766 define(function(require) {
17767
17768         var env = require('../env');
17769         var TimeoutError = require('../TimeoutError');
17770
17771         function setTimeout(f, ms, x, y) {
17772                 return env.setTimer(function() {
17773                         f(x, y, ms);
17774                 }, ms);
17775         }
17776
17777         return function timed(Promise) {
17778                 /**
17779                  * Return a new promise whose fulfillment value is revealed only
17780                  * after ms milliseconds
17781                  * @param {number} ms milliseconds
17782                  * @returns {Promise}
17783                  */
17784                 Promise.prototype.delay = function(ms) {
17785                         var p = this._beget();
17786                         this._handler.fold(handleDelay, ms, void 0, p._handler);
17787                         return p;
17788                 };
17789
17790                 function handleDelay(ms, x, h) {
17791                         setTimeout(resolveDelay, ms, x, h);
17792                 }
17793
17794                 function resolveDelay(x, h) {
17795                         h.resolve(x);
17796                 }
17797
17798                 /**
17799                  * Return a new promise that rejects after ms milliseconds unless
17800                  * this promise fulfills earlier, in which case the returned promise
17801                  * fulfills with the same value.
17802                  * @param {number} ms milliseconds
17803                  * @param {Error|*=} reason optional rejection reason to use, defaults
17804                  *   to a TimeoutError if not provided
17805                  * @returns {Promise}
17806                  */
17807                 Promise.prototype.timeout = function(ms, reason) {
17808                         var p = this._beget();
17809                         var h = p._handler;
17810
17811                         var t = setTimeout(onTimeout, ms, reason, p._handler);
17812
17813                         this._handler.visit(h,
17814                                 function onFulfill(x) {
17815                                         env.clearTimer(t);
17816                                         this.resolve(x); // this = h
17817                                 },
17818                                 function onReject(x) {
17819                                         env.clearTimer(t);
17820                                         this.reject(x); // this = h
17821                                 },
17822                                 h.notify);
17823
17824                         return p;
17825                 };
17826
17827                 function onTimeout(reason, h, ms) {
17828                         var e = typeof reason === 'undefined'
17829                                 ? new TimeoutError('timed out after ' + ms + 'ms')
17830                                 : reason;
17831                         h.reject(e);
17832                 }
17833
17834                 return Promise;
17835         };
17836
17837 });
17838 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17839
17840 },{"../TimeoutError":206,"../env":217}],215:[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(require) {
17847
17848         var setTimer = require('../env').setTimer;
17849         var format = require('../format');
17850
17851         return function unhandledRejection(Promise) {
17852
17853                 var logError = noop;
17854                 var logInfo = noop;
17855                 var localConsole;
17856
17857                 if(typeof console !== 'undefined') {
17858                         // Alias console to prevent things like uglify's drop_console option from
17859                         // removing console.log/error. Unhandled rejections fall into the same
17860                         // category as uncaught exceptions, and build tools shouldn't silence them.
17861                         localConsole = console;
17862                         logError = typeof localConsole.error !== 'undefined'
17863                                 ? function (e) { localConsole.error(e); }
17864                                 : function (e) { localConsole.log(e); };
17865
17866                         logInfo = typeof localConsole.info !== 'undefined'
17867                                 ? function (e) { localConsole.info(e); }
17868                                 : function (e) { localConsole.log(e); };
17869                 }
17870
17871                 Promise.onPotentiallyUnhandledRejection = function(rejection) {
17872                         enqueue(report, rejection);
17873                 };
17874
17875                 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
17876                         enqueue(unreport, rejection);
17877                 };
17878
17879                 Promise.onFatalRejection = function(rejection) {
17880                         enqueue(throwit, rejection.value);
17881                 };
17882
17883                 var tasks = [];
17884                 var reported = [];
17885                 var running = null;
17886
17887                 function report(r) {
17888                         if(!r.handled) {
17889                                 reported.push(r);
17890                                 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
17891                         }
17892                 }
17893
17894                 function unreport(r) {
17895                         var i = reported.indexOf(r);
17896                         if(i >= 0) {
17897                                 reported.splice(i, 1);
17898                                 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
17899                         }
17900                 }
17901
17902                 function enqueue(f, x) {
17903                         tasks.push(f, x);
17904                         if(running === null) {
17905                                 running = setTimer(flush, 0);
17906                         }
17907                 }
17908
17909                 function flush() {
17910                         running = null;
17911                         while(tasks.length > 0) {
17912                                 tasks.shift()(tasks.shift());
17913                         }
17914                 }
17915
17916                 return Promise;
17917         };
17918
17919         function throwit(e) {
17920                 throw e;
17921         }
17922
17923         function noop() {}
17924
17925 });
17926 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17927
17928 },{"../env":217,"../format":218}],216:[function(require,module,exports){
17929 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17930 /** @author Brian Cavalier */
17931 /** @author John Hann */
17932
17933 (function(define) { 'use strict';
17934 define(function() {
17935
17936         return function addWith(Promise) {
17937                 /**
17938                  * Returns a promise whose handlers will be called with `this` set to
17939                  * the supplied receiver.  Subsequent promises derived from the
17940                  * returned promise will also have their handlers called with receiver
17941                  * as `this`. Calling `with` with undefined or no arguments will return
17942                  * a promise whose handlers will again be called in the usual Promises/A+
17943                  * way (no `this`) thus safely undoing any previous `with` in the
17944                  * promise chain.
17945                  *
17946                  * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
17947                  * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
17948                  *
17949                  * @param {object} receiver `this` value for all handlers attached to
17950                  *  the returned promise.
17951                  * @returns {Promise}
17952                  */
17953                 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
17954                         var p = this._beget();
17955                         var child = p._handler;
17956                         child.receiver = receiver;
17957                         this._handler.chain(child, receiver);
17958                         return p;
17959                 };
17960
17961                 return Promise;
17962         };
17963
17964 });
17965 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17966
17967
17968 },{}],217:[function(require,module,exports){
17969 (function (process){
17970 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17971 /** @author Brian Cavalier */
17972 /** @author John Hann */
17973
17974 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
17975 (function(define) { 'use strict';
17976 define(function(require) {
17977         /*jshint maxcomplexity:6*/
17978
17979         // Sniff "best" async scheduling option
17980         // Prefer process.nextTick or MutationObserver, then check for
17981         // setTimeout, and finally vertx, since its the only env that doesn't
17982         // have setTimeout
17983
17984         var MutationObs;
17985         var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
17986
17987         // Default env
17988         var setTimer = function(f, ms) { return setTimeout(f, ms); };
17989         var clearTimer = function(t) { return clearTimeout(t); };
17990         var asap = function (f) { return capturedSetTimeout(f, 0); };
17991
17992         // Detect specific env
17993         if (isNode()) { // Node
17994                 asap = function (f) { return process.nextTick(f); };
17995
17996         } else if (MutationObs = hasMutationObserver()) { // Modern browser
17997                 asap = initMutationObserver(MutationObs);
17998
17999         } else if (!capturedSetTimeout) { // vert.x
18000                 var vertxRequire = require;
18001                 var vertx = vertxRequire('vertx');
18002                 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
18003                 clearTimer = vertx.cancelTimer;
18004                 asap = vertx.runOnLoop || vertx.runOnContext;
18005         }
18006
18007         return {
18008                 setTimer: setTimer,
18009                 clearTimer: clearTimer,
18010                 asap: asap
18011         };
18012
18013         function isNode () {
18014                 return typeof process !== 'undefined' &&
18015                         Object.prototype.toString.call(process) === '[object process]';
18016         }
18017
18018         function hasMutationObserver () {
18019             return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
18020                         (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
18021         }
18022
18023         function initMutationObserver(MutationObserver) {
18024                 var scheduled;
18025                 var node = document.createTextNode('');
18026                 var o = new MutationObserver(run);
18027                 o.observe(node, { characterData: true });
18028
18029                 function run() {
18030                         var f = scheduled;
18031                         scheduled = void 0;
18032                         f();
18033                 }
18034
18035                 var i = 0;
18036                 return function (f) {
18037                         scheduled = f;
18038                         node.data = (i ^= 1);
18039                 };
18040         }
18041 });
18042 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18043
18044 }).call(this,require('_process'))
18045
18046 },{"_process":4}],218:[function(require,module,exports){
18047 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18048 /** @author Brian Cavalier */
18049 /** @author John Hann */
18050
18051 (function(define) { 'use strict';
18052 define(function() {
18053
18054         return {
18055                 formatError: formatError,
18056                 formatObject: formatObject,
18057                 tryStringify: tryStringify
18058         };
18059
18060         /**
18061          * Format an error into a string.  If e is an Error and has a stack property,
18062          * it's returned.  Otherwise, e is formatted using formatObject, with a
18063          * warning added about e not being a proper Error.
18064          * @param {*} e
18065          * @returns {String} formatted string, suitable for output to developers
18066          */
18067         function formatError(e) {
18068                 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
18069                 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
18070         }
18071
18072         /**
18073          * Format an object, detecting "plain" objects and running them through
18074          * JSON.stringify if possible.
18075          * @param {Object} o
18076          * @returns {string}
18077          */
18078         function formatObject(o) {
18079                 var s = String(o);
18080                 if(s === '[object Object]' && typeof JSON !== 'undefined') {
18081                         s = tryStringify(o, s);
18082                 }
18083                 return s;
18084         }
18085
18086         /**
18087          * Try to return the result of JSON.stringify(x).  If that fails, return
18088          * defaultValue
18089          * @param {*} x
18090          * @param {*} defaultValue
18091          * @returns {String|*} JSON.stringify(x) or defaultValue
18092          */
18093         function tryStringify(x, defaultValue) {
18094                 try {
18095                         return JSON.stringify(x);
18096                 } catch(e) {
18097                         return defaultValue;
18098                 }
18099         }
18100
18101 });
18102 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18103
18104 },{}],219:[function(require,module,exports){
18105 (function (process){
18106 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18107 /** @author Brian Cavalier */
18108 /** @author John Hann */
18109
18110 (function(define) { 'use strict';
18111 define(function() {
18112
18113         return function makePromise(environment) {
18114
18115                 var tasks = environment.scheduler;
18116                 var emitRejection = initEmitRejection();
18117
18118                 var objectCreate = Object.create ||
18119                         function(proto) {
18120                                 function Child() {}
18121                                 Child.prototype = proto;
18122                                 return new Child();
18123                         };
18124
18125                 /**
18126                  * Create a promise whose fate is determined by resolver
18127                  * @constructor
18128                  * @returns {Promise} promise
18129                  * @name Promise
18130                  */
18131                 function Promise(resolver, handler) {
18132                         this._handler = resolver === Handler ? handler : init(resolver);
18133                 }
18134
18135                 /**
18136                  * Run the supplied resolver
18137                  * @param resolver
18138                  * @returns {Pending}
18139                  */
18140                 function init(resolver) {
18141                         var handler = new Pending();
18142
18143                         try {
18144                                 resolver(promiseResolve, promiseReject, promiseNotify);
18145                         } catch (e) {
18146                                 promiseReject(e);
18147                         }
18148
18149                         return handler;
18150
18151                         /**
18152                          * Transition from pre-resolution state to post-resolution state, notifying
18153                          * all listeners of the ultimate fulfillment or rejection
18154                          * @param {*} x resolution value
18155                          */
18156                         function promiseResolve (x) {
18157                                 handler.resolve(x);
18158                         }
18159                         /**
18160                          * Reject this promise with reason, which will be used verbatim
18161                          * @param {Error|*} reason rejection reason, strongly suggested
18162                          *   to be an Error type
18163                          */
18164                         function promiseReject (reason) {
18165                                 handler.reject(reason);
18166                         }
18167
18168                         /**
18169                          * @deprecated
18170                          * Issue a progress event, notifying all progress listeners
18171                          * @param {*} x progress event payload to pass to all listeners
18172                          */
18173                         function promiseNotify (x) {
18174                                 handler.notify(x);
18175                         }
18176                 }
18177
18178                 // Creation
18179
18180                 Promise.resolve = resolve;
18181                 Promise.reject = reject;
18182                 Promise.never = never;
18183
18184                 Promise._defer = defer;
18185                 Promise._handler = getHandler;
18186
18187                 /**
18188                  * Returns a trusted promise. If x is already a trusted promise, it is
18189                  * returned, otherwise returns a new trusted Promise which follows x.
18190                  * @param  {*} x
18191                  * @return {Promise} promise
18192                  */
18193                 function resolve(x) {
18194                         return isPromise(x) ? x
18195                                 : new Promise(Handler, new Async(getHandler(x)));
18196                 }
18197
18198                 /**
18199                  * Return a reject promise with x as its reason (x is used verbatim)
18200                  * @param {*} x
18201                  * @returns {Promise} rejected promise
18202                  */
18203                 function reject(x) {
18204                         return new Promise(Handler, new Async(new Rejected(x)));
18205                 }
18206
18207                 /**
18208                  * Return a promise that remains pending forever
18209                  * @returns {Promise} forever-pending promise.
18210                  */
18211                 function never() {
18212                         return foreverPendingPromise; // Should be frozen
18213                 }
18214
18215                 /**
18216                  * Creates an internal {promise, resolver} pair
18217                  * @private
18218                  * @returns {Promise}
18219                  */
18220                 function defer() {
18221                         return new Promise(Handler, new Pending());
18222                 }
18223
18224                 // Transformation and flow control
18225
18226                 /**
18227                  * Transform this promise's fulfillment value, returning a new Promise
18228                  * for the transformed result.  If the promise cannot be fulfilled, onRejected
18229                  * is called with the reason.  onProgress *may* be called with updates toward
18230                  * this promise's fulfillment.
18231                  * @param {function=} onFulfilled fulfillment handler
18232                  * @param {function=} onRejected rejection handler
18233                  * @param {function=} onProgress @deprecated progress handler
18234                  * @return {Promise} new promise
18235                  */
18236                 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
18237                         var parent = this._handler;
18238                         var state = parent.join().state();
18239
18240                         if ((typeof onFulfilled !== 'function' && state > 0) ||
18241                                 (typeof onRejected !== 'function' && state < 0)) {
18242                                 // Short circuit: value will not change, simply share handler
18243                                 return new this.constructor(Handler, parent);
18244                         }
18245
18246                         var p = this._beget();
18247                         var child = p._handler;
18248
18249                         parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
18250
18251                         return p;
18252                 };
18253
18254                 /**
18255                  * If this promise cannot be fulfilled due to an error, call onRejected to
18256                  * handle the error. Shortcut for .then(undefined, onRejected)
18257                  * @param {function?} onRejected
18258                  * @return {Promise}
18259                  */
18260                 Promise.prototype['catch'] = function(onRejected) {
18261                         return this.then(void 0, onRejected);
18262                 };
18263
18264                 /**
18265                  * Creates a new, pending promise of the same type as this promise
18266                  * @private
18267                  * @returns {Promise}
18268                  */
18269                 Promise.prototype._beget = function() {
18270                         return begetFrom(this._handler, this.constructor);
18271                 };
18272
18273                 function begetFrom(parent, Promise) {
18274                         var child = new Pending(parent.receiver, parent.join().context);
18275                         return new Promise(Handler, child);
18276                 }
18277
18278                 // Array combinators
18279
18280                 Promise.all = all;
18281                 Promise.race = race;
18282                 Promise._traverse = traverse;
18283
18284                 /**
18285                  * Return a promise that will fulfill when all promises in the
18286                  * input array have fulfilled, or will reject when one of the
18287                  * promises rejects.
18288                  * @param {array} promises array of promises
18289                  * @returns {Promise} promise for array of fulfillment values
18290                  */
18291                 function all(promises) {
18292                         return traverseWith(snd, null, promises);
18293                 }
18294
18295                 /**
18296                  * Array<Promise<X>> -> Promise<Array<f(X)>>
18297                  * @private
18298                  * @param {function} f function to apply to each promise's value
18299                  * @param {Array} promises array of promises
18300                  * @returns {Promise} promise for transformed values
18301                  */
18302                 function traverse(f, promises) {
18303                         return traverseWith(tryCatch2, f, promises);
18304                 }
18305
18306                 function traverseWith(tryMap, f, promises) {
18307                         var handler = typeof f === 'function' ? mapAt : settleAt;
18308
18309                         var resolver = new Pending();
18310                         var pending = promises.length >>> 0;
18311                         var results = new Array(pending);
18312
18313                         for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
18314                                 x = promises[i];
18315
18316                                 if (x === void 0 && !(i in promises)) {
18317                                         --pending;
18318                                         continue;
18319                                 }
18320
18321                                 traverseAt(promises, handler, i, x, resolver);
18322                         }
18323
18324                         if(pending === 0) {
18325                                 resolver.become(new Fulfilled(results));
18326                         }
18327
18328                         return new Promise(Handler, resolver);
18329
18330                         function mapAt(i, x, resolver) {
18331                                 if(!resolver.resolved) {
18332                                         traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
18333                                 }
18334                         }
18335
18336                         function settleAt(i, x, resolver) {
18337                                 results[i] = x;
18338                                 if(--pending === 0) {
18339                                         resolver.become(new Fulfilled(results));
18340                                 }
18341                         }
18342                 }
18343
18344                 function traverseAt(promises, handler, i, x, resolver) {
18345                         if (maybeThenable(x)) {
18346                                 var h = getHandlerMaybeThenable(x);
18347                                 var s = h.state();
18348
18349                                 if (s === 0) {
18350                                         h.fold(handler, i, void 0, resolver);
18351                                 } else if (s > 0) {
18352                                         handler(i, h.value, resolver);
18353                                 } else {
18354                                         resolver.become(h);
18355                                         visitRemaining(promises, i+1, h);
18356                                 }
18357                         } else {
18358                                 handler(i, x, resolver);
18359                         }
18360                 }
18361
18362                 Promise._visitRemaining = visitRemaining;
18363                 function visitRemaining(promises, start, handler) {
18364                         for(var i=start; i<promises.length; ++i) {
18365                                 markAsHandled(getHandler(promises[i]), handler);
18366                         }
18367                 }
18368
18369                 function markAsHandled(h, handler) {
18370                         if(h === handler) {
18371                                 return;
18372                         }
18373
18374                         var s = h.state();
18375                         if(s === 0) {
18376                                 h.visit(h, void 0, h._unreport);
18377                         } else if(s < 0) {
18378                                 h._unreport();
18379                         }
18380                 }
18381
18382                 /**
18383                  * Fulfill-reject competitive race. Return a promise that will settle
18384                  * to the same state as the earliest input promise to settle.
18385                  *
18386                  * WARNING: The ES6 Promise spec requires that race()ing an empty array
18387                  * must return a promise that is pending forever.  This implementation
18388                  * returns a singleton forever-pending promise, the same singleton that is
18389                  * returned by Promise.never(), thus can be checked with ===
18390                  *
18391                  * @param {array} promises array of promises to race
18392                  * @returns {Promise} if input is non-empty, a promise that will settle
18393                  * to the same outcome as the earliest input promise to settle. if empty
18394                  * is empty, returns a promise that will never settle.
18395                  */
18396                 function race(promises) {
18397                         if(typeof promises !== 'object' || promises === null) {
18398                                 return reject(new TypeError('non-iterable passed to race()'));
18399                         }
18400
18401                         // Sigh, race([]) is untestable unless we return *something*
18402                         // that is recognizable without calling .then() on it.
18403                         return promises.length === 0 ? never()
18404                                  : promises.length === 1 ? resolve(promises[0])
18405                                  : runRace(promises);
18406                 }
18407
18408                 function runRace(promises) {
18409                         var resolver = new Pending();
18410                         var i, x, h;
18411                         for(i=0; i<promises.length; ++i) {
18412                                 x = promises[i];
18413                                 if (x === void 0 && !(i in promises)) {
18414                                         continue;
18415                                 }
18416
18417                                 h = getHandler(x);
18418                                 if(h.state() !== 0) {
18419                                         resolver.become(h);
18420                                         visitRemaining(promises, i+1, h);
18421                                         break;
18422                                 } else {
18423                                         h.visit(resolver, resolver.resolve, resolver.reject);
18424                                 }
18425                         }
18426                         return new Promise(Handler, resolver);
18427                 }
18428
18429                 // Promise internals
18430                 // Below this, everything is @private
18431
18432                 /**
18433                  * Get an appropriate handler for x, without checking for cycles
18434                  * @param {*} x
18435                  * @returns {object} handler
18436                  */
18437                 function getHandler(x) {
18438                         if(isPromise(x)) {
18439                                 return x._handler.join();
18440                         }
18441                         return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
18442                 }
18443
18444                 /**
18445                  * Get a handler for thenable x.
18446                  * NOTE: You must only call this if maybeThenable(x) == true
18447                  * @param {object|function|Promise} x
18448                  * @returns {object} handler
18449                  */
18450                 function getHandlerMaybeThenable(x) {
18451                         return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
18452                 }
18453
18454                 /**
18455                  * Get a handler for potentially untrusted thenable x
18456                  * @param {*} x
18457                  * @returns {object} handler
18458                  */
18459                 function getHandlerUntrusted(x) {
18460                         try {
18461                                 var untrustedThen = x.then;
18462                                 return typeof untrustedThen === 'function'
18463                                         ? new Thenable(untrustedThen, x)
18464                                         : new Fulfilled(x);
18465                         } catch(e) {
18466                                 return new Rejected(e);
18467                         }
18468                 }
18469
18470                 /**
18471                  * Handler for a promise that is pending forever
18472                  * @constructor
18473                  */
18474                 function Handler() {}
18475
18476                 Handler.prototype.when
18477                         = Handler.prototype.become
18478                         = Handler.prototype.notify // deprecated
18479                         = Handler.prototype.fail
18480                         = Handler.prototype._unreport
18481                         = Handler.prototype._report
18482                         = noop;
18483
18484                 Handler.prototype._state = 0;
18485
18486                 Handler.prototype.state = function() {
18487                         return this._state;
18488                 };
18489
18490                 /**
18491                  * Recursively collapse handler chain to find the handler
18492                  * nearest to the fully resolved value.
18493                  * @returns {object} handler nearest the fully resolved value
18494                  */
18495                 Handler.prototype.join = function() {
18496                         var h = this;
18497                         while(h.handler !== void 0) {
18498                                 h = h.handler;
18499                         }
18500                         return h;
18501                 };
18502
18503                 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
18504                         this.when({
18505                                 resolver: to,
18506                                 receiver: receiver,
18507                                 fulfilled: fulfilled,
18508                                 rejected: rejected,
18509                                 progress: progress
18510                         });
18511                 };
18512
18513                 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
18514                         this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
18515                 };
18516
18517                 Handler.prototype.fold = function(f, z, c, to) {
18518                         this.when(new Fold(f, z, c, to));
18519                 };
18520
18521                 /**
18522                  * Handler that invokes fail() on any handler it becomes
18523                  * @constructor
18524                  */
18525                 function FailIfRejected() {}
18526
18527                 inherit(Handler, FailIfRejected);
18528
18529                 FailIfRejected.prototype.become = function(h) {
18530                         h.fail();
18531                 };
18532
18533                 var failIfRejected = new FailIfRejected();
18534
18535                 /**
18536                  * Handler that manages a queue of consumers waiting on a pending promise
18537                  * @constructor
18538                  */
18539                 function Pending(receiver, inheritedContext) {
18540                         Promise.createContext(this, inheritedContext);
18541
18542                         this.consumers = void 0;
18543                         this.receiver = receiver;
18544                         this.handler = void 0;
18545                         this.resolved = false;
18546                 }
18547
18548                 inherit(Handler, Pending);
18549
18550                 Pending.prototype._state = 0;
18551
18552                 Pending.prototype.resolve = function(x) {
18553                         this.become(getHandler(x));
18554                 };
18555
18556                 Pending.prototype.reject = function(x) {
18557                         if(this.resolved) {
18558                                 return;
18559                         }
18560
18561                         this.become(new Rejected(x));
18562                 };
18563
18564                 Pending.prototype.join = function() {
18565                         if (!this.resolved) {
18566                                 return this;
18567                         }
18568
18569                         var h = this;
18570
18571                         while (h.handler !== void 0) {
18572                                 h = h.handler;
18573                                 if (h === this) {
18574                                         return this.handler = cycle();
18575                                 }
18576                         }
18577
18578                         return h;
18579                 };
18580
18581                 Pending.prototype.run = function() {
18582                         var q = this.consumers;
18583                         var handler = this.handler;
18584                         this.handler = this.handler.join();
18585                         this.consumers = void 0;
18586
18587                         for (var i = 0; i < q.length; ++i) {
18588                                 handler.when(q[i]);
18589                         }
18590                 };
18591
18592                 Pending.prototype.become = function(handler) {
18593                         if(this.resolved) {
18594                                 return;
18595                         }
18596
18597                         this.resolved = true;
18598                         this.handler = handler;
18599                         if(this.consumers !== void 0) {
18600                                 tasks.enqueue(this);
18601                         }
18602
18603                         if(this.context !== void 0) {
18604                                 handler._report(this.context);
18605                         }
18606                 };
18607
18608                 Pending.prototype.when = function(continuation) {
18609                         if(this.resolved) {
18610                                 tasks.enqueue(new ContinuationTask(continuation, this.handler));
18611                         } else {
18612                                 if(this.consumers === void 0) {
18613                                         this.consumers = [continuation];
18614                                 } else {
18615                                         this.consumers.push(continuation);
18616                                 }
18617                         }
18618                 };
18619
18620                 /**
18621                  * @deprecated
18622                  */
18623                 Pending.prototype.notify = function(x) {
18624                         if(!this.resolved) {
18625                                 tasks.enqueue(new ProgressTask(x, this));
18626                         }
18627                 };
18628
18629                 Pending.prototype.fail = function(context) {
18630                         var c = typeof context === 'undefined' ? this.context : context;
18631                         this.resolved && this.handler.join().fail(c);
18632                 };
18633
18634                 Pending.prototype._report = function(context) {
18635                         this.resolved && this.handler.join()._report(context);
18636                 };
18637
18638                 Pending.prototype._unreport = function() {
18639                         this.resolved && this.handler.join()._unreport();
18640                 };
18641
18642                 /**
18643                  * Wrap another handler and force it into a future stack
18644                  * @param {object} handler
18645                  * @constructor
18646                  */
18647                 function Async(handler) {
18648                         this.handler = handler;
18649                 }
18650
18651                 inherit(Handler, Async);
18652
18653                 Async.prototype.when = function(continuation) {
18654                         tasks.enqueue(new ContinuationTask(continuation, this));
18655                 };
18656
18657                 Async.prototype._report = function(context) {
18658                         this.join()._report(context);
18659                 };
18660
18661                 Async.prototype._unreport = function() {
18662                         this.join()._unreport();
18663                 };
18664
18665                 /**
18666                  * Handler that wraps an untrusted thenable and assimilates it in a future stack
18667                  * @param {function} then
18668                  * @param {{then: function}} thenable
18669                  * @constructor
18670                  */
18671                 function Thenable(then, thenable) {
18672                         Pending.call(this);
18673                         tasks.enqueue(new AssimilateTask(then, thenable, this));
18674                 }
18675
18676                 inherit(Pending, Thenable);
18677
18678                 /**
18679                  * Handler for a fulfilled promise
18680                  * @param {*} x fulfillment value
18681                  * @constructor
18682                  */
18683                 function Fulfilled(x) {
18684                         Promise.createContext(this);
18685                         this.value = x;
18686                 }
18687
18688                 inherit(Handler, Fulfilled);
18689
18690                 Fulfilled.prototype._state = 1;
18691
18692                 Fulfilled.prototype.fold = function(f, z, c, to) {
18693                         runContinuation3(f, z, this, c, to);
18694                 };
18695
18696                 Fulfilled.prototype.when = function(cont) {
18697                         runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
18698                 };
18699
18700                 var errorId = 0;
18701
18702                 /**
18703                  * Handler for a rejected promise
18704                  * @param {*} x rejection reason
18705                  * @constructor
18706                  */
18707                 function Rejected(x) {
18708                         Promise.createContext(this);
18709
18710                         this.id = ++errorId;
18711                         this.value = x;
18712                         this.handled = false;
18713                         this.reported = false;
18714
18715                         this._report();
18716                 }
18717
18718                 inherit(Handler, Rejected);
18719
18720                 Rejected.prototype._state = -1;
18721
18722                 Rejected.prototype.fold = function(f, z, c, to) {
18723                         to.become(this);
18724                 };
18725
18726                 Rejected.prototype.when = function(cont) {
18727                         if(typeof cont.rejected === 'function') {
18728                                 this._unreport();
18729                         }
18730                         runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
18731                 };
18732
18733                 Rejected.prototype._report = function(context) {
18734                         tasks.afterQueue(new ReportTask(this, context));
18735                 };
18736
18737                 Rejected.prototype._unreport = function() {
18738                         if(this.handled) {
18739                                 return;
18740                         }
18741                         this.handled = true;
18742                         tasks.afterQueue(new UnreportTask(this));
18743                 };
18744
18745                 Rejected.prototype.fail = function(context) {
18746                         this.reported = true;
18747                         emitRejection('unhandledRejection', this);
18748                         Promise.onFatalRejection(this, context === void 0 ? this.context : context);
18749                 };
18750
18751                 function ReportTask(rejection, context) {
18752                         this.rejection = rejection;
18753                         this.context = context;
18754                 }
18755
18756                 ReportTask.prototype.run = function() {
18757                         if(!this.rejection.handled && !this.rejection.reported) {
18758                                 this.rejection.reported = true;
18759                                 emitRejection('unhandledRejection', this.rejection) ||
18760                                         Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
18761                         }
18762                 };
18763
18764                 function UnreportTask(rejection) {
18765                         this.rejection = rejection;
18766                 }
18767
18768                 UnreportTask.prototype.run = function() {
18769                         if(this.rejection.reported) {
18770                                 emitRejection('rejectionHandled', this.rejection) ||
18771                                         Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
18772                         }
18773                 };
18774
18775                 // Unhandled rejection hooks
18776                 // By default, everything is a noop
18777
18778                 Promise.createContext
18779                         = Promise.enterContext
18780                         = Promise.exitContext
18781                         = Promise.onPotentiallyUnhandledRejection
18782                         = Promise.onPotentiallyUnhandledRejectionHandled
18783                         = Promise.onFatalRejection
18784                         = noop;
18785
18786                 // Errors and singletons
18787
18788                 var foreverPendingHandler = new Handler();
18789                 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
18790
18791                 function cycle() {
18792                         return new Rejected(new TypeError('Promise cycle'));
18793                 }
18794
18795                 // Task runners
18796
18797                 /**
18798                  * Run a single consumer
18799                  * @constructor
18800                  */
18801                 function ContinuationTask(continuation, handler) {
18802                         this.continuation = continuation;
18803                         this.handler = handler;
18804                 }
18805
18806                 ContinuationTask.prototype.run = function() {
18807                         this.handler.join().when(this.continuation);
18808                 };
18809
18810                 /**
18811                  * Run a queue of progress handlers
18812                  * @constructor
18813                  */
18814                 function ProgressTask(value, handler) {
18815                         this.handler = handler;
18816                         this.value = value;
18817                 }
18818
18819                 ProgressTask.prototype.run = function() {
18820                         var q = this.handler.consumers;
18821                         if(q === void 0) {
18822                                 return;
18823                         }
18824
18825                         for (var c, i = 0; i < q.length; ++i) {
18826                                 c = q[i];
18827                                 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
18828                         }
18829                 };
18830
18831                 /**
18832                  * Assimilate a thenable, sending it's value to resolver
18833                  * @param {function} then
18834                  * @param {object|function} thenable
18835                  * @param {object} resolver
18836                  * @constructor
18837                  */
18838                 function AssimilateTask(then, thenable, resolver) {
18839                         this._then = then;
18840                         this.thenable = thenable;
18841                         this.resolver = resolver;
18842                 }
18843
18844                 AssimilateTask.prototype.run = function() {
18845                         var h = this.resolver;
18846                         tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
18847
18848                         function _resolve(x) { h.resolve(x); }
18849                         function _reject(x)  { h.reject(x); }
18850                         function _notify(x)  { h.notify(x); }
18851                 };
18852
18853                 function tryAssimilate(then, thenable, resolve, reject, notify) {
18854                         try {
18855                                 then.call(thenable, resolve, reject, notify);
18856                         } catch (e) {
18857                                 reject(e);
18858                         }
18859                 }
18860
18861                 /**
18862                  * Fold a handler value with z
18863                  * @constructor
18864                  */
18865                 function Fold(f, z, c, to) {
18866                         this.f = f; this.z = z; this.c = c; this.to = to;
18867                         this.resolver = failIfRejected;
18868                         this.receiver = this;
18869                 }
18870
18871                 Fold.prototype.fulfilled = function(x) {
18872                         this.f.call(this.c, this.z, x, this.to);
18873                 };
18874
18875                 Fold.prototype.rejected = function(x) {
18876                         this.to.reject(x);
18877                 };
18878
18879                 Fold.prototype.progress = function(x) {
18880                         this.to.notify(x);
18881                 };
18882
18883                 // Other helpers
18884
18885                 /**
18886                  * @param {*} x
18887                  * @returns {boolean} true iff x is a trusted Promise
18888                  */
18889                 function isPromise(x) {
18890                         return x instanceof Promise;
18891                 }
18892
18893                 /**
18894                  * Test just enough to rule out primitives, in order to take faster
18895                  * paths in some code
18896                  * @param {*} x
18897                  * @returns {boolean} false iff x is guaranteed *not* to be a thenable
18898                  */
18899                 function maybeThenable(x) {
18900                         return (typeof x === 'object' || typeof x === 'function') && x !== null;
18901                 }
18902
18903                 function runContinuation1(f, h, receiver, next) {
18904                         if(typeof f !== 'function') {
18905                                 return next.become(h);
18906                         }
18907
18908                         Promise.enterContext(h);
18909                         tryCatchReject(f, h.value, receiver, next);
18910                         Promise.exitContext();
18911                 }
18912
18913                 function runContinuation3(f, x, h, receiver, next) {
18914                         if(typeof f !== 'function') {
18915                                 return next.become(h);
18916                         }
18917
18918                         Promise.enterContext(h);
18919                         tryCatchReject3(f, x, h.value, receiver, next);
18920                         Promise.exitContext();
18921                 }
18922
18923                 /**
18924                  * @deprecated
18925                  */
18926                 function runNotify(f, x, h, receiver, next) {
18927                         if(typeof f !== 'function') {
18928                                 return next.notify(x);
18929                         }
18930
18931                         Promise.enterContext(h);
18932                         tryCatchReturn(f, x, receiver, next);
18933                         Promise.exitContext();
18934                 }
18935
18936                 function tryCatch2(f, a, b) {
18937                         try {
18938                                 return f(a, b);
18939                         } catch(e) {
18940                                 return reject(e);
18941                         }
18942                 }
18943
18944                 /**
18945                  * Return f.call(thisArg, x), or if it throws return a rejected promise for
18946                  * the thrown exception
18947                  */
18948                 function tryCatchReject(f, x, thisArg, next) {
18949                         try {
18950                                 next.become(getHandler(f.call(thisArg, x)));
18951                         } catch(e) {
18952                                 next.become(new Rejected(e));
18953                         }
18954                 }
18955
18956                 /**
18957                  * Same as above, but includes the extra argument parameter.
18958                  */
18959                 function tryCatchReject3(f, x, y, thisArg, next) {
18960                         try {
18961                                 f.call(thisArg, x, y, next);
18962                         } catch(e) {
18963                                 next.become(new Rejected(e));
18964                         }
18965                 }
18966
18967                 /**
18968                  * @deprecated
18969                  * Return f.call(thisArg, x), or if it throws, *return* the exception
18970                  */
18971                 function tryCatchReturn(f, x, thisArg, next) {
18972                         try {
18973                                 next.notify(f.call(thisArg, x));
18974                         } catch(e) {
18975                                 next.notify(e);
18976                         }
18977                 }
18978
18979                 function inherit(Parent, Child) {
18980                         Child.prototype = objectCreate(Parent.prototype);
18981                         Child.prototype.constructor = Child;
18982                 }
18983
18984                 function snd(x, y) {
18985                         return y;
18986                 }
18987
18988                 function noop() {}
18989
18990                 function hasCustomEvent() {
18991                         if(typeof CustomEvent === 'function') {
18992                                 try {
18993                                         var ev = new CustomEvent('unhandledRejection');
18994                                         return ev instanceof CustomEvent;
18995                                 } catch (ignoredException) {}
18996                         }
18997                         return false;
18998                 }
18999
19000                 function hasInternetExplorerCustomEvent() {
19001                         if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
19002                                 try {
19003                                         // Try to create one event to make sure it's supported
19004                                         var ev = document.createEvent('CustomEvent');
19005                                         ev.initCustomEvent('eventType', false, true, {});
19006                                         return true;
19007                                 } catch (ignoredException) {}
19008                         }
19009                         return false;
19010                 }
19011
19012                 function initEmitRejection() {
19013                         /*global process, self, CustomEvent*/
19014                         if(typeof process !== 'undefined' && process !== null
19015                                 && typeof process.emit === 'function') {
19016                                 // Returning falsy here means to call the default
19017                                 // onPotentiallyUnhandledRejection API.  This is safe even in
19018                                 // browserify since process.emit always returns falsy in browserify:
19019                                 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
19020                                 return function(type, rejection) {
19021                                         return type === 'unhandledRejection'
19022                                                 ? process.emit(type, rejection.value, rejection)
19023                                                 : process.emit(type, rejection);
19024                                 };
19025                         } else if(typeof self !== 'undefined' && hasCustomEvent()) {
19026                                 return (function (self, CustomEvent) {
19027                                         return function (type, rejection) {
19028                                                 var ev = new CustomEvent(type, {
19029                                                         detail: {
19030                                                                 reason: rejection.value,
19031                                                                 key: rejection
19032                                                         },
19033                                                         bubbles: false,
19034                                                         cancelable: true
19035                                                 });
19036
19037                                                 return !self.dispatchEvent(ev);
19038                                         };
19039                                 }(self, CustomEvent));
19040                         } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
19041                                 return (function(self, document) {
19042                                         return function(type, rejection) {
19043                                                 var ev = document.createEvent('CustomEvent');
19044                                                 ev.initCustomEvent(type, false, true, {
19045                                                         reason: rejection.value,
19046                                                         key: rejection
19047                                                 });
19048
19049                                                 return !self.dispatchEvent(ev);
19050                                         };
19051                                 }(self, document));
19052                         }
19053
19054                         return noop;
19055                 }
19056
19057                 return Promise;
19058         };
19059 });
19060 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19061
19062 }).call(this,require('_process'))
19063
19064 },{"_process":4}],220:[function(require,module,exports){
19065 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19066 /** @author Brian Cavalier */
19067 /** @author John Hann */
19068
19069 (function(define) { 'use strict';
19070 define(function() {
19071
19072         return {
19073                 pending: toPendingState,
19074                 fulfilled: toFulfilledState,
19075                 rejected: toRejectedState,
19076                 inspect: inspect
19077         };
19078
19079         function toPendingState() {
19080                 return { state: 'pending' };
19081         }
19082
19083         function toRejectedState(e) {
19084                 return { state: 'rejected', reason: e };
19085         }
19086
19087         function toFulfilledState(x) {
19088                 return { state: 'fulfilled', value: x };
19089         }
19090
19091         function inspect(handler) {
19092                 var state = handler.state();
19093                 return state === 0 ? toPendingState()
19094                          : state > 0   ? toFulfilledState(handler.value)
19095                                        : toRejectedState(handler.value);
19096         }
19097
19098 });
19099 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19100
19101 },{}],221:[function(require,module,exports){
19102 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19103
19104 /**
19105  * Promises/A+ and when() implementation
19106  * when is part of the cujoJS family of libraries (http://cujojs.com/)
19107  * @author Brian Cavalier
19108  * @author John Hann
19109  */
19110 (function(define) { 'use strict';
19111 define(function (require) {
19112
19113         var timed = require('./lib/decorators/timed');
19114         var array = require('./lib/decorators/array');
19115         var flow = require('./lib/decorators/flow');
19116         var fold = require('./lib/decorators/fold');
19117         var inspect = require('./lib/decorators/inspect');
19118         var generate = require('./lib/decorators/iterate');
19119         var progress = require('./lib/decorators/progress');
19120         var withThis = require('./lib/decorators/with');
19121         var unhandledRejection = require('./lib/decorators/unhandledRejection');
19122         var TimeoutError = require('./lib/TimeoutError');
19123
19124         var Promise = [array, flow, fold, generate, progress,
19125                 inspect, withThis, timed, unhandledRejection]
19126                 .reduce(function(Promise, feature) {
19127                         return feature(Promise);
19128                 }, require('./lib/Promise'));
19129
19130         var apply = require('./lib/apply')(Promise);
19131
19132         // Public API
19133
19134         when.promise     = promise;              // Create a pending promise
19135         when.resolve     = Promise.resolve;      // Create a resolved promise
19136         when.reject      = Promise.reject;       // Create a rejected promise
19137
19138         when.lift        = lift;                 // lift a function to return promises
19139         when['try']      = attempt;              // call a function and return a promise
19140         when.attempt     = attempt;              // alias for when.try
19141
19142         when.iterate     = Promise.iterate;      // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19143         when.unfold      = Promise.unfold;       // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19144
19145         when.join        = join;                 // Join 2 or more promises
19146
19147         when.all         = all;                  // Resolve a list of promises
19148         when.settle      = settle;               // Settle a list of promises
19149
19150         when.any         = lift(Promise.any);    // One-winner race
19151         when.some        = lift(Promise.some);   // Multi-winner race
19152         when.race        = lift(Promise.race);   // First-to-settle race
19153
19154         when.map         = map;                  // Array.map() for promises
19155         when.filter      = filter;               // Array.filter() for promises
19156         when.reduce      = lift(Promise.reduce);       // Array.reduce() for promises
19157         when.reduceRight = lift(Promise.reduceRight);  // Array.reduceRight() for promises
19158
19159         when.isPromiseLike = isPromiseLike;      // Is something promise-like, aka thenable
19160
19161         when.Promise     = Promise;              // Promise constructor
19162         when.defer       = defer;                // Create a {promise, resolve, reject} tuple
19163
19164         // Error types
19165
19166         when.TimeoutError = TimeoutError;
19167
19168         /**
19169          * Get a trusted promise for x, or by transforming x with onFulfilled
19170          *
19171          * @param {*} x
19172          * @param {function?} onFulfilled callback to be called when x is
19173          *   successfully fulfilled.  If promiseOrValue is an immediate value, callback
19174          *   will be invoked immediately.
19175          * @param {function?} onRejected callback to be called when x is
19176          *   rejected.
19177          * @param {function?} onProgress callback to be called when progress updates
19178          *   are issued for x. @deprecated
19179          * @returns {Promise} a new promise that will fulfill with the return
19180          *   value of callback or errback or the completion value of promiseOrValue if
19181          *   callback and/or errback is not supplied.
19182          */
19183         function when(x, onFulfilled, onRejected, onProgress) {
19184                 var p = Promise.resolve(x);
19185                 if (arguments.length < 2) {
19186                         return p;
19187                 }
19188
19189                 return p.then(onFulfilled, onRejected, onProgress);
19190         }
19191
19192         /**
19193          * Creates a new promise whose fate is determined by resolver.
19194          * @param {function} resolver function(resolve, reject, notify)
19195          * @returns {Promise} promise whose fate is determine by resolver
19196          */
19197         function promise(resolver) {
19198                 return new Promise(resolver);
19199         }
19200
19201         /**
19202          * Lift the supplied function, creating a version of f that returns
19203          * promises, and accepts promises as arguments.
19204          * @param {function} f
19205          * @returns {Function} version of f that returns promises
19206          */
19207         function lift(f) {
19208                 return function() {
19209                         for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
19210                                 a[i] = arguments[i];
19211                         }
19212                         return apply(f, this, a);
19213                 };
19214         }
19215
19216         /**
19217          * Call f in a future turn, with the supplied args, and return a promise
19218          * for the result.
19219          * @param {function} f
19220          * @returns {Promise}
19221          */
19222         function attempt(f /*, args... */) {
19223                 /*jshint validthis:true */
19224                 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
19225                         a[i] = arguments[i+1];
19226                 }
19227                 return apply(f, this, a);
19228         }
19229
19230         /**
19231          * Creates a {promise, resolver} pair, either or both of which
19232          * may be given out safely to consumers.
19233          * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
19234          */
19235         function defer() {
19236                 return new Deferred();
19237         }
19238
19239         function Deferred() {
19240                 var p = Promise._defer();
19241
19242                 function resolve(x) { p._handler.resolve(x); }
19243                 function reject(x) { p._handler.reject(x); }
19244                 function notify(x) { p._handler.notify(x); }
19245
19246                 this.promise = p;
19247                 this.resolve = resolve;
19248                 this.reject = reject;
19249                 this.notify = notify;
19250                 this.resolver = { resolve: resolve, reject: reject, notify: notify };
19251         }
19252
19253         /**
19254          * Determines if x is promise-like, i.e. a thenable object
19255          * NOTE: Will return true for *any thenable object*, and isn't truly
19256          * safe, since it may attempt to access the `then` property of x (i.e.
19257          *  clever/malicious getters may do weird things)
19258          * @param {*} x anything
19259          * @returns {boolean} true if x is promise-like
19260          */
19261         function isPromiseLike(x) {
19262                 return x && typeof x.then === 'function';
19263         }
19264
19265         /**
19266          * Return a promise that will resolve only once all the supplied arguments
19267          * have resolved. The resolution value of the returned promise will be an array
19268          * containing the resolution values of each of the arguments.
19269          * @param {...*} arguments may be a mix of promises and values
19270          * @returns {Promise}
19271          */
19272         function join(/* ...promises */) {
19273                 return Promise.all(arguments);
19274         }
19275
19276         /**
19277          * Return a promise that will fulfill once all input promises have
19278          * fulfilled, or reject when any one input promise rejects.
19279          * @param {array|Promise} promises array (or promise for an array) of promises
19280          * @returns {Promise}
19281          */
19282         function all(promises) {
19283                 return when(promises, Promise.all);
19284         }
19285
19286         /**
19287          * Return a promise that will always fulfill with an array containing
19288          * the outcome states of all input promises.  The returned promise
19289          * will only reject if `promises` itself is a rejected promise.
19290          * @param {array|Promise} promises array (or promise for an array) of promises
19291          * @returns {Promise} promise for array of settled state descriptors
19292          */
19293         function settle(promises) {
19294                 return when(promises, Promise.settle);
19295         }
19296
19297         /**
19298          * Promise-aware array map function, similar to `Array.prototype.map()`,
19299          * but input array may contain promises or values.
19300          * @param {Array|Promise} promises array of anything, may contain promises and values
19301          * @param {function(x:*, index:Number):*} mapFunc map function which may
19302          *  return a promise or value
19303          * @returns {Promise} promise that will fulfill with an array of mapped values
19304          *  or reject if any input promise rejects.
19305          */
19306         function map(promises, mapFunc) {
19307                 return when(promises, function(promises) {
19308                         return Promise.map(promises, mapFunc);
19309                 });
19310         }
19311
19312         /**
19313          * Filter the provided array of promises using the provided predicate.  Input may
19314          * contain promises and values
19315          * @param {Array|Promise} promises array of promises and values
19316          * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
19317          *  Must return truthy (or promise for truthy) for items to retain.
19318          * @returns {Promise} promise that will fulfill with an array containing all items
19319          *  for which predicate returned truthy.
19320          */
19321         function filter(promises, predicate) {
19322                 return when(promises, function(promises) {
19323                         return Promise.filter(promises, predicate);
19324                 });
19325         }
19326
19327         return when;
19328 });
19329 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
19330
19331 },{"./lib/Promise":204,"./lib/TimeoutError":206,"./lib/apply":207,"./lib/decorators/array":208,"./lib/decorators/flow":209,"./lib/decorators/fold":210,"./lib/decorators/inspect":211,"./lib/decorators/iterate":212,"./lib/decorators/progress":213,"./lib/decorators/timed":214,"./lib/decorators/unhandledRejection":215,"./lib/decorators/with":216}],222:[function(require,module,exports){
19332 var nativeIsArray = Array.isArray
19333 var toString = Object.prototype.toString
19334
19335 module.exports = nativeIsArray || isArray
19336
19337 function isArray(obj) {
19338     return toString.call(obj) === "[object Array]"
19339 }
19340
19341 },{}],223:[function(require,module,exports){
19342 "use strict";
19343 var APIv3_1 = require("./api/APIv3");
19344 exports.APIv3 = APIv3_1.APIv3;
19345 var ModelCreator_1 = require("./api/ModelCreator");
19346 exports.ModelCreator = ModelCreator_1.ModelCreator;
19347
19348 },{"./api/APIv3":235,"./api/ModelCreator":236}],224:[function(require,module,exports){
19349 "use strict";
19350 var Component_1 = require("./component/Component");
19351 exports.Component = Component_1.Component;
19352 var ComponentService_1 = require("./component/ComponentService");
19353 exports.ComponentService = ComponentService_1.ComponentService;
19354 var AttributionComponent_1 = require("./component/AttributionComponent");
19355 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
19356 var BackgroundComponent_1 = require("./component/BackgroundComponent");
19357 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
19358 var BearingComponent_1 = require("./component/BearingComponent");
19359 exports.BearingComponent = BearingComponent_1.BearingComponent;
19360 var CacheComponent_1 = require("./component/CacheComponent");
19361 exports.CacheComponent = CacheComponent_1.CacheComponent;
19362 var CoverComponent_1 = require("./component/CoverComponent");
19363 exports.CoverComponent = CoverComponent_1.CoverComponent;
19364 var DebugComponent_1 = require("./component/DebugComponent");
19365 exports.DebugComponent = DebugComponent_1.DebugComponent;
19366 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
19367 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
19368 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
19369 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
19370 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
19371 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
19372 var ImageComponent_1 = require("./component/ImageComponent");
19373 exports.ImageComponent = ImageComponent_1.ImageComponent;
19374 var KeyboardComponent_1 = require("./component/KeyboardComponent");
19375 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
19376 var LoadingComponent_1 = require("./component/LoadingComponent");
19377 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
19378 var Marker_1 = require("./component/marker/marker/Marker");
19379 exports.Marker = Marker_1.Marker;
19380 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
19381 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
19382 var MarkerScene_1 = require("./component/marker/MarkerScene");
19383 exports.MarkerScene = MarkerScene_1.MarkerScene;
19384 var MarkerSet_1 = require("./component/marker/MarkerSet");
19385 exports.MarkerSet = MarkerSet_1.MarkerSet;
19386 var MouseComponent_1 = require("./component/mouse/MouseComponent");
19387 exports.MouseComponent = MouseComponent_1.MouseComponent;
19388 var MouseHandlerBase_1 = require("./component/mouse/MouseHandlerBase");
19389 exports.MouseHandlerBase = MouseHandlerBase_1.MouseHandlerBase;
19390 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
19391 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
19392 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
19393 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
19394 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
19395 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
19396 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
19397 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
19398 var NavigationComponent_1 = require("./component/NavigationComponent");
19399 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
19400 var RouteComponent_1 = require("./component/RouteComponent");
19401 exports.RouteComponent = RouteComponent_1.RouteComponent;
19402 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
19403 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
19404 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
19405 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
19406 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
19407 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
19408 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
19409 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
19410 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
19411 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
19412 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
19413 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
19414 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
19415 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
19416 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
19417 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
19418 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
19419 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
19420 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
19421 exports.CircleMarker = CircleMarker_1.CircleMarker;
19422 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
19423 exports.SliderComponent = SliderComponent_1.SliderComponent;
19424 var StatsComponent_1 = require("./component/StatsComponent");
19425 exports.StatsComponent = StatsComponent_1.StatsComponent;
19426 var Tag_1 = require("./component/tag/tag/Tag");
19427 exports.Tag = Tag_1.Tag;
19428 var Alignment_1 = require("./component/tag/tag/Alignment");
19429 exports.Alignment = Alignment_1.Alignment;
19430 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
19431 exports.OutlineTag = OutlineTag_1.OutlineTag;
19432 var RenderTag_1 = require("./component/tag/tag/RenderTag");
19433 exports.RenderTag = RenderTag_1.RenderTag;
19434 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
19435 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
19436 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
19437 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
19438 var SpotTag_1 = require("./component/tag/tag/SpotTag");
19439 exports.SpotTag = SpotTag_1.SpotTag;
19440 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
19441 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
19442 var TagComponent_1 = require("./component/tag/TagComponent");
19443 exports.TagComponent = TagComponent_1.TagComponent;
19444 var TagCreator_1 = require("./component/tag/TagCreator");
19445 exports.TagCreator = TagCreator_1.TagCreator;
19446 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
19447 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
19448 var TagGLRenderer_1 = require("./component/tag/TagGLRenderer");
19449 exports.TagGLRenderer = TagGLRenderer_1.TagGLRenderer;
19450 var TagOperation_1 = require("./component/tag/TagOperation");
19451 exports.TagOperation = TagOperation_1.TagOperation;
19452 var TagSet_1 = require("./component/tag/TagSet");
19453 exports.TagSet = TagSet_1.TagSet;
19454 var Geometry_1 = require("./component/tag/geometry/Geometry");
19455 exports.Geometry = Geometry_1.Geometry;
19456 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
19457 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
19458 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
19459 exports.RectGeometry = RectGeometry_1.RectGeometry;
19460 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
19461 exports.PointGeometry = PointGeometry_1.PointGeometry;
19462 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
19463 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
19464 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
19465 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
19466
19467 },{"./component/AttributionComponent":237,"./component/BackgroundComponent":238,"./component/BearingComponent":239,"./component/CacheComponent":240,"./component/Component":241,"./component/ComponentService":242,"./component/CoverComponent":243,"./component/DebugComponent":244,"./component/ImageComponent":245,"./component/KeyboardComponent":246,"./component/LoadingComponent":247,"./component/NavigationComponent":248,"./component/RouteComponent":249,"./component/StatsComponent":250,"./component/direction/DirectionComponent":251,"./component/direction/DirectionDOMCalculator":252,"./component/direction/DirectionDOMRenderer":253,"./component/imageplane/ImagePlaneComponent":254,"./component/imageplane/ImagePlaneFactory":255,"./component/imageplane/ImagePlaneGLRenderer":256,"./component/imageplane/ImagePlaneScene":257,"./component/imageplane/ImagePlaneShaders":258,"./component/imageplane/SliderComponent":259,"./component/marker/MarkerComponent":261,"./component/marker/MarkerScene":262,"./component/marker/MarkerSet":263,"./component/marker/marker/CircleMarker":264,"./component/marker/marker/Marker":265,"./component/marker/marker/SimpleMarker":266,"./component/mouse/DoubleClickZoomHandler":267,"./component/mouse/DragPanHandler":268,"./component/mouse/MouseComponent":269,"./component/mouse/MouseHandlerBase":270,"./component/mouse/ScrollZoomHandler":271,"./component/mouse/TouchZoomHandler":272,"./component/sequence/SequenceComponent":273,"./component/sequence/SequenceDOMInteraction":274,"./component/sequence/SequenceDOMRenderer":275,"./component/tag/TagComponent":277,"./component/tag/TagCreator":278,"./component/tag/TagDOMRenderer":279,"./component/tag/TagGLRenderer":280,"./component/tag/TagOperation":281,"./component/tag/TagSet":282,"./component/tag/error/GeometryTagError":283,"./component/tag/geometry/Geometry":284,"./component/tag/geometry/PointGeometry":285,"./component/tag/geometry/PolygonGeometry":286,"./component/tag/geometry/RectGeometry":287,"./component/tag/geometry/VertexGeometry":288,"./component/tag/tag/Alignment":289,"./component/tag/tag/OutlineCreateTag":290,"./component/tag/tag/OutlineRenderTag":291,"./component/tag/tag/OutlineTag":292,"./component/tag/tag/RenderTag":293,"./component/tag/tag/SpotRenderTag":294,"./component/tag/tag/SpotTag":295,"./component/tag/tag/Tag":296}],225:[function(require,module,exports){
19468 "use strict";
19469 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
19470 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
19471 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
19472 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
19473 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
19474 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
19475 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
19476 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
19477 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
19478 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
19479
19480 },{"./graph/edge/EdgeCalculator":314,"./graph/edge/EdgeCalculatorCoefficients":315,"./graph/edge/EdgeCalculatorDirections":316,"./graph/edge/EdgeCalculatorSettings":317,"./graph/edge/EdgeDirection":318}],226:[function(require,module,exports){
19481 "use strict";
19482 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
19483 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
19484 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
19485 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
19486 var MapillaryError_1 = require("./error/MapillaryError");
19487 exports.MapillaryError = MapillaryError_1.MapillaryError;
19488
19489 },{"./error/ArgumentMapillaryError":297,"./error/GraphMapillaryError":298,"./error/MapillaryError":299}],227:[function(require,module,exports){
19490 "use strict";
19491 var Camera_1 = require("./geo/Camera");
19492 exports.Camera = Camera_1.Camera;
19493 var GeoCoords_1 = require("./geo/GeoCoords");
19494 exports.GeoCoords = GeoCoords_1.GeoCoords;
19495 var ViewportCoords_1 = require("./geo/ViewportCoords");
19496 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
19497 var Spatial_1 = require("./geo/Spatial");
19498 exports.Spatial = Spatial_1.Spatial;
19499 var Transform_1 = require("./geo/Transform");
19500 exports.Transform = Transform_1.Transform;
19501
19502 },{"./geo/Camera":300,"./geo/GeoCoords":301,"./geo/Spatial":302,"./geo/Transform":303,"./geo/ViewportCoords":304}],228:[function(require,module,exports){
19503 "use strict";
19504 var FilterCreator_1 = require("./graph/FilterCreator");
19505 exports.FilterCreator = FilterCreator_1.FilterCreator;
19506 var Graph_1 = require("./graph/Graph");
19507 exports.Graph = Graph_1.Graph;
19508 var GraphCalculator_1 = require("./graph/GraphCalculator");
19509 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
19510 var GraphService_1 = require("./graph/GraphService");
19511 exports.GraphService = GraphService_1.GraphService;
19512 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
19513 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
19514 var MeshReader_1 = require("./graph/MeshReader");
19515 exports.MeshReader = MeshReader_1.MeshReader;
19516 var Node_1 = require("./graph/Node");
19517 exports.Node = Node_1.Node;
19518 var NodeCache_1 = require("./graph/NodeCache");
19519 exports.NodeCache = NodeCache_1.NodeCache;
19520 var Sequence_1 = require("./graph/Sequence");
19521 exports.Sequence = Sequence_1.Sequence;
19522
19523 },{"./graph/FilterCreator":305,"./graph/Graph":306,"./graph/GraphCalculator":307,"./graph/GraphService":308,"./graph/ImageLoadingService":309,"./graph/MeshReader":310,"./graph/Node":311,"./graph/NodeCache":312,"./graph/Sequence":313}],229:[function(require,module,exports){
19524 /**
19525  * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
19526  * @name Mapillary
19527  */
19528 "use strict";
19529 var Edge_1 = require("./Edge");
19530 exports.EdgeDirection = Edge_1.EdgeDirection;
19531 var Render_1 = require("./Render");
19532 exports.RenderMode = Render_1.RenderMode;
19533 var Viewer_1 = require("./Viewer");
19534 exports.ImageSize = Viewer_1.ImageSize;
19535 exports.Viewer = Viewer_1.Viewer;
19536 var TagComponent = require("./component/tag/Tag");
19537 exports.TagComponent = TagComponent;
19538 var MarkerComponent = require("./component/marker/Marker");
19539 exports.MarkerComponent = MarkerComponent;
19540
19541 },{"./Edge":225,"./Render":230,"./Viewer":234,"./component/marker/Marker":260,"./component/tag/Tag":276}],230:[function(require,module,exports){
19542 "use strict";
19543 var DOMRenderer_1 = require("./render/DOMRenderer");
19544 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
19545 var GLRenderer_1 = require("./render/GLRenderer");
19546 exports.GLRenderer = GLRenderer_1.GLRenderer;
19547 var GLRenderStage_1 = require("./render/GLRenderStage");
19548 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
19549 var RenderCamera_1 = require("./render/RenderCamera");
19550 exports.RenderCamera = RenderCamera_1.RenderCamera;
19551 var RenderMode_1 = require("./render/RenderMode");
19552 exports.RenderMode = RenderMode_1.RenderMode;
19553 var RenderService_1 = require("./render/RenderService");
19554 exports.RenderService = RenderService_1.RenderService;
19555
19556 },{"./render/DOMRenderer":319,"./render/GLRenderStage":320,"./render/GLRenderer":321,"./render/RenderCamera":322,"./render/RenderMode":323,"./render/RenderService":324}],231:[function(require,module,exports){
19557 "use strict";
19558 var State_1 = require("./state/State");
19559 exports.State = State_1.State;
19560 var StateBase_1 = require("./state/states/StateBase");
19561 exports.StateBase = StateBase_1.StateBase;
19562 var StateContext_1 = require("./state/StateContext");
19563 exports.StateContext = StateContext_1.StateContext;
19564 var StateService_1 = require("./state/StateService");
19565 exports.StateService = StateService_1.StateService;
19566 var TraversingState_1 = require("./state/states/TraversingState");
19567 exports.TraversingState = TraversingState_1.TraversingState;
19568 var WaitingState_1 = require("./state/states/WaitingState");
19569 exports.WaitingState = WaitingState_1.WaitingState;
19570
19571 },{"./state/State":325,"./state/StateContext":326,"./state/StateService":327,"./state/states/StateBase":328,"./state/states/TraversingState":329,"./state/states/WaitingState":330}],232:[function(require,module,exports){
19572 "use strict";
19573 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
19574 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
19575 var ImageTileStore_1 = require("./tiles/ImageTileStore");
19576 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
19577 var TextureProvider_1 = require("./tiles/TextureProvider");
19578 exports.TextureProvider = TextureProvider_1.TextureProvider;
19579 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
19580 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
19581
19582 },{"./tiles/ImageTileLoader":331,"./tiles/ImageTileStore":332,"./tiles/RegionOfInterestCalculator":333,"./tiles/TextureProvider":334}],233:[function(require,module,exports){
19583 "use strict";
19584 var EventEmitter_1 = require("./utils/EventEmitter");
19585 exports.EventEmitter = EventEmitter_1.EventEmitter;
19586 var Settings_1 = require("./utils/Settings");
19587 exports.Settings = Settings_1.Settings;
19588 var Urls_1 = require("./utils/Urls");
19589 exports.Urls = Urls_1.Urls;
19590
19591 },{"./utils/EventEmitter":335,"./utils/Settings":336,"./utils/Urls":337}],234:[function(require,module,exports){
19592 "use strict";
19593 var CacheService_1 = require("./viewer/CacheService");
19594 exports.CacheService = CacheService_1.CacheService;
19595 var ComponentController_1 = require("./viewer/ComponentController");
19596 exports.ComponentController = ComponentController_1.ComponentController;
19597 var Container_1 = require("./viewer/Container");
19598 exports.Container = Container_1.Container;
19599 var Observer_1 = require("./viewer/Observer");
19600 exports.Observer = Observer_1.Observer;
19601 var ImageSize_1 = require("./viewer/ImageSize");
19602 exports.ImageSize = ImageSize_1.ImageSize;
19603 var LoadingService_1 = require("./viewer/LoadingService");
19604 exports.LoadingService = LoadingService_1.LoadingService;
19605 var MouseService_1 = require("./viewer/MouseService");
19606 exports.MouseService = MouseService_1.MouseService;
19607 var Navigator_1 = require("./viewer/Navigator");
19608 exports.Navigator = Navigator_1.Navigator;
19609 var Projection_1 = require("./viewer/Projection");
19610 exports.Projection = Projection_1.Projection;
19611 var SpriteAlignment_1 = require("./viewer/SpriteAlignment");
19612 exports.SpriteAlignment = SpriteAlignment_1.SpriteAlignment;
19613 var SpriteService_1 = require("./viewer/SpriteService");
19614 exports.SpriteService = SpriteService_1.SpriteService;
19615 var TouchService_1 = require("./viewer/TouchService");
19616 exports.TouchService = TouchService_1.TouchService;
19617 var Viewer_1 = require("./viewer/Viewer");
19618 exports.Viewer = Viewer_1.Viewer;
19619
19620 },{"./viewer/CacheService":338,"./viewer/ComponentController":339,"./viewer/Container":340,"./viewer/ImageSize":341,"./viewer/LoadingService":342,"./viewer/MouseService":343,"./viewer/Navigator":344,"./viewer/Observer":345,"./viewer/Projection":346,"./viewer/SpriteAlignment":347,"./viewer/SpriteService":348,"./viewer/TouchService":349,"./viewer/Viewer":350}],235:[function(require,module,exports){
19621 /// <reference path="../../typings/index.d.ts" />
19622 "use strict";
19623 var Observable_1 = require("rxjs/Observable");
19624 require("rxjs/add/observable/defer");
19625 require("rxjs/add/observable/fromPromise");
19626 require("rxjs/add/operator/catch");
19627 require("rxjs/add/operator/map");
19628 var API_1 = require("../API");
19629 /**
19630  * @class APIv3
19631  *
19632  * @classdesc Provides methods for access of API v3.
19633  */
19634 var APIv3 = (function () {
19635     /**
19636      * Create a new api v3 instance.
19637      *
19638      * @param {number} clientId - Client id for API requests.
19639      * @param {number} [token] - Optional bearer token for API requests of
19640      * protected resources.
19641      * @param {ModelCreator} [creator] - Optional model creator instance.
19642      */
19643     function APIv3(clientId, token, creator) {
19644         this._clientId = clientId;
19645         this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
19646         this._model = this._modelCreator.createModel(clientId, token);
19647         this._pageCount = 999;
19648         this._pathImageByKey = "imageByKey";
19649         this._pathImageCloseTo = "imageCloseTo";
19650         this._pathImagesByH = "imagesByH";
19651         this._pathImageViewAdd = "imageViewAdd";
19652         this._pathSequenceByKey = "sequenceByKey";
19653         this._pathSequenceViewAdd = "sequenceViewAdd";
19654         this._propertiesCore = [
19655             "cl",
19656             "l",
19657             "sequence",
19658         ];
19659         this._propertiesFill = [
19660             "captured_at",
19661             "user",
19662             "project",
19663         ];
19664         this._propertiesKey = [
19665             "key",
19666         ];
19667         this._propertiesSequence = [
19668             "keys",
19669         ];
19670         this._propertiesSpatial = [
19671             "atomic_scale",
19672             "ca",
19673             "calt",
19674             "cca",
19675             "cfocal",
19676             "gpano",
19677             "height",
19678             "merge_cc",
19679             "merge_version",
19680             "c_rotation",
19681             "orientation",
19682             "width",
19683         ];
19684         this._propertiesUser = [
19685             "username",
19686         ];
19687     }
19688     ;
19689     APIv3.prototype.imageByKeyFill$ = function (keys) {
19690         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19691             this._pathImageByKey,
19692             keys,
19693             this._propertiesKey
19694                 .concat(this._propertiesFill)
19695                 .concat(this._propertiesSpatial),
19696             this._propertiesKey
19697                 .concat(this._propertiesUser)
19698         ]))
19699             .map(function (value) {
19700             return value.json.imageByKey;
19701         }), this._pathImageByKey, keys);
19702     };
19703     APIv3.prototype.imageByKeyFull$ = function (keys) {
19704         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19705             this._pathImageByKey,
19706             keys,
19707             this._propertiesKey
19708                 .concat(this._propertiesCore)
19709                 .concat(this._propertiesFill)
19710                 .concat(this._propertiesSpatial),
19711             this._propertiesKey
19712                 .concat(this._propertiesUser)
19713         ]))
19714             .map(function (value) {
19715             return value.json.imageByKey;
19716         }), this._pathImageByKey, keys);
19717     };
19718     APIv3.prototype.imageCloseTo$ = function (lat, lon) {
19719         var lonLat = lon + ":" + lat;
19720         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19721             this._pathImageCloseTo,
19722             [lonLat],
19723             this._propertiesKey
19724                 .concat(this._propertiesCore)
19725                 .concat(this._propertiesFill)
19726                 .concat(this._propertiesSpatial),
19727             this._propertiesKey
19728                 .concat(this._propertiesUser)
19729         ]))
19730             .map(function (value) {
19731             return value != null ? value.json.imageCloseTo[lonLat] : null;
19732         }), this._pathImageCloseTo, [lonLat]);
19733     };
19734     APIv3.prototype.imagesByH$ = function (hs) {
19735         var _this = this;
19736         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19737             this._pathImagesByH,
19738             hs,
19739             { from: 0, to: this._pageCount },
19740             this._propertiesKey
19741                 .concat(this._propertiesCore),
19742             this._propertiesKey
19743         ]))
19744             .map(function (value) {
19745             if (value == null) {
19746                 value = { json: { imagesByH: {} } };
19747                 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
19748                     var h = hs_1[_i];
19749                     value.json.imagesByH[h] = {};
19750                     for (var i = 0; i <= _this._pageCount; i++) {
19751                         value.json.imagesByH[h][i] = null;
19752                     }
19753                 }
19754             }
19755             return value.json.imagesByH;
19756         }), this._pathImagesByH, hs);
19757     };
19758     APIv3.prototype.imageViewAdd$ = function (keys) {
19759         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
19760     };
19761     APIv3.prototype.invalidateImageByKey = function (keys) {
19762         this._invalidateGet(this._pathImageByKey, keys);
19763     };
19764     APIv3.prototype.invalidateImagesByH = function (hs) {
19765         this._invalidateGet(this._pathImagesByH, hs);
19766     };
19767     APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
19768         this._invalidateGet(this._pathSequenceByKey, sKeys);
19769     };
19770     APIv3.prototype.setToken = function (token) {
19771         this._model.invalidate([]);
19772         this._model = null;
19773         this._model = this._modelCreator.createModel(this._clientId, token);
19774     };
19775     APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
19776         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19777             this._pathSequenceByKey,
19778             sequenceKeys,
19779             this._propertiesKey
19780                 .concat(this._propertiesSequence)
19781         ]))
19782             .map(function (value) {
19783             return value.json.sequenceByKey;
19784         }), this._pathSequenceByKey, sequenceKeys);
19785     };
19786     APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
19787         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
19788     };
19789     Object.defineProperty(APIv3.prototype, "clientId", {
19790         get: function () {
19791             return this._clientId;
19792         },
19793         enumerable: true,
19794         configurable: true
19795     });
19796     APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
19797         var _this = this;
19798         return observable
19799             .catch(function (error) {
19800             _this._invalidateGet(path, paths);
19801             throw error;
19802         });
19803     };
19804     APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
19805         var _this = this;
19806         return observable
19807             .catch(function (error) {
19808             _this._invalidateCall(path, paths);
19809             throw error;
19810         });
19811     };
19812     APIv3.prototype._invalidateGet = function (path, paths) {
19813         this._model.invalidate([path, paths]);
19814     };
19815     APIv3.prototype._invalidateCall = function (path, paths) {
19816         this._model.invalidate([path], [paths]);
19817     };
19818     APIv3.prototype._wrapPromise$ = function (promise) {
19819         return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
19820     };
19821     return APIv3;
19822 }());
19823 exports.APIv3 = APIv3;
19824 Object.defineProperty(exports, "__esModule", { value: true });
19825 exports.default = APIv3;
19826
19827 },{"../API":223,"rxjs/Observable":28,"rxjs/add/observable/defer":38,"rxjs/add/observable/fromPromise":42,"rxjs/add/operator/catch":51,"rxjs/add/operator/map":64}],236:[function(require,module,exports){
19828 /// <reference path="../../typings/index.d.ts" />
19829 "use strict";
19830 var falcor = require("falcor");
19831 var HttpDataSource = require("falcor-http-datasource");
19832 var Utils_1 = require("../Utils");
19833 /**
19834  * @class ModelCreator
19835  *
19836  * @classdesc Creates API models.
19837  */
19838 var ModelCreator = (function () {
19839     function ModelCreator() {
19840     }
19841     /**
19842      * Creates a Falcor model.
19843      *
19844      * @description Max cache size will be set to 16 MB. Authorization
19845      * header will be added if bearer token is supplied.
19846      *
19847      * @param {number} clientId - Client id for API requests.
19848      * @param {number} [token] - Optional bearer token for API requests of
19849      * protected resources.
19850      * @returns {falcor.Model} Falcor model for HTTP requests.
19851      */
19852     ModelCreator.prototype.createModel = function (clientId, token) {
19853         var configuration = {
19854             crossDomain: true,
19855             withCredentials: false,
19856         };
19857         if (token != null) {
19858             configuration.headers = { "Authorization": "Bearer " + token };
19859         }
19860         return new falcor.Model({
19861             maxSize: 16 * 1024 * 1024,
19862             source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
19863         });
19864     };
19865     return ModelCreator;
19866 }());
19867 exports.ModelCreator = ModelCreator;
19868 Object.defineProperty(exports, "__esModule", { value: true });
19869 exports.default = ModelCreator;
19870
19871 },{"../Utils":233,"falcor":13,"falcor-http-datasource":8}],237:[function(require,module,exports){
19872 /// <reference path="../../typings/index.d.ts" />
19873 "use strict";
19874 var __extends = (this && this.__extends) || function (d, b) {
19875     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19876     function __() { this.constructor = d; }
19877     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19878 };
19879 var vd = require("virtual-dom");
19880 var Component_1 = require("../Component");
19881 var AttributionComponent = (function (_super) {
19882     __extends(AttributionComponent, _super);
19883     function AttributionComponent(name, container, navigator) {
19884         return _super.call(this, name, container, navigator) || this;
19885     }
19886     AttributionComponent.prototype._activate = function () {
19887         var _this = this;
19888         this._disposable = this._navigator.stateService.currentNode$
19889             .map(function (node) {
19890             return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
19891         })
19892             .subscribe(this._container.domRenderer.render$);
19893     };
19894     AttributionComponent.prototype._deactivate = function () {
19895         this._disposable.unsubscribe();
19896     };
19897     AttributionComponent.prototype._getDefaultConfiguration = function () {
19898         return {};
19899     };
19900     AttributionComponent.prototype._getAttributionNode = function (username, photoId) {
19901         return vd.h("div.Attribution", {}, [
19902             vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
19903                 target: "_blank",
19904                 textContent: "@" + username,
19905             }, []),
19906             vd.h("span", { textContent: "|" }, []),
19907             vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo",
19908                 target: "_blank",
19909                 textContent: "mapillary.com",
19910             }, []),
19911         ]);
19912     };
19913     return AttributionComponent;
19914 }(Component_1.Component));
19915 AttributionComponent.componentName = "attribution";
19916 exports.AttributionComponent = AttributionComponent;
19917 Component_1.ComponentService.register(AttributionComponent);
19918 Object.defineProperty(exports, "__esModule", { value: true });
19919 exports.default = AttributionComponent;
19920
19921 },{"../Component":224,"virtual-dom":180}],238:[function(require,module,exports){
19922 /// <reference path="../../typings/index.d.ts" />
19923 "use strict";
19924 var __extends = (this && this.__extends) || function (d, b) {
19925     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19926     function __() { this.constructor = d; }
19927     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19928 };
19929 var vd = require("virtual-dom");
19930 var Component_1 = require("../Component");
19931 var BackgroundComponent = (function (_super) {
19932     __extends(BackgroundComponent, _super);
19933     function BackgroundComponent(name, container, navigator) {
19934         return _super.call(this, name, container, navigator) || this;
19935     }
19936     BackgroundComponent.prototype._activate = function () {
19937         this._container.domRenderer.render$
19938             .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") });
19939     };
19940     BackgroundComponent.prototype._deactivate = function () {
19941         return;
19942     };
19943     BackgroundComponent.prototype._getDefaultConfiguration = function () {
19944         return {};
19945     };
19946     BackgroundComponent.prototype._getBackgroundNode = function (notice) {
19947         // todo: add condition for when to display the DOM node
19948         return vd.h("div.BackgroundWrapper", {}, [
19949             vd.h("p", { textContent: notice }, []),
19950         ]);
19951     };
19952     return BackgroundComponent;
19953 }(Component_1.Component));
19954 BackgroundComponent.componentName = "background";
19955 exports.BackgroundComponent = BackgroundComponent;
19956 Component_1.ComponentService.register(BackgroundComponent);
19957 Object.defineProperty(exports, "__esModule", { value: true });
19958 exports.default = BackgroundComponent;
19959
19960 },{"../Component":224,"virtual-dom":180}],239:[function(require,module,exports){
19961 /// <reference path="../../typings/index.d.ts" />
19962 "use strict";
19963 var __extends = (this && this.__extends) || function (d, b) {
19964     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19965     function __() { this.constructor = d; }
19966     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19967 };
19968 var vd = require("virtual-dom");
19969 var Observable_1 = require("rxjs/Observable");
19970 var Component_1 = require("../Component");
19971 var Geo_1 = require("../Geo");
19972 var BearingComponent = (function (_super) {
19973     __extends(BearingComponent, _super);
19974     function BearingComponent(name, container, navigator) {
19975         var _this = _super.call(this, name, container, navigator) || this;
19976         _this._spatial = new Geo_1.Spatial();
19977         _this._svgNamespace = "http://www.w3.org/2000/svg";
19978         _this._distinctThreshold = Math.PI / 90;
19979         return _this;
19980     }
19981     BearingComponent.prototype._activate = function () {
19982         var _this = this;
19983         var nodeBearingFov$ = this._navigator.stateService.currentState$
19984             .distinctUntilChanged(undefined, function (frame) {
19985             return frame.state.currentNode.key;
19986         })
19987             .map(function (frame) {
19988             var node = frame.state.currentNode;
19989             var transform = frame.state.currentTransform;
19990             if (node.pano) {
19991                 var hFov_1 = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
19992                 return [_this._spatial.degToRad(node.ca), hFov_1];
19993             }
19994             var size = Math.max(transform.basicWidth, transform.basicHeight);
19995             if (size <= 0) {
19996                 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
19997                     "Not showing available fov.");
19998             }
19999             var hFov = size > 0 ?
20000                 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
20001                 0;
20002             return [_this._spatial.degToRad(node.ca), hFov];
20003         })
20004             .distinctUntilChanged(function (a1, a2) {
20005             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20006                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20007         });
20008         var cameraBearingFov$ = this._container.renderService.renderCamera$
20009             .map(function (rc) {
20010             var vFov = _this._spatial.degToRad(rc.perspective.fov);
20011             var hFov = Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
20012             return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
20013         })
20014             .distinctUntilChanged(function (a1, a2) {
20015             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20016                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20017         });
20018         this._renderSubscription = Observable_1.Observable
20019             .combineLatest(nodeBearingFov$, cameraBearingFov$)
20020             .map(function (args) {
20021             var background = vd.h("div.BearingIndicatorBackground", { oncontextmenu: function (event) { event.preventDefault(); } }, [
20022                 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
20023                 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
20024             ]);
20025             var north = vd.h("div.BearingIndicatorNorth", {}, []);
20026             var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
20027             var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
20028             var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
20029             return {
20030                 name: _this._name,
20031                 vnode: vd.h("div.BearingIndicator", {}, [
20032                     background,
20033                     north,
20034                     compass,
20035                 ]),
20036             };
20037         })
20038             .subscribe(this._container.domRenderer.render$);
20039     };
20040     BearingComponent.prototype._deactivate = function () {
20041         this._renderSubscription.unsubscribe();
20042     };
20043     BearingComponent.prototype._getDefaultConfiguration = function () {
20044         return {};
20045     };
20046     BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
20047         var group = vd.h("g", {
20048             attributes: { transform: "translate(1,1)" },
20049             namespace: this._svgNamespace,
20050         }, [nodeSector, cameraSector]);
20051         var centerCircle = vd.h("circle", {
20052             attributes: {
20053                 cx: "1",
20054                 cy: "1",
20055                 fill: "#abb1b9",
20056                 r: "0.291667",
20057                 stroke: "#000",
20058                 "stroke-width": "0.0833333",
20059             },
20060             namespace: this._svgNamespace,
20061         }, []);
20062         var svg = vd.h("svg", {
20063             attributes: { viewBox: "0 0 2 2" },
20064             namespace: this._svgNamespace,
20065             style: {
20066                 bottom: "4px",
20067                 height: "48px",
20068                 left: "4px",
20069                 position: "absolute",
20070                 width: "48px",
20071             },
20072         }, [group, centerCircle]);
20073         return svg;
20074     };
20075     BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
20076         if (fov > 2 * Math.PI - Math.PI / 90) {
20077             return vd.h("circle", {
20078                 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
20079                 namespace: this._svgNamespace,
20080             }, []);
20081         }
20082         var arcStart = bearing - fov / 2 - Math.PI / 2;
20083         var arcEnd = arcStart + fov;
20084         var startX = Math.cos(arcStart);
20085         var startY = Math.sin(arcStart);
20086         var endX = Math.cos(arcEnd);
20087         var endY = Math.sin(arcEnd);
20088         var largeArc = fov >= Math.PI ? 1 : 0;
20089         var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
20090         return vd.h("path", {
20091             attributes: { d: description, fill: fill },
20092             namespace: this._svgNamespace,
20093         }, []);
20094     };
20095     return BearingComponent;
20096 }(Component_1.Component));
20097 BearingComponent.componentName = "bearing";
20098 exports.BearingComponent = BearingComponent;
20099 Component_1.ComponentService.register(BearingComponent);
20100 Object.defineProperty(exports, "__esModule", { value: true });
20101 exports.default = BearingComponent;
20102
20103 },{"../Component":224,"../Geo":227,"rxjs/Observable":28,"virtual-dom":180}],240:[function(require,module,exports){
20104 "use strict";
20105 var __extends = (this && this.__extends) || function (d, b) {
20106     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20107     function __() { this.constructor = d; }
20108     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20109 };
20110 var Observable_1 = require("rxjs/Observable");
20111 require("rxjs/add/observable/combineLatest");
20112 require("rxjs/add/observable/from");
20113 require("rxjs/add/observable/merge");
20114 require("rxjs/add/observable/of");
20115 require("rxjs/add/observable/zip");
20116 require("rxjs/add/operator/catch");
20117 require("rxjs/add/operator/combineLatest");
20118 require("rxjs/add/operator/distinct");
20119 require("rxjs/add/operator/expand");
20120 require("rxjs/add/operator/filter");
20121 require("rxjs/add/operator/map");
20122 require("rxjs/add/operator/merge");
20123 require("rxjs/add/operator/mergeMap");
20124 require("rxjs/add/operator/mergeAll");
20125 require("rxjs/add/operator/skip");
20126 require("rxjs/add/operator/switchMap");
20127 var Edge_1 = require("../Edge");
20128 var Component_1 = require("../Component");
20129 var CacheComponent = (function (_super) {
20130     __extends(CacheComponent, _super);
20131     function CacheComponent(name, container, navigator) {
20132         return _super.call(this, name, container, navigator) || this;
20133     }
20134     /**
20135      * Set the cache depth.
20136      *
20137      * Configures the cache depth. The cache depth can be different for
20138      * different edge direction types.
20139      *
20140      * @param {ICacheDepth} depth - Cache depth structure.
20141      */
20142     CacheComponent.prototype.setDepth = function (depth) {
20143         this.configure({ depth: depth });
20144     };
20145     CacheComponent.prototype._activate = function () {
20146         var _this = this;
20147         this._sequenceSubscription = Observable_1.Observable
20148             .combineLatest(this._navigator.stateService.currentNode$
20149             .switchMap(function (node) {
20150             return node.sequenceEdges$;
20151         })
20152             .filter(function (status) {
20153             return status.cached;
20154         }), this._configuration$)
20155             .switchMap(function (nc) {
20156             var status = nc[0];
20157             var configuration = nc[1];
20158             var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
20159             var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
20160             var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
20161             return Observable_1.Observable
20162                 .merge(next$, prev$)
20163                 .catch(function (error, caught) {
20164                 console.error("Failed to cache sequence edges.", error);
20165                 return Observable_1.Observable.empty();
20166             });
20167         })
20168             .subscribe(function () { });
20169         this._spatialSubscription = this._navigator.stateService.currentNode$
20170             .switchMap(function (node) {
20171             return Observable_1.Observable
20172                 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
20173                 .filter(function (status) {
20174                 return status.cached;
20175             }));
20176         })
20177             .combineLatest(this._configuration$, function (ns, configuration) {
20178             return [ns[0], ns[1], configuration];
20179         })
20180             .switchMap(function (args) {
20181             var node = args[0];
20182             var edges = args[1].edges;
20183             var depth = args[2].depth;
20184             var panoDepth = Math.max(0, Math.min(2, depth.pano));
20185             var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
20186             var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
20187             var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
20188             var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
20189             var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
20190             var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
20191             var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
20192             var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
20193             var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
20194             var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
20195             return Observable_1.Observable
20196                 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
20197                 .catch(function (error, caught) {
20198                 console.error("Failed to cache spatial edges.", error);
20199                 return Observable_1.Observable.empty();
20200             });
20201         })
20202             .subscribe(function () { });
20203     };
20204     CacheComponent.prototype._deactivate = function () {
20205         this._sequenceSubscription.unsubscribe();
20206         this._spatialSubscription.unsubscribe();
20207     };
20208     CacheComponent.prototype._getDefaultConfiguration = function () {
20209         return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
20210     };
20211     CacheComponent.prototype._cache$ = function (edges, direction, depth) {
20212         var _this = this;
20213         return Observable_1.Observable
20214             .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
20215             .expand(function (ed) {
20216             var es = ed[0];
20217             var d = ed[1];
20218             var edgesDepths$ = [];
20219             if (d > 0) {
20220                 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
20221                     var edge = es_1[_i];
20222                     if (edge.data.direction === direction) {
20223                         edgesDepths$.push(Observable_1.Observable
20224                             .zip(_this._navigator.graphService.cacheNode$(edge.to)
20225                             .mergeMap(function (n) {
20226                             return _this._nodeToEdges$(n, direction);
20227                         }), Observable_1.Observable.of(d - 1)));
20228                     }
20229                 }
20230             }
20231             return Observable_1.Observable
20232                 .from(edgesDepths$)
20233                 .mergeAll();
20234         })
20235             .skip(1);
20236     };
20237     CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
20238         return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
20239             node.sequenceEdges$ :
20240             node.spatialEdges$)
20241             .first(function (status) {
20242             return status.cached;
20243         })
20244             .map(function (status) {
20245             return status.edges;
20246         });
20247     };
20248     return CacheComponent;
20249 }(Component_1.Component));
20250 CacheComponent.componentName = "cache";
20251 exports.CacheComponent = CacheComponent;
20252 Component_1.ComponentService.register(CacheComponent);
20253 Object.defineProperty(exports, "__esModule", { value: true });
20254 exports.default = CacheComponent;
20255
20256 },{"../Component":224,"../Edge":225,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/from":40,"rxjs/add/observable/merge":43,"rxjs/add/observable/of":44,"rxjs/add/observable/zip":47,"rxjs/add/operator/catch":51,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/distinct":56,"rxjs/add/operator/expand":59,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeAll":66,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/skip":74,"rxjs/add/operator/switchMap":78}],241:[function(require,module,exports){
20257 "use strict";
20258 var __extends = (this && this.__extends) || function (d, b) {
20259     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20260     function __() { this.constructor = d; }
20261     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20262 };
20263 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
20264 var Subject_1 = require("rxjs/Subject");
20265 require("rxjs/add/operator/publishReplay");
20266 require("rxjs/add/operator/scan");
20267 require("rxjs/add/operator/startWith");
20268 var Utils_1 = require("../Utils");
20269 var Component = (function (_super) {
20270     __extends(Component, _super);
20271     function Component(name, container, navigator) {
20272         var _this = _super.call(this) || this;
20273         _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
20274         _this._configurationSubject$ = new Subject_1.Subject();
20275         _this._activated = false;
20276         _this._container = container;
20277         _this._name = name;
20278         _this._navigator = navigator;
20279         _this._configuration$ =
20280             _this._configurationSubject$
20281                 .startWith(_this.defaultConfiguration)
20282                 .scan(function (conf, newConf) {
20283                 for (var key in newConf) {
20284                     if (newConf.hasOwnProperty(key)) {
20285                         conf[key] = newConf[key];
20286                     }
20287                 }
20288                 return conf;
20289             })
20290                 .publishReplay(1)
20291                 .refCount();
20292         _this._configuration$.subscribe(function () { });
20293         return _this;
20294     }
20295     Object.defineProperty(Component.prototype, "activated", {
20296         get: function () {
20297             return this._activated;
20298         },
20299         enumerable: true,
20300         configurable: true
20301     });
20302     Object.defineProperty(Component.prototype, "activated$", {
20303         get: function () {
20304             return this._activated$;
20305         },
20306         enumerable: true,
20307         configurable: true
20308     });
20309     Object.defineProperty(Component.prototype, "defaultConfiguration", {
20310         /**
20311          * Get default configuration.
20312          *
20313          * @returns {TConfiguration} Default configuration for component.
20314          */
20315         get: function () {
20316             return this._getDefaultConfiguration();
20317         },
20318         enumerable: true,
20319         configurable: true
20320     });
20321     Object.defineProperty(Component.prototype, "configuration$", {
20322         get: function () {
20323             return this._configuration$;
20324         },
20325         enumerable: true,
20326         configurable: true
20327     });
20328     Object.defineProperty(Component.prototype, "name", {
20329         get: function () {
20330             return this._name;
20331         },
20332         enumerable: true,
20333         configurable: true
20334     });
20335     Component.prototype.activate = function (conf) {
20336         if (this._activated) {
20337             return;
20338         }
20339         if (conf !== undefined) {
20340             this._configurationSubject$.next(conf);
20341         }
20342         this._activated = true;
20343         this._activate();
20344         this._activated$.next(true);
20345     };
20346     ;
20347     Component.prototype.configure = function (conf) {
20348         this._configurationSubject$.next(conf);
20349     };
20350     Component.prototype.deactivate = function () {
20351         if (!this._activated) {
20352             return;
20353         }
20354         this._activated = false;
20355         this._deactivate();
20356         this._container.domRenderer.clear(this._name);
20357         this._container.glRenderer.clear(this._name);
20358         this._activated$.next(false);
20359     };
20360     ;
20361     /**
20362      * Detect the viewer's new width and height and resize the component's
20363      * rendered elements accordingly if applicable.
20364      */
20365     Component.prototype.resize = function () { return; };
20366     return Component;
20367 }(Utils_1.EventEmitter));
20368 /**
20369  * Component name. Used when interacting with component through the Viewer's API.
20370  */
20371 Component.componentName = "not_worthy";
20372 exports.Component = Component;
20373 Object.defineProperty(exports, "__esModule", { value: true });
20374 exports.default = Component;
20375
20376 },{"../Utils":233,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/startWith":77}],242:[function(require,module,exports){
20377 /// <reference path="../../typings/index.d.ts" />
20378 "use strict";
20379 var _ = require("underscore");
20380 var Error_1 = require("../Error");
20381 var ComponentService = (function () {
20382     function ComponentService(container, navigator) {
20383         this._components = {};
20384         this._container = container;
20385         this._navigator = navigator;
20386         for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
20387             var component = _a[_i];
20388             this._components[component.componentName] = {
20389                 active: false,
20390                 component: new component(component.componentName, container, navigator),
20391             };
20392         }
20393         this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
20394         this._coverComponent.activate();
20395         this._coverActivated = true;
20396     }
20397     ComponentService.register = function (component) {
20398         if (ComponentService.registeredComponents[component.componentName] === undefined) {
20399             ComponentService.registeredComponents[component.componentName] = component;
20400         }
20401     };
20402     ComponentService.registerCover = function (coverComponent) {
20403         ComponentService.registeredCoverComponent = coverComponent;
20404     };
20405     ComponentService.prototype.activateCover = function () {
20406         if (this._coverActivated) {
20407             return;
20408         }
20409         this._coverActivated = true;
20410         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
20411             var component = _a[_i];
20412             if (component.active) {
20413                 component.component.deactivate();
20414             }
20415         }
20416         return;
20417     };
20418     ComponentService.prototype.deactivateCover = function () {
20419         if (!this._coverActivated) {
20420             return;
20421         }
20422         this._coverActivated = false;
20423         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
20424             var component = _a[_i];
20425             if (component.active) {
20426                 component.component.activate();
20427             }
20428         }
20429         return;
20430     };
20431     ComponentService.prototype.activate = function (name) {
20432         this._checkName(name);
20433         this._components[name].active = true;
20434         if (!this._coverActivated) {
20435             this.get(name).activate();
20436         }
20437     };
20438     ComponentService.prototype.configure = function (name, conf) {
20439         this._checkName(name);
20440         this.get(name).configure(conf);
20441     };
20442     ComponentService.prototype.deactivate = function (name) {
20443         this._checkName(name);
20444         this._components[name].active = false;
20445         if (!this._coverActivated) {
20446             this.get(name).deactivate();
20447         }
20448     };
20449     ComponentService.prototype.resize = function () {
20450         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
20451             var component = _a[_i];
20452             component.component.resize();
20453         }
20454     };
20455     ComponentService.prototype.get = function (name) {
20456         return this._components[name].component;
20457     };
20458     ComponentService.prototype.getCover = function () {
20459         return this._coverComponent;
20460     };
20461     ComponentService.prototype._checkName = function (name) {
20462         if (!(name in this._components)) {
20463             throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
20464         }
20465     };
20466     return ComponentService;
20467 }());
20468 ComponentService.registeredComponents = {};
20469 exports.ComponentService = ComponentService;
20470 Object.defineProperty(exports, "__esModule", { value: true });
20471 exports.default = ComponentService;
20472
20473 },{"../Error":226,"underscore":175}],243:[function(require,module,exports){
20474 /// <reference path="../../typings/index.d.ts" />
20475 "use strict";
20476 var __extends = (this && this.__extends) || function (d, b) {
20477     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20478     function __() { this.constructor = d; }
20479     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20480 };
20481 var vd = require("virtual-dom");
20482 require("rxjs/add/operator/filter");
20483 require("rxjs/add/operator/map");
20484 require("rxjs/add/operator/withLatestFrom");
20485 var Component_1 = require("../Component");
20486 var CoverComponent = (function (_super) {
20487     __extends(CoverComponent, _super);
20488     function CoverComponent(name, container, navigator) {
20489         return _super.call(this, name, container, navigator) || this;
20490     }
20491     CoverComponent.prototype._activate = function () {
20492         var _this = this;
20493         this._keyDisposable = this._navigator.stateService.currentNode$
20494             .withLatestFrom(this._configuration$, function (node, configuration) {
20495             return [node, configuration];
20496         })
20497             .filter(function (nc) {
20498             return nc[0].key !== nc[1].key;
20499         })
20500             .map(function (nc) { return nc[0]; })
20501             .map(function (node) {
20502             return { key: node.key, src: node.image.src };
20503         })
20504             .subscribe(this._configurationSubject$);
20505         this._disposable = this._configuration$
20506             .map(function (conf) {
20507             if (!conf.key) {
20508                 return { name: _this._name, vnode: vd.h("div", []) };
20509             }
20510             if (!conf.visible) {
20511                 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
20512             }
20513             return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
20514         })
20515             .subscribe(this._container.domRenderer.render$);
20516     };
20517     CoverComponent.prototype._deactivate = function () {
20518         this._disposable.unsubscribe();
20519         this._keyDisposable.unsubscribe();
20520     };
20521     CoverComponent.prototype._getDefaultConfiguration = function () {
20522         return { "loading": false, "visible": true };
20523     };
20524     CoverComponent.prototype._getCoverButtonVNode = function (conf) {
20525         var _this = this;
20526         var cover = conf.loading ? "div.Cover.CoverLoading" : "div.Cover";
20527         return vd.h(cover, [
20528             this._getCoverBackgroundVNode(conf),
20529             vd.h("button.CoverButton", { onclick: function () { _this.configure({ loading: true }); } }, ["Explore"]),
20530             vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
20531         ]);
20532     };
20533     CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
20534         var url = conf.src != null ?
20535             "url(" + conf.src + ")" :
20536             "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
20537         var properties = { style: { backgroundImage: url } };
20538         var children = [];
20539         if (conf.loading) {
20540             children.push(vd.h("div.Spinner", {}, []));
20541         }
20542         children.push(vd.h("div.CoverBackgroundGradient", {}, []));
20543         return vd.h("div.CoverBackground", properties, children);
20544     };
20545     return CoverComponent;
20546 }(Component_1.Component));
20547 CoverComponent.componentName = "cover";
20548 exports.CoverComponent = CoverComponent;
20549 Component_1.ComponentService.registerCover(CoverComponent);
20550 Object.defineProperty(exports, "__esModule", { value: true });
20551 exports.default = CoverComponent;
20552
20553 },{"../Component":224,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/withLatestFrom":82,"virtual-dom":180}],244:[function(require,module,exports){
20554 /// <reference path="../../typings/index.d.ts" />
20555 "use strict";
20556 var __extends = (this && this.__extends) || function (d, b) {
20557     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20558     function __() { this.constructor = d; }
20559     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20560 };
20561 var _ = require("underscore");
20562 var vd = require("virtual-dom");
20563 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
20564 require("rxjs/add/operator/combineLatest");
20565 var Component_1 = require("../Component");
20566 var DebugComponent = (function (_super) {
20567     __extends(DebugComponent, _super);
20568     function DebugComponent(name, container, navigator) {
20569         var _this = _super.call(this, name, container, navigator) || this;
20570         _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
20571         _this._displaying = false;
20572         return _this;
20573     }
20574     DebugComponent.prototype._activate = function () {
20575         var _this = this;
20576         this._disposable = this._navigator.stateService.currentState$
20577             .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
20578             return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
20579         })
20580             .subscribe(this._container.domRenderer.render$);
20581     };
20582     DebugComponent.prototype._deactivate = function () {
20583         this._disposable.unsubscribe();
20584     };
20585     DebugComponent.prototype._getDefaultConfiguration = function () {
20586         return {};
20587     };
20588     DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
20589         var ret = [];
20590         ret.push(vd.h("h2", "Node"));
20591         if (frame.state.currentNode) {
20592             ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
20593         }
20594         if (frame.state.previousNode) {
20595             ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
20596         }
20597         ret.push(vd.h("h2", "Loading"));
20598         var total = 0;
20599         var loaded = 0;
20600         var loading = 0;
20601         for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
20602             var loadStat = _a[_i];
20603             total += loadStat.loaded;
20604             if (loadStat.loaded !== loadStat.total) {
20605                 loading++;
20606             }
20607             else {
20608                 loaded++;
20609             }
20610         }
20611         ret.push(vd.h("p", "Loaded Images: " + loaded));
20612         ret.push(vd.h("p", "Loading Images: " + loading));
20613         ret.push(vd.h("p", "Total bytes loaded: " + total));
20614         ret.push(vd.h("h2", "Camera"));
20615         ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
20616         ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
20617         ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
20618         ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
20619         ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
20620         ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
20621         ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
20622         ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
20623         ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
20624         return ret;
20625     };
20626     DebugComponent.prototype._getDebugVNode = function (open, info) {
20627         if (open) {
20628             return vd.h("div.Debug", {}, [
20629                 vd.h("h2", {}, ["Debug"]),
20630                 this._getDebugVNodeButton(open),
20631                 vd.h("pre", {}, info),
20632             ]);
20633         }
20634         else {
20635             return this._getDebugVNodeButton(open);
20636         }
20637     };
20638     DebugComponent.prototype._getDebugVNodeButton = function (open) {
20639         var buttonText = open ? "Disable Debug" : "D";
20640         var buttonCssClass = open ? "" : ".DebugButtonFixed";
20641         if (open) {
20642             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
20643         }
20644         else {
20645             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
20646         }
20647     };
20648     DebugComponent.prototype._closeDebugElement = function (open) {
20649         this._open$.next(false);
20650     };
20651     DebugComponent.prototype._openDebugElement = function () {
20652         this._open$.next(true);
20653     };
20654     return DebugComponent;
20655 }(Component_1.Component));
20656 DebugComponent.componentName = "debug";
20657 exports.DebugComponent = DebugComponent;
20658 Component_1.ComponentService.register(DebugComponent);
20659 Object.defineProperty(exports, "__esModule", { value: true });
20660 exports.default = DebugComponent;
20661
20662 },{"../Component":224,"rxjs/BehaviorSubject":25,"rxjs/add/operator/combineLatest":52,"underscore":175,"virtual-dom":180}],245:[function(require,module,exports){
20663 /// <reference path="../../typings/index.d.ts" />
20664 "use strict";
20665 var __extends = (this && this.__extends) || function (d, b) {
20666     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20667     function __() { this.constructor = d; }
20668     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20669 };
20670 var vd = require("virtual-dom");
20671 require("rxjs/add/operator/combineLatest");
20672 var Component_1 = require("../Component");
20673 var ImageComponent = (function (_super) {
20674     __extends(ImageComponent, _super);
20675     function ImageComponent(name, container, navigator) {
20676         var _this = _super.call(this, name, container, navigator) || this;
20677         _this._canvasId = container.id + "-" + _this._name;
20678         return _this;
20679     }
20680     ImageComponent.prototype._activate = function () {
20681         var _this = this;
20682         this.drawSubscription = this._container.domRenderer.element$
20683             .combineLatest(this._navigator.stateService.currentNode$, function (element, node) {
20684             var canvas = document.getElementById(_this._canvasId);
20685             return { canvas: canvas, node: node };
20686         })
20687             .subscribe(function (canvasNode) {
20688             var canvas = canvasNode.canvas;
20689             var node = canvasNode.node;
20690             if (!node || !canvas) {
20691                 return null;
20692             }
20693             var adaptableDomRenderer = canvas.parentElement;
20694             var width = adaptableDomRenderer.offsetWidth;
20695             var height = adaptableDomRenderer.offsetHeight;
20696             canvas.width = width;
20697             canvas.height = height;
20698             var ctx = canvas.getContext("2d");
20699             ctx.drawImage(node.image, 0, 0, width, height);
20700         });
20701         this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
20702     };
20703     ImageComponent.prototype._deactivate = function () {
20704         this.drawSubscription.unsubscribe();
20705     };
20706     ImageComponent.prototype._getDefaultConfiguration = function () {
20707         return {};
20708     };
20709     return ImageComponent;
20710 }(Component_1.Component));
20711 ImageComponent.componentName = "image";
20712 exports.ImageComponent = ImageComponent;
20713 Component_1.ComponentService.register(ImageComponent);
20714 Object.defineProperty(exports, "__esModule", { value: true });
20715 exports.default = ImageComponent;
20716
20717 },{"../Component":224,"rxjs/add/operator/combineLatest":52,"virtual-dom":180}],246:[function(require,module,exports){
20718 "use strict";
20719 var __extends = (this && this.__extends) || function (d, b) {
20720     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20721     function __() { this.constructor = d; }
20722     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20723 };
20724 var Observable_1 = require("rxjs/Observable");
20725 require("rxjs/add/observable/fromEvent");
20726 require("rxjs/add/operator/withLatestFrom");
20727 var Edge_1 = require("../Edge");
20728 var Component_1 = require("../Component");
20729 var Geo_1 = require("../Geo");
20730 var KeyboardComponent = (function (_super) {
20731     __extends(KeyboardComponent, _super);
20732     function KeyboardComponent(name, container, navigator) {
20733         var _this = _super.call(this, name, container, navigator) || this;
20734         _this._spatial = new Geo_1.Spatial();
20735         _this._perspectiveDirections = [
20736             Edge_1.EdgeDirection.StepForward,
20737             Edge_1.EdgeDirection.StepBackward,
20738             Edge_1.EdgeDirection.StepLeft,
20739             Edge_1.EdgeDirection.StepRight,
20740             Edge_1.EdgeDirection.TurnLeft,
20741             Edge_1.EdgeDirection.TurnRight,
20742             Edge_1.EdgeDirection.TurnU,
20743         ];
20744         return _this;
20745     }
20746     KeyboardComponent.prototype._activate = function () {
20747         var _this = this;
20748         var sequenceEdges$ = this._navigator.stateService.currentNode$
20749             .switchMap(function (node) {
20750             return node.sequenceEdges$;
20751         });
20752         var spatialEdges$ = this._navigator.stateService.currentNode$
20753             .switchMap(function (node) {
20754             return node.spatialEdges$;
20755         });
20756         this._disposable = Observable_1.Observable
20757             .fromEvent(document, "keydown")
20758             .withLatestFrom(this._navigator.stateService.currentState$, sequenceEdges$, spatialEdges$, function (event, frame, sequenceEdges, spatialEdges) {
20759             return { event: event, frame: frame, sequenceEdges: sequenceEdges, spatialEdges: spatialEdges };
20760         })
20761             .subscribe(function (kf) {
20762             if (!kf.frame.state.currentNode.pano) {
20763                 _this._navigatePerspective(kf.event, kf.sequenceEdges, kf.spatialEdges);
20764             }
20765             else {
20766                 _this._navigatePanorama(kf.event, kf.sequenceEdges, kf.spatialEdges, kf.frame.state.camera);
20767             }
20768         });
20769     };
20770     KeyboardComponent.prototype._deactivate = function () {
20771         this._disposable.unsubscribe();
20772     };
20773     KeyboardComponent.prototype._getDefaultConfiguration = function () {
20774         return {};
20775     };
20776     KeyboardComponent.prototype._navigatePanorama = function (event, sequenceEdges, spatialEdges, camera) {
20777         var navigationAngle = 0;
20778         var stepDirection = null;
20779         var sequenceDirection = null;
20780         var phi = this._rotationFromCamera(camera).phi;
20781         switch (event.keyCode) {
20782             case 37:
20783                 if (event.shiftKey || event.altKey) {
20784                     break;
20785                 }
20786                 navigationAngle = Math.PI / 2 + phi;
20787                 stepDirection = Edge_1.EdgeDirection.StepLeft;
20788                 break;
20789             case 38:
20790                 if (event.shiftKey) {
20791                     break;
20792                 }
20793                 if (event.altKey) {
20794                     sequenceDirection = Edge_1.EdgeDirection.Next;
20795                     break;
20796                 }
20797                 navigationAngle = phi;
20798                 stepDirection = Edge_1.EdgeDirection.StepForward;
20799                 break;
20800             case 39:
20801                 if (event.shiftKey || event.altKey) {
20802                     break;
20803                 }
20804                 navigationAngle = -Math.PI / 2 + phi;
20805                 stepDirection = Edge_1.EdgeDirection.StepRight;
20806                 break;
20807             case 40:
20808                 if (event.shiftKey) {
20809                     break;
20810                 }
20811                 if (event.altKey) {
20812                     sequenceDirection = Edge_1.EdgeDirection.Prev;
20813                     break;
20814                 }
20815                 navigationAngle = Math.PI + phi;
20816                 stepDirection = Edge_1.EdgeDirection.StepBackward;
20817                 break;
20818             default:
20819                 return;
20820         }
20821         event.preventDefault();
20822         if (sequenceDirection != null) {
20823             this._moveInDir(sequenceDirection, sequenceEdges);
20824             return;
20825         }
20826         if (stepDirection == null || !spatialEdges.cached) {
20827             return;
20828         }
20829         navigationAngle = this._spatial.wrapAngle(navigationAngle);
20830         var threshold = Math.PI / 4;
20831         var edges = spatialEdges.edges.filter(function (e) {
20832             return e.data.direction === Edge_1.EdgeDirection.Pano ||
20833                 e.data.direction === stepDirection;
20834         });
20835         var smallestAngle = Number.MAX_VALUE;
20836         var toKey = null;
20837         for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
20838             var edge = edges_1[_i];
20839             var angle = Math.abs(this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
20840             if (angle < Math.min(smallestAngle, threshold)) {
20841                 smallestAngle = angle;
20842                 toKey = edge.to;
20843             }
20844         }
20845         if (toKey == null) {
20846             return;
20847         }
20848         this._navigator.moveToKey$(toKey)
20849             .subscribe(function (n) { return; }, function (e) { console.error(e); });
20850     };
20851     KeyboardComponent.prototype._rotationFromCamera = function (camera) {
20852         var direction = camera.lookat.clone().sub(camera.position);
20853         var upProjection = direction.clone().dot(camera.up);
20854         var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
20855         var phi = Math.atan2(planeProjection.y, planeProjection.x);
20856         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
20857         return { phi: phi, theta: theta };
20858     };
20859     KeyboardComponent.prototype._navigatePerspective = function (event, sequenceEdges, spatialEdges) {
20860         var direction = null;
20861         var sequenceDirection = null;
20862         switch (event.keyCode) {
20863             case 37:
20864                 if (event.altKey) {
20865                     break;
20866                 }
20867                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
20868                 break;
20869             case 38:
20870                 if (event.altKey) {
20871                     sequenceDirection = Edge_1.EdgeDirection.Next;
20872                     break;
20873                 }
20874                 direction = event.shiftKey ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
20875                 break;
20876             case 39:
20877                 if (event.altKey) {
20878                     break;
20879                 }
20880                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
20881                 break;
20882             case 40:
20883                 if (event.altKey) {
20884                     sequenceDirection = Edge_1.EdgeDirection.Prev;
20885                     break;
20886                 }
20887                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
20888                 break;
20889             default:
20890                 return;
20891         }
20892         event.preventDefault();
20893         if (sequenceDirection != null) {
20894             this._moveInDir(sequenceDirection, sequenceEdges);
20895             return;
20896         }
20897         this._moveInDir(direction, spatialEdges);
20898     };
20899     KeyboardComponent.prototype._moveInDir = function (direction, edgeStatus) {
20900         if (!edgeStatus.cached) {
20901             return;
20902         }
20903         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
20904             var edge = _a[_i];
20905             if (edge.data.direction === direction) {
20906                 this._navigator.moveToKey$(edge.to)
20907                     .subscribe(function (n) { return; }, function (e) { console.error(e); });
20908                 return;
20909             }
20910         }
20911     };
20912     return KeyboardComponent;
20913 }(Component_1.Component));
20914 KeyboardComponent.componentName = "keyboard";
20915 exports.KeyboardComponent = KeyboardComponent;
20916 Component_1.ComponentService.register(KeyboardComponent);
20917 Object.defineProperty(exports, "__esModule", { value: true });
20918 exports.default = KeyboardComponent;
20919
20920 },{"../Component":224,"../Edge":225,"../Geo":227,"rxjs/Observable":28,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/withLatestFrom":82}],247:[function(require,module,exports){
20921 /// <reference path="../../typings/index.d.ts" />
20922 "use strict";
20923 var __extends = (this && this.__extends) || function (d, b) {
20924     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20925     function __() { this.constructor = d; }
20926     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20927 };
20928 var _ = require("underscore");
20929 var vd = require("virtual-dom");
20930 require("rxjs/add/operator/combineLatest");
20931 var Component_1 = require("../Component");
20932 var LoadingComponent = (function (_super) {
20933     __extends(LoadingComponent, _super);
20934     function LoadingComponent(name, container, navigator) {
20935         return _super.call(this, name, container, navigator) || this;
20936     }
20937     LoadingComponent.prototype._activate = function () {
20938         var _this = this;
20939         this._loadingSubscription = this._navigator.loadingService.loading$
20940             .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) {
20941             if (!loading) {
20942                 return { name: "loading", vnode: _this._getBarVNode(100) };
20943             }
20944             var total = 0;
20945             var loaded = 0;
20946             for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
20947                 var loadStat = _a[_i];
20948                 if (loadStat.loaded !== loadStat.total) {
20949                     loaded += loadStat.loaded;
20950                     total += loadStat.total;
20951                 }
20952             }
20953             var percentage = 100;
20954             if (total !== 0) {
20955                 percentage = (loaded / total) * 100;
20956             }
20957             return { name: _this._name, vnode: _this._getBarVNode(percentage) };
20958         })
20959             .subscribe(this._container.domRenderer.render$);
20960     };
20961     LoadingComponent.prototype._deactivate = function () {
20962         this._loadingSubscription.unsubscribe();
20963     };
20964     LoadingComponent.prototype._getDefaultConfiguration = function () {
20965         return {};
20966     };
20967     LoadingComponent.prototype._getBarVNode = function (percentage) {
20968         var loadingBarStyle = {};
20969         var loadingContainerStyle = {};
20970         if (percentage !== 100) {
20971             loadingBarStyle.width = percentage.toFixed(0) + "%";
20972             loadingBarStyle.opacity = "1";
20973         }
20974         else {
20975             loadingBarStyle.width = "100%";
20976             loadingBarStyle.opacity = "0";
20977         }
20978         return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
20979     };
20980     return LoadingComponent;
20981 }(Component_1.Component));
20982 LoadingComponent.componentName = "loading";
20983 exports.LoadingComponent = LoadingComponent;
20984 Component_1.ComponentService.register(LoadingComponent);
20985 Object.defineProperty(exports, "__esModule", { value: true });
20986 exports.default = LoadingComponent;
20987
20988 },{"../Component":224,"rxjs/add/operator/combineLatest":52,"underscore":175,"virtual-dom":180}],248:[function(require,module,exports){
20989 /// <reference path="../../typings/index.d.ts" />
20990 "use strict";
20991 var __extends = (this && this.__extends) || function (d, b) {
20992     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20993     function __() { this.constructor = d; }
20994     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20995 };
20996 var vd = require("virtual-dom");
20997 var Observable_1 = require("rxjs/Observable");
20998 require("rxjs/add/operator/map");
20999 require("rxjs/add/operator/first");
21000 var Edge_1 = require("../Edge");
21001 var Component_1 = require("../Component");
21002 var NavigationComponent = (function (_super) {
21003     __extends(NavigationComponent, _super);
21004     function NavigationComponent(name, container, navigator) {
21005         var _this = _super.call(this, name, container, navigator) || this;
21006         _this._dirNames = {};
21007         _this._dirNames[Edge_1.EdgeDirection.StepForward] = "Forward";
21008         _this._dirNames[Edge_1.EdgeDirection.StepBackward] = "Backward";
21009         _this._dirNames[Edge_1.EdgeDirection.StepLeft] = "Left";
21010         _this._dirNames[Edge_1.EdgeDirection.StepRight] = "Right";
21011         _this._dirNames[Edge_1.EdgeDirection.TurnLeft] = "Turnleft";
21012         _this._dirNames[Edge_1.EdgeDirection.TurnRight] = "Turnright";
21013         _this._dirNames[Edge_1.EdgeDirection.TurnU] = "Turnaround";
21014         return _this;
21015     }
21016     NavigationComponent.prototype._activate = function () {
21017         var _this = this;
21018         this._renderSubscription = this._navigator.stateService.currentNode$
21019             .switchMap(function (node) {
21020             return node.pano ?
21021                 Observable_1.Observable.of([]) :
21022                 Observable_1.Observable.combineLatest(node.sequenceEdges$, node.spatialEdges$, function (seq, spa) {
21023                     return seq.edges.concat(spa.edges);
21024                 });
21025         })
21026             .map(function (edges) {
21027             var btns = [];
21028             for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
21029                 var edge = edges_1[_i];
21030                 var direction = edge.data.direction;
21031                 var name_1 = _this._dirNames[direction];
21032                 if (name_1 == null) {
21033                     continue;
21034                 }
21035                 btns.push(_this._createVNode(direction, name_1));
21036             }
21037             return { name: _this._name, vnode: vd.h("div.NavigationComponent", btns) };
21038         })
21039             .subscribe(this._container.domRenderer.render$);
21040     };
21041     NavigationComponent.prototype._deactivate = function () {
21042         this._renderSubscription.unsubscribe();
21043     };
21044     NavigationComponent.prototype._getDefaultConfiguration = function () {
21045         return {};
21046     };
21047     NavigationComponent.prototype._createVNode = function (direction, name) {
21048         var _this = this;
21049         return vd.h("span.Direction.Direction" + name, {
21050             onclick: function (ev) {
21051                 _this._navigator.moveDir$(direction)
21052                     .subscribe(function (node) { return; }, function (error) { console.error(error); });
21053             },
21054         }, []);
21055     };
21056     return NavigationComponent;
21057 }(Component_1.Component));
21058 NavigationComponent.componentName = "navigation";
21059 exports.NavigationComponent = NavigationComponent;
21060 Component_1.ComponentService.register(NavigationComponent);
21061 Object.defineProperty(exports, "__esModule", { value: true });
21062 exports.default = NavigationComponent;
21063
21064 },{"../Component":224,"../Edge":225,"rxjs/Observable":28,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"virtual-dom":180}],249:[function(require,module,exports){
21065 /// <reference path="../../typings/index.d.ts" />
21066 "use strict";
21067 var __extends = (this && this.__extends) || function (d, b) {
21068     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21069     function __() { this.constructor = d; }
21070     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21071 };
21072 var _ = require("underscore");
21073 var vd = require("virtual-dom");
21074 var Observable_1 = require("rxjs/Observable");
21075 require("rxjs/add/observable/fromPromise");
21076 require("rxjs/add/observable/of");
21077 require("rxjs/add/operator/combineLatest");
21078 require("rxjs/add/operator/distinct");
21079 require("rxjs/add/operator/distinctUntilChanged");
21080 require("rxjs/add/operator/filter");
21081 require("rxjs/add/operator/map");
21082 require("rxjs/add/operator/mergeMap");
21083 require("rxjs/add/operator/pluck");
21084 require("rxjs/add/operator/scan");
21085 var Component_1 = require("../Component");
21086 var DescriptionState = (function () {
21087     function DescriptionState() {
21088     }
21089     return DescriptionState;
21090 }());
21091 var RouteState = (function () {
21092     function RouteState() {
21093     }
21094     return RouteState;
21095 }());
21096 var RouteTrack = (function () {
21097     function RouteTrack() {
21098         this.nodeInstructions = [];
21099         this.nodeInstructionsOrdered = [];
21100     }
21101     return RouteTrack;
21102 }());
21103 var RouteComponent = (function (_super) {
21104     __extends(RouteComponent, _super);
21105     function RouteComponent(name, container, navigator) {
21106         return _super.call(this, name, container, navigator) || this;
21107     }
21108     RouteComponent.prototype._activate = function () {
21109         var _this = this;
21110         var _slowedStream$;
21111         _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
21112             return (frame.id % 2) === 0;
21113         }).filter(function (frame) {
21114             return frame.state.nodesAhead < 15;
21115         }).distinctUntilChanged(undefined, function (frame) {
21116             return frame.state.lastNode.key;
21117         });
21118         var _routeTrack$;
21119         _routeTrack$ = this.configuration$.mergeMap(function (conf) {
21120             return Observable_1.Observable.from(conf.paths);
21121         }).distinct(function (p) {
21122             return p.sequenceKey;
21123         }).mergeMap(function (path) {
21124             return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
21125                 .map(function (sequenceByKey) {
21126                 return sequenceByKey[path.sequenceKey];
21127             });
21128         }).combineLatest(this.configuration$, function (sequence, conf) {
21129             var i = 0;
21130             var instructionPlaces = [];
21131             for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
21132                 var path = _a[_i];
21133                 if (path.sequenceKey === sequence.key) {
21134                     var nodeInstructions = [];
21135                     var saveKey = false;
21136                     for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
21137                         var key = _c[_b];
21138                         if (path.startKey === key) {
21139                             saveKey = true;
21140                         }
21141                         if (saveKey) {
21142                             var description = null;
21143                             for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
21144                                 var infoKey = _e[_d];
21145                                 if (infoKey.key === key) {
21146                                     description = infoKey.description;
21147                                 }
21148                             }
21149                             nodeInstructions.push({ description: description, key: key });
21150                         }
21151                         if (path.stopKey === key) {
21152                             saveKey = false;
21153                         }
21154                     }
21155                     instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
21156                 }
21157                 i++;
21158             }
21159             return instructionPlaces;
21160         }).scan(function (routeTrack, instructionPlaces) {
21161             for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
21162                 var instructionPlace = instructionPlaces_1[_i];
21163                 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
21164             }
21165             routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
21166             return routeTrack;
21167         }, new RouteTrack());
21168         this._disposable = _slowedStream$
21169             .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
21170             return { conf: conf, frame: frame, routeTrack: routeTrack };
21171         }).scan(function (routeState, rtAndFrame) {
21172             if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
21173                 routeState.routeTrack = rtAndFrame.routeTrack;
21174                 routeState.currentNode = rtAndFrame.frame.state.currentNode;
21175                 routeState.lastNode = rtAndFrame.frame.state.lastNode;
21176                 routeState.playing = true;
21177             }
21178             else {
21179                 _this._navigator.stateService.cutNodes();
21180                 routeState.playing = false;
21181             }
21182             return routeState;
21183         }, new RouteState())
21184             .filter(function (routeState) {
21185             return routeState.playing;
21186         }).filter(function (routeState) {
21187             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21188                 var nodeInstruction = _a[_i];
21189                 if (!nodeInstruction) {
21190                     continue;
21191                 }
21192                 if (nodeInstruction.key === routeState.lastNode.key) {
21193                     return true;
21194                 }
21195             }
21196             return false;
21197         }).distinctUntilChanged(undefined, function (routeState) {
21198             return routeState.lastNode.key;
21199         }).mergeMap(function (routeState) {
21200             var i = 0;
21201             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21202                 var nodeInstruction = _a[_i];
21203                 if (nodeInstruction.key === routeState.lastNode.key) {
21204                     break;
21205                 }
21206                 i++;
21207             }
21208             var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
21209             if (!nextInstruction) {
21210                 return Observable_1.Observable.of(null);
21211             }
21212             return _this._navigator.graphService.cacheNode$(nextInstruction.key);
21213         }).combineLatest(this.configuration$, function (node, conf) {
21214             return { conf: conf, node: node };
21215         }).filter(function (cAN) {
21216             return cAN.node !== null && cAN.conf.playing;
21217         }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
21218         this._disposableDescription = this._navigator.stateService.currentNode$
21219             .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
21220             if (conf.playing !== undefined && !conf.playing) {
21221                 return "quit";
21222             }
21223             var description = null;
21224             for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
21225                 var nodeInstruction = _a[_i];
21226                 if (nodeInstruction.key === node.key) {
21227                     description = nodeInstruction.description;
21228                     break;
21229                 }
21230             }
21231             return description;
21232         }).scan(function (descriptionState, description) {
21233             if (description !== descriptionState.description && description !== null) {
21234                 descriptionState.description = description;
21235                 descriptionState.showsLeft = 6;
21236             }
21237             else {
21238                 descriptionState.showsLeft--;
21239             }
21240             if (description === "quit") {
21241                 descriptionState.description = null;
21242             }
21243             return descriptionState;
21244         }, new DescriptionState()).map(function (descriptionState) {
21245             if (descriptionState.showsLeft > 0 && descriptionState.description) {
21246                 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
21247             }
21248             else {
21249                 return { name: _this._name, vnode: vd.h("div", []) };
21250             }
21251         }).subscribe(this._container.domRenderer.render$);
21252     };
21253     RouteComponent.prototype._deactivate = function () {
21254         this._disposable.unsubscribe();
21255         this._disposableDescription.unsubscribe();
21256     };
21257     RouteComponent.prototype._getDefaultConfiguration = function () {
21258         return {};
21259     };
21260     RouteComponent.prototype.play = function () {
21261         this.configure({ playing: true });
21262     };
21263     RouteComponent.prototype.stop = function () {
21264         this.configure({ playing: false });
21265     };
21266     RouteComponent.prototype._getRouteAnnotationNode = function (description) {
21267         return vd.h("div.RouteFrame", {}, [
21268             vd.h("p", { textContent: description }, []),
21269         ]);
21270     };
21271     return RouteComponent;
21272 }(Component_1.Component));
21273 RouteComponent.componentName = "route";
21274 exports.RouteComponent = RouteComponent;
21275 Component_1.ComponentService.register(RouteComponent);
21276 Object.defineProperty(exports, "__esModule", { value: true });
21277 exports.default = RouteComponent;
21278
21279 },{"../Component":224,"rxjs/Observable":28,"rxjs/add/observable/fromPromise":42,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/distinct":56,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/pluck":69,"rxjs/add/operator/scan":72,"underscore":175,"virtual-dom":180}],250:[function(require,module,exports){
21280 "use strict";
21281 var __extends = (this && this.__extends) || function (d, b) {
21282     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21283     function __() { this.constructor = d; }
21284     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21285 };
21286 var Observable_1 = require("rxjs/Observable");
21287 require("rxjs/add/operator/buffer");
21288 require("rxjs/add/operator/debounceTime");
21289 require("rxjs/add/operator/filter");
21290 require("rxjs/add/operator/map");
21291 require("rxjs/add/operator/scan");
21292 var Component_1 = require("../Component");
21293 var StatsComponent = (function (_super) {
21294     __extends(StatsComponent, _super);
21295     function StatsComponent(name, container, navigator) {
21296         return _super.call(this, name, container, navigator) || this;
21297     }
21298     StatsComponent.prototype._activate = function () {
21299         var _this = this;
21300         this._sequenceSubscription = this._navigator.stateService.currentNode$
21301             .scan(function (keys, node) {
21302             var sKey = node.sequenceKey;
21303             keys.report = [];
21304             if (!(sKey in keys.reported)) {
21305                 keys.report = [sKey];
21306                 keys.reported[sKey] = true;
21307             }
21308             return keys;
21309         }, { report: [], reported: {} })
21310             .filter(function (keys) {
21311             return keys.report.length > 0;
21312         })
21313             .mergeMap(function (keys) {
21314             return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
21315                 .catch(function (error, caught) {
21316                 console.error("Failed to report sequence stats (" + keys.report + ")", error);
21317                 return Observable_1.Observable.empty();
21318             });
21319         })
21320             .subscribe(function () { });
21321         this._imageSubscription = this._navigator.stateService.currentNode$
21322             .map(function (node) {
21323             return node.key;
21324         })
21325             .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
21326             .scan(function (keys, newKeys) {
21327             keys.report = [];
21328             for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
21329                 var key = newKeys_1[_i];
21330                 if (!(key in keys.reported)) {
21331                     keys.report.push(key);
21332                     keys.reported[key] = true;
21333                 }
21334             }
21335             return keys;
21336         }, { report: [], reported: {} })
21337             .filter(function (keys) {
21338             return keys.report.length > 0;
21339         })
21340             .mergeMap(function (keys) {
21341             return _this._navigator.apiV3.imageViewAdd$(keys.report)
21342                 .catch(function (error, caught) {
21343                 console.error("Failed to report image stats (" + keys.report + ")", error);
21344                 return Observable_1.Observable.empty();
21345             });
21346         })
21347             .subscribe(function () { });
21348     };
21349     StatsComponent.prototype._deactivate = function () {
21350         this._sequenceSubscription.unsubscribe();
21351         this._imageSubscription.unsubscribe();
21352     };
21353     StatsComponent.prototype._getDefaultConfiguration = function () {
21354         return {};
21355     };
21356     return StatsComponent;
21357 }(Component_1.Component));
21358 StatsComponent.componentName = "stats";
21359 exports.StatsComponent = StatsComponent;
21360 Component_1.ComponentService.register(StatsComponent);
21361 Object.defineProperty(exports, "__esModule", { value: true });
21362 exports.default = StatsComponent;
21363
21364 },{"../Component":224,"rxjs/Observable":28,"rxjs/add/operator/buffer":48,"rxjs/add/operator/debounceTime":54,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/scan":72}],251:[function(require,module,exports){
21365 /// <reference path="../../../typings/index.d.ts" />
21366 "use strict";
21367 var __extends = (this && this.__extends) || function (d, b) {
21368     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21369     function __() { this.constructor = d; }
21370     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21371 };
21372 var vd = require("virtual-dom");
21373 var Observable_1 = require("rxjs/Observable");
21374 var Subject_1 = require("rxjs/Subject");
21375 require("rxjs/add/observable/combineLatest");
21376 require("rxjs/add/operator/do");
21377 require("rxjs/add/operator/distinctUntilChanged");
21378 require("rxjs/add/operator/filter");
21379 require("rxjs/add/operator/map");
21380 require("rxjs/add/operator/share");
21381 var Component_1 = require("../../Component");
21382 /**
21383  * @class DirectionComponent
21384  * @classdesc Component showing navigation arrows for steps and turns.
21385  */
21386 var DirectionComponent = (function (_super) {
21387     __extends(DirectionComponent, _super);
21388     function DirectionComponent(name, container, navigator) {
21389         var _this = _super.call(this, name, container, navigator) || this;
21390         _this._renderer = new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
21391         _this._hoveredKeySubject$ = new Subject_1.Subject();
21392         _this._hoveredKey$ = _this._hoveredKeySubject$.share();
21393         return _this;
21394     }
21395     Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
21396         /**
21397          * Get hovered key observable.
21398          *
21399          * @description An observable emitting the key of the node for the direction
21400          * arrow that is being hovered. When the mouse leaves a direction arrow null
21401          * is emitted.
21402          *
21403          * @returns {Observable<string>}
21404          */
21405         get: function () {
21406             return this._hoveredKey$;
21407         },
21408         enumerable: true,
21409         configurable: true
21410     });
21411     /**
21412      * Set highlight key.
21413      *
21414      * @description The arrow pointing towards the node corresponding to the
21415      * highlight key will be highlighted.
21416      *
21417      * @param {string} highlightKey Key of node to be highlighted if existing
21418      * among arrows.
21419      */
21420     DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
21421         this.configure({ highlightKey: highlightKey });
21422     };
21423     /**
21424      * Set min width of container element.
21425      *
21426      * @description  Set min width of the non transformed container element holding
21427      * the navigation arrows. If the min width is larger than the max width the
21428      * min width value will be used.
21429      *
21430      * The container element is automatically resized when the resize
21431      * method on the Viewer class is called.
21432      *
21433      * @param {number} minWidth
21434      */
21435     DirectionComponent.prototype.setMinWidth = function (minWidth) {
21436         this.configure({ minWidth: minWidth });
21437     };
21438     /**
21439      * Set max width of container element.
21440      *
21441      * @description Set max width of the non transformed container element holding
21442      * the navigation arrows. If the min width is larger than the max width the
21443      * min width value will be used.
21444      *
21445      * The container element is automatically resized when the resize
21446      * method on the Viewer class is called.
21447      *
21448      * @param {number} minWidth
21449      */
21450     DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
21451         this.configure({ maxWidth: maxWidth });
21452     };
21453     /** @inheritdoc */
21454     DirectionComponent.prototype.resize = function () {
21455         this._renderer.resize(this._container.element);
21456     };
21457     DirectionComponent.prototype._activate = function () {
21458         var _this = this;
21459         this._configurationSubscription = this._configuration$
21460             .subscribe(function (configuration) {
21461             _this._renderer.setConfiguration(configuration);
21462         });
21463         this._nodeSubscription = this._navigator.stateService.currentNode$
21464             .do(function (node) {
21465             _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
21466             _this._renderer.setNode(node);
21467         })
21468             .withLatestFrom(this._configuration$)
21469             .switchMap(function (nc) {
21470             var node = nc[0];
21471             var configuration = nc[1];
21472             return node.spatialEdges$
21473                 .withLatestFrom(configuration.distinguishSequence ?
21474                 _this._navigator.graphService
21475                     .cacheSequence$(node.sequenceKey)
21476                     .catch(function (error, caught) {
21477                     console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
21478                     return Observable_1.Observable.empty();
21479                 }) :
21480                 Observable_1.Observable.of(null));
21481         })
21482             .subscribe(function (es) {
21483             _this._renderer.setEdges(es[0], es[1]);
21484         });
21485         this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
21486             .do(function (renderCamera) {
21487             _this._renderer.setRenderCamera(renderCamera);
21488         })
21489             .map(function (renderCamera) {
21490             return _this._renderer;
21491         })
21492             .filter(function (renderer) {
21493             return renderer.needsRender;
21494         })
21495             .map(function (renderer) {
21496             return { name: _this._name, vnode: renderer.render(_this._navigator) };
21497         })
21498             .subscribe(this._container.domRenderer.render$);
21499         this._hoveredKeySubscription = Observable_1.Observable
21500             .combineLatest([
21501             this._container.domRenderer.element$,
21502             this._container.renderService.renderCamera$,
21503             this._container.mouseService.mouseMove$.startWith(null),
21504             this._container.mouseService.mouseUp$.startWith(null),
21505         ], function (e, rc, mm, mu) {
21506             return e;
21507         })
21508             .map(function (element) {
21509             var elements = element.getElementsByClassName("DirectionsPerspective");
21510             for (var i = 0; i < elements.length; i++) {
21511                 var hovered = elements.item(i).querySelector(":hover");
21512                 if (hovered != null && hovered.hasAttribute("data-key")) {
21513                     return hovered.getAttribute("data-key");
21514                 }
21515             }
21516             return null;
21517         })
21518             .distinctUntilChanged()
21519             .subscribe(this._hoveredKeySubject$);
21520     };
21521     DirectionComponent.prototype._deactivate = function () {
21522         this._configurationSubscription.unsubscribe();
21523         this._nodeSubscription.unsubscribe();
21524         this._renderCameraSubscription.unsubscribe();
21525         this._hoveredKeySubscription.unsubscribe();
21526     };
21527     DirectionComponent.prototype._getDefaultConfiguration = function () {
21528         return {
21529             distinguishSequence: false,
21530             maxWidth: 460,
21531             minWidth: 260,
21532         };
21533     };
21534     return DirectionComponent;
21535 }(Component_1.Component));
21536 /** @inheritdoc */
21537 DirectionComponent.componentName = "direction";
21538 exports.DirectionComponent = DirectionComponent;
21539 Component_1.ComponentService.register(DirectionComponent);
21540 Object.defineProperty(exports, "__esModule", { value: true });
21541 exports.default = DirectionComponent;
21542
21543 },{"../../Component":224,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/do":58,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/share":73,"virtual-dom":180}],252:[function(require,module,exports){
21544 "use strict";
21545 var Geo_1 = require("../../Geo");
21546 /**
21547  * @class DirectionDOMCalculator
21548  * @classdesc Helper class for calculating DOM CSS properties.
21549  */
21550 var DirectionDOMCalculator = (function () {
21551     function DirectionDOMCalculator(configuration, element) {
21552         this._spatial = new Geo_1.Spatial();
21553         this._minThresholdWidth = 320;
21554         this._maxThresholdWidth = 1480;
21555         this._minThresholdHeight = 240;
21556         this._maxThresholdHeight = 820;
21557         this._configure(configuration);
21558         this._resize(element);
21559         this._reset();
21560     }
21561     Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
21562         get: function () {
21563             return this._minWidth;
21564         },
21565         enumerable: true,
21566         configurable: true
21567     });
21568     Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
21569         get: function () {
21570             return this._maxWidth;
21571         },
21572         enumerable: true,
21573         configurable: true
21574     });
21575     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
21576         get: function () {
21577             return this._containerWidth;
21578         },
21579         enumerable: true,
21580         configurable: true
21581     });
21582     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
21583         get: function () {
21584             return this._containerWidthCss;
21585         },
21586         enumerable: true,
21587         configurable: true
21588     });
21589     Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
21590         get: function () {
21591             return this._containerMarginCss;
21592         },
21593         enumerable: true,
21594         configurable: true
21595     });
21596     Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
21597         get: function () {
21598             return this._containerLeftCss;
21599         },
21600         enumerable: true,
21601         configurable: true
21602     });
21603     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
21604         get: function () {
21605             return this._containerHeight;
21606         },
21607         enumerable: true,
21608         configurable: true
21609     });
21610     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
21611         get: function () {
21612             return this._containerHeightCss;
21613         },
21614         enumerable: true,
21615         configurable: true
21616     });
21617     Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
21618         get: function () {
21619             return this._containerBottomCss;
21620         },
21621         enumerable: true,
21622         configurable: true
21623     });
21624     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
21625         get: function () {
21626             return this._stepCircleSize;
21627         },
21628         enumerable: true,
21629         configurable: true
21630     });
21631     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
21632         get: function () {
21633             return this._stepCircleSizeCss;
21634         },
21635         enumerable: true,
21636         configurable: true
21637     });
21638     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
21639         get: function () {
21640             return this._stepCircleMarginCss;
21641         },
21642         enumerable: true,
21643         configurable: true
21644     });
21645     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
21646         get: function () {
21647             return this._turnCircleSize;
21648         },
21649         enumerable: true,
21650         configurable: true
21651     });
21652     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
21653         get: function () {
21654             return this._turnCircleSizeCss;
21655         },
21656         enumerable: true,
21657         configurable: true
21658     });
21659     Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
21660         get: function () {
21661             return this._outerRadius;
21662         },
21663         enumerable: true,
21664         configurable: true
21665     });
21666     Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
21667         get: function () {
21668             return this._innerRadius;
21669         },
21670         enumerable: true,
21671         configurable: true
21672     });
21673     Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
21674         get: function () {
21675             return this._shadowOffset;
21676         },
21677         enumerable: true,
21678         configurable: true
21679     });
21680     /**
21681      * Configures the min and max width values.
21682      *
21683      * @param {IDirectionConfiguration} configuration Configuration
21684      * with min and max width values.
21685      */
21686     DirectionDOMCalculator.prototype.configure = function (configuration) {
21687         this._configure(configuration);
21688         this._reset();
21689     };
21690     /**
21691      * Resizes all properties according to the width and height
21692      * of the element.
21693      *
21694      * @param {HTMLElement} element The container element from which to extract
21695      * the width and height.
21696      */
21697     DirectionDOMCalculator.prototype.resize = function (element) {
21698         this._resize(element);
21699         this._reset();
21700     };
21701     /**
21702      * Calculates the coordinates on the unit circle for an angle.
21703      *
21704      * @param {number} angle Angle in radians.
21705      * @returns {Array<number>} The x and y coordinates on the unit circle.
21706      */
21707     DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
21708         return [Math.cos(angle), Math.sin(angle)];
21709     };
21710     /**
21711      * Calculates the coordinates on the unit circle for the
21712      * relative angle between the first and second angle.
21713      *
21714      * @param {number} first Angle in radians.
21715      * @param {number} second Angle in radians.
21716      * @returns {Array<number>} The x and y coordinates on the unit circle
21717      * for the relative angle between the first and second angle.
21718      */
21719     DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
21720         var relativeAngle = this._spatial.wrapAngle(first - second);
21721         return this.angleToCoordinates(relativeAngle);
21722     };
21723     DirectionDOMCalculator.prototype._configure = function (configuration) {
21724         this._minWidth = configuration.minWidth;
21725         this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
21726     };
21727     DirectionDOMCalculator.prototype._resize = function (element) {
21728         this._elementWidth = element.offsetWidth;
21729         this._elementHeight = element.offsetHeight;
21730     };
21731     DirectionDOMCalculator.prototype._reset = function () {
21732         this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
21733         this._containerHeight = this._getContainerHeight(this.containerWidth);
21734         this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
21735         this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
21736         this._outerRadius = this._getOuterRadius(this._containerHeight);
21737         this._innerRadius = this._getInnerRadius(this._containerHeight);
21738         this._shadowOffset = 3;
21739         this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
21740         this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
21741         this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
21742         this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
21743         this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
21744         this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
21745         this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
21746         this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
21747     };
21748     DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
21749         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
21750         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
21751         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
21752         coeff = 0.04 * Math.round(25 * coeff);
21753         return this._minWidth + coeff * (this._maxWidth - this._minWidth);
21754     };
21755     DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
21756         return 0.77 * containerWidth;
21757     };
21758     DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
21759         return 0.34 * containerHeight;
21760     };
21761     DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
21762         return 0.3 * containerHeight;
21763     };
21764     DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
21765         return 0.31 * containerHeight;
21766     };
21767     DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
21768         return 0.125 * containerHeight;
21769     };
21770     DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
21771         return value + "px";
21772     };
21773     DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
21774         return value > minWidth ? value : minWidth;
21775     };
21776     return DirectionDOMCalculator;
21777 }());
21778 exports.DirectionDOMCalculator = DirectionDOMCalculator;
21779 Object.defineProperty(exports, "__esModule", { value: true });
21780 exports.default = DirectionDOMCalculator;
21781
21782 },{"../../Geo":227}],253:[function(require,module,exports){
21783 /// <reference path="../../../typings/index.d.ts" />
21784 "use strict";
21785 var vd = require("virtual-dom");
21786 var Component_1 = require("../../Component");
21787 var Edge_1 = require("../../Edge");
21788 var Geo_1 = require("../../Geo");
21789 /**
21790  * @class DirectionDOMRenderer
21791  * @classdesc DOM renderer for direction arrows.
21792  */
21793 var DirectionDOMRenderer = (function () {
21794     function DirectionDOMRenderer(configuration, element) {
21795         this._isEdge = false;
21796         this._spatial = new Geo_1.Spatial();
21797         this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
21798         this._node = null;
21799         this._rotation = { phi: 0, theta: 0 };
21800         this._epsilon = 0.5 * Math.PI / 180;
21801         this._highlightKey = null;
21802         this._distinguishSequence = false;
21803         this._needsRender = false;
21804         this._stepEdges = [];
21805         this._turnEdges = [];
21806         this._panoEdges = [];
21807         this._sequenceEdgeKeys = [];
21808         this._stepDirections = [
21809             Edge_1.EdgeDirection.StepForward,
21810             Edge_1.EdgeDirection.StepBackward,
21811             Edge_1.EdgeDirection.StepLeft,
21812             Edge_1.EdgeDirection.StepRight,
21813         ];
21814         this._turnDirections = [
21815             Edge_1.EdgeDirection.TurnLeft,
21816             Edge_1.EdgeDirection.TurnRight,
21817             Edge_1.EdgeDirection.TurnU,
21818         ];
21819         this._turnNames = {};
21820         this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
21821         this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
21822         this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
21823         // detects IE 8-11, then Edge 20+.
21824         var isIE = !!document.documentMode;
21825         this._isEdge = !isIE && !!window.StyleMedia;
21826     }
21827     Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
21828         /**
21829          * Get needs render.
21830          *
21831          * @returns {boolean} Value indicating whether render should be called.
21832          */
21833         get: function () {
21834             return this._needsRender;
21835         },
21836         enumerable: true,
21837         configurable: true
21838     });
21839     /**
21840      * Renders virtual DOM elements.
21841      *
21842      * @description Calling render resets the needs render property.
21843      */
21844     DirectionDOMRenderer.prototype.render = function (navigator) {
21845         this._needsRender = false;
21846         var rotation = this._rotation;
21847         var steps = [];
21848         var turns = [];
21849         if (this._node.pano) {
21850             steps = steps.concat(this._createPanoArrows(navigator, rotation));
21851         }
21852         else {
21853             steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
21854             steps = steps.concat(this._createStepArrows(navigator, rotation));
21855             turns = turns.concat(this._createTurnArrows(navigator));
21856         }
21857         return this._getContainer(steps, turns, rotation);
21858     };
21859     DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
21860         this._setEdges(edgeStatus, sequence);
21861         this._setNeedsRender();
21862     };
21863     /**
21864      * Set node for which to show edges.
21865      *
21866      * @param {Node} node
21867      */
21868     DirectionDOMRenderer.prototype.setNode = function (node) {
21869         this._node = node;
21870         this._clearEdges();
21871         this._setNeedsRender();
21872     };
21873     /**
21874      * Set the render camera to use for calculating rotations.
21875      *
21876      * @param {RenderCamera} renderCamera
21877      */
21878     DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
21879         var rotation = renderCamera.rotation;
21880         if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
21881             return;
21882         }
21883         this._rotation = rotation;
21884         this._setNeedsRender();
21885     };
21886     /**
21887      * Set configuration values.
21888      *
21889      * @param {IDirectionConfiguration} configuration
21890      */
21891     DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
21892         var needsRender = false;
21893         if (this._highlightKey !== configuration.highlightKey ||
21894             this._distinguishSequence !== configuration.distinguishSequence) {
21895             this._highlightKey = configuration.highlightKey;
21896             this._distinguishSequence = configuration.distinguishSequence;
21897             needsRender = true;
21898         }
21899         if (this._calculator.minWidth !== configuration.minWidth ||
21900             this._calculator.maxWidth !== configuration.maxWidth) {
21901             this._calculator.configure(configuration);
21902             needsRender = true;
21903         }
21904         if (needsRender) {
21905             this._setNeedsRender();
21906         }
21907     };
21908     /**
21909      * Detect the element's width and height and resize
21910      * elements accordingly.
21911      *
21912      * @param {HTMLElement} element Viewer container element.
21913      */
21914     DirectionDOMRenderer.prototype.resize = function (element) {
21915         this._calculator.resize(element);
21916         this._setNeedsRender();
21917     };
21918     DirectionDOMRenderer.prototype._setNeedsRender = function () {
21919         if (this._node != null) {
21920             this._needsRender = true;
21921         }
21922     };
21923     DirectionDOMRenderer.prototype._clearEdges = function () {
21924         this._stepEdges = [];
21925         this._turnEdges = [];
21926         this._panoEdges = [];
21927         this._sequenceEdgeKeys = [];
21928     };
21929     DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
21930         this._stepEdges = [];
21931         this._turnEdges = [];
21932         this._panoEdges = [];
21933         this._sequenceEdgeKeys = [];
21934         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
21935             var edge = _a[_i];
21936             var direction = edge.data.direction;
21937             if (this._stepDirections.indexOf(direction) > -1) {
21938                 this._stepEdges.push(edge);
21939                 continue;
21940             }
21941             if (this._turnDirections.indexOf(direction) > -1) {
21942                 this._turnEdges.push(edge);
21943                 continue;
21944             }
21945             if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
21946                 this._panoEdges.push(edge);
21947             }
21948         }
21949         if (this._distinguishSequence && sequence != null) {
21950             var edges = this._panoEdges
21951                 .concat(this._stepEdges)
21952                 .concat(this._turnEdges);
21953             for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
21954                 var edge = edges_1[_b];
21955                 var edgeKey = edge.to;
21956                 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
21957                     var sequenceKey = _d[_c];
21958                     if (sequenceKey === edgeKey) {
21959                         this._sequenceEdgeKeys.push(edgeKey);
21960                         break;
21961                     }
21962                 }
21963             }
21964         }
21965     };
21966     DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
21967         var arrows = [];
21968         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
21969             var panoEdge = _a[_i];
21970             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
21971         }
21972         for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
21973             var stepEdge = _c[_b];
21974             arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
21975         }
21976         return arrows;
21977     };
21978     DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
21979         var threshold = Math.PI / 8;
21980         var relativePhi = rotation.phi;
21981         switch (direction) {
21982             case Edge_1.EdgeDirection.StepBackward:
21983                 relativePhi = rotation.phi - Math.PI;
21984                 break;
21985             case Edge_1.EdgeDirection.StepLeft:
21986                 relativePhi = rotation.phi + Math.PI / 2;
21987                 break;
21988             case Edge_1.EdgeDirection.StepRight:
21989                 relativePhi = rotation.phi - Math.PI / 2;
21990                 break;
21991             default:
21992                 break;
21993         }
21994         if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
21995             return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
21996         }
21997         return this._createVNodeDisabled(key, azimuth, rotation);
21998     };
21999     DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
22000         var arrows = [];
22001         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22002             var panoEdge = _a[_i];
22003             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
22004         }
22005         return arrows;
22006     };
22007     DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
22008         var arrows = [];
22009         for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
22010             var stepEdge = _a[_i];
22011             arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22012         }
22013         return arrows;
22014     };
22015     DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
22016         var turns = [];
22017         for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
22018             var turnEdge = _a[_i];
22019             var direction = turnEdge.data.direction;
22020             var name_1 = this._turnNames[direction];
22021             turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
22022         }
22023         return turns;
22024     };
22025     DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
22026         var onClick = function (e) {
22027             navigator.moveToKey$(key)
22028                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22029         };
22030         return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
22031     };
22032     DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
22033         var onClick = function (e) {
22034             navigator.moveDir$(direction)
22035                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22036         };
22037         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
22038     };
22039     DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
22040         var onClick = function (e) {
22041             navigator.moveDir$(direction)
22042                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22043         };
22044         var style = {
22045             height: this._calculator.turnCircleSizeCss,
22046             transform: "rotate(0)",
22047             width: this._calculator.turnCircleSizeCss,
22048         };
22049         switch (direction) {
22050             case Edge_1.EdgeDirection.TurnLeft:
22051                 style.left = "5px";
22052                 style.top = "5px";
22053                 break;
22054             case Edge_1.EdgeDirection.TurnRight:
22055                 style.right = "5px";
22056                 style.top = "5px";
22057                 break;
22058             case Edge_1.EdgeDirection.TurnU:
22059                 style.left = "5px";
22060                 style.bottom = "5px";
22061                 break;
22062             default:
22063                 break;
22064         }
22065         var circleProperties = {
22066             attributes: {
22067                 "data-key": key,
22068             },
22069             onclick: onClick,
22070             style: style,
22071         };
22072         var circleClassName = "TurnCircle";
22073         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22074             circleClassName += "Sequence";
22075         }
22076         if (this._highlightKey === key) {
22077             circleClassName += "Highlight";
22078         }
22079         var turn = vd.h("div." + className, {}, []);
22080         return vd.h("div." + circleClassName, circleProperties, [turn]);
22081     };
22082     DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
22083         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
22084     };
22085     DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
22086         var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
22087         // rotate 90 degrees clockwise and flip over X-axis
22088         var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
22089         var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
22090         var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
22091         var shadowOffset = this._calculator.shadowOffset;
22092         var shadowTranslationX = -shadowOffset * shadowTranslation[1];
22093         var shadowTranslationY = shadowOffset * shadowTranslation[0];
22094         var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
22095         var properties = {
22096             style: {
22097                 "-webkit-filter": filter,
22098                 filter: filter,
22099             },
22100         };
22101         var chevron = vd.h("div." + className, properties, []);
22102         var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
22103         var circleTransform = shiftVertically ?
22104             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
22105             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
22106         var circleProperties = {
22107             attributes: { "data-key": key },
22108             onclick: onClick,
22109             style: {
22110                 height: this._calculator.stepCircleSizeCss,
22111                 marginLeft: this._calculator.stepCircleMarginCss,
22112                 marginTop: this._calculator.stepCircleMarginCss,
22113                 transform: circleTransform,
22114                 width: this._calculator.stepCircleSizeCss,
22115             },
22116         };
22117         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22118             circleClassName += "Sequence";
22119         }
22120         if (this._highlightKey === key) {
22121             circleClassName += "Highlight";
22122         }
22123         return vd.h("div." + circleClassName, circleProperties, [chevron]);
22124     };
22125     DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
22126         // edge does not handle hover on perspective transforms.
22127         var transform = this._isEdge ?
22128             "rotateX(60deg)" :
22129             "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
22130         var properties = {
22131             oncontextmenu: function (event) { event.preventDefault(); },
22132             style: {
22133                 bottom: this._calculator.containerBottomCss,
22134                 height: this._calculator.containerHeightCss,
22135                 left: this._calculator.containerLeftCss,
22136                 marginLeft: this._calculator.containerMarginCss,
22137                 transform: transform,
22138                 width: this._calculator.containerWidthCss,
22139             },
22140         };
22141         return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
22142     };
22143     return DirectionDOMRenderer;
22144 }());
22145 exports.DirectionDOMRenderer = DirectionDOMRenderer;
22146 Object.defineProperty(exports, "__esModule", { value: true });
22147 exports.default = DirectionDOMRenderer;
22148
22149 },{"../../Component":224,"../../Edge":225,"../../Geo":227,"virtual-dom":180}],254:[function(require,module,exports){
22150 "use strict";
22151 var __extends = (this && this.__extends) || function (d, b) {
22152     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
22153     function __() { this.constructor = d; }
22154     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22155 };
22156 var Observable_1 = require("rxjs/Observable");
22157 var Subject_1 = require("rxjs/Subject");
22158 require("rxjs/add/operator/catch");
22159 require("rxjs/add/operator/combineLatest");
22160 require("rxjs/add/operator/debounceTime");
22161 require("rxjs/add/operator/distinctUntilChanged");
22162 require("rxjs/add/operator/filter");
22163 require("rxjs/add/operator/map");
22164 require("rxjs/add/operator/pairwise");
22165 require("rxjs/add/operator/publish");
22166 require("rxjs/add/operator/publishReplay");
22167 require("rxjs/add/operator/scan");
22168 require("rxjs/add/operator/skipWhile");
22169 require("rxjs/add/operator/startWith");
22170 require("rxjs/add/operator/switchMap");
22171 require("rxjs/add/operator/takeUntil");
22172 require("rxjs/add/operator/withLatestFrom");
22173 var Component_1 = require("../../Component");
22174 var Render_1 = require("../../Render");
22175 var Tiles_1 = require("../../Tiles");
22176 var Utils_1 = require("../../Utils");
22177 var ImagePlaneComponent = (function (_super) {
22178     __extends(ImagePlaneComponent, _super);
22179     function ImagePlaneComponent(name, container, navigator) {
22180         var _this = _super.call(this, name, container, navigator) || this;
22181         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
22182         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
22183         _this._rendererOperation$ = new Subject_1.Subject();
22184         _this._rendererCreator$ = new Subject_1.Subject();
22185         _this._rendererDisposer$ = new Subject_1.Subject();
22186         _this._renderer$ = _this._rendererOperation$
22187             .scan(function (renderer, operation) {
22188             return operation(renderer);
22189         }, null)
22190             .filter(function (renderer) {
22191             return renderer != null;
22192         })
22193             .distinctUntilChanged(undefined, function (renderer) {
22194             return renderer.frameId;
22195         });
22196         _this._rendererCreator$
22197             .map(function () {
22198             return function (renderer) {
22199                 if (renderer != null) {
22200                     throw new Error("Multiple image plane states can not be created at the same time");
22201                 }
22202                 return new Component_1.ImagePlaneGLRenderer();
22203             };
22204         })
22205             .subscribe(_this._rendererOperation$);
22206         _this._rendererDisposer$
22207             .map(function () {
22208             return function (renderer) {
22209                 renderer.dispose();
22210                 return null;
22211             };
22212         })
22213             .subscribe(_this._rendererOperation$);
22214         return _this;
22215     }
22216     ImagePlaneComponent.prototype._activate = function () {
22217         var _this = this;
22218         this._rendererSubscription = this._renderer$
22219             .map(function (renderer) {
22220             var renderHash = {
22221                 name: _this._name,
22222                 render: {
22223                     frameId: renderer.frameId,
22224                     needsRender: renderer.needsRender,
22225                     render: renderer.render.bind(renderer),
22226                     stage: Render_1.GLRenderStage.Background,
22227                 },
22228             };
22229             renderer.clearNeedsRender();
22230             return renderHash;
22231         })
22232             .subscribe(this._container.glRenderer.render$);
22233         this._rendererCreator$.next(null);
22234         this._stateSubscription = this._navigator.stateService.currentState$
22235             .map(function (frame) {
22236             return function (renderer) {
22237                 renderer.updateFrame(frame);
22238                 return renderer;
22239             };
22240         })
22241             .subscribe(this._rendererOperation$);
22242         var textureProvider$ = this._navigator.stateService.currentState$
22243             .distinctUntilChanged(undefined, function (frame) {
22244             return frame.state.currentNode.key;
22245         })
22246             .combineLatest(this._configuration$)
22247             .filter(function (args) {
22248             return args[1].imageTiling === true;
22249         })
22250             .map(function (args) {
22251             return args[0];
22252         })
22253             .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
22254             .map(function (args) {
22255             var state = args[0].state;
22256             var renderer = args[1];
22257             var viewportSize = args[2];
22258             var currentNode = state.currentNode;
22259             var currentTransform = state.currentTransform;
22260             var tileSize = Math.max(viewportSize.width, viewportSize.height) > 1024 ? 1024 : 512;
22261             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
22262         })
22263             .publishReplay(1)
22264             .refCount();
22265         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
22266         this._setTextureProviderSubscription = textureProvider$
22267             .map(function (provider) {
22268             return function (renderer) {
22269                 renderer.setTextureProvider(provider.key, provider);
22270                 return renderer;
22271             };
22272         })
22273             .subscribe(this._rendererOperation$);
22274         this._abortTextureProviderSubscription = textureProvider$
22275             .pairwise()
22276             .subscribe(function (pair) {
22277             var previous = pair[0];
22278             previous.abort();
22279         });
22280         var roiTrigger$ = this._container.renderService.renderCameraFrame$
22281             .map(function (renderCamera) {
22282             return [
22283                 renderCamera.camera.position.clone(),
22284                 renderCamera.camera.lookat.clone(),
22285                 renderCamera.zoom.valueOf()
22286             ];
22287         })
22288             .pairwise()
22289             .skipWhile(function (pls) {
22290             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
22291         })
22292             .map(function (pls) {
22293             var samePosition = pls[0][0].equals(pls[1][0]);
22294             var sameLookat = pls[0][1].equals(pls[1][1]);
22295             var sameZoom = pls[0][2] === pls[1][2];
22296             return samePosition && sameLookat && sameZoom;
22297         })
22298             .distinctUntilChanged()
22299             .filter(function (stalled) {
22300             return stalled;
22301         })
22302             .switchMap(function (stalled) {
22303             return _this._container.renderService.renderCameraFrame$
22304                 .first();
22305         })
22306             .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
22307         this._setRegionOfInterestSubscription = textureProvider$
22308             .switchMap(function (provider) {
22309             return roiTrigger$
22310                 .map(function (args) {
22311                 return [
22312                     _this._roiCalculator.computeRegionOfInterest(args[0], args[1], args[2]),
22313                     provider,
22314                 ];
22315             });
22316         })
22317             .filter(function (args) {
22318             return !args[1].disposed;
22319         })
22320             .subscribe(function (args) {
22321             var roi = args[0];
22322             var provider = args[1];
22323             provider.setRegionOfInterest(roi);
22324         });
22325         var hasTexture$ = textureProvider$
22326             .switchMap(function (provider) {
22327             return provider.hasTexture$;
22328         })
22329             .startWith(false)
22330             .publishReplay(1)
22331             .refCount();
22332         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
22333         var nodeImage$ = this._navigator.stateService.currentNode$
22334             .debounceTime(1000)
22335             .withLatestFrom(hasTexture$)
22336             .filter(function (args) {
22337             return !args[1];
22338         })
22339             .map(function (args) {
22340             return args[0];
22341         })
22342             .filter(function (node) {
22343             return node.pano ?
22344                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
22345                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
22346         })
22347             .switchMap(function (node) {
22348             var baseImageSize = node.pano ?
22349                 Utils_1.Settings.basePanoramaSize :
22350                 Utils_1.Settings.baseImageSize;
22351             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
22352                 return Observable_1.Observable.empty();
22353             }
22354             var image$ = node
22355                 .cacheImage$(Utils_1.Settings.maxImageSize)
22356                 .map(function (n) {
22357                 return [n.image, n];
22358             });
22359             return image$
22360                 .takeUntil(hasTexture$
22361                 .filter(function (hasTexture) {
22362                 return hasTexture;
22363             }))
22364                 .catch(function (error, caught) {
22365                 console.error("Failed to fetch high res image (" + node.key + ")", error);
22366                 return Observable_1.Observable.empty();
22367             });
22368         })
22369             .publish()
22370             .refCount();
22371         this._updateBackgroundSubscription = nodeImage$
22372             .withLatestFrom(textureProvider$)
22373             .subscribe(function (args) {
22374             if (args[0][1].key !== args[1].key ||
22375                 args[1].disposed) {
22376                 return;
22377             }
22378             args[1].updateBackground(args[0][0]);
22379         });
22380         this._updateTextureImageSubscription = nodeImage$
22381             .map(function (imn) {
22382             return function (renderer) {
22383                 renderer.updateTextureImage(imn[0], imn[1]);
22384                 return renderer;
22385             };
22386         })
22387             .subscribe(this._rendererOperation$);
22388     };
22389     ImagePlaneComponent.prototype._deactivate = function () {
22390         this._rendererDisposer$.next(null);
22391         this._abortTextureProviderSubscription.unsubscribe();
22392         this._hasTextureSubscription.unsubscribe();
22393         this._rendererSubscription.unsubscribe();
22394         this._setRegionOfInterestSubscription.unsubscribe();
22395         this._setTextureProviderSubscription.unsubscribe();
22396         this._stateSubscription.unsubscribe();
22397         this._textureProviderSubscription.unsubscribe();
22398         this._updateBackgroundSubscription.unsubscribe();
22399         this._updateTextureImageSubscription.unsubscribe();
22400     };
22401     ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
22402         return { imageTiling: false };
22403     };
22404     return ImagePlaneComponent;
22405 }(Component_1.Component));
22406 ImagePlaneComponent.componentName = "imagePlane";
22407 exports.ImagePlaneComponent = ImagePlaneComponent;
22408 Component_1.ComponentService.register(ImagePlaneComponent);
22409 Object.defineProperty(exports, "__esModule", { value: true });
22410 exports.default = ImagePlaneComponent;
22411
22412 },{"../../Component":224,"../../Render":230,"../../Tiles":232,"../../Utils":233,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/catch":51,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/debounceTime":54,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/pairwise":68,"rxjs/add/operator/publish":70,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/skipWhile":76,"rxjs/add/operator/startWith":77,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/takeUntil":80,"rxjs/add/operator/withLatestFrom":82}],255:[function(require,module,exports){
22413 /// <reference path="../../../typings/index.d.ts" />
22414 "use strict";
22415 var THREE = require("three");
22416 var Component_1 = require("../../Component");
22417 var ImagePlaneFactory = (function () {
22418     function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
22419         this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
22420         this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
22421     }
22422     ImagePlaneFactory.prototype.createMesh = function (node, transform) {
22423         var mesh = node.pano ?
22424             this._createImageSphere(node, transform) :
22425             this._createImagePlane(node, transform);
22426         return mesh;
22427     };
22428     ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
22429         var texture = this._createTexture(node.image);
22430         var materialParameters = this._createSphereMaterialParameters(transform, texture);
22431         var material = new THREE.ShaderMaterial(materialParameters);
22432         var mesh = this._useMesh(transform, node) ?
22433             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
22434             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
22435         return mesh;
22436     };
22437     ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
22438         var texture = this._createTexture(node.image);
22439         var materialParameters = this._createPlaneMaterialParameters(transform, texture);
22440         var material = new THREE.ShaderMaterial(materialParameters);
22441         var geometry = this._useMesh(transform, node) ?
22442             this._getImagePlaneGeo(transform, node) :
22443             this._getFlatImagePlaneGeo(transform);
22444         return new THREE.Mesh(geometry, material);
22445     };
22446     ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
22447         var gpano = transform.gpano;
22448         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
22449         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
22450         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
22451         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
22452         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
22453         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
22454         var materialParameters = {
22455             depthWrite: false,
22456             fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
22457             side: THREE.DoubleSide,
22458             transparent: true,
22459             uniforms: {
22460                 opacity: {
22461                     type: "f",
22462                     value: 1,
22463                 },
22464                 phiLength: {
22465                     type: "f",
22466                     value: phiLength,
22467                 },
22468                 phiShift: {
22469                     type: "f",
22470                     value: phiShift,
22471                 },
22472                 projectorMat: {
22473                     type: "m4",
22474                     value: transform.rt,
22475                 },
22476                 projectorTex: {
22477                     type: "t",
22478                     value: texture,
22479                 },
22480                 thetaLength: {
22481                     type: "f",
22482                     value: thetaLength,
22483                 },
22484                 thetaShift: {
22485                     type: "f",
22486                     value: thetaShift,
22487                 },
22488             },
22489             vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
22490         };
22491         return materialParameters;
22492     };
22493     ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
22494         var materialParameters = {
22495             depthWrite: false,
22496             fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
22497             side: THREE.DoubleSide,
22498             transparent: true,
22499             uniforms: {
22500                 bbox: {
22501                     type: "v4",
22502                     value: new THREE.Vector4(0, 0, 1, 1),
22503                 },
22504                 opacity: {
22505                     type: "f",
22506                     value: 1,
22507                 },
22508                 projectorMat: {
22509                     type: "m4",
22510                     value: transform.projectorMatrix(),
22511                 },
22512                 projectorTex: {
22513                     type: "t",
22514                     value: texture,
22515                 },
22516             },
22517             vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
22518         };
22519         return materialParameters;
22520     };
22521     ImagePlaneFactory.prototype._createTexture = function (image) {
22522         var texture = new THREE.Texture(image);
22523         texture.minFilter = THREE.LinearFilter;
22524         texture.needsUpdate = true;
22525         return texture;
22526     };
22527     ImagePlaneFactory.prototype._useMesh = function (transform, node) {
22528         return node.mesh.vertices.length &&
22529             transform.scale > 1e-2 &&
22530             transform.scale < 50;
22531     };
22532     ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
22533         var t = new THREE.Matrix4().getInverse(transform.srt);
22534         // push everything at least 5 meters in front of the camera
22535         var minZ = 5.0 * transform.scale;
22536         var maxZ = this._imageSphereRadius * transform.scale;
22537         var vertices = node.mesh.vertices;
22538         var numVertices = vertices.length / 3;
22539         var positions = new Float32Array(vertices.length);
22540         for (var i = 0; i < numVertices; ++i) {
22541             var index = 3 * i;
22542             var x = vertices[index + 0];
22543             var y = vertices[index + 1];
22544             var z = vertices[index + 2];
22545             var l = Math.sqrt(x * x + y * y + z * z);
22546             var boundedL = Math.max(minZ, Math.min(l, maxZ));
22547             var factor = boundedL / l;
22548             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
22549             p.applyMatrix4(t);
22550             positions[index + 0] = p.x;
22551             positions[index + 1] = p.y;
22552             positions[index + 2] = p.z;
22553         }
22554         var faces = node.mesh.faces;
22555         var indices = new Uint16Array(faces.length);
22556         for (var i = 0; i < faces.length; ++i) {
22557             indices[i] = faces[i];
22558         }
22559         var geometry = new THREE.BufferGeometry();
22560         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22561         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22562         return geometry;
22563     };
22564     ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
22565         var t = new THREE.Matrix4().getInverse(transform.srt);
22566         // push everything at least 5 meters in front of the camera
22567         var minZ = 5.0 * transform.scale;
22568         var maxZ = this._imagePlaneDepth * transform.scale;
22569         var vertices = node.mesh.vertices;
22570         var numVertices = vertices.length / 3;
22571         var positions = new Float32Array(vertices.length);
22572         for (var i = 0; i < numVertices; ++i) {
22573             var index = 3 * i;
22574             var x = vertices[index + 0];
22575             var y = vertices[index + 1];
22576             var z = vertices[index + 2];
22577             var boundedZ = Math.max(minZ, Math.min(z, maxZ));
22578             var factor = boundedZ / z;
22579             var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
22580             p.applyMatrix4(t);
22581             positions[index + 0] = p.x;
22582             positions[index + 1] = p.y;
22583             positions[index + 2] = p.z;
22584         }
22585         var faces = node.mesh.faces;
22586         var indices = new Uint16Array(faces.length);
22587         for (var i = 0; i < faces.length; ++i) {
22588             indices[i] = faces[i];
22589         }
22590         var geometry = new THREE.BufferGeometry();
22591         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22592         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22593         return geometry;
22594     };
22595     ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
22596         var gpano = transform.gpano;
22597         var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
22598         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
22599         var thetaStart = Math.PI *
22600             (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
22601             gpano.FullPanoHeightPixels;
22602         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
22603         var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
22604         geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
22605         return geometry;
22606     };
22607     ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
22608         var width = transform.width;
22609         var height = transform.height;
22610         var size = Math.max(width, height);
22611         var dx = width / 2.0 / size;
22612         var dy = height / 2.0 / size;
22613         var vertices = [];
22614         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
22615         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
22616         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
22617         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
22618         var positions = new Float32Array(12);
22619         for (var i = 0; i < vertices.length; i++) {
22620             var index = 3 * i;
22621             positions[index + 0] = vertices[i][0];
22622             positions[index + 1] = vertices[i][1];
22623             positions[index + 2] = vertices[i][2];
22624         }
22625         var indices = new Uint16Array(6);
22626         indices[0] = 0;
22627         indices[1] = 1;
22628         indices[2] = 3;
22629         indices[3] = 1;
22630         indices[4] = 2;
22631         indices[5] = 3;
22632         var geometry = new THREE.BufferGeometry();
22633         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22634         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22635         return geometry;
22636     };
22637     return ImagePlaneFactory;
22638 }());
22639 exports.ImagePlaneFactory = ImagePlaneFactory;
22640 Object.defineProperty(exports, "__esModule", { value: true });
22641 exports.default = ImagePlaneFactory;
22642
22643 },{"../../Component":224,"three":174}],256:[function(require,module,exports){
22644 /// <reference path="../../../typings/index.d.ts" />
22645 "use strict";
22646 var Component_1 = require("../../Component");
22647 var Geo_1 = require("../../Geo");
22648 var ImagePlaneGLRenderer = (function () {
22649     function ImagePlaneGLRenderer() {
22650         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
22651         this._imagePlaneScene = new Component_1.ImagePlaneScene();
22652         this._alpha = 0;
22653         this._alphaOld = 0;
22654         this._fadeOutSpeed = 0.05;
22655         this._lastCamera = new Geo_1.Camera();
22656         this._epsilon = 0.000001;
22657         this._currentKey = null;
22658         this._previousKey = null;
22659         this._providerDisposers = {};
22660         this._frameId = 0;
22661         this._needsRender = false;
22662     }
22663     Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
22664         get: function () {
22665             return this._frameId;
22666         },
22667         enumerable: true,
22668         configurable: true
22669     });
22670     Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
22671         get: function () {
22672             return this._needsRender;
22673         },
22674         enumerable: true,
22675         configurable: true
22676     });
22677     ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
22678         this._needsRender = true;
22679     };
22680     ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
22681         this._updateFrameId(frame.id);
22682         this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
22683         this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
22684         this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
22685     };
22686     ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
22687         var _this = this;
22688         if (key !== this._currentKey) {
22689             return;
22690         }
22691         var createdSubscription = provider.textureCreated$
22692             .subscribe(function (texture) {
22693             _this._updateTexture(texture);
22694         });
22695         var updatedSubscription = provider.textureUpdated$
22696             .subscribe(function (updated) {
22697             _this._needsRender = true;
22698         });
22699         var dispose = function () {
22700             createdSubscription.unsubscribe();
22701             updatedSubscription.unsubscribe();
22702             provider.dispose();
22703         };
22704         if (key in this._providerDisposers) {
22705             var disposeProvider = this._providerDisposers[key];
22706             disposeProvider();
22707             delete this._providerDisposers[key];
22708         }
22709         this._providerDisposers[key] = dispose;
22710     };
22711     ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
22712         this._needsRender = true;
22713         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
22714             var plane = _a[_i];
22715             var material = plane.material;
22716             var oldTexture = material.uniforms.projectorTex.value;
22717             material.uniforms.projectorTex.value = null;
22718             oldTexture.dispose();
22719             material.uniforms.projectorTex.value = texture;
22720         }
22721     };
22722     ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
22723         if (this._currentKey !== node.key) {
22724             return;
22725         }
22726         this._needsRender = true;
22727         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
22728             var plane = _a[_i];
22729             var material = plane.material;
22730             var texture = material.uniforms.projectorTex.value;
22731             texture.image = image;
22732             texture.needsUpdate = true;
22733         }
22734     };
22735     ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
22736         var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
22737         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
22738             var plane = _a[_i];
22739             plane.material.uniforms.opacity.value = planeAlpha;
22740         }
22741         for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
22742             var plane = _c[_b];
22743             plane.material.uniforms.opacity.value = this._alphaOld;
22744         }
22745         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
22746         renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
22747         for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
22748             var plane = _e[_d];
22749             plane.material.uniforms.opacity.value = this._alpha;
22750         }
22751         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
22752     };
22753     ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
22754         this._needsRender = false;
22755     };
22756     ImagePlaneGLRenderer.prototype.dispose = function () {
22757         this._imagePlaneScene.clear();
22758     };
22759     ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
22760         this._frameId = frameId;
22761     };
22762     ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
22763         if (alpha === this._alpha) {
22764             return false;
22765         }
22766         this._alpha = alpha;
22767         return true;
22768     };
22769     ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
22770         if (alpha < 1 || this._alphaOld === 0) {
22771             return false;
22772         }
22773         this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
22774         return true;
22775     };
22776     ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
22777         if (state.currentNode == null || state.currentNode.key === this._currentKey) {
22778             return false;
22779         }
22780         var previousKey = state.previousNode != null ? state.previousNode.key : null;
22781         var currentKey = state.currentNode.key;
22782         if (this._previousKey !== previousKey &&
22783             this._previousKey !== currentKey &&
22784             this._previousKey in this._providerDisposers) {
22785             var disposeProvider = this._providerDisposers[this._previousKey];
22786             disposeProvider();
22787             delete this._providerDisposers[this._previousKey];
22788         }
22789         if (previousKey != null) {
22790             if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
22791                 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
22792                 this._imagePlaneScene.updateImagePlanes([previousMesh]);
22793             }
22794             this._previousKey = previousKey;
22795         }
22796         this._currentKey = currentKey;
22797         var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
22798         this._imagePlaneScene.updateImagePlanes([currentMesh]);
22799         this._alphaOld = 1;
22800         return true;
22801     };
22802     return ImagePlaneGLRenderer;
22803 }());
22804 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
22805 Object.defineProperty(exports, "__esModule", { value: true });
22806 exports.default = ImagePlaneGLRenderer;
22807
22808 },{"../../Component":224,"../../Geo":227}],257:[function(require,module,exports){
22809 /// <reference path="../../../typings/index.d.ts" />
22810 "use strict";
22811 var THREE = require("three");
22812 var ImagePlaneScene = (function () {
22813     function ImagePlaneScene() {
22814         this.scene = new THREE.Scene();
22815         this.sceneOld = new THREE.Scene();
22816         this.imagePlanes = [];
22817         this.imagePlanesOld = [];
22818     }
22819     ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
22820         this._dispose(this.imagePlanesOld, this.sceneOld);
22821         for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
22822             var plane = _a[_i];
22823             this.scene.remove(plane);
22824             this.sceneOld.add(plane);
22825         }
22826         for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
22827             var plane = planes_1[_b];
22828             this.scene.add(plane);
22829         }
22830         this.imagePlanesOld = this.imagePlanes;
22831         this.imagePlanes = planes;
22832     };
22833     ImagePlaneScene.prototype.addImagePlanes = function (planes) {
22834         for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
22835             var plane = planes_2[_i];
22836             this.scene.add(plane);
22837             this.imagePlanes.push(plane);
22838         }
22839     };
22840     ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
22841         for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
22842             var plane = planes_3[_i];
22843             this.sceneOld.add(plane);
22844             this.imagePlanesOld.push(plane);
22845         }
22846     };
22847     ImagePlaneScene.prototype.setImagePlanes = function (planes) {
22848         this._clear();
22849         this.addImagePlanes(planes);
22850     };
22851     ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
22852         this._clearOld();
22853         this.addImagePlanesOld(planes);
22854     };
22855     ImagePlaneScene.prototype.clear = function () {
22856         this._clear();
22857         this._clearOld();
22858     };
22859     ImagePlaneScene.prototype._clear = function () {
22860         this._dispose(this.imagePlanes, this.scene);
22861         this.imagePlanes.length = 0;
22862     };
22863     ImagePlaneScene.prototype._clearOld = function () {
22864         this._dispose(this.imagePlanesOld, this.sceneOld);
22865         this.imagePlanesOld.length = 0;
22866     };
22867     ImagePlaneScene.prototype._dispose = function (planes, scene) {
22868         for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
22869             var plane = planes_4[_i];
22870             scene.remove(plane);
22871             plane.geometry.dispose();
22872             plane.material.dispose();
22873             var texture = plane.material.uniforms.projectorTex.value;
22874             if (texture != null) {
22875                 texture.dispose();
22876             }
22877         }
22878     };
22879     return ImagePlaneScene;
22880 }());
22881 exports.ImagePlaneScene = ImagePlaneScene;
22882 Object.defineProperty(exports, "__esModule", { value: true });
22883 exports.default = ImagePlaneScene;
22884
22885 },{"three":174}],258:[function(require,module,exports){
22886 /// <reference path="../../../typings/index.d.ts" />
22887 "use strict";
22888
22889 var path = require("path");
22890 var ImagePlaneShaders = (function () {
22891     function ImagePlaneShaders() {
22892     }
22893     return ImagePlaneShaders;
22894 }());
22895 ImagePlaneShaders.equirectangular = {
22896     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}",
22897     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}",
22898 };
22899 ImagePlaneShaders.perspective = {
22900     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}",
22901     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}",
22902 };
22903 exports.ImagePlaneShaders = ImagePlaneShaders;
22904
22905 },{"path":21}],259:[function(require,module,exports){
22906 /// <reference path="../../../typings/index.d.ts" />
22907 "use strict";
22908 var __extends = (this && this.__extends) || function (d, b) {
22909     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
22910     function __() { this.constructor = d; }
22911     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22912 };
22913 var vd = require("virtual-dom");
22914 var Observable_1 = require("rxjs/Observable");
22915 var Subject_1 = require("rxjs/Subject");
22916 require("rxjs/add/observable/combineLatest");
22917 require("rxjs/add/observable/fromEvent");
22918 require("rxjs/add/observable/of");
22919 require("rxjs/add/observable/zip");
22920 require("rxjs/add/operator/distinctUntilChanged");
22921 require("rxjs/add/operator/filter");
22922 require("rxjs/add/operator/first");
22923 require("rxjs/add/operator/map");
22924 require("rxjs/add/operator/merge");
22925 require("rxjs/add/operator/mergeMap");
22926 require("rxjs/add/operator/scan");
22927 require("rxjs/add/operator/switchMap");
22928 require("rxjs/add/operator/withLatestFrom");
22929 require("rxjs/add/operator/zip");
22930 var State_1 = require("../../State");
22931 var Render_1 = require("../../Render");
22932 var Utils_1 = require("../../Utils");
22933 var Component_1 = require("../../Component");
22934 var SliderState = (function () {
22935     function SliderState() {
22936         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
22937         this._imagePlaneScene = new Component_1.ImagePlaneScene();
22938         this._currentKey = null;
22939         this._previousKey = null;
22940         this._currentPano = false;
22941         this._frameId = 0;
22942         this._glNeedsRender = false;
22943         this._domNeedsRender = true;
22944         this._curtain = 1;
22945     }
22946     Object.defineProperty(SliderState.prototype, "frameId", {
22947         get: function () {
22948             return this._frameId;
22949         },
22950         enumerable: true,
22951         configurable: true
22952     });
22953     Object.defineProperty(SliderState.prototype, "curtain", {
22954         get: function () {
22955             return this._curtain;
22956         },
22957         enumerable: true,
22958         configurable: true
22959     });
22960     Object.defineProperty(SliderState.prototype, "glNeedsRender", {
22961         get: function () {
22962             return this._glNeedsRender;
22963         },
22964         enumerable: true,
22965         configurable: true
22966     });
22967     Object.defineProperty(SliderState.prototype, "domNeedsRender", {
22968         get: function () {
22969             return this._domNeedsRender;
22970         },
22971         enumerable: true,
22972         configurable: true
22973     });
22974     Object.defineProperty(SliderState.prototype, "sliderVisible", {
22975         get: function () {
22976             return this._sliderVisible;
22977         },
22978         set: function (value) {
22979             this._sliderVisible = value;
22980             this._domNeedsRender = true;
22981         },
22982         enumerable: true,
22983         configurable: true
22984     });
22985     Object.defineProperty(SliderState.prototype, "disabled", {
22986         get: function () {
22987             return this._currentKey == null ||
22988                 this._previousKey == null ||
22989                 this._currentPano;
22990         },
22991         enumerable: true,
22992         configurable: true
22993     });
22994     SliderState.prototype.update = function (frame) {
22995         this._updateFrameId(frame.id);
22996         var needsRender = this._updateImagePlanes(frame.state);
22997         this._domNeedsRender = needsRender || this._domNeedsRender;
22998         needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
22999         this._glNeedsRender = needsRender || this._glNeedsRender;
23000     };
23001     SliderState.prototype.updateTexture = function (image, node) {
23002         var imagePlanes = node.key === this._currentKey ?
23003             this._imagePlaneScene.imagePlanes :
23004             node.key === this._previousKey ?
23005                 this._imagePlaneScene.imagePlanesOld :
23006                 [];
23007         if (imagePlanes.length === 0) {
23008             return;
23009         }
23010         this._glNeedsRender = true;
23011         for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
23012             var plane = imagePlanes_1[_i];
23013             var material = plane.material;
23014             var texture = material.uniforms.projectorTex.value;
23015             texture.image = image;
23016             texture.needsUpdate = true;
23017         }
23018     };
23019     SliderState.prototype.render = function (perspectiveCamera, renderer) {
23020         if (!this.disabled) {
23021             renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23022         }
23023         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23024     };
23025     SliderState.prototype.dispose = function () {
23026         this._imagePlaneScene.clear();
23027     };
23028     SliderState.prototype.clearGLNeedsRender = function () {
23029         this._glNeedsRender = false;
23030     };
23031     SliderState.prototype.clearDomNeedsRender = function () {
23032         this._domNeedsRender = false;
23033     };
23034     SliderState.prototype._updateFrameId = function (frameId) {
23035         this._frameId = frameId;
23036     };
23037     SliderState.prototype._updateImagePlanes = function (state) {
23038         if (state.currentNode == null) {
23039             return;
23040         }
23041         var needsRender = false;
23042         if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
23043             needsRender = true;
23044             this._previousKey = state.previousNode.key;
23045             this._imagePlaneScene.setImagePlanesOld([
23046                 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
23047             ]);
23048         }
23049         if (this._currentKey !== state.currentNode.key) {
23050             needsRender = true;
23051             this._currentKey = state.currentNode.key;
23052             this._currentPano = state.currentNode.pano;
23053             this._imagePlaneScene.setImagePlanes([
23054                 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
23055             ]);
23056             if (!this.disabled) {
23057                 this._updateBbox();
23058             }
23059         }
23060         return needsRender;
23061     };
23062     SliderState.prototype._updateCurtain = function (alpha) {
23063         if (this.disabled ||
23064             Math.abs(this._curtain - alpha) < 0.001) {
23065             return false;
23066         }
23067         this._curtain = alpha;
23068         this._updateBbox();
23069         return true;
23070     };
23071     SliderState.prototype._updateBbox = function () {
23072         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23073             var plane = _a[_i];
23074             var shaderMaterial = plane.material;
23075             var bbox = shaderMaterial.uniforms.bbox.value;
23076             bbox.z = this._curtain;
23077         }
23078     };
23079     return SliderState;
23080 }());
23081 var SliderComponent = (function (_super) {
23082     __extends(SliderComponent, _super);
23083     /**
23084      * Create a new slider component instance.
23085      * @class SliderComponent
23086      */
23087     function SliderComponent(name, container, navigator) {
23088         var _this = _super.call(this, name, container, navigator) || this;
23089         _this._sliderStateOperation$ = new Subject_1.Subject();
23090         _this._sliderStateCreator$ = new Subject_1.Subject();
23091         _this._sliderStateDisposer$ = new Subject_1.Subject();
23092         _this._sliderState$ = _this._sliderStateOperation$
23093             .scan(function (sliderState, operation) {
23094             return operation(sliderState);
23095         }, null)
23096             .filter(function (sliderState) {
23097             return sliderState != null;
23098         })
23099             .distinctUntilChanged(undefined, function (sliderState) {
23100             return sliderState.frameId;
23101         });
23102         _this._sliderStateCreator$
23103             .map(function () {
23104             return function (sliderState) {
23105                 if (sliderState != null) {
23106                     throw new Error("Multiple slider states can not be created at the same time");
23107                 }
23108                 return new SliderState();
23109             };
23110         })
23111             .subscribe(_this._sliderStateOperation$);
23112         _this._sliderStateDisposer$
23113             .map(function () {
23114             return function (sliderState) {
23115                 sliderState.dispose();
23116                 return null;
23117             };
23118         })
23119             .subscribe(_this._sliderStateOperation$);
23120         return _this;
23121     }
23122     /**
23123      * Set the image keys.
23124      *
23125      * Configures the component to show the image planes for the supplied image keys.
23126      *
23127      * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
23128      */
23129     SliderComponent.prototype.setKeys = function (keys) {
23130         this.configure({ keys: keys });
23131     };
23132     /**
23133      * Set the initial position.
23134      *
23135      * Configures the intial position of the slider. The inital position value will be used when the component is activated.
23136      *
23137      * @param {number} initialPosition - Initial slider position.
23138      */
23139     SliderComponent.prototype.setInitialPosition = function (initialPosition) {
23140         this.configure({ initialPosition: initialPosition });
23141     };
23142     /**
23143      * Set the value controlling if the slider is visible.
23144      *
23145      * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
23146      */
23147     SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
23148         this.configure({ sliderVisible: sliderVisible });
23149     };
23150     SliderComponent.prototype._activate = function () {
23151         var _this = this;
23152         Observable_1.Observable
23153             .combineLatest(this._navigator.stateService.state$, this._configuration$)
23154             .first()
23155             .subscribe(function (_a) {
23156             var state = _a[0], configuration = _a[1];
23157             if (state === State_1.State.Traversing) {
23158                 _this._navigator.stateService.wait();
23159                 var position = configuration.initialPosition;
23160                 _this._navigator.stateService.moveTo(position != null ? position : 1);
23161             }
23162         });
23163         this._glRenderSubscription = this._sliderState$
23164             .map(function (sliderState) {
23165             var renderHash = {
23166                 name: _this._name,
23167                 render: {
23168                     frameId: sliderState.frameId,
23169                     needsRender: sliderState.glNeedsRender,
23170                     render: sliderState.render.bind(sliderState),
23171                     stage: Render_1.GLRenderStage.Background,
23172                 },
23173             };
23174             sliderState.clearGLNeedsRender();
23175             return renderHash;
23176         })
23177             .subscribe(this._container.glRenderer.render$);
23178         this._domRenderSubscription = this._sliderState$
23179             .filter(function (sliderState) {
23180             return sliderState.domNeedsRender;
23181         })
23182             .map(function (sliderState) {
23183             var sliderInput = vd.h("input.SliderControl", {
23184                 max: 1000,
23185                 min: 0,
23186                 oninput: function (e) {
23187                     var curtain = Number(e.target.value) / 1000;
23188                     _this._navigator.stateService.moveTo(curtain);
23189                 },
23190                 type: "range",
23191                 value: 1000 * sliderState.curtain,
23192             }, []);
23193             var vNode = sliderState.disabled || !sliderState.sliderVisible ?
23194                 null :
23195                 vd.h("div.SliderWrapper", {}, [sliderInput]);
23196             var hash = {
23197                 name: _this._name,
23198                 vnode: vNode,
23199             };
23200             sliderState.clearDomNeedsRender();
23201             return hash;
23202         })
23203             .subscribe(this._container.domRenderer.render$);
23204         this._sliderStateCreator$.next(null);
23205         this._stateSubscription = this._navigator.stateService.currentState$
23206             .map(function (frame) {
23207             return function (sliderState) {
23208                 sliderState.update(frame);
23209                 return sliderState;
23210             };
23211         })
23212             .subscribe(this._sliderStateOperation$);
23213         this._setSliderVisibleSubscription = this._configuration$
23214             .map(function (configuration) {
23215             return configuration.sliderVisible == null || configuration.sliderVisible;
23216         })
23217             .distinctUntilChanged()
23218             .map(function (sliderVisible) {
23219             return function (sliderState) {
23220                 sliderState.sliderVisible = sliderVisible;
23221                 return sliderState;
23222             };
23223         })
23224             .subscribe(this._sliderStateOperation$);
23225         this._setKeysSubscription = this._configuration$
23226             .filter(function (configuration) {
23227             return configuration.keys != null;
23228         })
23229             .switchMap(function (configuration) {
23230             return Observable_1.Observable
23231                 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
23232                 .map(function (nodes) {
23233                 return { background: nodes[0], foreground: nodes[1] };
23234             })
23235                 .zip(_this._navigator.stateService.currentState$.first())
23236                 .map(function (nf) {
23237                 return { nodes: nf[0], state: nf[1].state };
23238             });
23239         })
23240             .subscribe(function (co) {
23241             if (co.state.currentNode != null &&
23242                 co.state.previousNode != null &&
23243                 co.state.currentNode.key === co.nodes.foreground.key &&
23244                 co.state.previousNode.key === co.nodes.background.key) {
23245                 return;
23246             }
23247             if (co.state.currentNode.key === co.nodes.background.key) {
23248                 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23249                 return;
23250             }
23251             if (co.state.currentNode.key === co.nodes.foreground.key &&
23252                 co.state.trajectory.length === 1) {
23253                 _this._navigator.stateService.prependNodes([co.nodes.background]);
23254                 return;
23255             }
23256             _this._navigator.stateService.setNodes([co.nodes.background]);
23257             _this._navigator.stateService.setNodes([co.nodes.foreground]);
23258         }, function (e) {
23259             console.error(e);
23260         });
23261         var previousNode$ = this._navigator.stateService.currentState$
23262             .map(function (frame) {
23263             return frame.state.previousNode;
23264         })
23265             .filter(function (node) {
23266             return node != null;
23267         })
23268             .distinctUntilChanged(undefined, function (node) {
23269             return node.key;
23270         });
23271         this._nodeSubscription = Observable_1.Observable
23272             .merge(previousNode$, this._navigator.stateService.currentNode$)
23273             .filter(function (node) {
23274             return node.pano ?
23275                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
23276                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
23277         })
23278             .mergeMap(function (node) {
23279             var baseImageSize = node.pano ?
23280                 Utils_1.Settings.basePanoramaSize :
23281                 Utils_1.Settings.baseImageSize;
23282             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
23283                 return Observable_1.Observable.empty();
23284             }
23285             return node.cacheImage$(Utils_1.Settings.maxImageSize)
23286                 .map(function (n) {
23287                 return [n.image, n];
23288             })
23289                 .catch(function (error, caught) {
23290                 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
23291                 return Observable_1.Observable.empty();
23292             });
23293         })
23294             .map(function (_a) {
23295             var element = _a[0], node = _a[1];
23296             return function (sliderState) {
23297                 sliderState.updateTexture(element, node);
23298                 return sliderState;
23299             };
23300         })
23301             .subscribe(this._sliderStateOperation$);
23302     };
23303     SliderComponent.prototype._deactivate = function () {
23304         var _this = this;
23305         this._navigator.stateService.state$
23306             .first()
23307             .subscribe(function (state) {
23308             if (state === State_1.State.Waiting) {
23309                 _this._navigator.stateService.traverse();
23310             }
23311         });
23312         this._sliderStateDisposer$.next(null);
23313         this._setKeysSubscription.unsubscribe();
23314         this._setSliderVisibleSubscription.unsubscribe();
23315         this._stateSubscription.unsubscribe();
23316         this._glRenderSubscription.unsubscribe();
23317         this._domRenderSubscription.unsubscribe();
23318         this._nodeSubscription.unsubscribe();
23319         this.configure({ keys: null });
23320     };
23321     SliderComponent.prototype._getDefaultConfiguration = function () {
23322         return {};
23323     };
23324     SliderComponent.prototype._catchCacheNode$ = function (key) {
23325         return this._navigator.graphService.cacheNode$(key)
23326             .catch(function (error, caught) {
23327             console.error("Failed to cache slider node (" + key + ")", error);
23328             return Observable_1.Observable.empty();
23329         });
23330     };
23331     return SliderComponent;
23332 }(Component_1.Component));
23333 SliderComponent.componentName = "slider";
23334 exports.SliderComponent = SliderComponent;
23335 Component_1.ComponentService.register(SliderComponent);
23336 Object.defineProperty(exports, "__esModule", { value: true });
23337 exports.default = SliderComponent;
23338
23339 },{"../../Component":224,"../../Render":230,"../../State":231,"../../Utils":233,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/fromEvent":41,"rxjs/add/observable/of":44,"rxjs/add/observable/zip":47,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/scan":72,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/withLatestFrom":82,"rxjs/add/operator/zip":83,"virtual-dom":180}],260:[function(require,module,exports){
23340 "use strict";
23341 var MarkerComponent_1 = require("./MarkerComponent");
23342 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
23343 var SimpleMarker_1 = require("./marker/SimpleMarker");
23344 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
23345 var CircleMarker_1 = require("./marker/CircleMarker");
23346 exports.CircleMarker = CircleMarker_1.CircleMarker;
23347
23348 },{"./MarkerComponent":261,"./marker/CircleMarker":264,"./marker/SimpleMarker":266}],261:[function(require,module,exports){
23349 /// <reference path="../../../typings/index.d.ts" />
23350 "use strict";
23351 var __extends = (this && this.__extends) || function (d, b) {
23352     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23353     function __() { this.constructor = d; }
23354     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23355 };
23356 var THREE = require("three");
23357 var when = require("when");
23358 var Observable_1 = require("rxjs/Observable");
23359 require("rxjs/add/observable/combineLatest");
23360 require("rxjs/add/operator/distinctUntilChanged");
23361 require("rxjs/add/operator/map");
23362 var Component_1 = require("../../Component");
23363 var Render_1 = require("../../Render");
23364 var Graph_1 = require("../../Graph");
23365 var Geo_1 = require("../../Geo");
23366 /**
23367  * @class MarkerComponent
23368  *
23369  * @classdesc Component for showing and editing 3D marker objects.
23370  *
23371  * The `add` method is used for adding new markers or replacing
23372  * markers already in the set.
23373  *
23374  * If a marker already in the set has the same
23375  * id as one of the markers added, the old marker will be removed
23376  * the added marker will take its place.
23377  *
23378  * It is not possible to update markers in the set by updating any properties
23379  * directly on the marker object. Markers need to be replaced by
23380  * re-adding them for updates to geographic position or configuration
23381  * to be reflected.
23382  *
23383  * Markers added to the marker component can be either interactive
23384  * or non-interactive. Different marker types define their behavior.
23385  * Markers with interaction support can be configured with options
23386  * to respond to dragging inside the viewer and be detected when
23387  * retrieving markers from pixel points with the `getMarkerIdAt` method.
23388  *
23389  * To retrive and use the marker component
23390  *
23391  * @example
23392  * ```
23393  * var markerComponent = viewer.getComponent("marker");
23394  * ```
23395  */
23396 var MarkerComponent = (function (_super) {
23397     __extends(MarkerComponent, _super);
23398     function MarkerComponent(name, container, navigator) {
23399         var _this = _super.call(this, name, container, navigator) || this;
23400         _this._relativeGroundAltitude = -2;
23401         _this._geoCoords = new Geo_1.GeoCoords();
23402         _this._graphCalculator = new Graph_1.GraphCalculator();
23403         _this._markerScene = new Component_1.MarkerScene();
23404         _this._markerSet = new Component_1.MarkerSet();
23405         _this._viewportCoords = new Geo_1.ViewportCoords();
23406         return _this;
23407     }
23408     /**
23409      * Add markers to the marker set or replace markers in the marker set.
23410      *
23411      * @description If a marker already in the set has the same
23412      * id as one of the markers added, the old marker will be removed
23413      * the added marker will take its place.
23414      *
23415      * Any marker inside the visible bounding bbox
23416      * will be initialized and placed in the viewer.
23417      *
23418      * @param {Array<Marker>} markers - Markers to add.
23419      *
23420      * @example ```markerComponent.add([marker1, marker2]);```
23421      */
23422     MarkerComponent.prototype.add = function (markers) {
23423         this._markerSet.add(markers);
23424     };
23425     /**
23426      * Check if a marker exist in the marker set.
23427      *
23428      * @param {string} markerId - Id of the marker.
23429      *
23430      * @example ```var markerExists = markerComponent.has("markerId");```
23431      */
23432     MarkerComponent.prototype.has = function (markerId) {
23433         return this._markerSet.has(markerId);
23434     };
23435     /**
23436      * Returns the marker in the marker set with the specified id, or
23437      * undefined if the id matches no marker.
23438      *
23439      * @param {string} markerId - Id of the marker.
23440      *
23441      * @example ```var marker = markerComponent.get("markerId");```
23442      *
23443      */
23444     MarkerComponent.prototype.get = function (markerId) {
23445         return this._markerSet.get(markerId);
23446     };
23447     /**
23448      * Returns an array of all markers.
23449      *
23450      * @example ```var markers = markerComponent.getAll();```
23451      */
23452     MarkerComponent.prototype.getAll = function () {
23453         return this._markerSet.getAll();
23454     };
23455     /**
23456      * Returns the id of the interactive marker closest to the current camera
23457      * position ids for marker currently visible at the specified point.
23458      *
23459      * @description Notice that the pixelPoint argument requires x, y
23460      * coordinates from pixel space.
23461      *
23462      * With this function, you can use the coordinates provided by mouse
23463      * events to get information out of the marker component.
23464      *
23465      * If no interactive geometry of an interactive marker exist at the pixel
23466      * point, null will be returned.
23467      *
23468      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
23469      * @returns {string} Id of the interactive marker closest to the camera. If no
23470      * interactive marker exist at the pixel point, null will be returned.
23471      *
23472      * @example
23473      * ```
23474      * markerComponent.getMarkerIdAt([100, 100])
23475      *     .then((markerId) => { console.log(markerId); });
23476      * ```
23477      */
23478     MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
23479         var _this = this;
23480         return when.promise(function (resolve, reject) {
23481             _this._container.renderService.renderCamera$
23482                 .first()
23483                 .map(function (render) {
23484                 var viewport = _this._viewportCoords
23485                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
23486                 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
23487                 return id;
23488             })
23489                 .subscribe(function (id) {
23490                 resolve(id);
23491             }, function (error) {
23492                 reject(error);
23493             });
23494         });
23495     };
23496     /**
23497      * Remove markers with the specified ids from the marker set.
23498      *
23499      * @param {Array<string>} markerIds - Ids for markers to remove.
23500      *
23501      * @example ```markerComponent.remove(["id-1", "id-2"]);```
23502      */
23503     MarkerComponent.prototype.remove = function (markerIds) {
23504         this._markerSet.remove(markerIds);
23505     };
23506     /**
23507      * Remove all markers from the marker set.
23508      *
23509      * @example ```markerComponent.removeAll();```
23510      */
23511     MarkerComponent.prototype.removeAll = function () {
23512         this._markerSet.removeAll();
23513     };
23514     MarkerComponent.prototype._activate = function () {
23515         var _this = this;
23516         var groundAltitude$ = this._navigator.stateService.currentState$
23517             .map(function (frame) {
23518             return frame.state.camera.position.z + _this._relativeGroundAltitude;
23519         })
23520             .distinctUntilChanged(function (a1, a2) {
23521             return Math.abs(a1 - a2) < 0.01;
23522         })
23523             .publishReplay(1)
23524             .refCount();
23525         var geoInitiated$ = Observable_1.Observable
23526             .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
23527             .first()
23528             .map(function () { })
23529             .publishReplay(1)
23530             .refCount();
23531         var clampedConfiguration$ = this._configuration$
23532             .map(function (configuration) {
23533             return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
23534         });
23535         var currentlatLon$ = this._navigator.stateService.currentNode$
23536             .map(function (node) { return node.latLon; })
23537             .publishReplay(1)
23538             .refCount();
23539         var visibleBBox$ = Observable_1.Observable
23540             .combineLatest(clampedConfiguration$, currentlatLon$)
23541             .map(function (_a) {
23542             var configuration = _a[0], latLon = _a[1];
23543             return _this._graphCalculator
23544                 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
23545         })
23546             .publishReplay(1)
23547             .refCount();
23548         var visibleMarkers$ = Observable_1.Observable
23549             .combineLatest(Observable_1.Observable
23550             .of(this._markerSet)
23551             .concat(this._markerSet.changed$), visibleBBox$)
23552             .map(function (_a) {
23553             var set = _a[0], bbox = _a[1];
23554             return set.search(bbox);
23555         });
23556         this._setChangedSubscription = geoInitiated$
23557             .switchMap(function () {
23558             return visibleMarkers$
23559                 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
23560         })
23561             .subscribe(function (_a) {
23562             var markers = _a[0], reference = _a[1], alt = _a[2];
23563             var geoCoords = _this._geoCoords;
23564             var markerScene = _this._markerScene;
23565             var sceneMarkers = markerScene.markers;
23566             var markersToRemove = Object.assign({}, sceneMarkers);
23567             for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
23568                 var marker = markers_1[_i];
23569                 if (marker.id in sceneMarkers) {
23570                     delete markersToRemove[marker.id];
23571                 }
23572                 else {
23573                     var point3d = geoCoords
23574                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23575                     markerScene.add(marker, point3d);
23576                 }
23577             }
23578             for (var id in markersToRemove) {
23579                 if (!markersToRemove.hasOwnProperty(id)) {
23580                     continue;
23581                 }
23582                 markerScene.remove(id);
23583             }
23584         });
23585         this._markersUpdatedSubscription = geoInitiated$
23586             .switchMap(function () {
23587             return _this._markerSet.updated$
23588                 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
23589         })
23590             .subscribe(function (_a) {
23591             var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
23592             var geoCoords = _this._geoCoords;
23593             var markerScene = _this._markerScene;
23594             for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
23595                 var marker = markers_2[_i];
23596                 var exists = markerScene.has(marker.id);
23597                 var visible = marker.latLon.lat > sw.lat &&
23598                     marker.latLon.lat < ne.lat &&
23599                     marker.latLon.lon > sw.lon &&
23600                     marker.latLon.lon < ne.lon;
23601                 if (visible) {
23602                     var point3d = geoCoords
23603                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23604                     markerScene.add(marker, point3d);
23605                 }
23606                 else if (!visible && exists) {
23607                     markerScene.remove(marker.id);
23608                 }
23609             }
23610         });
23611         this._referenceSubscription = this._navigator.stateService.reference$
23612             .skip(1)
23613             .withLatestFrom(groundAltitude$)
23614             .subscribe(function (_a) {
23615             var reference = _a[0], alt = _a[1];
23616             var geoCoords = _this._geoCoords;
23617             var markerScene = _this._markerScene;
23618             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
23619                 var marker = _b[_i];
23620                 var point3d = geoCoords
23621                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23622                 markerScene.update(marker.id, point3d);
23623             }
23624         });
23625         this._adjustHeightSubscription = groundAltitude$
23626             .skip(1)
23627             .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
23628             .subscribe(function (_a) {
23629             var alt = _a[0], reference = _a[1], latLon = _a[2];
23630             var geoCoords = _this._geoCoords;
23631             var markerScene = _this._markerScene;
23632             var position = geoCoords
23633                 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23634             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
23635                 var marker = _b[_i];
23636                 var point3d = geoCoords
23637                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23638                 var distanceX = point3d[0] - position[0];
23639                 var distanceY = point3d[1] - position[1];
23640                 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
23641                 if (groundDistance > 50) {
23642                     continue;
23643                 }
23644                 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
23645             }
23646         });
23647         this._renderSubscription = this._navigator.stateService.currentState$
23648             .map(function (frame) {
23649             var scene = _this._markerScene;
23650             return {
23651                 name: _this._name,
23652                 render: {
23653                     frameId: frame.id,
23654                     needsRender: scene.needsRender,
23655                     render: scene.render.bind(scene),
23656                     stage: Render_1.GLRenderStage.Foreground,
23657                 },
23658             };
23659         })
23660             .subscribe(this._container.glRenderer.render$);
23661         var hoveredMarkerId$ = Observable_1.Observable
23662             .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
23663             .map(function (_a) {
23664             var render = _a[0], event = _a[1];
23665             var viewport = _this._viewportCoords.canvasToViewport(event.clientX, event.clientY, _this._container.element);
23666             var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
23667             return markerId;
23668         })
23669             .publishReplay(1)
23670             .refCount();
23671         var draggingStarted$ = this._container.mouseService
23672             .filtered$(this._name, this._container.mouseService.mouseDragStart$)
23673             .map(function (event) {
23674             return true;
23675         });
23676         var draggingStopped$ = this._container.mouseService
23677             .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
23678             .map(function (event) {
23679             return false;
23680         });
23681         var dragging$ = Observable_1.Observable
23682             .merge(draggingStarted$, draggingStopped$)
23683             .startWith(false);
23684         this._dragEventSubscription = draggingStarted$
23685             .withLatestFrom(hoveredMarkerId$)
23686             .merge(Observable_1.Observable
23687             .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
23688             .startWith([false, null])
23689             .pairwise()
23690             .subscribe(function (_a) {
23691             var previous = _a[0], current = _a[1];
23692             var dragging = current[0];
23693             var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
23694             var id = dragging ? current[1] : previous[1];
23695             var marker = _this._markerScene.get(id);
23696             var markerEvent = { marker: marker, target: _this, type: eventType };
23697             _this.fire(eventType, markerEvent);
23698         });
23699         this._mouseClaimSubscription = Observable_1.Observable
23700             .combineLatest(this._container.mouseService.active$, hoveredMarkerId$, dragging$)
23701             .map(function (_a) {
23702             var active = _a[0], markerId = _a[1], dragging = _a[2];
23703             return (!active && markerId != null) || dragging;
23704         })
23705             .distinctUntilChanged()
23706             .subscribe(function (hovered) {
23707             if (hovered) {
23708                 _this._container.mouseService.claimMouse(_this._name, 1);
23709             }
23710             else {
23711                 _this._container.mouseService.unclaimMouse(_this._name);
23712             }
23713         });
23714         var offset$ = this._container.mouseService
23715             .filtered$(this._name, this._container.mouseService.mouseDragStart$)
23716             .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
23717             .map(function (_a) {
23718             var e = _a[0], id = _a[1], r = _a[2];
23719             var marker = _this._markerScene.get(id);
23720             var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), _this._container.element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
23721             var offset = [e.clientX - groundCanvasX, e.clientY - groundCanvasY];
23722             return [marker, offset, r];
23723         })
23724             .publishReplay(1)
23725             .refCount();
23726         this._updateMarkerSubscription = this._container.mouseService
23727             .filtered$(this._name, this._container.mouseService.mouseDrag$)
23728             .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
23729             .subscribe(function (_a) {
23730             var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
23731             if (!_this._markerScene.has(marker.id)) {
23732                 return;
23733             }
23734             var groundX = event.clientX - offset[0];
23735             var groundY = event.clientY - offset[1];
23736             var _c = _this._viewportCoords
23737                 .canvasToViewport(groundX, groundY, _this._container.element), viewportX = _c[0], viewportY = _c[1];
23738             var direction = new THREE.Vector3(viewportX, viewportY, 1)
23739                 .unproject(render.perspective)
23740                 .sub(render.perspective.position)
23741                 .normalize();
23742             var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
23743             if (distance < 0) {
23744                 return;
23745             }
23746             var intersection = direction
23747                 .clone()
23748                 .multiplyScalar(distance)
23749                 .add(render.perspective.position);
23750             intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
23751             var _d = _this._geoCoords
23752                 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _d[0], lon = _d[1];
23753             _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
23754             _this._markerSet.update(marker);
23755             var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
23756             _this.fire(MarkerComponent.changed, markerEvent);
23757         });
23758     };
23759     MarkerComponent.prototype._deactivate = function () {
23760         this._adjustHeightSubscription.unsubscribe();
23761         this._dragEventSubscription.unsubscribe();
23762         this._markersUpdatedSubscription.unsubscribe();
23763         this._mouseClaimSubscription.unsubscribe();
23764         this._referenceSubscription.unsubscribe();
23765         this._renderSubscription.unsubscribe();
23766         this._setChangedSubscription.unsubscribe();
23767         this._updateMarkerSubscription.unsubscribe();
23768         this._markerScene.clear();
23769     };
23770     MarkerComponent.prototype._getDefaultConfiguration = function () {
23771         return { visibleBBoxSize: 100 };
23772     };
23773     return MarkerComponent;
23774 }(Component_1.Component));
23775 MarkerComponent.componentName = "marker";
23776 /**
23777  * Fired when the position of a marker is changed.
23778  * @event
23779  * @type {IMarkerEvent} markerEvent - Marker event data.
23780  * @example
23781  * ```
23782  * markerComponent.on("changed", function(e) {
23783  *     console.log(e.marker.id, e.marker.latLon);
23784  * });
23785  * ```
23786  */
23787 MarkerComponent.changed = "changed";
23788 /**
23789  * Fired when a marker drag interaction starts.
23790  * @event
23791  * @type {IMarkerEvent} markerEvent - Marker event data.
23792  * @example
23793  * ```
23794  * markerComponent.on("dragstart", function(e) {
23795  *     console.log(e.marker.id, e.marker.latLon);
23796  * });
23797  * ```
23798  */
23799 MarkerComponent.dragstart = "dragstart";
23800 /**
23801  * Fired when a marker drag interaction ends.
23802  * @event
23803  * @type {IMarkerEvent} markerEvent - Marker event data.
23804  * @example
23805  * ```
23806  * markerComponent.on("dragend", function(e) {
23807  *     console.log(e.marker.id, e.marker.latLon);
23808  * });
23809  * ```
23810  */
23811 MarkerComponent.dragend = "dragend";
23812 exports.MarkerComponent = MarkerComponent;
23813 Component_1.ComponentService.register(MarkerComponent);
23814 Object.defineProperty(exports, "__esModule", { value: true });
23815 exports.default = MarkerComponent;
23816
23817 },{"../../Component":224,"../../Geo":227,"../../Graph":228,"../../Render":230,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/map":64,"three":174,"when":221}],262:[function(require,module,exports){
23818 /// <reference path="../../../typings/index.d.ts" />
23819 "use strict";
23820 var THREE = require("three");
23821 var MarkerScene = (function () {
23822     function MarkerScene(scene, raycaster) {
23823         this._needsRender = false;
23824         this._interactiveObjects = [];
23825         this._markers = {};
23826         this._objectMarkers = {};
23827         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
23828         this._scene = !!scene ? scene : new THREE.Scene();
23829     }
23830     Object.defineProperty(MarkerScene.prototype, "markers", {
23831         get: function () {
23832             return this._markers;
23833         },
23834         enumerable: true,
23835         configurable: true
23836     });
23837     Object.defineProperty(MarkerScene.prototype, "needsRender", {
23838         get: function () {
23839             return this._needsRender;
23840         },
23841         enumerable: true,
23842         configurable: true
23843     });
23844     MarkerScene.prototype.add = function (marker, position) {
23845         if (marker.id in this._markers) {
23846             this._dispose(marker.id);
23847         }
23848         marker.createGeometry(position);
23849         this._scene.add(marker.geometry);
23850         this._markers[marker.id] = marker;
23851         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
23852             var interactiveObject = _a[_i];
23853             this._interactiveObjects.push(interactiveObject);
23854             this._objectMarkers[interactiveObject.uuid] = marker.id;
23855         }
23856         this._needsRender = true;
23857     };
23858     MarkerScene.prototype.clear = function () {
23859         for (var id in this._markers) {
23860             if (!this._markers.hasOwnProperty) {
23861                 continue;
23862             }
23863             this._dispose(id);
23864         }
23865         this._needsRender = true;
23866     };
23867     MarkerScene.prototype.get = function (id) {
23868         return this._markers[id];
23869     };
23870     MarkerScene.prototype.getAll = function () {
23871         var _this = this;
23872         return Object
23873             .keys(this._markers)
23874             .map(function (id) { return _this._markers[id]; });
23875     };
23876     MarkerScene.prototype.has = function (id) {
23877         return id in this._markers;
23878     };
23879     MarkerScene.prototype.intersectObjects = function (_a, camera) {
23880         var viewportX = _a[0], viewportY = _a[1];
23881         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
23882         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
23883         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
23884             var intersect = intersects_1[_i];
23885             if (intersect.object.uuid in this._objectMarkers) {
23886                 return this._objectMarkers[intersect.object.uuid];
23887             }
23888         }
23889         return null;
23890     };
23891     MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
23892         if (!(id in this._markers)) {
23893             return;
23894         }
23895         this._markers[id].lerpAltitude(alt, alpha);
23896         this._needsRender = true;
23897     };
23898     MarkerScene.prototype.remove = function (id) {
23899         if (!(id in this._markers)) {
23900             return;
23901         }
23902         this._dispose(id);
23903         this._needsRender = true;
23904     };
23905     MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
23906         renderer.render(this._scene, perspectiveCamera);
23907         this._needsRender = false;
23908     };
23909     MarkerScene.prototype.update = function (id, position, latLon) {
23910         if (!(id in this._markers)) {
23911             return;
23912         }
23913         var marker = this._markers[id];
23914         marker.updatePosition(position, latLon);
23915         this._needsRender = true;
23916     };
23917     MarkerScene.prototype._dispose = function (id) {
23918         var marker = this._markers[id];
23919         this._scene.remove(marker.geometry);
23920         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
23921             var interactiveObject = _a[_i];
23922             var index = this._interactiveObjects.indexOf(interactiveObject);
23923             if (index !== -1) {
23924                 this._interactiveObjects.splice(index, 1);
23925             }
23926             else {
23927                 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
23928             }
23929             delete this._objectMarkers[interactiveObject.uuid];
23930         }
23931         marker.disposeGeometry();
23932         delete this._markers[id];
23933     };
23934     return MarkerScene;
23935 }());
23936 exports.MarkerScene = MarkerScene;
23937 Object.defineProperty(exports, "__esModule", { value: true });
23938 exports.default = MarkerScene;
23939
23940 },{"three":174}],263:[function(require,module,exports){
23941 /// <reference path="../../../typings/index.d.ts" />
23942 "use strict";
23943 var rbush = require("rbush");
23944 var Subject_1 = require("rxjs/Subject");
23945 require("rxjs/add/operator/map");
23946 require("rxjs/add/operator/publishReplay");
23947 require("rxjs/add/operator/scan");
23948 var MarkerSet = (function () {
23949     function MarkerSet() {
23950         this._hash = {};
23951         this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
23952         this._indexChanged$ = new Subject_1.Subject();
23953         this._updated$ = new Subject_1.Subject();
23954     }
23955     Object.defineProperty(MarkerSet.prototype, "changed$", {
23956         get: function () {
23957             return this._indexChanged$;
23958         },
23959         enumerable: true,
23960         configurable: true
23961     });
23962     Object.defineProperty(MarkerSet.prototype, "updated$", {
23963         get: function () {
23964             return this._updated$;
23965         },
23966         enumerable: true,
23967         configurable: true
23968     });
23969     MarkerSet.prototype.add = function (markers) {
23970         var updated = [];
23971         var hash = this._hash;
23972         var index = this._index;
23973         for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
23974             var marker = markers_1[_i];
23975             var id = marker.id;
23976             if (id in hash) {
23977                 index.remove(hash[id]);
23978                 updated.push(marker);
23979             }
23980             var item = {
23981                 lat: marker.latLon.lat,
23982                 lon: marker.latLon.lon,
23983                 marker: marker,
23984             };
23985             hash[id] = item;
23986             index.insert(item);
23987         }
23988         if (updated.length > 0) {
23989             this._updated$.next(updated);
23990         }
23991         if (markers.length > updated.length) {
23992             this._indexChanged$.next(this);
23993         }
23994     };
23995     MarkerSet.prototype.has = function (id) {
23996         return id in this._hash;
23997     };
23998     MarkerSet.prototype.get = function (id) {
23999         return this.has(id) ? this._hash[id].marker : undefined;
24000     };
24001     MarkerSet.prototype.getAll = function () {
24002         return this._index
24003             .all()
24004             .map(function (indexItem) {
24005             return indexItem.marker;
24006         });
24007     };
24008     MarkerSet.prototype.remove = function (ids) {
24009         var hash = this._hash;
24010         var index = this._index;
24011         var changed = false;
24012         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
24013             var id = ids_1[_i];
24014             if (!(id in hash)) {
24015                 continue;
24016             }
24017             var item = hash[id];
24018             index.remove(item);
24019             delete hash[id];
24020             changed = true;
24021         }
24022         if (changed) {
24023             this._indexChanged$.next(this);
24024         }
24025     };
24026     MarkerSet.prototype.removeAll = function () {
24027         this._hash = {};
24028         this._index.clear();
24029         this._indexChanged$.next(this);
24030     };
24031     MarkerSet.prototype.search = function (_a) {
24032         var sw = _a[0], ne = _a[1];
24033         return this._index
24034             .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
24035             .map(function (indexItem) {
24036             return indexItem.marker;
24037         });
24038     };
24039     MarkerSet.prototype.update = function (marker) {
24040         var hash = this._hash;
24041         var index = this._index;
24042         var id = marker.id;
24043         if (!(id in hash)) {
24044             return;
24045         }
24046         index.remove(hash[id]);
24047         var item = {
24048             lat: marker.latLon.lat,
24049             lon: marker.latLon.lon,
24050             marker: marker,
24051         };
24052         hash[id] = item;
24053         index.insert(item);
24054     };
24055     return MarkerSet;
24056 }());
24057 exports.MarkerSet = MarkerSet;
24058 Object.defineProperty(exports, "__esModule", { value: true });
24059 exports.default = MarkerSet;
24060
24061 },{"rbush":24,"rxjs/Subject":33,"rxjs/add/operator/map":64,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72}],264:[function(require,module,exports){
24062 /// <reference path="../../../../typings/index.d.ts" />
24063 "use strict";
24064 var __extends = (this && this.__extends) || function (d, b) {
24065     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24066     function __() { this.constructor = d; }
24067     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24068 };
24069 var THREE = require("three");
24070 var Component_1 = require("../../../Component");
24071 /**
24072  * @class CircleMarker
24073  *
24074  * @classdesc Non-interactive marker with a flat circle shape. The circle
24075  * marker can not be configured to be interactive.
24076  *
24077  * Circle marker properties can not be updated after creation.
24078  *
24079  * To create and add one `CircleMarker` with default configuration
24080  * and one with configuration use
24081  *
24082  * @example
24083  * ```
24084  * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
24085  *     "id-1",
24086  *     { lat: 0, lon: 0, });
24087  *
24088  * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
24089  *     "id-2",
24090  *     { lat: 0, lon: 0, },
24091  *     {
24092  *         color: "#0Ff",
24093  *         opacity: 0.3,
24094  *         radius: 0.7,
24095  *     });
24096  *
24097  * markerComponent.add([defaultMarker, configuredMarker]);
24098  * ```
24099  */
24100 var CircleMarker = (function (_super) {
24101     __extends(CircleMarker, _super);
24102     function CircleMarker(id, latLon, options) {
24103         var _this = _super.call(this, id, latLon) || this;
24104         options = !!options ? options : {};
24105         _this._color = options.color != null ? options.color : 0xffffff;
24106         _this._opacity = options.opacity != null ? options.opacity : 0.4;
24107         _this._radius = options.radius != null ? options.radius : 1;
24108         return _this;
24109     }
24110     CircleMarker.prototype._createGeometry = function (position) {
24111         var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
24112             color: this._color,
24113             opacity: this._opacity,
24114             transparent: true,
24115         }));
24116         circle.up.fromArray([0, 0, 1]);
24117         circle.renderOrder = -1;
24118         var group = new THREE.Object3D();
24119         group.add(circle);
24120         group.position.fromArray(position);
24121         this._geometry = group;
24122     };
24123     CircleMarker.prototype._disposeGeometry = function () {
24124         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
24125             var mesh = _a[_i];
24126             mesh.geometry.dispose();
24127             mesh.material.dispose();
24128         }
24129     };
24130     CircleMarker.prototype._getInteractiveObjects = function () {
24131         return [];
24132     };
24133     return CircleMarker;
24134 }(Component_1.Marker));
24135 exports.CircleMarker = CircleMarker;
24136 Object.defineProperty(exports, "__esModule", { value: true });
24137 exports.default = CircleMarker;
24138
24139 },{"../../../Component":224,"three":174}],265:[function(require,module,exports){
24140 /// <reference path="../../../../typings/index.d.ts" />
24141 "use strict";
24142 /**
24143  * @class Marker
24144  *
24145  * @classdesc Represents an abstract marker class that should be extended
24146  * by marker implementations used in the marker component.
24147  */
24148 var Marker = (function () {
24149     function Marker(id, latLon) {
24150         this._id = id;
24151         this._latLon = latLon;
24152     }
24153     Object.defineProperty(Marker.prototype, "id", {
24154         /**
24155          * Get id.
24156          * @returns {string} The id of the marker.
24157          */
24158         get: function () {
24159             return this._id;
24160         },
24161         enumerable: true,
24162         configurable: true
24163     });
24164     Object.defineProperty(Marker.prototype, "geometry", {
24165         get: function () {
24166             return this._geometry;
24167         },
24168         enumerable: true,
24169         configurable: true
24170     });
24171     Object.defineProperty(Marker.prototype, "latLon", {
24172         /**
24173          * Get lat lon.
24174          * @returns {ILatLon} The geographic coordinates of the marker.
24175          */
24176         get: function () {
24177             return this._latLon;
24178         },
24179         enumerable: true,
24180         configurable: true
24181     });
24182     Marker.prototype.createGeometry = function (position) {
24183         if (!!this._geometry) {
24184             return;
24185         }
24186         this._createGeometry(position);
24187         // update matrix world if raycasting occurs before first render
24188         this._geometry.updateMatrixWorld(true);
24189     };
24190     Marker.prototype.disposeGeometry = function () {
24191         if (!this._geometry) {
24192             return;
24193         }
24194         this._disposeGeometry();
24195         this._geometry = undefined;
24196     };
24197     Marker.prototype.getInteractiveObjects = function () {
24198         if (!this._geometry) {
24199             return [];
24200         }
24201         return this._getInteractiveObjects();
24202     };
24203     Marker.prototype.lerpAltitude = function (alt, alpha) {
24204         if (!this._geometry) {
24205             return;
24206         }
24207         this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
24208     };
24209     Marker.prototype.updatePosition = function (position, latLon) {
24210         if (!!latLon) {
24211             this._latLon.lat = latLon.lat;
24212             this._latLon.lon = latLon.lon;
24213         }
24214         if (!this._geometry) {
24215             return;
24216         }
24217         this._geometry.position.fromArray(position);
24218         this._geometry.updateMatrixWorld(true);
24219     };
24220     return Marker;
24221 }());
24222 exports.Marker = Marker;
24223 Object.defineProperty(exports, "__esModule", { value: true });
24224 exports.default = Marker;
24225
24226 },{}],266:[function(require,module,exports){
24227 /// <reference path="../../../../typings/index.d.ts" />
24228 "use strict";
24229 var __extends = (this && this.__extends) || function (d, b) {
24230     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24231     function __() { this.constructor = d; }
24232     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24233 };
24234 var THREE = require("three");
24235 var Component_1 = require("../../../Component");
24236 /**
24237  * @class SimpleMarker
24238  *
24239  * @classdesc Interactive marker with ice cream shape. The sphere
24240  * inside the ice cream can be configured to be interactive.
24241  *
24242  * Simple marker properties can not be updated after creation.
24243  *
24244  * To create and add one `SimpleMarker` with default configuration
24245  * (non-interactive) and one interactive with configuration use
24246  *
24247  * @example
24248  * ```
24249  * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
24250  *     "id-1",
24251  *     { lat: 0, lon: 0, });
24252  *
24253  * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
24254  *     "id-2",
24255  *     { lat: 0, lon: 0, },
24256  *     {
24257  *         ballColor: "#00f",
24258  *         ballOpacity: 0.5,
24259  *         color: "#00f",
24260  *         interactive: true,
24261  *         opacity: 0.3,
24262  *         radius: 0.7,
24263  *     });
24264  *
24265  * markerComponent.add([defaultMarker, interactiveMarker]);
24266  * ```
24267  */
24268 var SimpleMarker = (function (_super) {
24269     __extends(SimpleMarker, _super);
24270     function SimpleMarker(id, latLon, options) {
24271         var _this = _super.call(this, id, latLon) || this;
24272         options = !!options ? options : {};
24273         _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
24274         _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
24275         _this._circleToRayAngle = 2;
24276         _this._color = options.color != null ? options.color : 0xff0000;
24277         _this._interactive = !!options.interactive;
24278         _this._opacity = options.opacity != null ? options.opacity : 0.4;
24279         _this._radius = options.radius != null ? options.radius : 1;
24280         return _this;
24281     }
24282     SimpleMarker.prototype._createGeometry = function (position) {
24283         var radius = this._radius;
24284         var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
24285             color: this._color,
24286             opacity: this._opacity,
24287             shading: THREE.SmoothShading,
24288             transparent: true,
24289         }));
24290         cone.renderOrder = 1;
24291         var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
24292             color: this._ballColor,
24293             opacity: this._ballOpacity,
24294             shading: THREE.SmoothShading,
24295             transparent: true,
24296         }));
24297         ball.position.z = this._markerHeight(radius);
24298         var group = new THREE.Object3D();
24299         group.add(ball);
24300         group.add(cone);
24301         group.position.fromArray(position);
24302         this._geometry = group;
24303     };
24304     SimpleMarker.prototype._disposeGeometry = function () {
24305         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
24306             var mesh = _a[_i];
24307             mesh.geometry.dispose();
24308             mesh.material.dispose();
24309         }
24310     };
24311     SimpleMarker.prototype._getInteractiveObjects = function () {
24312         return this._interactive ? [this._geometry.children[0]] : [];
24313     };
24314     SimpleMarker.prototype._markerHeight = function (radius) {
24315         var t = Math.tan(Math.PI - this._circleToRayAngle);
24316         return radius * Math.sqrt(1 + t * t);
24317     };
24318     SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
24319         var geometry = new THREE.Geometry();
24320         widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
24321         heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
24322         var height = this._markerHeight(radius);
24323         var vertices = [];
24324         for (var y = 0; y <= heightSegments; ++y) {
24325             var verticesRow = [];
24326             for (var x = 0; x <= widthSegments; ++x) {
24327                 var u = x / widthSegments * Math.PI * 2;
24328                 var v = y / heightSegments * Math.PI;
24329                 var r = void 0;
24330                 if (v < this._circleToRayAngle) {
24331                     r = radius;
24332                 }
24333                 else {
24334                     var t = Math.tan(v - this._circleToRayAngle);
24335                     r = radius * Math.sqrt(1 + t * t);
24336                 }
24337                 var vertex = new THREE.Vector3();
24338                 vertex.x = r * Math.cos(u) * Math.sin(v);
24339                 vertex.y = r * Math.sin(u) * Math.sin(v);
24340                 vertex.z = r * Math.cos(v) + height;
24341                 geometry.vertices.push(vertex);
24342                 verticesRow.push(geometry.vertices.length - 1);
24343             }
24344             vertices.push(verticesRow);
24345         }
24346         for (var y = 0; y < heightSegments; ++y) {
24347             for (var x = 0; x < widthSegments; ++x) {
24348                 var v1 = vertices[y][x + 1];
24349                 var v2 = vertices[y][x];
24350                 var v3 = vertices[y + 1][x];
24351                 var v4 = vertices[y + 1][x + 1];
24352                 var n1 = geometry.vertices[v1].clone().normalize();
24353                 var n2 = geometry.vertices[v2].clone().normalize();
24354                 var n3 = geometry.vertices[v3].clone().normalize();
24355                 var n4 = geometry.vertices[v4].clone().normalize();
24356                 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
24357                 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
24358             }
24359         }
24360         geometry.computeFaceNormals();
24361         geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
24362         return geometry;
24363     };
24364     return SimpleMarker;
24365 }(Component_1.Marker));
24366 exports.SimpleMarker = SimpleMarker;
24367 Object.defineProperty(exports, "__esModule", { value: true });
24368 exports.default = SimpleMarker;
24369
24370 },{"../../../Component":224,"three":174}],267:[function(require,module,exports){
24371 "use strict";
24372 var __extends = (this && this.__extends) || function (d, b) {
24373     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24374     function __() { this.constructor = d; }
24375     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24376 };
24377 var Observable_1 = require("rxjs/Observable");
24378 var Component_1 = require("../../Component");
24379 /**
24380  * The `DoubleClickZoomHandler` allows the user to zoom the viewer photo at a point by double clicking.
24381  */
24382 var DoubleClickZoomHandler = (function (_super) {
24383     __extends(DoubleClickZoomHandler, _super);
24384     function DoubleClickZoomHandler() {
24385         return _super !== null && _super.apply(this, arguments) || this;
24386     }
24387     DoubleClickZoomHandler.prototype._enable = function () {
24388         var _this = this;
24389         this._zoomSubscription = Observable_1.Observable
24390             .merge(this._container.mouseService
24391             .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
24392             .map(function (e) {
24393             var touch = e.touches[0];
24394             return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
24395         }))
24396             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
24397             .subscribe(function (_a) {
24398             var event = _a[0], render = _a[1], transform = _a[2];
24399             var element = _this._container.element;
24400             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24401             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
24402             var reference = transform.projectBasic(unprojected.toArray());
24403             var delta = !!event.shiftKey ? -1 : 1;
24404             _this._navigator.stateService.zoomIn(delta, reference);
24405         });
24406     };
24407     DoubleClickZoomHandler.prototype._disable = function () {
24408         this._zoomSubscription.unsubscribe();
24409     };
24410     DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
24411         return { doubleClickZoom: enable };
24412     };
24413     return DoubleClickZoomHandler;
24414 }(Component_1.MouseHandlerBase));
24415 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
24416 Object.defineProperty(exports, "__esModule", { value: true });
24417 exports.default = DoubleClickZoomHandler;
24418
24419 },{"../../Component":224,"rxjs/Observable":28}],268:[function(require,module,exports){
24420 /// <reference path="../../../typings/index.d.ts" />
24421 "use strict";
24422 var __extends = (this && this.__extends) || function (d, b) {
24423     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24424     function __() { this.constructor = d; }
24425     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24426 };
24427 var THREE = require("three");
24428 var Observable_1 = require("rxjs/Observable");
24429 var Component_1 = require("../../Component");
24430 /**
24431  * The `DragPanHandler` allows the user to pan the viewer photo by clicking and dragging the cursor.
24432  */
24433 var DragPanHandler = (function (_super) {
24434     __extends(DragPanHandler, _super);
24435     function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
24436         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
24437         _this._spatial = spatial;
24438         _this._basicRotationThreshold = 5e-2;
24439         _this._forceCoeff = 2e-1;
24440         return _this;
24441     }
24442     DragPanHandler.prototype._enable = function () {
24443         var _this = this;
24444         this._preventDefaultSubscription = Observable_1.Observable.merge(this._container.mouseService.mouseDragStart$, this._container.mouseService.mouseDrag$, this._container.touchService.touchMove$)
24445             .subscribe(function (event) {
24446             event.preventDefault(); // prevent selection of content outside the viewer
24447         });
24448         var draggingStarted$ = this._container.mouseService
24449             .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
24450             .map(function (event) {
24451             return true;
24452         });
24453         var draggingStopped$ = this._container.mouseService
24454             .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
24455             .map(function (event) {
24456             return false;
24457         });
24458         this._activeMouseSubscription = Observable_1.Observable
24459             .merge(draggingStarted$, draggingStopped$)
24460             .subscribe(this._container.mouseService.activate$);
24461         var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
24462             .map(function (event) {
24463             return true;
24464         });
24465         var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
24466             .map(function (event) {
24467             return false;
24468         });
24469         this._activeTouchSubscription = Observable_1.Observable
24470             .merge(touchMovingStarted$, touchMovingStopped$)
24471             .subscribe(this._container.touchService.activate$);
24472         this._rotateBasicSubscription = this._navigator.stateService.currentState$
24473             .map(function (frame) {
24474             return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
24475         })
24476             .distinctUntilChanged()
24477             .switchMap(function (enable) {
24478             if (!enable) {
24479                 return Observable_1.Observable.empty();
24480             }
24481             var mouseDrag$ = Observable_1.Observable
24482                 .merge(_this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDragStart$), _this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDrag$), _this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDragEnd$)
24483                 .map(function (e) { return null; }))
24484                 .pairwise()
24485                 .filter(function (pair) {
24486                 return pair[0] != null && pair[1] != null;
24487             });
24488             var singleTouchDrag$ = Observable_1.Observable
24489                 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
24490                 .map(function (event) {
24491                 return event != null && event.touches.length > 0 ?
24492                     event.touches[0] : null;
24493             })
24494                 .pairwise()
24495                 .filter(function (pair) {
24496                 return pair[0] != null && pair[1] != null;
24497             });
24498             return Observable_1.Observable
24499                 .merge(mouseDrag$, singleTouchDrag$);
24500         })
24501             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
24502             .map(function (_a) {
24503             var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
24504             var camera = c.clone();
24505             var previousEvent = events[0];
24506             var event = events[1];
24507             var movementX = event.clientX - previousEvent.clientX;
24508             var movementY = event.clientY - previousEvent.clientY;
24509             var element = _this._container.element;
24510             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24511             var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
24512                 .sub(render.perspective.position);
24513             var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
24514                 .sub(render.perspective.position);
24515             var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
24516                 .sub(render.perspective.position);
24517             var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
24518             var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
24519             var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
24520             var upQuaternionInverse = upQuaternion.clone().inverse();
24521             var offset = new THREE.Vector3();
24522             offset.copy(camera.lookat).sub(camera.position);
24523             offset.applyQuaternion(upQuaternion);
24524             var length = offset.length();
24525             var phi = Math.atan2(offset.y, offset.x);
24526             phi += deltaPhi;
24527             var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
24528             theta += deltaTheta;
24529             theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
24530             offset.x = Math.sin(theta) * Math.cos(phi);
24531             offset.y = Math.sin(theta) * Math.sin(phi);
24532             offset.z = Math.cos(theta);
24533             offset.applyQuaternion(upQuaternionInverse);
24534             var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
24535             var basic = transform.projectBasic(lookat.toArray());
24536             var original = transform.projectBasic(camera.lookat.toArray());
24537             var x = basic[0] - original[0];
24538             var y = basic[1] - original[1];
24539             if (Math.abs(x) > 1) {
24540                 x = 0;
24541             }
24542             else if (x > 0.5) {
24543                 x = x - 1;
24544             }
24545             else if (x < -0.5) {
24546                 x = x + 1;
24547             }
24548             var rotationThreshold = _this._basicRotationThreshold;
24549             x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
24550             y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
24551             if (transform.fullPano) {
24552                 return [x, y];
24553             }
24554             var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
24555             var coeff = _this._forceCoeff;
24556             if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
24557                 y /= Math.max(1, coeff * pixelDistances[0]);
24558             }
24559             if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
24560                 x /= Math.max(1, coeff * pixelDistances[1]);
24561             }
24562             if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
24563                 y /= Math.max(1, coeff * pixelDistances[2]);
24564             }
24565             if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
24566                 x /= Math.max(1, coeff * pixelDistances[3]);
24567             }
24568             return [x, y];
24569         })
24570             .subscribe(function (basicRotation) {
24571             _this._navigator.stateService.rotateBasic(basicRotation);
24572         });
24573     };
24574     DragPanHandler.prototype._disable = function () {
24575         this._activeMouseSubscription.unsubscribe();
24576         this._activeTouchSubscription.unsubscribe();
24577         this._preventDefaultSubscription.unsubscribe();
24578         this._rotateBasicSubscription.unsubscribe();
24579         this._activeMouseSubscription = null;
24580         this._activeTouchSubscription = null;
24581         this._rotateBasicSubscription = null;
24582     };
24583     DragPanHandler.prototype._getConfiguration = function (enable) {
24584         return { dragPan: enable };
24585     };
24586     return DragPanHandler;
24587 }(Component_1.MouseHandlerBase));
24588 exports.DragPanHandler = DragPanHandler;
24589 Object.defineProperty(exports, "__esModule", { value: true });
24590 exports.default = DragPanHandler;
24591
24592 },{"../../Component":224,"rxjs/Observable":28,"three":174}],269:[function(require,module,exports){
24593 /// <reference path="../../../typings/index.d.ts" />
24594 "use strict";
24595 var __extends = (this && this.__extends) || function (d, b) {
24596     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24597     function __() { this.constructor = d; }
24598     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24599 };
24600 var Observable_1 = require("rxjs/Observable");
24601 require("rxjs/add/observable/merge");
24602 require("rxjs/add/operator/filter");
24603 require("rxjs/add/operator/map");
24604 require("rxjs/add/operator/withLatestFrom");
24605 var Component_1 = require("../../Component");
24606 var Geo_1 = require("../../Geo");
24607 /**
24608  * @class MouseComponent
24609  *
24610  * @classdesc Component handling mouse and touch events for camera movement.
24611  */
24612 var MouseComponent = (function (_super) {
24613     __extends(MouseComponent, _super);
24614     function MouseComponent(name, container, navigator) {
24615         var _this = _super.call(this, name, container, navigator) || this;
24616         _this._basicDistanceThreshold = 1e-3;
24617         _this._basicRotationThreshold = 5e-2;
24618         _this._bounceCoeff = 1e-1;
24619         var spatial = new Geo_1.Spatial();
24620         var viewportCoords = new Geo_1.ViewportCoords();
24621         _this._spatial = spatial;
24622         _this._viewportCoords = viewportCoords;
24623         _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
24624         _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
24625         _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
24626         _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
24627         return _this;
24628     }
24629     Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
24630         /**
24631          * Get double click zoom.
24632          *
24633          * @returns {DoubleClickZoomHandler} The double click zoom handler.
24634          */
24635         get: function () {
24636             return this._doubleClickZoomHandler;
24637         },
24638         enumerable: true,
24639         configurable: true
24640     });
24641     Object.defineProperty(MouseComponent.prototype, "dragPan", {
24642         /**
24643          * Get drag pan.
24644          *
24645          * @returns {DragPanHandler} The drag pan handler.
24646          */
24647         get: function () {
24648             return this._dragPanHandler;
24649         },
24650         enumerable: true,
24651         configurable: true
24652     });
24653     Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
24654         /**
24655          * Get scroll zoom.
24656          *
24657          * @returns {ScrollZoomHandler} The scroll zoom handler.
24658          */
24659         get: function () {
24660             return this._scrollZoomHandler;
24661         },
24662         enumerable: true,
24663         configurable: true
24664     });
24665     Object.defineProperty(MouseComponent.prototype, "touchZoom", {
24666         /**
24667          * Get touch zoom.
24668          *
24669          * @returns {TouchZoomHandler} The touch zoom handler.
24670          */
24671         get: function () {
24672             return this._touchZoomHandler;
24673         },
24674         enumerable: true,
24675         configurable: true
24676     });
24677     MouseComponent.prototype._activate = function () {
24678         var _this = this;
24679         this._configurationSubscription = this._configuration$
24680             .subscribe(function (configuration) {
24681             if (configuration.doubleClickZoom) {
24682                 _this._doubleClickZoomHandler.enable();
24683             }
24684             else {
24685                 _this._doubleClickZoomHandler.disable();
24686             }
24687             if (configuration.dragPan) {
24688                 _this._dragPanHandler.enable();
24689             }
24690             else {
24691                 _this._dragPanHandler.disable();
24692             }
24693             if (configuration.scrollZoom) {
24694                 _this._scrollZoomHandler.enable();
24695             }
24696             else {
24697                 _this._scrollZoomHandler.disable();
24698             }
24699             if (configuration.touchZoom) {
24700                 _this._touchZoomHandler.enable();
24701             }
24702             else {
24703                 _this._touchZoomHandler.disable();
24704             }
24705         });
24706         var inTransition$ = this._navigator.stateService.currentState$
24707             .map(function (frame) {
24708             return frame.state.alpha < 1;
24709         });
24710         this._bounceSubscription = Observable_1.Observable
24711             .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
24712             .map(function (noForce) {
24713             return noForce[0] || noForce[1] || noForce[2] || noForce[3];
24714         })
24715             .distinctUntilChanged()
24716             .switchMap(function (noForce) {
24717             return noForce ?
24718                 Observable_1.Observable.empty() :
24719                 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
24720         })
24721             .subscribe(function (args) {
24722             var renderCamera = args[0];
24723             var perspectiveCamera = renderCamera.perspective;
24724             var transform = args[1];
24725             var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
24726             var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
24727             if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
24728                 return;
24729             }
24730             var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
24731             var basicX = 0;
24732             var basicY = 0;
24733             if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
24734                 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
24735                 return;
24736             }
24737             if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
24738                 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
24739                 return;
24740             }
24741             var coeff = _this._bounceCoeff;
24742             if (basicDistances[1] > 0 && basicDistances[3] === 0) {
24743                 basicX = -coeff * basicDistances[1];
24744             }
24745             else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
24746                 basicX = coeff * basicDistances[3];
24747             }
24748             else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
24749                 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
24750             }
24751             if (basicDistances[0] > 0 && basicDistances[2] === 0) {
24752                 basicY = coeff * basicDistances[0];
24753             }
24754             else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
24755                 basicY = -coeff * basicDistances[2];
24756             }
24757             else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
24758                 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
24759             }
24760             var rotationThreshold = _this._basicRotationThreshold;
24761             basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
24762             basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
24763             _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
24764         });
24765         this._container.mouseService.claimMouse(this._name, 0);
24766     };
24767     MouseComponent.prototype._deactivate = function () {
24768         this._container.mouseService.unclaimMouse(this._name);
24769         this._bounceSubscription.unsubscribe();
24770         this._configurationSubscription.unsubscribe();
24771         this._doubleClickZoomHandler.disable();
24772         this._dragPanHandler.disable();
24773         this._scrollZoomHandler.disable();
24774         this._touchZoomHandler.disable();
24775     };
24776     MouseComponent.prototype._getDefaultConfiguration = function () {
24777         return { doubleClickZoom: true, dragPan: true, scrollZoom: true, touchZoom: true };
24778     };
24779     return MouseComponent;
24780 }(Component_1.Component));
24781 /** @inheritdoc */
24782 MouseComponent.componentName = "mouse";
24783 exports.MouseComponent = MouseComponent;
24784 Component_1.ComponentService.register(MouseComponent);
24785 Object.defineProperty(exports, "__esModule", { value: true });
24786 exports.default = MouseComponent;
24787
24788 },{"../../Component":224,"../../Geo":227,"rxjs/Observable":28,"rxjs/add/observable/merge":43,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/withLatestFrom":82}],270:[function(require,module,exports){
24789 "use strict";
24790 var MouseHandlerBase = (function () {
24791     function MouseHandlerBase(component, container, navigator, viewportCoords) {
24792         this._component = component;
24793         this._container = container;
24794         this._navigator = navigator;
24795         this._viewportCoords = viewportCoords;
24796         this._enabled = false;
24797     }
24798     Object.defineProperty(MouseHandlerBase.prototype, "isEnabled", {
24799         /**
24800          * Returns a Boolean indicating whether the interaction is enabled.
24801          *
24802          * @returns {boolean} `true` if the interaction is enabled.
24803          */
24804         get: function () {
24805             return this._enabled;
24806         },
24807         enumerable: true,
24808         configurable: true
24809     });
24810     /**
24811      * Enables the interaction.
24812      *
24813      * @example ```mouseComponent.<handler-name>.enable();```
24814      */
24815     MouseHandlerBase.prototype.enable = function () {
24816         if (this._enabled || !this._component.activated) {
24817             return;
24818         }
24819         this._enable();
24820         this._enabled = true;
24821         this._component.configure(this._getConfiguration(true));
24822     };
24823     /**
24824      * Disables the interaction.
24825      *
24826      * @example ```mouseComponent.<handler-name>.disable();```
24827      */
24828     MouseHandlerBase.prototype.disable = function () {
24829         if (!this._enabled) {
24830             return;
24831         }
24832         this._disable();
24833         this._enabled = false;
24834         if (this._component.activated) {
24835             this._component.configure(this._getConfiguration(false));
24836         }
24837     };
24838     return MouseHandlerBase;
24839 }());
24840 exports.MouseHandlerBase = MouseHandlerBase;
24841 Object.defineProperty(exports, "__esModule", { value: true });
24842 exports.default = MouseHandlerBase;
24843
24844 },{}],271:[function(require,module,exports){
24845 "use strict";
24846 var __extends = (this && this.__extends) || function (d, b) {
24847     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24848     function __() { this.constructor = d; }
24849     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24850 };
24851 var Component_1 = require("../../Component");
24852 /**
24853  * The `ScrollZoomHandler` allows the user to zoom the viewer photo by scrolling.
24854  */
24855 var ScrollZoomHandler = (function (_super) {
24856     __extends(ScrollZoomHandler, _super);
24857     function ScrollZoomHandler() {
24858         return _super !== null && _super.apply(this, arguments) || this;
24859     }
24860     ScrollZoomHandler.prototype._enable = function () {
24861         var _this = this;
24862         this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
24863             .subscribe(function (event) {
24864             event.preventDefault();
24865         });
24866         this._zoomSubscription = this._container.mouseService
24867             .filtered$(this._component.name, this._container.mouseService.mouseWheel$)
24868             .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
24869             return [w, f];
24870         })
24871             .filter(function (args) {
24872             var state = args[1].state;
24873             return state.currentNode.fullPano || state.nodesAhead < 1;
24874         })
24875             .map(function (args) {
24876             return args[0];
24877         })
24878             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
24879             return [w, r, t];
24880         })
24881             .subscribe(function (args) {
24882             var event = args[0];
24883             var render = args[1];
24884             var transform = args[2];
24885             var element = _this._container.element;
24886             var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
24887             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
24888             var reference = transform.projectBasic(unprojected.toArray());
24889             var deltaY = event.deltaY;
24890             if (event.deltaMode === 1) {
24891                 deltaY = 40 * deltaY;
24892             }
24893             else if (event.deltaMode === 2) {
24894                 deltaY = 800 * deltaY;
24895             }
24896             var canvasSize = _this._viewportCoords.containerToCanvas(element);
24897             var zoom = -3 * deltaY / canvasSize[1];
24898             _this._navigator.stateService.zoomIn(zoom, reference);
24899         });
24900     };
24901     ScrollZoomHandler.prototype._disable = function () {
24902         this._preventDefaultSubscription.unsubscribe();
24903         this._zoomSubscription.unsubscribe();
24904         this._preventDefaultSubscription = null;
24905         this._zoomSubscription = null;
24906     };
24907     ScrollZoomHandler.prototype._getConfiguration = function (enable) {
24908         return { scrollZoom: enable };
24909     };
24910     return ScrollZoomHandler;
24911 }(Component_1.MouseHandlerBase));
24912 exports.ScrollZoomHandler = ScrollZoomHandler;
24913 Object.defineProperty(exports, "__esModule", { value: true });
24914 exports.default = ScrollZoomHandler;
24915
24916 },{"../../Component":224}],272:[function(require,module,exports){
24917 /// <reference path="../../../typings/index.d.ts" />
24918 "use strict";
24919 var __extends = (this && this.__extends) || function (d, b) {
24920     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24921     function __() { this.constructor = d; }
24922     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24923 };
24924 var Observable_1 = require("rxjs/Observable");
24925 var Component_1 = require("../../Component");
24926 /**
24927  * The `TouchZoomHandler` allows the user to zoom the viewer photo by pinching on a touchscreen.
24928  */
24929 var TouchZoomHandler = (function (_super) {
24930     __extends(TouchZoomHandler, _super);
24931     function TouchZoomHandler() {
24932         return _super !== null && _super.apply(this, arguments) || this;
24933     }
24934     TouchZoomHandler.prototype._enable = function () {
24935         var _this = this;
24936         this._preventDefaultSubscription = this._container.touchService.pinch$
24937             .subscribe(function (pinch) {
24938             pinch.originalEvent.preventDefault();
24939         });
24940         var pinchStarted$ = this._container.touchService.pinchStart$
24941             .map(function (event) {
24942             return true;
24943         });
24944         var pinchStopped$ = this._container.touchService.pinchEnd$
24945             .map(function (event) {
24946             return false;
24947         });
24948         this._activeSubscription = Observable_1.Observable
24949             .merge(pinchStarted$, pinchStopped$)
24950             .subscribe(this._container.touchService.activate$);
24951         this._zoomSubscription = this._container.touchService.pinch$
24952             .withLatestFrom(this._navigator.stateService.currentState$)
24953             .filter(function (args) {
24954             var state = args[1].state;
24955             return state.currentNode.fullPano || state.nodesAhead < 1;
24956         })
24957             .map(function (args) {
24958             return args[0];
24959         })
24960             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
24961             .subscribe(function (_a) {
24962             var pinch = _a[0], render = _a[1], transform = _a[2];
24963             var element = _this._container.element;
24964             var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
24965             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
24966             var reference = transform.projectBasic(unprojected.toArray());
24967             var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
24968             var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
24969             _this._navigator.stateService.zoomIn(zoom, reference);
24970         });
24971     };
24972     TouchZoomHandler.prototype._disable = function () {
24973         this._activeSubscription.unsubscribe();
24974         this._preventDefaultSubscription.unsubscribe();
24975         this._zoomSubscription.unsubscribe();
24976         this._preventDefaultSubscription = null;
24977         this._zoomSubscription = null;
24978     };
24979     TouchZoomHandler.prototype._getConfiguration = function (enable) {
24980         return { touchZoom: enable };
24981     };
24982     return TouchZoomHandler;
24983 }(Component_1.MouseHandlerBase));
24984 exports.TouchZoomHandler = TouchZoomHandler;
24985 Object.defineProperty(exports, "__esModule", { value: true });
24986 exports.default = TouchZoomHandler;
24987
24988 },{"../../Component":224,"rxjs/Observable":28}],273:[function(require,module,exports){
24989 /// <reference path="../../../typings/index.d.ts" />
24990 "use strict";
24991 var __extends = (this && this.__extends) || function (d, b) {
24992     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24993     function __() { this.constructor = d; }
24994     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24995 };
24996 var Observable_1 = require("rxjs/Observable");
24997 var Subject_1 = require("rxjs/Subject");
24998 require("rxjs/add/observable/combineLatest");
24999 require("rxjs/add/observable/of");
25000 require("rxjs/add/operator/bufferCount");
25001 require("rxjs/add/operator/concat");
25002 require("rxjs/add/operator/distinctUntilChanged");
25003 require("rxjs/add/operator/filter");
25004 require("rxjs/add/operator/finally");
25005 require("rxjs/add/operator/first");
25006 require("rxjs/add/operator/map");
25007 require("rxjs/add/operator/publishReplay");
25008 require("rxjs/add/operator/scan");
25009 require("rxjs/add/operator/share");
25010 require("rxjs/add/operator/switchMap");
25011 require("rxjs/add/operator/takeUntil");
25012 require("rxjs/add/operator/withLatestFrom");
25013 var Component_1 = require("../../Component");
25014 var Edge_1 = require("../../Edge");
25015 /**
25016  * @class SequenceComponent
25017  * @classdesc Component showing navigation arrows for sequence directions
25018  * as well as playing button. Exposes an API to start and stop play.
25019  */
25020 var SequenceComponent = (function (_super) {
25021     __extends(SequenceComponent, _super);
25022     function SequenceComponent(name, container, navigator) {
25023         var _this = _super.call(this, name, container, navigator) || this;
25024         _this._nodesAhead = 5;
25025         _this._configurationOperation$ = new Subject_1.Subject();
25026         _this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element);
25027         _this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
25028         _this._containerWidth$ = new Subject_1.Subject();
25029         _this._hoveredKeySubject$ = new Subject_1.Subject();
25030         _this._hoveredKey$ = _this._hoveredKeySubject$.share();
25031         _this._edgeStatus$ = _this._navigator.stateService.currentNode$
25032             .switchMap(function (node) {
25033             return node.sequenceEdges$;
25034         })
25035             .publishReplay(1)
25036             .refCount();
25037         return _this;
25038     }
25039     Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
25040         /**
25041          * Get hovered key observable.
25042          *
25043          * @description An observable emitting the key of the node for the direction
25044          * arrow that is being hovered. When the mouse leaves a direction arrow null
25045          * is emitted.
25046          *
25047          * @returns {Observable<string>}
25048          */
25049         get: function () {
25050             return this._hoveredKey$;
25051         },
25052         enumerable: true,
25053         configurable: true
25054     });
25055     /**
25056      * Start playing.
25057      *
25058      * @fires PlayerComponent#playingchanged
25059      */
25060     SequenceComponent.prototype.play = function () {
25061         this.configure({ playing: true });
25062     };
25063     /**
25064      * Stop playing.
25065      *
25066      * @fires PlayerComponent#playingchanged
25067      */
25068     SequenceComponent.prototype.stop = function () {
25069         this.configure({ playing: false });
25070     };
25071     /**
25072      * Set the direction to follow when playing.
25073      *
25074      * @param {EdgeDirection} direction - The direction that will be followed when playing.
25075      */
25076     SequenceComponent.prototype.setDirection = function (direction) {
25077         this.configure({ direction: direction });
25078     };
25079     /**
25080      * Set highlight key.
25081      *
25082      * @description The arrow pointing towards the node corresponding to the
25083      * highlight key will be highlighted.
25084      *
25085      * @param {string} highlightKey Key of node to be highlighted if existing.
25086      */
25087     SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
25088         this.configure({ highlightKey: highlightKey });
25089     };
25090     /**
25091      * Set max width of container element.
25092      *
25093      * @description Set max width of the container element holding
25094      * the sequence navigation elements. If the min width is larger than the
25095      * max width the min width value will be used.
25096      *
25097      * The container element is automatically resized when the resize
25098      * method on the Viewer class is called.
25099      *
25100      * @param {number} minWidth
25101      */
25102     SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
25103         this.configure({ maxWidth: maxWidth });
25104     };
25105     /**
25106      * Set min width of container element.
25107      *
25108      * @description Set min width of the container element holding
25109      * the sequence navigation elements. If the min width is larger than the
25110      * max width the min width value will be used.
25111      *
25112      * The container element is automatically resized when the resize
25113      * method on the Viewer class is called.
25114      *
25115      * @param {number} minWidth
25116      */
25117     SequenceComponent.prototype.setMinWidth = function (minWidth) {
25118         this.configure({ minWidth: minWidth });
25119     };
25120     /**
25121      * Set the value indicating whether the sequence UI elements should be visible.
25122      *
25123      * @param {boolean} visible
25124      */
25125     SequenceComponent.prototype.setVisible = function (visible) {
25126         this.configure({ visible: visible });
25127     };
25128     /** @inheritdoc */
25129     SequenceComponent.prototype.resize = function () {
25130         var _this = this;
25131         this._configuration$
25132             .first()
25133             .map(function (configuration) {
25134             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
25135         })
25136             .subscribe(function (containerWidth) {
25137             _this._containerWidth$.next(containerWidth);
25138         });
25139     };
25140     SequenceComponent.prototype._activate = function () {
25141         var _this = this;
25142         this._renderSubscription = Observable_1.Observable
25143             .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$)
25144             .map(function (ec) {
25145             var edgeStatus = ec[0];
25146             var configuration = ec[1];
25147             var containerWidth = ec[2];
25148             var vNode = _this._sequenceDOMRenderer
25149                 .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator);
25150             return { name: _this._name, vnode: vNode };
25151         })
25152             .subscribe(this._container.domRenderer.render$);
25153         this._containerWidthSubscription = this._configuration$
25154             .distinctUntilChanged(function (value1, value2) {
25155             return value1[0] === value2[0] && value1[1] === value2[1];
25156         }, function (configuration) {
25157             return [configuration.minWidth, configuration.maxWidth];
25158         })
25159             .map(function (configuration) {
25160             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
25161         })
25162             .subscribe(this._containerWidth$);
25163         this._configurationSubscription = this._configurationOperation$
25164             .scan(function (configuration, operation) {
25165             return operation(configuration);
25166         }, { playing: false })
25167             .finally(function () {
25168             if (_this._playingSubscription != null) {
25169                 _this._navigator.stateService.cutNodes();
25170                 _this._stop();
25171             }
25172         })
25173             .subscribe(function () { });
25174         this._configuration$
25175             .map(function (newConfiguration) {
25176             return function (configuration) {
25177                 if (newConfiguration.playing !== configuration.playing) {
25178                     _this._navigator.stateService.cutNodes();
25179                     if (newConfiguration.playing) {
25180                         _this._play();
25181                     }
25182                     else {
25183                         _this._stop();
25184                     }
25185                 }
25186                 configuration.playing = newConfiguration.playing;
25187                 return configuration;
25188             };
25189         })
25190             .subscribe(this._configurationOperation$);
25191         this._stopSubscription = this._configuration$
25192             .switchMap(function (configuration) {
25193             var edgeStatus$ = configuration.playing ?
25194                 _this._edgeStatus$ :
25195                 Observable_1.Observable.empty();
25196             var edgeDirection$ = Observable_1.Observable
25197                 .of(configuration.direction);
25198             return Observable_1.Observable
25199                 .combineLatest(edgeStatus$, edgeDirection$);
25200         })
25201             .map(function (ne) {
25202             var edgeStatus = ne[0];
25203             var direction = ne[1];
25204             if (!edgeStatus.cached) {
25205                 return true;
25206             }
25207             for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25208                 var edge = _a[_i];
25209                 if (edge.data.direction === direction) {
25210                     return true;
25211                 }
25212             }
25213             return false;
25214         })
25215             .filter(function (hasEdge) {
25216             return !hasEdge;
25217         })
25218             .map(function (hasEdge) {
25219             return { playing: false };
25220         })
25221             .subscribe(this._configurationSubject$);
25222         this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
25223             .switchMap(function (direction) {
25224             return _this._edgeStatus$
25225                 .map(function (edgeStatus) {
25226                 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25227                     var edge = _a[_i];
25228                     if (edge.data.direction === direction) {
25229                         return edge.to;
25230                     }
25231                 }
25232                 return null;
25233             })
25234                 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
25235                 .concat(Observable_1.Observable.of(null));
25236         })
25237             .distinctUntilChanged()
25238             .subscribe(this._hoveredKeySubject$);
25239     };
25240     SequenceComponent.prototype._deactivate = function () {
25241         this._stopSubscription.unsubscribe();
25242         this._renderSubscription.unsubscribe();
25243         this._configurationSubscription.unsubscribe();
25244         this._containerWidthSubscription.unsubscribe();
25245         this._hoveredKeySubscription.unsubscribe();
25246         this.stop();
25247     };
25248     SequenceComponent.prototype._getDefaultConfiguration = function () {
25249         return {
25250             direction: Edge_1.EdgeDirection.Next,
25251             maxWidth: 117,
25252             minWidth: 70,
25253             playing: false,
25254             visible: true,
25255         };
25256     };
25257     SequenceComponent.prototype._play = function () {
25258         var _this = this;
25259         this._playingSubscription = this._navigator.stateService.currentState$
25260             .filter(function (frame) {
25261             return frame.state.nodesAhead < _this._nodesAhead;
25262         })
25263             .map(function (frame) {
25264             return frame.state.lastNode;
25265         })
25266             .distinctUntilChanged(undefined, function (lastNode) {
25267             return lastNode.key;
25268         })
25269             .withLatestFrom(this._configuration$, function (lastNode, configuration) {
25270             return [lastNode, configuration.direction];
25271         })
25272             .switchMap(function (nd) {
25273             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ?
25274                 nd[0].sequenceEdges$ :
25275                 nd[0].spatialEdges$)
25276                 .filter(function (status) {
25277                 return status.cached;
25278             })
25279                 .zip(Observable_1.Observable.of(nd[1]), function (status, direction) {
25280                 return [status, direction];
25281             });
25282         })
25283             .map(function (ed) {
25284             var direction = ed[1];
25285             for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) {
25286                 var edge = _a[_i];
25287                 if (edge.data.direction === direction) {
25288                     return edge.to;
25289                 }
25290             }
25291             return null;
25292         })
25293             .filter(function (key) {
25294             return key != null;
25295         })
25296             .switchMap(function (key) {
25297             return _this._navigator.graphService.cacheNode$(key);
25298         })
25299             .subscribe(function (node) {
25300             _this._navigator.stateService.appendNodes([node]);
25301         }, function (error) {
25302             console.error(error);
25303             _this.stop();
25304         });
25305         this._clearSubscription = this._navigator.stateService.currentNode$
25306             .bufferCount(1, 7)
25307             .subscribe(function (nodes) {
25308             _this._navigator.stateService.clearPriorNodes();
25309         });
25310         this.fire(SequenceComponent.playingchanged, true);
25311     };
25312     SequenceComponent.prototype._stop = function () {
25313         this._playingSubscription.unsubscribe();
25314         this._playingSubscription = null;
25315         this._clearSubscription.unsubscribe();
25316         this._clearSubscription = null;
25317         this.fire(SequenceComponent.playingchanged, false);
25318     };
25319     return SequenceComponent;
25320 }(Component_1.Component));
25321 /** @inheritdoc */
25322 SequenceComponent.componentName = "sequence";
25323 /**
25324  * Event fired when playing starts or stops.
25325  *
25326  * @event PlayerComponent#playingchanged
25327  * @type {boolean} Indicates whether the player is playing.
25328  */
25329 SequenceComponent.playingchanged = "playingchanged";
25330 exports.SequenceComponent = SequenceComponent;
25331 Component_1.ComponentService.register(SequenceComponent);
25332 Object.defineProperty(exports, "__esModule", { value: true });
25333 exports.default = SequenceComponent;
25334
25335 },{"../../Component":224,"../../Edge":225,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/of":44,"rxjs/add/operator/bufferCount":49,"rxjs/add/operator/concat":53,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/finally":61,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/takeUntil":80,"rxjs/add/operator/withLatestFrom":82}],274:[function(require,module,exports){
25336 "use strict";
25337 var Subject_1 = require("rxjs/Subject");
25338 var SequenceDOMInteraction = (function () {
25339     function SequenceDOMInteraction() {
25340         this._mouseEnterDirection$ = new Subject_1.Subject();
25341         this._mouseLeaveDirection$ = new Subject_1.Subject();
25342     }
25343     Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
25344         get: function () {
25345             return this._mouseEnterDirection$;
25346         },
25347         enumerable: true,
25348         configurable: true
25349     });
25350     Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
25351         get: function () {
25352             return this._mouseLeaveDirection$;
25353         },
25354         enumerable: true,
25355         configurable: true
25356     });
25357     return SequenceDOMInteraction;
25358 }());
25359 exports.SequenceDOMInteraction = SequenceDOMInteraction;
25360 Object.defineProperty(exports, "__esModule", { value: true });
25361 exports.default = SequenceDOMInteraction;
25362
25363 },{"rxjs/Subject":33}],275:[function(require,module,exports){
25364 /// <reference path="../../../typings/index.d.ts" />
25365 "use strict";
25366 var vd = require("virtual-dom");
25367 var Edge_1 = require("../../Edge");
25368 var SequenceDOMRenderer = (function () {
25369     function SequenceDOMRenderer(element) {
25370         this._minThresholdWidth = 320;
25371         this._maxThresholdWidth = 1480;
25372         this._minThresholdHeight = 240;
25373         this._maxThresholdHeight = 820;
25374     }
25375     SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
25376         if (configuration.visible === false) {
25377             return vd.h("div.SequenceContainer", {}, []);
25378         }
25379         var nextKey = null;
25380         var prevKey = null;
25381         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25382             var edge = _a[_i];
25383             if (edge.data.direction === Edge_1.EdgeDirection.Next) {
25384                 nextKey = edge.to;
25385             }
25386             if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
25387                 prevKey = edge.to;
25388             }
25389         }
25390         var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
25391         var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator);
25392         var containerProperties = {
25393             oncontextmenu: function (event) { event.preventDefault(); },
25394             style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" },
25395         };
25396         return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton]));
25397     };
25398     SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
25399         var elementWidth = element.offsetWidth;
25400         var elementHeight = element.offsetHeight;
25401         var minWidth = configuration.minWidth;
25402         var maxWidth = configuration.maxWidth;
25403         if (maxWidth < minWidth) {
25404             maxWidth = minWidth;
25405         }
25406         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
25407         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
25408         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
25409         return minWidth + coeff * (maxWidth - minWidth);
25410     };
25411     SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
25412         var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
25413             configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
25414         var onclick = configuration.playing ?
25415             function (e) { component.stop(); } :
25416             canPlay ? function (e) { component.play(); } : null;
25417         var buttonProperties = {
25418             onclick: onclick,
25419             style: {},
25420         };
25421         var iconClass = configuration.playing ?
25422             "Stop" :
25423             canPlay ? "Play" : "PlayDisabled";
25424         var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []);
25425         var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
25426         return vd.h("div." + buttonClass, buttonProperties, [icon]);
25427     };
25428     SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) {
25429         var nextProperties = {
25430             onclick: nextKey != null ?
25431                 function (e) {
25432                     navigator.moveDir$(Edge_1.EdgeDirection.Next)
25433                         .subscribe(function (node) { return; }, function (error) { console.error(error); });
25434                 } :
25435                 null,
25436             onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
25437             onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
25438             style: {},
25439         };
25440         var prevProperties = {
25441             onclick: prevKey != null ?
25442                 function (e) {
25443                     navigator.moveDir$(Edge_1.EdgeDirection.Prev)
25444                         .subscribe(function (node) { return; }, function (error) { console.error(error); });
25445                 } :
25446                 null,
25447             onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
25448             onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
25449             style: {},
25450         };
25451         var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
25452         var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
25453         var nextIcon = vd.h("div.SequenceComponentIcon", []);
25454         var prevIcon = vd.h("div.SequenceComponentIcon", []);
25455         return [
25456             vd.h("div." + nextClass, nextProperties, [nextIcon]),
25457             vd.h("div." + prevClass, prevProperties, [prevIcon]),
25458         ];
25459     };
25460     SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
25461         var className = direction === Edge_1.EdgeDirection.Next ?
25462             "SequenceStepNext" :
25463             "SequenceStepPrev";
25464         if (key == null) {
25465             className += "Disabled";
25466         }
25467         else {
25468             if (highlightKey === key) {
25469                 className += "Highlight";
25470             }
25471         }
25472         return className;
25473     };
25474     return SequenceDOMRenderer;
25475 }());
25476 exports.SequenceDOMRenderer = SequenceDOMRenderer;
25477 Object.defineProperty(exports, "__esModule", { value: true });
25478 exports.default = SequenceDOMRenderer;
25479
25480 },{"../../Edge":225,"virtual-dom":180}],276:[function(require,module,exports){
25481 "use strict";
25482 var GeometryTagError_1 = require("./error/GeometryTagError");
25483 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
25484 var PointGeometry_1 = require("./geometry/PointGeometry");
25485 exports.PointGeometry = PointGeometry_1.PointGeometry;
25486 var RectGeometry_1 = require("./geometry/RectGeometry");
25487 exports.RectGeometry = RectGeometry_1.RectGeometry;
25488 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
25489 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
25490 var OutlineTag_1 = require("./tag/OutlineTag");
25491 exports.OutlineTag = OutlineTag_1.OutlineTag;
25492 var SpotTag_1 = require("./tag/SpotTag");
25493 exports.SpotTag = SpotTag_1.SpotTag;
25494 var Alignment_1 = require("./tag/Alignment");
25495 exports.Alignment = Alignment_1.Alignment;
25496 var TagComponent_1 = require("./TagComponent");
25497 exports.TagComponent = TagComponent_1.TagComponent;
25498
25499 },{"./TagComponent":277,"./error/GeometryTagError":283,"./geometry/PointGeometry":285,"./geometry/PolygonGeometry":286,"./geometry/RectGeometry":287,"./tag/Alignment":289,"./tag/OutlineTag":292,"./tag/SpotTag":295}],277:[function(require,module,exports){
25500 /// <reference path="../../../typings/index.d.ts" />
25501 "use strict";
25502 var __extends = (this && this.__extends) || function (d, b) {
25503     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25504     function __() { this.constructor = d; }
25505     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25506 };
25507 var Observable_1 = require("rxjs/Observable");
25508 var Subject_1 = require("rxjs/Subject");
25509 require("rxjs/add/observable/combineLatest");
25510 require("rxjs/add/observable/empty");
25511 require("rxjs/add/observable/from");
25512 require("rxjs/add/observable/merge");
25513 require("rxjs/add/observable/of");
25514 require("rxjs/add/operator/combineLatest");
25515 require("rxjs/add/operator/concat");
25516 require("rxjs/add/operator/distinctUntilChanged");
25517 require("rxjs/add/operator/do");
25518 require("rxjs/add/operator/filter");
25519 require("rxjs/add/operator/map");
25520 require("rxjs/add/operator/merge");
25521 require("rxjs/add/operator/mergeMap");
25522 require("rxjs/add/operator/publishReplay");
25523 require("rxjs/add/operator/scan");
25524 require("rxjs/add/operator/share");
25525 require("rxjs/add/operator/skip");
25526 require("rxjs/add/operator/skipUntil");
25527 require("rxjs/add/operator/startWith");
25528 require("rxjs/add/operator/switchMap");
25529 require("rxjs/add/operator/take");
25530 require("rxjs/add/operator/takeUntil");
25531 require("rxjs/add/operator/withLatestFrom");
25532 var Component_1 = require("../../Component");
25533 var Geo_1 = require("../../Geo");
25534 var Render_1 = require("../../Render");
25535 /**
25536  * @class TagComponent
25537  * @classdesc Component for showing and editing 2D tags with different geometries.
25538  */
25539 var TagComponent = (function (_super) {
25540     __extends(TagComponent, _super);
25541     function TagComponent(name, container, navigator) {
25542         var _this = _super.call(this, name, container, navigator) || this;
25543         _this._tagDomRenderer = new Component_1.TagDOMRenderer();
25544         _this._tagSet = new Component_1.TagSet();
25545         _this._tagCreator = new Component_1.TagCreator();
25546         _this._viewportCoords = new Geo_1.ViewportCoords();
25547         _this._tagGlRendererOperation$ = new Subject_1.Subject();
25548         _this._tagGlRenderer$ = _this._tagGlRendererOperation$
25549             .startWith(function (renderer) {
25550             return renderer;
25551         })
25552             .scan(function (renderer, operation) {
25553             return operation(renderer);
25554         }, new Component_1.TagGLRenderer());
25555         _this._tags$ = _this._tagSet.tagData$
25556             .map(function (tagData) {
25557             var tags = [];
25558             // ensure that tags are always rendered in the same order
25559             // to avoid hover tracking problems on first resize.
25560             for (var _i = 0, _a = Object.keys(tagData).sort(); _i < _a.length; _i++) {
25561                 var key = _a[_i];
25562                 tags.push(tagData[key]);
25563             }
25564             return tags;
25565         })
25566             .share();
25567         _this._renderTags$ = _this.tags$
25568             .withLatestFrom(_this._navigator.stateService.currentTransform$)
25569             .map(function (args) {
25570             var tags = args[0];
25571             var transform = args[1];
25572             var renderTags = tags
25573                 .map(function (tag) {
25574                 if (tag instanceof Component_1.OutlineTag) {
25575                     return new Component_1.OutlineRenderTag(tag, transform);
25576                 }
25577                 else if (tag instanceof Component_1.SpotTag) {
25578                     return new Component_1.SpotRenderTag(tag, transform);
25579                 }
25580                 throw new Error("Tag type not supported");
25581             });
25582             return renderTags;
25583         })
25584             .share();
25585         _this._tagChanged$ = _this._tags$
25586             .switchMap(function (tags) {
25587             return Observable_1.Observable
25588                 .from(tags)
25589                 .mergeMap(function (tag) {
25590                 return Observable_1.Observable
25591                     .merge(tag.changed$, tag.geometryChanged$);
25592             });
25593         })
25594             .share();
25595         _this._renderTagGLChanged$ = _this._renderTags$
25596             .switchMap(function (tags) {
25597             return Observable_1.Observable
25598                 .from(tags)
25599                 .mergeMap(function (tag) {
25600                 return tag.glObjectsChanged$;
25601             });
25602         })
25603             .share();
25604         _this._tagInterationInitiated$ = _this._renderTags$
25605             .switchMap(function (tags) {
25606             return Observable_1.Observable
25607                 .from(tags)
25608                 .mergeMap(function (tag) {
25609                 return tag.interact$
25610                     .map(function (interaction) {
25611                     return interaction.tag.id;
25612                 });
25613             });
25614         })
25615             .share();
25616         _this._tagInteractionAbort$ = Observable_1.Observable
25617             .merge(_this._container.mouseService.documentMouseUp$)
25618             .map(function (e) { })
25619             .share();
25620         _this._activeTag$ = _this._renderTags$
25621             .switchMap(function (tags) {
25622             return Observable_1.Observable
25623                 .from(tags)
25624                 .mergeMap(function (tag) {
25625                 return tag.interact$;
25626             });
25627         })
25628             .merge(_this._tagInteractionAbort$
25629             .map(function () {
25630             return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
25631         }))
25632             .share();
25633         _this._createGeometryChanged$ = _this._tagCreator.tag$
25634             .switchMap(function (tag) {
25635             return tag != null ?
25636                 tag.geometryChanged$ :
25637                 Observable_1.Observable.empty();
25638         })
25639             .share();
25640         _this._tagCreated$ = _this._tagCreator.tag$
25641             .switchMap(function (tag) {
25642             return tag != null ?
25643                 tag.created$ :
25644                 Observable_1.Observable.empty();
25645         })
25646             .share();
25647         _this._vertexGeometryCreated$ = _this._tagCreated$
25648             .map(function (tag) {
25649             return tag.geometry;
25650         })
25651             .share();
25652         _this._pointGeometryCreated$ = new Subject_1.Subject();
25653         _this._geometryCreated$ = Observable_1.Observable
25654             .merge(_this._vertexGeometryCreated$, _this._pointGeometryCreated$)
25655             .share();
25656         _this._basicClick$ = _this._container.mouseService.staticClick$
25657             .withLatestFrom(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$, function (event, renderCamera, transform) {
25658             return [event, renderCamera, transform];
25659         })
25660             .map(function (ert) {
25661             var event = ert[0];
25662             var camera = ert[1];
25663             var transform = ert[2];
25664             var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
25665             return basic;
25666         })
25667             .share();
25668         _this._validBasicClick$ = _this._basicClick$
25669             .filter(function (basic) {
25670             var x = basic[0];
25671             var y = basic[1];
25672             return 0 <= x && x <= 1 && 0 <= y && y <= 1;
25673         })
25674             .share();
25675         _this._creatingConfiguration$ = _this._configuration$
25676             .distinctUntilChanged(function (c1, c2) {
25677             return c1.creating === c2.creating && c1.createType === c2.createType;
25678         }, function (configuration) {
25679             return {
25680                 createColor: configuration.createColor,
25681                 createType: configuration.createType,
25682                 creating: configuration.creating,
25683             };
25684         })
25685             .publishReplay(1)
25686             .refCount();
25687         _this._creating$ = _this._creatingConfiguration$
25688             .map(function (configuration) {
25689             return configuration.creating;
25690         })
25691             .publishReplay(1)
25692             .refCount();
25693         _this._creating$
25694             .subscribe(function (creating) {
25695             _this.fire(TagComponent.creatingchanged, creating);
25696         });
25697         return _this;
25698     }
25699     Object.defineProperty(TagComponent.prototype, "tags$", {
25700         /**
25701          * Get tags observable.
25702          *
25703          * @description An observable emitting every time the items in the
25704          * tag array changes.
25705          *
25706          * @returns {Observable<Tag[]>}
25707          */
25708         get: function () {
25709             return this._tags$;
25710         },
25711         enumerable: true,
25712         configurable: true
25713     });
25714     Object.defineProperty(TagComponent.prototype, "geometryCreated$", {
25715         /**
25716          * Get geometry created observable.
25717          *
25718          * @description An observable emitting every time a geometry
25719          * has been created.
25720          *
25721          * @returns {Observable<Geometry>}
25722          */
25723         get: function () {
25724             return this._geometryCreated$;
25725         },
25726         enumerable: true,
25727         configurable: true
25728     });
25729     /**
25730      * Set the tags to display.
25731      *
25732      * @param {Tag[]} tags - The tags.
25733      */
25734     TagComponent.prototype.setTags = function (tags) {
25735         this._tagSet.set$.next(tags);
25736     };
25737     /**
25738      * Configure the component to enter create mode for
25739      * creating a geometry of a certain type.
25740      *
25741      * @description Supported geometry types are: rect
25742      *
25743      * @param {string} geometryType - String specifying the geometry type.
25744      */
25745     TagComponent.prototype.startCreate = function (geometryType) {
25746         this.configure({ createType: geometryType, creating: true });
25747     };
25748     /**
25749      * Configure the component to leave create mode.
25750      *
25751      * @description A non completed geometry will be removed.
25752      */
25753     TagComponent.prototype.stopCreate = function () {
25754         this.configure({ createType: null, creating: false });
25755     };
25756     TagComponent.prototype._activate = function () {
25757         var _this = this;
25758         this._preventDefaultSubscription = Observable_1.Observable.merge(this._container.mouseService.documentCanvasMouseDown$, this._container.mouseService.documentCanvasMouseMove$)
25759             .subscribe(function (event) {
25760             event.preventDefault(); // prevent selection of content outside the viewer
25761         });
25762         this._geometryCreatedEventSubscription = this._geometryCreated$
25763             .subscribe(function (geometry) {
25764             _this.fire(TagComponent.geometrycreated, geometry);
25765         });
25766         this._tagsChangedEventSubscription = this._tags$
25767             .subscribe(function (tags) {
25768             _this.fire(TagComponent.tagschanged, tags);
25769         });
25770         var nodeChanged$ = this.configuration$
25771             .switchMap(function (configuration) {
25772             return configuration.creating ?
25773                 _this._navigator.stateService.currentNode$
25774                     .skip(1)
25775                     .take(1)
25776                     .map(function (n) { return null; }) :
25777                 Observable_1.Observable.empty();
25778         });
25779         var tagAborted$ = this._tagCreator.tag$
25780             .switchMap(function (tag) {
25781             return tag != null ?
25782                 tag.aborted$
25783                     .map(function (t) { return null; }) :
25784                 Observable_1.Observable.empty();
25785         });
25786         var tagCreated$ = this._tagCreated$
25787             .map(function (t) { return null; });
25788         var pointGeometryCreated$ = this._pointGeometryCreated$
25789             .map(function (p) { return null; });
25790         this._stopCreateSubscription = Observable_1.Observable
25791             .merge(nodeChanged$, tagAborted$, tagCreated$, pointGeometryCreated$)
25792             .subscribe(function () { _this.stopCreate(); });
25793         this._creatorConfigurationSubscription = this._configuration$
25794             .subscribe(this._tagCreator.configuration$);
25795         this._createSubscription = this._creatingConfiguration$
25796             .switchMap(function (configuration) {
25797             return configuration.creating &&
25798                 configuration.createType === "rect" ||
25799                 configuration.createType === "polygon" ?
25800                 _this._validBasicClick$.take(1) :
25801                 Observable_1.Observable.empty();
25802         })
25803             .subscribe(this._tagCreator.create$);
25804         this._createPointSubscription = this._creatingConfiguration$
25805             .switchMap(function (configuration) {
25806             return configuration.creating &&
25807                 configuration.createType === "point" ?
25808                 _this._validBasicClick$.take(1) :
25809                 Observable_1.Observable.empty();
25810         })
25811             .map(function (basic) {
25812             return new Component_1.PointGeometry(basic);
25813         })
25814             .subscribe(this._pointGeometryCreated$);
25815         this._setCreateVertexSubscription = Observable_1.Observable
25816             .combineLatest(this._container.mouseService.documentCanvasMouseMove$, this._tagCreator.tag$, this._container.renderService.renderCamera$)
25817             .filter(function (etr) {
25818             return etr[1] != null;
25819         })
25820             .withLatestFrom(this._navigator.stateService.currentTransform$, function (etr, transform) {
25821             return [etr[0], etr[1], etr[2], transform];
25822         })
25823             .subscribe(function (etrt) {
25824             var event = etrt[0];
25825             var tag = etrt[1];
25826             var camera = etrt[2];
25827             var transform = etrt[3];
25828             var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
25829             if (tag.geometry instanceof Component_1.RectGeometry) {
25830                 tag.geometry.setVertex2d(3, basic, transform);
25831             }
25832             else if (tag.geometry instanceof Component_1.PolygonGeometry) {
25833                 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basic, transform);
25834             }
25835         });
25836         this._addPointSubscription = this._creatingConfiguration$
25837             .switchMap(function (configuration) {
25838             var createType = configuration.createType;
25839             return configuration.creating &&
25840                 (createType === "rect" || createType === "polygon") ?
25841                 _this._basicClick$.skipUntil(_this._validBasicClick$).skip(1) :
25842                 Observable_1.Observable.empty();
25843         })
25844             .withLatestFrom(this._tagCreator.tag$, function (basic, tag) {
25845             return [basic, tag];
25846         })
25847             .subscribe(function (bt) {
25848             var basic = bt[0];
25849             var tag = bt[1];
25850             tag.addPoint(basic);
25851         });
25852         this._containerClassListSubscription = this._creating$
25853             .subscribe(function (creating) {
25854             if (creating) {
25855                 _this._container.element.classList.add("component-tag-create");
25856             }
25857             else {
25858                 _this._container.element.classList.remove("component-tag-create");
25859             }
25860         });
25861         this._deleteCreatedSubscription = this._creating$
25862             .subscribe(function (creating) {
25863             _this._tagCreator.delete$.next(null);
25864         });
25865         this._setGLCreateTagSubscription = Observable_1.Observable
25866             .merge(this._tagCreator.tag$, this._createGeometryChanged$)
25867             .withLatestFrom(this._navigator.stateService.currentTransform$, function (tag, transform) {
25868             return [tag, transform];
25869         })
25870             .map(function (tt) {
25871             return function (renderer) {
25872                 var tag = tt[0];
25873                 var transform = tt[1];
25874                 if (tag == null) {
25875                     renderer.removeCreateTag();
25876                 }
25877                 else {
25878                     renderer.setCreateTag(tag, transform);
25879                 }
25880                 return renderer;
25881             };
25882         })
25883             .subscribe(this._tagGlRendererOperation$);
25884         this._claimMouseSubscription = this._tagInterationInitiated$
25885             .switchMap(function (id) {
25886             return _this._container.mouseService.documentCanvasMouseMove$
25887                 .takeUntil(_this._tagInteractionAbort$)
25888                 .take(1);
25889         })
25890             .subscribe(function (e) {
25891             _this._container.mouseService.claimMouse(_this._name, 1);
25892         });
25893         this._mouseDragSubscription = this._activeTag$
25894             .withLatestFrom(this._container.mouseService.documentCanvasMouseMove$, function (a, e) {
25895             return [a, e];
25896         })
25897             .switchMap(function (args) {
25898             var activeTag = args[0];
25899             var mouseMove = args[1];
25900             if (activeTag.operation === Component_1.TagOperation.None) {
25901                 return Observable_1.Observable.empty();
25902             }
25903             var mouseDrag$ = Observable_1.Observable
25904                 .of(mouseMove)
25905                 .concat(_this._container.mouseService.filtered$(_this._name, _this._container.mouseService.documentCanvasMouseDrag$));
25906             return Observable_1.Observable
25907                 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
25908                 .withLatestFrom(Observable_1.Observable.of(activeTag), _this._navigator.stateService.currentTransform$, function (ec, a, t) {
25909                 return [ec[0], ec[1], a, t];
25910             });
25911         })
25912             .subscribe(function (args) {
25913             var mouseEvent = args[0];
25914             var renderCamera = args[1];
25915             var activeTag = args[2];
25916             var transform = args[3];
25917             if (activeTag.operation === Component_1.TagOperation.None) {
25918                 return;
25919             }
25920             var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, activeTag.offsetX, activeTag.offsetY);
25921             if (activeTag.operation === Component_1.TagOperation.Centroid) {
25922                 activeTag.tag.geometry.setCentroid2d(basic, transform);
25923             }
25924             else if (activeTag.operation === Component_1.TagOperation.Vertex) {
25925                 var vertexGeometry = activeTag.tag.geometry;
25926                 vertexGeometry.setVertex2d(activeTag.vertexIndex, basic, transform);
25927             }
25928         });
25929         this._unclaimMouseSubscription = this._container.mouseService
25930             .filtered$(this._name, this._container.mouseService.documentCanvasMouseDragEnd$)
25931             .subscribe(function (e) {
25932             _this._container.mouseService.unclaimMouse(_this._name);
25933         });
25934         this._setTagsSubscription = this._renderTags$
25935             .map(function (tags) {
25936             return function (renderer) {
25937                 renderer.setTags(tags);
25938                 return renderer;
25939             };
25940         })
25941             .subscribe(this._tagGlRendererOperation$);
25942         this._updateGLTagSubscription = this._renderTagGLChanged$
25943             .map(function (tag) {
25944             return function (renderer) {
25945                 renderer.updateTag(tag);
25946                 return renderer;
25947             };
25948         })
25949             .subscribe(this._tagGlRendererOperation$);
25950         this._setNeedsRenderSubscription = this._tagChanged$
25951             .map(function (tag) {
25952             return function (renderer) {
25953                 renderer.setNeedsRender();
25954                 return renderer;
25955             };
25956         })
25957             .subscribe(this._tagGlRendererOperation$);
25958         this._domSubscription = this._renderTags$
25959             .startWith([])
25960             .do(function (tags) {
25961             _this._container.domRenderer.render$.next({
25962                 name: _this._name,
25963                 vnode: _this._tagDomRenderer.clear(),
25964             });
25965         })
25966             .combineLatest(this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._tagChanged$.startWith(null), this._tagCreator.tag$.merge(this._createGeometryChanged$).startWith(null), function (renderTags, rc, atlas, tag, ct) {
25967             return [rc, atlas, renderTags, tag, ct];
25968         })
25969             .withLatestFrom(this._navigator.stateService.currentTransform$, function (args, transform) {
25970             return [args[0], args[1], args[2], args[3], args[4], transform];
25971         })
25972             .map(function (args) {
25973             return {
25974                 name: _this._name,
25975                 vnode: _this._tagDomRenderer.render(args[2], args[4], args[1], args[0].perspective, args[5]),
25976             };
25977         })
25978             .subscribe(this._container.domRenderer.render$);
25979         this._glSubscription = this._navigator.stateService.currentState$
25980             .withLatestFrom(this._tagGlRenderer$, function (frame, renderer) {
25981             return [frame, renderer];
25982         })
25983             .map(function (fr) {
25984             var frame = fr[0];
25985             var renderer = fr[1];
25986             return {
25987                 name: _this._name,
25988                 render: {
25989                     frameId: frame.id,
25990                     needsRender: renderer.needsRender,
25991                     render: renderer.render.bind(renderer),
25992                     stage: Render_1.GLRenderStage.Foreground,
25993                 },
25994             };
25995         })
25996             .subscribe(this._container.glRenderer.render$);
25997     };
25998     TagComponent.prototype._deactivate = function () {
25999         this._tagGlRendererOperation$
26000             .next(function (renderer) {
26001             renderer.dispose();
26002             return renderer;
26003         });
26004         this._tagSet.set$.next([]);
26005         this._tagCreator.delete$.next(null);
26006         this._claimMouseSubscription.unsubscribe();
26007         this._mouseDragSubscription.unsubscribe();
26008         this._unclaimMouseSubscription.unsubscribe();
26009         this._setTagsSubscription.unsubscribe();
26010         this._updateGLTagSubscription.unsubscribe();
26011         this._setNeedsRenderSubscription.unsubscribe();
26012         this._stopCreateSubscription.unsubscribe();
26013         this._creatorConfigurationSubscription.unsubscribe();
26014         this._createSubscription.unsubscribe();
26015         this._createPointSubscription.unsubscribe();
26016         this._setCreateVertexSubscription.unsubscribe();
26017         this._addPointSubscription.unsubscribe();
26018         this._deleteCreatedSubscription.unsubscribe();
26019         this._setGLCreateTagSubscription.unsubscribe();
26020         this._preventDefaultSubscription.unsubscribe();
26021         this._containerClassListSubscription.unsubscribe();
26022         this._domSubscription.unsubscribe();
26023         this._glSubscription.unsubscribe();
26024         this._geometryCreatedEventSubscription.unsubscribe();
26025         this._tagsChangedEventSubscription.unsubscribe();
26026     };
26027     TagComponent.prototype._getDefaultConfiguration = function () {
26028         return {
26029             createColor: 0xFFFFFF,
26030             creating: false,
26031         };
26032     };
26033     TagComponent.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
26034         offsetX = offsetX != null ? offsetX : 0;
26035         offsetY = offsetY != null ? offsetY : 0;
26036         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
26037         var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
26038         return basic;
26039     };
26040     return TagComponent;
26041 }(Component_1.Component));
26042 /** @inheritdoc */
26043 TagComponent.componentName = "tag";
26044 /**
26045  * Event fired when creation starts and stops.
26046  *
26047  * @event TagComponent#creatingchanged
26048  * @type {boolean} Indicates whether the component is creating a tag.
26049  */
26050 TagComponent.creatingchanged = "creatingchanged";
26051 /**
26052  * Event fired when a geometry has been created.
26053  *
26054  * @event TagComponent#geometrycreated
26055  * @type {Geometry} Created geometry.
26056  */
26057 TagComponent.geometrycreated = "geometrycreated";
26058 /**
26059  * Event fired when the tags collection has changed.
26060  *
26061  * @event TagComponent#tagschanged
26062  * @type {Array<Tag>} Current array of tags.
26063  */
26064 TagComponent.tagschanged = "tagschanged";
26065 exports.TagComponent = TagComponent;
26066 Component_1.ComponentService.register(TagComponent);
26067 Object.defineProperty(exports, "__esModule", { value: true });
26068 exports.default = TagComponent;
26069
26070 },{"../../Component":224,"../../Geo":227,"../../Render":230,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/empty":39,"rxjs/add/observable/from":40,"rxjs/add/observable/merge":43,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/concat":53,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/do":58,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73,"rxjs/add/operator/skip":74,"rxjs/add/operator/skipUntil":75,"rxjs/add/operator/startWith":77,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/take":79,"rxjs/add/operator/takeUntil":80,"rxjs/add/operator/withLatestFrom":82}],278:[function(require,module,exports){
26071 "use strict";
26072 var Subject_1 = require("rxjs/Subject");
26073 require("rxjs/add/operator/map");
26074 require("rxjs/add/operator/scan");
26075 require("rxjs/add/operator/share");
26076 require("rxjs/add/operator/withLatestFrom");
26077 var Component_1 = require("../../Component");
26078 var TagCreator = (function () {
26079     function TagCreator() {
26080         this._tagOperation$ = new Subject_1.Subject();
26081         this._create$ = new Subject_1.Subject();
26082         this._delete$ = new Subject_1.Subject();
26083         this._configuration$ = new Subject_1.Subject();
26084         this._tag$ = this._tagOperation$
26085             .scan(function (tag, operation) {
26086             return operation(tag);
26087         }, null)
26088             .share();
26089         this._create$
26090             .withLatestFrom(this._configuration$, function (coordinate, type) {
26091             return [coordinate, type];
26092         })
26093             .map(function (ct) {
26094             return function (tag) {
26095                 var coordinate = ct[0];
26096                 var configuration = ct[1];
26097                 if (configuration.createType === "rect") {
26098                     var geometry = new Component_1.RectGeometry([
26099                         coordinate[0],
26100                         coordinate[1],
26101                         coordinate[0],
26102                         coordinate[1],
26103                     ]);
26104                     return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor });
26105                 }
26106                 else if (configuration.createType === "polygon") {
26107                     var geometry = new Component_1.PolygonGeometry([
26108                         [coordinate[0], coordinate[1]],
26109                         [coordinate[0], coordinate[1]],
26110                         [coordinate[0], coordinate[1]],
26111                     ]);
26112                     return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor });
26113                 }
26114                 return null;
26115             };
26116         })
26117             .subscribe(this._tagOperation$);
26118         this._delete$
26119             .map(function () {
26120             return function (tag) {
26121                 return null;
26122             };
26123         })
26124             .subscribe(this._tagOperation$);
26125     }
26126     Object.defineProperty(TagCreator.prototype, "create$", {
26127         get: function () {
26128             return this._create$;
26129         },
26130         enumerable: true,
26131         configurable: true
26132     });
26133     Object.defineProperty(TagCreator.prototype, "delete$", {
26134         get: function () {
26135             return this._delete$;
26136         },
26137         enumerable: true,
26138         configurable: true
26139     });
26140     Object.defineProperty(TagCreator.prototype, "configuration$", {
26141         get: function () {
26142             return this._configuration$;
26143         },
26144         enumerable: true,
26145         configurable: true
26146     });
26147     Object.defineProperty(TagCreator.prototype, "tag$", {
26148         get: function () {
26149             return this._tag$;
26150         },
26151         enumerable: true,
26152         configurable: true
26153     });
26154     return TagCreator;
26155 }());
26156 exports.TagCreator = TagCreator;
26157 Object.defineProperty(exports, "__esModule", { value: true });
26158 exports.default = TagCreator;
26159
26160 },{"../../Component":224,"rxjs/Subject":33,"rxjs/add/operator/map":64,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73,"rxjs/add/operator/withLatestFrom":82}],279:[function(require,module,exports){
26161 /// <reference path="../../../typings/index.d.ts" />
26162 "use strict";
26163 var THREE = require("three");
26164 var vd = require("virtual-dom");
26165 var TagDOMRenderer = (function () {
26166     function TagDOMRenderer() {
26167     }
26168     TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, transform) {
26169         var matrixWorldInverse = new THREE.Matrix4().getInverse(camera.matrixWorld);
26170         var projectionMatrix = camera.projectionMatrix;
26171         var vNodes = [];
26172         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
26173             var tag = tags_1[_i];
26174             vNodes = vNodes.concat(tag.getDOMObjects(atlas, matrixWorldInverse, projectionMatrix));
26175         }
26176         if (createTag != null) {
26177             vNodes = vNodes.concat(createTag.getDOMObjects(transform, matrixWorldInverse, projectionMatrix));
26178         }
26179         return vd.h("div.TagContainer", {}, vNodes);
26180     };
26181     TagDOMRenderer.prototype.clear = function () {
26182         return vd.h("div", {}, []);
26183     };
26184     return TagDOMRenderer;
26185 }());
26186 exports.TagDOMRenderer = TagDOMRenderer;
26187
26188 },{"three":174,"virtual-dom":180}],280:[function(require,module,exports){
26189 /// <reference path="../../../typings/index.d.ts" />
26190 "use strict";
26191 var THREE = require("three");
26192 var TagGLRenderer = (function () {
26193     function TagGLRenderer() {
26194         this._scene = new THREE.Scene();
26195         this._tags = {};
26196         this._createTag = null;
26197         this._needsRender = false;
26198     }
26199     Object.defineProperty(TagGLRenderer.prototype, "needsRender", {
26200         get: function () {
26201             return this._needsRender;
26202         },
26203         enumerable: true,
26204         configurable: true
26205     });
26206     TagGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
26207         renderer.render(this._scene, perspectiveCamera);
26208         this._needsRender = false;
26209     };
26210     TagGLRenderer.prototype.setCreateTag = function (tag, transform) {
26211         this._disposeCreateTag();
26212         this._addCreateTag(tag, transform);
26213         this._needsRender = true;
26214     };
26215     TagGLRenderer.prototype.removeCreateTag = function () {
26216         this._disposeCreateTag();
26217         this._needsRender = true;
26218     };
26219     TagGLRenderer.prototype.setTags = function (tags) {
26220         this._disposeTags();
26221         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
26222             var tag = tags_1[_i];
26223             this._addTag(tag);
26224         }
26225         this._needsRender = true;
26226     };
26227     TagGLRenderer.prototype.updateTag = function (tag) {
26228         for (var _i = 0, _a = this._tags[tag.tag.id][1]; _i < _a.length; _i++) {
26229             var object3d = _a[_i];
26230             this._scene.remove(object3d);
26231         }
26232         this._addTag(tag);
26233     };
26234     TagGLRenderer.prototype.setNeedsRender = function () {
26235         this._needsRender = true;
26236     };
26237     TagGLRenderer.prototype.dispose = function () {
26238         this._disposeTags();
26239         this._disposeCreateTag();
26240         this._needsRender = false;
26241     };
26242     TagGLRenderer.prototype._addTag = function (tag) {
26243         var objects = tag.glObjects;
26244         this._tags[tag.tag.id] = [tag, []];
26245         for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) {
26246             var object = objects_1[_i];
26247             this._tags[tag.tag.id][1].push(object);
26248             this._scene.add(object);
26249         }
26250     };
26251     TagGLRenderer.prototype._addCreateTag = function (tag, transform) {
26252         var object = tag.getGLObject(transform);
26253         this._createTag = object;
26254         this._scene.add(object);
26255     };
26256     TagGLRenderer.prototype._disposeTags = function () {
26257         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
26258             var id = _a[_i];
26259             for (var _b = 0, _c = this._tags[id][1]; _b < _c.length; _b++) {
26260                 var object = _c[_b];
26261                 this._scene.remove(object);
26262             }
26263             this._tags[id][0].dispose();
26264             delete this._tags[id];
26265         }
26266     };
26267     TagGLRenderer.prototype._disposeCreateTag = function () {
26268         if (this._createTag == null) {
26269             return;
26270         }
26271         var mesh = this._createTag;
26272         this._scene.remove(mesh);
26273         mesh.geometry.dispose();
26274         mesh.material.dispose();
26275         this._createTag = null;
26276     };
26277     return TagGLRenderer;
26278 }());
26279 exports.TagGLRenderer = TagGLRenderer;
26280
26281 },{"three":174}],281:[function(require,module,exports){
26282 "use strict";
26283 var TagOperation;
26284 (function (TagOperation) {
26285     TagOperation[TagOperation["None"] = 0] = "None";
26286     TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
26287     TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
26288 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
26289 Object.defineProperty(exports, "__esModule", { value: true });
26290 exports.default = TagOperation;
26291
26292 },{}],282:[function(require,module,exports){
26293 "use strict";
26294 var Subject_1 = require("rxjs/Subject");
26295 require("rxjs/add/operator/map");
26296 require("rxjs/add/operator/scan");
26297 require("rxjs/add/operator/share");
26298 var TagSet = (function () {
26299     function TagSet() {
26300         this._tagDataOperation$ = new Subject_1.Subject();
26301         this._set$ = new Subject_1.Subject();
26302         this._tagData$ = this._tagDataOperation$
26303             .scan(function (tagData, operation) {
26304             return operation(tagData);
26305         }, {})
26306             .share();
26307         this._set$
26308             .map(function (tags) {
26309             return function (tagData) {
26310                 for (var _i = 0, _a = Object.keys(tagData); _i < _a.length; _i++) {
26311                     var key = _a[_i];
26312                     delete tagData[key];
26313                 }
26314                 for (var _b = 0, tags_1 = tags; _b < tags_1.length; _b++) {
26315                     var tag = tags_1[_b];
26316                     tagData[tag.id] = tag;
26317                 }
26318                 return tagData;
26319             };
26320         })
26321             .subscribe(this._tagDataOperation$);
26322     }
26323     Object.defineProperty(TagSet.prototype, "tagData$", {
26324         get: function () {
26325             return this._tagData$;
26326         },
26327         enumerable: true,
26328         configurable: true
26329     });
26330     Object.defineProperty(TagSet.prototype, "set$", {
26331         get: function () {
26332             return this._set$;
26333         },
26334         enumerable: true,
26335         configurable: true
26336     });
26337     return TagSet;
26338 }());
26339 exports.TagSet = TagSet;
26340 Object.defineProperty(exports, "__esModule", { value: true });
26341 exports.default = TagSet;
26342
26343 },{"rxjs/Subject":33,"rxjs/add/operator/map":64,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73}],283:[function(require,module,exports){
26344 "use strict";
26345 var __extends = (this && this.__extends) || function (d, b) {
26346     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26347     function __() { this.constructor = d; }
26348     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26349 };
26350 var Error_1 = require("../../../Error");
26351 var GeometryTagError = (function (_super) {
26352     __extends(GeometryTagError, _super);
26353     function GeometryTagError(message) {
26354         var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
26355         _this.name = "GeometryTagError";
26356         return _this;
26357     }
26358     return GeometryTagError;
26359 }(Error_1.MapillaryError));
26360 exports.GeometryTagError = GeometryTagError;
26361 Object.defineProperty(exports, "__esModule", { value: true });
26362 exports.default = Error_1.MapillaryError;
26363
26364 },{"../../../Error":226}],284:[function(require,module,exports){
26365 "use strict";
26366 var Subject_1 = require("rxjs/Subject");
26367 /**
26368  * @class Geometry
26369  * @abstract
26370  * @classdesc Represents a geometry.
26371  */
26372 var Geometry = (function () {
26373     /**
26374      * Create a geometry.
26375      *
26376      * @constructor
26377      */
26378     function Geometry() {
26379         this._notifyChanged$ = new Subject_1.Subject();
26380     }
26381     Object.defineProperty(Geometry.prototype, "changed$", {
26382         /**
26383          * Get changed observable.
26384          *
26385          * @description Emits the geometry itself every time the geometry
26386          * has changed.
26387          *
26388          * @returns {Observable<Geometry>} Observable emitting the geometry instance.
26389          */
26390         get: function () {
26391             return this._notifyChanged$;
26392         },
26393         enumerable: true,
26394         configurable: true
26395     });
26396     return Geometry;
26397 }());
26398 exports.Geometry = Geometry;
26399 Object.defineProperty(exports, "__esModule", { value: true });
26400 exports.default = Geometry;
26401
26402 },{"rxjs/Subject":33}],285:[function(require,module,exports){
26403 "use strict";
26404 var __extends = (this && this.__extends) || function (d, b) {
26405     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26406     function __() { this.constructor = d; }
26407     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26408 };
26409 var Component_1 = require("../../../Component");
26410 /**
26411  * @class PointGeometry
26412  * @classdesc Represents a point geometry in the basic coordinate system.
26413  */
26414 var PointGeometry = (function (_super) {
26415     __extends(PointGeometry, _super);
26416     /**
26417      * Create a point geometry.
26418      *
26419      * @constructor
26420      * @param {Array<number>} point - An array representing the basic coordinates of
26421      * the point.
26422      *
26423      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
26424      */
26425     function PointGeometry(point) {
26426         var _this = _super.call(this) || this;
26427         var x = point[0];
26428         var y = point[1];
26429         if (x < 0 || x > 1 || y < 0 || y > 1) {
26430             throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
26431         }
26432         _this._point = point.slice();
26433         return _this;
26434     }
26435     Object.defineProperty(PointGeometry.prototype, "point", {
26436         /**
26437          * Get point property.
26438          * @returns {Array<number>} Array representing the basic coordinates of the point.
26439          */
26440         get: function () {
26441             return this._point;
26442         },
26443         enumerable: true,
26444         configurable: true
26445     });
26446     /**
26447      * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
26448      * world coordinates of the point itself.
26449      *
26450      * @param {Transform} transform - The transform of the node related to the point.
26451      * @returns {Array<number>} 3D world coordinates representing the centroid.
26452      */
26453     PointGeometry.prototype.getCentroid3d = function (transform) {
26454         return transform.unprojectBasic(this._point, 200);
26455     };
26456     /**
26457      * Set the centroid of the point, i.e. the point coordinates.
26458      *
26459      * @param {Array<number>} value - The new value of the centroid.
26460      * @param {Transform} transform - The transform of the node related to the point.
26461      */
26462     PointGeometry.prototype.setCentroid2d = function (value, transform) {
26463         var changed = [
26464             Math.max(0, Math.min(1, value[0])),
26465             Math.max(0, Math.min(1, value[1])),
26466         ];
26467         this._point[0] = changed[0];
26468         this._point[1] = changed[1];
26469         this._notifyChanged$.next(this);
26470     };
26471     return PointGeometry;
26472 }(Component_1.Geometry));
26473 exports.PointGeometry = PointGeometry;
26474
26475 },{"../../../Component":224}],286:[function(require,module,exports){
26476 "use strict";
26477 var __extends = (this && this.__extends) || function (d, b) {
26478     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26479     function __() { this.constructor = d; }
26480     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26481 };
26482 var Component_1 = require("../../../Component");
26483 /**
26484  * @class PolygonGeometry
26485  * @classdesc Represents a polygon geometry in the basic coordinate system.
26486  */
26487 var PolygonGeometry = (function (_super) {
26488     __extends(PolygonGeometry, _super);
26489     /**
26490      * Create a polygon geometry.
26491      *
26492      * @constructor
26493      * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
26494      * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
26495      * Each array of holes vertices must be closed.
26496      *
26497      * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
26498      */
26499     function PolygonGeometry(polygon, holes) {
26500         var _this = _super.call(this) || this;
26501         var polygonLength = polygon.length;
26502         if (polygonLength < 3) {
26503             throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
26504         }
26505         if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
26506             polygon[0][1] !== polygon[polygonLength - 1][1]) {
26507             throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
26508         }
26509         _this._polygon = [];
26510         for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
26511             var vertex = polygon_1[_i];
26512             if (vertex[0] < 0 || vertex[0] > 1 ||
26513                 vertex[1] < 0 || vertex[1] > 1) {
26514                 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
26515             }
26516             _this._polygon.push(vertex.slice());
26517         }
26518         _this._holes = [];
26519         if (holes == null) {
26520             return _this;
26521         }
26522         for (var i = 0; i < holes.length; i++) {
26523             var hole = holes[i];
26524             var holeLength = hole.length;
26525             if (holeLength < 3) {
26526                 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
26527             }
26528             if (hole[0][0] !== hole[holeLength - 1][0] ||
26529                 hole[0][1] !== hole[holeLength - 1][1]) {
26530                 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
26531             }
26532             _this._holes.push([]);
26533             for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
26534                 var vertex = hole_1[_a];
26535                 if (vertex[0] < 0 || vertex[0] > 1 ||
26536                     vertex[1] < 0 || vertex[1] > 1) {
26537                     throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
26538                 }
26539                 _this._holes[i].push(vertex.slice());
26540             }
26541         }
26542         return _this;
26543     }
26544     Object.defineProperty(PolygonGeometry.prototype, "polygon", {
26545         /**
26546          * Get polygon property.
26547          * @returns {Array<Array<number>>} Closed 2d polygon.
26548          */
26549         get: function () {
26550             return this._polygon;
26551         },
26552         enumerable: true,
26553         configurable: true
26554     });
26555     Object.defineProperty(PolygonGeometry.prototype, "holes", {
26556         /**
26557          * Get holes property.
26558          * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
26559          */
26560         get: function () {
26561             return this._holes;
26562         },
26563         enumerable: true,
26564         configurable: true
26565     });
26566     /**
26567      * Add a vertex to the polygon by appending it after the last vertex.
26568      *
26569      * @param {Array<number>} vertex - Vertex to add.
26570      */
26571     PolygonGeometry.prototype.addVertex2d = function (vertex) {
26572         var clamped = [
26573             Math.max(0, Math.min(1, vertex[0])),
26574             Math.max(0, Math.min(1, vertex[1])),
26575         ];
26576         this._polygon.splice(this._polygon.length - 1, 0, clamped);
26577         this._notifyChanged$.next(this);
26578     };
26579     /**
26580      * Remove a vertex from the polygon.
26581      *
26582      * @param {number} index - The index of the vertex to remove.
26583      */
26584     PolygonGeometry.prototype.removeVertex2d = function (index) {
26585         if (index < 0 ||
26586             index >= this._polygon.length ||
26587             this._polygon.length < 4) {
26588             throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
26589         }
26590         if (index > 0 && index < this._polygon.length - 1) {
26591             this._polygon.splice(index, 1);
26592         }
26593         else {
26594             this._polygon.splice(0, 1);
26595             this._polygon.pop();
26596             var closing = this._polygon[0].slice();
26597             this._polygon.push(closing);
26598         }
26599         this._notifyChanged$.next(this);
26600     };
26601     /** @inheritdoc */
26602     PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
26603         var changed = [
26604             Math.max(0, Math.min(1, value[0])),
26605             Math.max(0, Math.min(1, value[1])),
26606         ];
26607         if (index === 0 || index === this._polygon.length - 1) {
26608             this._polygon[0] = changed.slice();
26609             this._polygon[this._polygon.length - 1] = changed.slice();
26610         }
26611         else {
26612             this._polygon[index] = changed.slice();
26613         }
26614         this._notifyChanged$.next(this);
26615     };
26616     /** @inheritdoc */
26617     PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
26618         var xs = this._polygon.map(function (point) { return point[0]; });
26619         var ys = this._polygon.map(function (point) { return point[1]; });
26620         var minX = Math.min.apply(Math, xs);
26621         var maxX = Math.max.apply(Math, xs);
26622         var minY = Math.min.apply(Math, ys);
26623         var maxY = Math.max.apply(Math, ys);
26624         var centroid = this._getCentroid2d();
26625         var minTranslationX = -minX;
26626         var maxTranslationX = 1 - maxX;
26627         var minTranslationY = -minY;
26628         var maxTranslationY = 1 - maxY;
26629         var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
26630         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
26631         for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
26632             var point = _a[_i];
26633             point[0] += translationX;
26634             point[1] += translationY;
26635         }
26636         this._notifyChanged$.next(this);
26637     };
26638     /** @inheritdoc */
26639     PolygonGeometry.prototype.getPoints3d = function (transform) {
26640         return this.getVertices3d(transform);
26641     };
26642     /** @inheritdoc */
26643     PolygonGeometry.prototype.getVertex3d = function (index, transform) {
26644         return transform.unprojectBasic(this._polygon[index], 200);
26645     };
26646     /** @inheritdoc */
26647     PolygonGeometry.prototype.getVertices3d = function (transform) {
26648         return this._polygon
26649             .map(function (point) {
26650             return transform.unprojectBasic(point, 200);
26651         });
26652     };
26653     /**
26654      * Get a polygon representation of the 3D coordinates for the vertices of each hole
26655      * of the geometry.
26656      *
26657      * @param {Transform} transform - The transform of the node related to the geometry.
26658      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
26659      * representing the vertices of each hole of the geometry.
26660      */
26661     PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
26662         var holes3d = [];
26663         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
26664             var hole = _a[_i];
26665             var hole3d = hole
26666                 .map(function (point) {
26667                 return transform.unprojectBasic(point, 200);
26668             });
26669             holes3d.push(hole3d);
26670         }
26671         return holes3d;
26672     };
26673     /** @inheritdoc */
26674     PolygonGeometry.prototype.getCentroid3d = function (transform) {
26675         var centroid2d = this._getCentroid2d();
26676         return transform.unprojectBasic(centroid2d, 200);
26677     };
26678     /** @inheritdoc */
26679     PolygonGeometry.prototype.getTriangles3d = function (transform) {
26680         return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
26681     };
26682     PolygonGeometry.prototype._getCentroid2d = function () {
26683         var polygon = this._polygon;
26684         var area = 0;
26685         var centroidX = 0;
26686         var centroidY = 0;
26687         for (var i = 0; i < polygon.length - 1; i++) {
26688             var xi = polygon[i][0];
26689             var yi = polygon[i][1];
26690             var xi1 = polygon[i + 1][0];
26691             var yi1 = polygon[i + 1][1];
26692             var a = xi * yi1 - xi1 * yi;
26693             area += a;
26694             centroidX += (xi + xi1) * a;
26695             centroidY += (yi + yi1) * a;
26696         }
26697         area /= 2;
26698         centroidX /= 6 * area;
26699         centroidY /= 6 * area;
26700         return [centroidX, centroidY];
26701     };
26702     return PolygonGeometry;
26703 }(Component_1.VertexGeometry));
26704 exports.PolygonGeometry = PolygonGeometry;
26705 Object.defineProperty(exports, "__esModule", { value: true });
26706 exports.default = PolygonGeometry;
26707
26708 },{"../../../Component":224}],287:[function(require,module,exports){
26709 "use strict";
26710 var __extends = (this && this.__extends) || function (d, b) {
26711     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26712     function __() { this.constructor = d; }
26713     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26714 };
26715 var Component_1 = require("../../../Component");
26716 /**
26717  * @class RectGeometry
26718  * @classdesc Represents a rectangle geometry in the basic coordinate system.
26719  */
26720 var RectGeometry = (function (_super) {
26721     __extends(RectGeometry, _super);
26722     /**
26723      * Create a rectangle geometry.
26724      *
26725      * @constructor
26726      * @param {Array<number>} rect - An array representing the top-left and bottom-right
26727      * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
26728      *
26729      * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
26730      */
26731     function RectGeometry(rect) {
26732         var _this = _super.call(this) || this;
26733         if (rect[1] > rect[3]) {
26734             throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
26735         }
26736         for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
26737             var coord = rect_1[_i];
26738             if (coord < 0 || coord > 1) {
26739                 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
26740             }
26741         }
26742         _this._rect = rect.slice(0, 4);
26743         if (_this._rect[0] > _this._rect[2]) {
26744             _this._inverted = true;
26745         }
26746         return _this;
26747     }
26748     Object.defineProperty(RectGeometry.prototype, "rect", {
26749         /**
26750          * Get rect property.
26751          * @returns {Array<number>} Array representing the top-left and bottom-right
26752          * corners of the rectangle in basic coordinates.
26753          */
26754         get: function () {
26755             return this._rect;
26756         },
26757         enumerable: true,
26758         configurable: true
26759     });
26760     /**
26761      * Set the value of a vertex in the polygon representation of the rectangle.
26762      *
26763      * @description The polygon is defined to have the first vertex at the
26764      * bottom-left corner with the rest of the vertices following in clockwise order.
26765      *
26766      * @param {number} index - The index of the vertex to be set.
26767      * @param {Array<number>} value - The new value of the vertex.
26768      * @param {Transform} transform - The transform of the node related to the rectangle.
26769      */
26770     RectGeometry.prototype.setVertex2d = function (index, value, transform) {
26771         var original = this._rect.slice();
26772         var changed = [
26773             Math.max(0, Math.min(1, value[0])),
26774             Math.max(0, Math.min(1, value[1])),
26775         ];
26776         var rect = [];
26777         if (index === 0) {
26778             rect[0] = changed[0];
26779             rect[1] = original[1];
26780             rect[2] = original[2];
26781             rect[3] = changed[1];
26782         }
26783         else if (index === 1) {
26784             rect[0] = changed[0];
26785             rect[1] = changed[1];
26786             rect[2] = original[2];
26787             rect[3] = original[3];
26788         }
26789         else if (index === 2) {
26790             rect[0] = original[0];
26791             rect[1] = changed[1];
26792             rect[2] = changed[0];
26793             rect[3] = original[3];
26794         }
26795         else if (index === 3) {
26796             rect[0] = original[0];
26797             rect[1] = original[1];
26798             rect[2] = changed[0];
26799             rect[3] = changed[1];
26800         }
26801         if (transform.gpano) {
26802             var passingBoundaryLeft = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
26803                 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
26804             var passingBoundaryRight = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
26805                 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
26806             if (passingBoundaryLeft || passingBoundaryRight) {
26807                 this._inverted = !this._inverted;
26808             }
26809             else {
26810                 if (rect[0] - original[0] < -0.25) {
26811                     rect[0] = original[0];
26812                 }
26813                 if (rect[2] - original[2] > 0.25) {
26814                     rect[2] = original[2];
26815                 }
26816             }
26817             if (!this._inverted && rect[0] > rect[2] ||
26818                 this._inverted && rect[0] < rect[2]) {
26819                 rect[0] = original[0];
26820                 rect[2] = original[2];
26821             }
26822         }
26823         else {
26824             if (rect[0] > rect[2]) {
26825                 rect[0] = original[0];
26826                 rect[2] = original[2];
26827             }
26828         }
26829         if (rect[1] > rect[3]) {
26830             rect[1] = original[1];
26831             rect[3] = original[3];
26832         }
26833         this._rect[0] = rect[0];
26834         this._rect[1] = rect[1];
26835         this._rect[2] = rect[2];
26836         this._rect[3] = rect[3];
26837         this._notifyChanged$.next(this);
26838     };
26839     /** @inheritdoc */
26840     RectGeometry.prototype.setCentroid2d = function (value, transform) {
26841         var original = this._rect.slice();
26842         var x0 = original[0];
26843         var x1 = this._inverted ? original[2] + 1 : original[2];
26844         var y0 = original[1];
26845         var y1 = original[3];
26846         var centerX = x0 + (x1 - x0) / 2;
26847         var centerY = y0 + (y1 - y0) / 2;
26848         var translationX = 0;
26849         if (transform.gpano != null &&
26850             transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
26851             translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
26852         }
26853         else {
26854             var minTranslationX = -x0;
26855             var maxTranslationX = 1 - x1;
26856             translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
26857         }
26858         var minTranslationY = -y0;
26859         var maxTranslationY = 1 - y1;
26860         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
26861         this._rect[0] = original[0] + translationX;
26862         this._rect[1] = original[1] + translationY;
26863         this._rect[2] = original[2] + translationX;
26864         this._rect[3] = original[3] + translationY;
26865         if (this._rect[0] < 0) {
26866             this._rect[0] += 1;
26867             this._inverted = !this._inverted;
26868         }
26869         else if (this._rect[0] > 1) {
26870             this._rect[0] -= 1;
26871             this._inverted = !this._inverted;
26872         }
26873         if (this._rect[2] < 0) {
26874             this._rect[2] += 1;
26875             this._inverted = !this._inverted;
26876         }
26877         else if (this._rect[2] > 1) {
26878             this._rect[2] -= 1;
26879             this._inverted = !this._inverted;
26880         }
26881         this._notifyChanged$.next(this);
26882     };
26883     /**
26884      * Get the 3D coordinates for the vertices of the rectangle with
26885      * interpolated points along the lines.
26886      *
26887      * @param {Transform} transform - The transform of the node related to
26888      * the rectangle.
26889      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
26890      * representing the rectangle.
26891      */
26892     RectGeometry.prototype.getPoints3d = function (transform) {
26893         return this._getPoints2d(transform)
26894             .map(function (point) {
26895             return transform.unprojectBasic(point, 200);
26896         });
26897     };
26898     /**
26899      * Get a vertex from the polygon representation of the 3D coordinates for the
26900      * vertices of the geometry.
26901      *
26902      * @description The first vertex represents the bottom-left corner with the rest of
26903      * the vertices following in clockwise order.
26904      *
26905      * @param {number} index - Vertex index.
26906      * @param {Transform} transform - The transform of the node related to the geometry.
26907      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
26908      * the vertices of the geometry.
26909      */
26910     RectGeometry.prototype.getVertex3d = function (index, transform) {
26911         return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
26912     };
26913     /**
26914      * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
26915      *
26916      * @description The first vertex represents the bottom-left corner with the rest of
26917      * the vertices following in clockwise order.
26918      *
26919      * @param {Transform} transform - The transform of the node related to the rectangle.
26920      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
26921      * the rectangle vertices.
26922      */
26923     RectGeometry.prototype.getVertices3d = function (transform) {
26924         return this._rectToVertices2d(this._rect)
26925             .map(function (vertex) {
26926             return transform.unprojectBasic(vertex, 200);
26927         });
26928     };
26929     /** @inheritdoc */
26930     RectGeometry.prototype.getCentroid3d = function (transform) {
26931         var rect = this._rect;
26932         var x0 = rect[0];
26933         var x1 = this._inverted ? rect[2] + 1 : rect[2];
26934         var y0 = rect[1];
26935         var y1 = rect[3];
26936         var centroidX = x0 + (x1 - x0) / 2;
26937         var centroidY = y0 + (y1 - y0) / 2;
26938         return transform.unprojectBasic([centroidX, centroidY], 200);
26939     };
26940     /** @inheritdoc */
26941     RectGeometry.prototype.getTriangles3d = function (transform) {
26942         return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
26943     };
26944     /**
26945      * Check if a particular bottom-right value is valid according to the current
26946      * rectangle coordinates.
26947      *
26948      * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
26949      * @returns {boolean} Value indicating whether the provided bottom-right coordinates
26950      * are valid.
26951      */
26952     RectGeometry.prototype.validate = function (bottomRight) {
26953         var rect = this._rect;
26954         if (!this._inverted && bottomRight[0] < rect[0] ||
26955             bottomRight[0] - rect[2] > 0.25 ||
26956             bottomRight[1] < rect[1]) {
26957             return false;
26958         }
26959         return true;
26960     };
26961     /**
26962      * Get the 2D coordinates for the vertices of the rectangle with
26963      * interpolated points along the lines.
26964      *
26965      * @param {Transform} transform - The transform of the node related to
26966      * the rectangle.
26967      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
26968      * representing the rectangle.
26969      */
26970     RectGeometry.prototype._getPoints2d = function (transform) {
26971         var vertices2d = this._rectToVertices2d(this._rect);
26972         var sides = vertices2d.length - 1;
26973         var sections = 10;
26974         var points2d = [];
26975         for (var i = 0; i < sides; ++i) {
26976             var startX = vertices2d[i][0];
26977             var startY = vertices2d[i][1];
26978             var endX = vertices2d[i + 1][0];
26979             var endY = vertices2d[i + 1][1];
26980             var intervalX = (endX - startX) / (sections - 1);
26981             var intervalY = (endY - startY) / (sections - 1);
26982             for (var j = 0; j < sections; ++j) {
26983                 var point = [
26984                     startX + j * intervalX,
26985                     startY + j * intervalY,
26986                 ];
26987                 points2d.push(point);
26988             }
26989         }
26990         return points2d;
26991     };
26992     /**
26993      * Convert the top-left, bottom-right representation of a rectangle to a polygon
26994      * representation of the vertices starting at the bottom-right corner going
26995      * clockwise.
26996      *
26997      * @param {Array<number>} rect - Top-left, bottom-right representation of a
26998      * rectangle.
26999      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
27000      * rectangle.
27001      */
27002     RectGeometry.prototype._rectToVertices2d = function (rect) {
27003         return [
27004             [rect[0], rect[3]],
27005             [rect[0], rect[1]],
27006             [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
27007             [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
27008             [rect[0], rect[3]],
27009         ];
27010     };
27011     return RectGeometry;
27012 }(Component_1.VertexGeometry));
27013 exports.RectGeometry = RectGeometry;
27014 Object.defineProperty(exports, "__esModule", { value: true });
27015 exports.default = RectGeometry;
27016
27017 },{"../../../Component":224}],288:[function(require,module,exports){
27018 /// <reference path="../../../../typings/index.d.ts" />
27019 "use strict";
27020 var __extends = (this && this.__extends) || function (d, b) {
27021     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
27022     function __() { this.constructor = d; }
27023     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27024 };
27025 var earcut = require("earcut");
27026 var Component_1 = require("../../../Component");
27027 /**
27028  * @class VertexGeometry
27029  * @abstract
27030  * @classdesc Represents a vertex geometry.
27031  */
27032 var VertexGeometry = (function (_super) {
27033     __extends(VertexGeometry, _super);
27034     /**
27035      * Create a vertex geometry.
27036      *
27037      * @constructor
27038      */
27039     function VertexGeometry() {
27040         return _super.call(this) || this;
27041     }
27042     /**
27043      * Triangulates a 2d polygon and returns the triangle
27044      * representation as a flattened array of 3d points.
27045      *
27046      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
27047      * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
27048      * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
27049      * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
27050      * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
27051      */
27052     VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
27053         var data = [points2d.slice(0, -1)];
27054         for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
27055             var hole2d = _a[_i];
27056             data.push(hole2d.slice(0, -1));
27057         }
27058         var points = points3d.slice(0, -1);
27059         for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
27060             var hole3d = _c[_b];
27061             points = points.concat(hole3d.slice(0, -1));
27062         }
27063         var flattened = earcut.flatten(data);
27064         var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
27065         var triangles = [];
27066         for (var i = 0; i < indices.length; ++i) {
27067             var point = points[indices[i]];
27068             triangles.push(point[0]);
27069             triangles.push(point[1]);
27070             triangles.push(point[2]);
27071         }
27072         return triangles;
27073     };
27074     return VertexGeometry;
27075 }(Component_1.Geometry));
27076 exports.VertexGeometry = VertexGeometry;
27077 Object.defineProperty(exports, "__esModule", { value: true });
27078 exports.default = VertexGeometry;
27079
27080 },{"../../../Component":224,"earcut":6}],289:[function(require,module,exports){
27081 "use strict";
27082 var Alignment;
27083 (function (Alignment) {
27084     Alignment[Alignment["Center"] = 0] = "Center";
27085     Alignment[Alignment["Outer"] = 1] = "Outer";
27086 })(Alignment = exports.Alignment || (exports.Alignment = {}));
27087 Object.defineProperty(exports, "__esModule", { value: true });
27088 exports.default = Alignment;
27089
27090 },{}],290:[function(require,module,exports){
27091 /// <reference path="../../../../typings/index.d.ts" />
27092 "use strict";
27093 var THREE = require("three");
27094 var vd = require("virtual-dom");
27095 var Subject_1 = require("rxjs/Subject");
27096 var Component_1 = require("../../../Component");
27097 var OutlineCreateTag = (function () {
27098     function OutlineCreateTag(geometry, options) {
27099         this._geometry = geometry;
27100         this._options = { color: options.color == null ? 0xFFFFFF : options.color };
27101         this._created$ = new Subject_1.Subject();
27102         this._aborted$ = new Subject_1.Subject();
27103     }
27104     Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
27105         get: function () {
27106             return this._geometry;
27107         },
27108         enumerable: true,
27109         configurable: true
27110     });
27111     Object.defineProperty(OutlineCreateTag.prototype, "created$", {
27112         get: function () {
27113             return this._created$;
27114         },
27115         enumerable: true,
27116         configurable: true
27117     });
27118     Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
27119         get: function () {
27120             return this._aborted$;
27121         },
27122         enumerable: true,
27123         configurable: true
27124     });
27125     Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
27126         get: function () {
27127             var _this = this;
27128             return this._geometry.changed$
27129                 .map(function (geometry) {
27130                 return _this;
27131             });
27132         },
27133         enumerable: true,
27134         configurable: true
27135     });
27136     OutlineCreateTag.prototype.getGLObject = function (transform) {
27137         var polygon3d = this._geometry.getPoints3d(transform);
27138         var positions = this._getPositions(polygon3d);
27139         var geometry = new THREE.BufferGeometry();
27140         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
27141         var material = new THREE.LineBasicMaterial({
27142             color: this._options.color,
27143             linewidth: 1,
27144         });
27145         return new THREE.Line(geometry, material);
27146     };
27147     OutlineCreateTag.prototype.getDOMObjects = function (transform, matrixWorldInverse, projectionMatrix) {
27148         var _this = this;
27149         var vNodes = [];
27150         var abort = function (e) {
27151             e.stopPropagation();
27152             _this._aborted$.next(_this);
27153         };
27154         if (this._geometry instanceof Component_1.RectGeometry) {
27155             var topLeftPoint3d = this._geometry.getVertex3d(1, transform);
27156             var topLeftCameraSpace = this._convertToCameraSpace(topLeftPoint3d, matrixWorldInverse);
27157             if (topLeftCameraSpace.z < 0) {
27158                 var centerCanvas = this._projectToCanvas(topLeftCameraSpace, projectionMatrix);
27159                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27160                 var pointProperties = {
27161                     style: {
27162                         background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
27163                         left: centerCss[0],
27164                         position: "absolute",
27165                         top: centerCss[1],
27166                     },
27167                 };
27168                 var completerProperties = {
27169                     onclick: abort,
27170                     style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
27171                 };
27172                 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
27173                 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
27174             }
27175         }
27176         else if (this._geometry instanceof Component_1.PolygonGeometry) {
27177             var polygonGeometry_1 = this._geometry;
27178             var firstVertex3d = this._geometry.getVertex3d(0, transform);
27179             var firstCameraSpace = this._convertToCameraSpace(firstVertex3d, matrixWorldInverse);
27180             if (firstCameraSpace.z < 0) {
27181                 var centerCanvas = this._projectToCanvas(firstCameraSpace, projectionMatrix);
27182                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27183                 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
27184                     function (e) {
27185                         e.stopPropagation();
27186                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
27187                         _this._created$.next(_this);
27188                     } :
27189                     abort;
27190                 var completerProperties = {
27191                     onclick: firstOnclick,
27192                     style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
27193                 };
27194                 var firstClass = polygonGeometry_1.polygon.length > 4 ?
27195                     "TagCompleter" :
27196                     "TagInteractor";
27197                 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
27198             }
27199             if (polygonGeometry_1.polygon.length > 3) {
27200                 var lastVertex3d = this._geometry.getVertex3d(polygonGeometry_1.polygon.length - 3, transform);
27201                 var lastCameraSpace = this._convertToCameraSpace(lastVertex3d, matrixWorldInverse);
27202                 if (lastCameraSpace.z < 0) {
27203                     var centerCanvas = this._projectToCanvas(lastCameraSpace, projectionMatrix);
27204                     var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27205                     var remove = function (e) {
27206                         e.stopPropagation();
27207                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
27208                     };
27209                     var completerProperties = {
27210                         onclick: remove,
27211                         style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
27212                     };
27213                     vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
27214                 }
27215             }
27216             var vertices3d = this._geometry.getVertices3d(transform);
27217             vertices3d.splice(-2, 2);
27218             for (var _i = 0, vertices3d_1 = vertices3d; _i < vertices3d_1.length; _i++) {
27219                 var vertex = vertices3d_1[_i];
27220                 var vertexCameraSpace = this._convertToCameraSpace(vertex, matrixWorldInverse);
27221                 if (vertexCameraSpace.z < 0) {
27222                     var centerCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
27223                     var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27224                     var pointProperties = {
27225                         style: {
27226                             background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
27227                             left: centerCss[0],
27228                             position: "absolute",
27229                             top: centerCss[1],
27230                         },
27231                     };
27232                     vNodes.push(vd.h("div.TagVertex", pointProperties, []));
27233                 }
27234             }
27235         }
27236         return vNodes;
27237     };
27238     OutlineCreateTag.prototype.addPoint = function (point) {
27239         if (this._geometry instanceof Component_1.RectGeometry) {
27240             var rectGeometry = this._geometry;
27241             if (!rectGeometry.validate(point)) {
27242                 return;
27243             }
27244             this._created$.next(this);
27245         }
27246         else if (this._geometry instanceof Component_1.PolygonGeometry) {
27247             var polygonGeometry = this._geometry;
27248             polygonGeometry.addVertex2d(point);
27249         }
27250     };
27251     OutlineCreateTag.prototype._getPositions = function (polygon3d) {
27252         var length = polygon3d.length;
27253         var positions = new Float32Array(length * 3);
27254         for (var i = 0; i < length; ++i) {
27255             var index = 3 * i;
27256             var position = polygon3d[i];
27257             positions[index] = position[0];
27258             positions[index + 1] = position[1];
27259             positions[index + 2] = position[2];
27260         }
27261         return positions;
27262     };
27263     OutlineCreateTag.prototype._projectToCanvas = function (point, projectionMatrix) {
27264         var projected = new THREE.Vector3(point.x, point.y, point.z)
27265             .applyProjection(projectionMatrix);
27266         return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
27267     };
27268     OutlineCreateTag.prototype._convertToCameraSpace = function (point, matrixWorldInverse) {
27269         return new THREE.Vector3(point[0], point[1], point[2]).applyMatrix4(matrixWorldInverse);
27270     };
27271     return OutlineCreateTag;
27272 }());
27273 exports.OutlineCreateTag = OutlineCreateTag;
27274 Object.defineProperty(exports, "__esModule", { value: true });
27275 exports.default = OutlineCreateTag;
27276
27277 },{"../../../Component":224,"rxjs/Subject":33,"three":174,"virtual-dom":180}],291:[function(require,module,exports){
27278 /// <reference path="../../../../typings/index.d.ts" />
27279 "use strict";
27280 var __extends = (this && this.__extends) || function (d, b) {
27281     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
27282     function __() { this.constructor = d; }
27283     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27284 };
27285 var THREE = require("three");
27286 var vd = require("virtual-dom");
27287 var Component_1 = require("../../../Component");
27288 var Viewer_1 = require("../../../Viewer");
27289 /**
27290  * @class OutlineRenderTag
27291  * @classdesc Tag visualizing the properties of an OutlineTag.
27292  */
27293 var OutlineRenderTag = (function (_super) {
27294     __extends(OutlineRenderTag, _super);
27295     function OutlineRenderTag(tag, transform) {
27296         var _this = _super.call(this, tag, transform) || this;
27297         _this._fill = _this._tag.fillOpacity > 0 && !transform.gpano ?
27298             _this._createFill() :
27299             null;
27300         _this._holes = _this._tag.lineWidth >= 1 ?
27301             _this._createHoles() :
27302             [];
27303         _this._outline = _this._tag.lineWidth >= 1 ?
27304             _this._createOutline() :
27305             null;
27306         _this._glObjects = _this._createGLObjects();
27307         _this._tag.geometry.changed$
27308             .subscribe(function (geometry) {
27309             if (_this._fill != null) {
27310                 _this._updateFillGeometry();
27311             }
27312             if (_this._holes.length > 0) {
27313                 _this._updateHoleGeometries();
27314             }
27315             if (_this._outline != null) {
27316                 _this._updateOulineGeometry();
27317             }
27318         });
27319         _this._tag.changed$
27320             .subscribe(function (changedTag) {
27321             var glObjectsChanged = false;
27322             if (_this._fill == null) {
27323                 if (_this._tag.fillOpacity > 0 && !_this._transform.gpano) {
27324                     _this._fill = _this._createFill();
27325                     glObjectsChanged = true;
27326                 }
27327             }
27328             else {
27329                 _this._updateFillMaterial();
27330             }
27331             if (_this._outline == null) {
27332                 if (_this._tag.lineWidth > 0) {
27333                     _this._holes = _this._createHoles();
27334                     _this._outline = _this._createOutline();
27335                     glObjectsChanged = true;
27336                 }
27337             }
27338             else {
27339                 _this._updateHoleMaterials();
27340                 _this._updateOutlineMaterial();
27341             }
27342             if (glObjectsChanged) {
27343                 _this._glObjects = _this._createGLObjects();
27344                 _this._glObjectsChanged$.next(_this);
27345             }
27346         });
27347         return _this;
27348     }
27349     OutlineRenderTag.prototype.dispose = function () {
27350         this._disposeFill();
27351         this._disposeHoles();
27352         this._disposeOutline();
27353     };
27354     OutlineRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
27355         var _this = this;
27356         var vNodes = [];
27357         if (this._tag.geometry instanceof Component_1.RectGeometry) {
27358             if (this._tag.icon != null) {
27359                 var iconVertex = this._tag.geometry.getVertex3d(this._tag.iconIndex, this._transform);
27360                 var iconCameraSpace = this._convertToCameraSpace(iconVertex, matrixWorldInverse);
27361                 if (iconCameraSpace.z < 0) {
27362                     var interact = function (e) {
27363                         _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
27364                     };
27365                     if (atlas.loaded) {
27366                         var spriteAlignments = this._getSpriteAlignment(this._tag.iconIndex, this._tag.iconAlignment);
27367                         var sprite = atlas.getDOMSprite(this._tag.icon, spriteAlignments[0], spriteAlignments[1]);
27368                         var click = function (e) {
27369                             e.stopPropagation();
27370                             _this._tag.click$.next(_this._tag);
27371                         };
27372                         var iconCanvas = this._projectToCanvas(iconCameraSpace, projectionMatrix);
27373                         var iconCss = iconCanvas.map(function (coord) { return (100 * coord) + "%"; });
27374                         var properties = {
27375                             onclick: click,
27376                             onmousedown: interact,
27377                             style: {
27378                                 left: iconCss[0],
27379                                 pointerEvents: "all",
27380                                 position: "absolute",
27381                                 top: iconCss[1],
27382                             },
27383                         };
27384                         vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
27385                     }
27386                 }
27387             }
27388             else if (this._tag.text != null) {
27389                 var textVertex = this._tag.geometry.getVertex3d(3, this._transform);
27390                 var textCameraSpace = this._convertToCameraSpace(textVertex, matrixWorldInverse);
27391                 if (textCameraSpace.z < 0) {
27392                     var interact = function (e) {
27393                         _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
27394                     };
27395                     var labelCanvas = this._projectToCanvas(textCameraSpace, projectionMatrix);
27396                     var labelCss = labelCanvas.map(function (coord) { return (100 * coord) + "%"; });
27397                     var properties = {
27398                         onmousedown: interact,
27399                         style: {
27400                             color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
27401                             left: labelCss[0],
27402                             pointerEvents: "all",
27403                             position: "absolute",
27404                             top: labelCss[1],
27405                         },
27406                         textContent: this._tag.text,
27407                     };
27408                     vNodes.push(vd.h("span.TagSymbol", properties, []));
27409                 }
27410             }
27411         }
27412         if (!this._tag.editable) {
27413             return vNodes;
27414         }
27415         var lineColor = "#" + ("000000" + this._tag.lineColor.toString(16)).substr(-6);
27416         if (this._tag.geometry instanceof Component_1.RectGeometry) {
27417             var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
27418             var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
27419             if (centroidCameraSpace.z < 0) {
27420                 var interact = this._interact(Component_1.TagOperation.Centroid);
27421                 var centerCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
27422                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27423                 var properties = {
27424                     onmousedown: interact,
27425                     style: { background: lineColor, left: centerCss[0], position: "absolute", top: centerCss[1] },
27426                 };
27427                 vNodes.push(vd.h("div.TagMover", properties, []));
27428             }
27429         }
27430         var vertices3d = this._tag.geometry.getVertices3d(this._transform);
27431         for (var i = 0; i < vertices3d.length - 1; i++) {
27432             var isRectGeometry = this._tag.geometry instanceof Component_1.RectGeometry;
27433             if (isRectGeometry &&
27434                 ((this._tag.icon != null && i === this._tag.iconIndex) ||
27435                     (this._tag.icon == null && this._tag.text != null && i === 3))) {
27436                 continue;
27437             }
27438             var vertexCameraSpace = this._convertToCameraSpace(vertices3d[i], matrixWorldInverse);
27439             if (vertexCameraSpace.z > 0) {
27440                 continue;
27441             }
27442             var interact = this._interact(Component_1.TagOperation.Vertex, i);
27443             var vertexCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
27444             var vertexCss = vertexCanvas.map(function (coord) { return (100 * coord) + "%"; });
27445             var properties = {
27446                 onmousedown: interact,
27447                 style: {
27448                     background: lineColor,
27449                     left: vertexCss[0],
27450                     position: "absolute",
27451                     top: vertexCss[1],
27452                 },
27453             };
27454             if (isRectGeometry) {
27455                 properties.style.cursor = i % 2 === 0 ? "nesw-resize" : "nwse-resize";
27456             }
27457             vNodes.push(vd.h("div.TagResizer", properties, []));
27458             if (!this._tag.indicateVertices) {
27459                 continue;
27460             }
27461             var pointProperties = {
27462                 style: {
27463                     background: lineColor,
27464                     left: vertexCss[0],
27465                     position: "absolute",
27466                     top: vertexCss[1],
27467                 },
27468             };
27469             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
27470         }
27471         return vNodes;
27472     };
27473     OutlineRenderTag.prototype._createFill = function () {
27474         var triangles = this._tag.geometry.getTriangles3d(this._transform);
27475         var positions = new Float32Array(triangles);
27476         var geometry = new THREE.BufferGeometry();
27477         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
27478         geometry.computeBoundingSphere();
27479         var material = new THREE.MeshBasicMaterial({
27480             color: this._tag.fillColor,
27481             opacity: this._tag.fillOpacity,
27482             side: THREE.DoubleSide,
27483             transparent: true,
27484         });
27485         return new THREE.Mesh(geometry, material);
27486     };
27487     OutlineRenderTag.prototype._createGLObjects = function () {
27488         var glObjects = [];
27489         if (this._fill != null) {
27490             glObjects.push(this._fill);
27491         }
27492         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
27493             var hole = _a[_i];
27494             glObjects.push(hole);
27495         }
27496         if (this._outline != null) {
27497             glObjects.push(this._outline);
27498         }
27499         return glObjects;
27500     };
27501     OutlineRenderTag.prototype._createHoles = function () {
27502         var holes = [];
27503         if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
27504             var polygonGeometry = this._tag.geometry;
27505             var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
27506             for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
27507                 var holePoints3d = holes3d_1[_i];
27508                 var hole = this._createLine(holePoints3d);
27509                 holes.push(hole);
27510             }
27511         }
27512         return holes;
27513     };
27514     OutlineRenderTag.prototype._createLine = function (points3d) {
27515         var positions = this._getLinePositions(points3d);
27516         var geometry = new THREE.BufferGeometry();
27517         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
27518         geometry.computeBoundingSphere();
27519         var material = new THREE.LineBasicMaterial({
27520             color: this._tag.lineColor,
27521             linewidth: this._tag.lineWidth,
27522         });
27523         return new THREE.Line(geometry, material);
27524     };
27525     OutlineRenderTag.prototype._createOutline = function () {
27526         var points3d = this._tag.geometry.getPoints3d(this._transform);
27527         return this._createLine(points3d);
27528     };
27529     OutlineRenderTag.prototype._disposeFill = function () {
27530         if (this._fill == null) {
27531             return;
27532         }
27533         this._fill.geometry.dispose();
27534         this._fill.material.dispose();
27535         this._fill = null;
27536     };
27537     OutlineRenderTag.prototype._disposeHoles = function () {
27538         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
27539             var hole = _a[_i];
27540             hole.geometry.dispose();
27541             hole.material.dispose();
27542         }
27543         this._holes = [];
27544     };
27545     OutlineRenderTag.prototype._disposeOutline = function () {
27546         if (this._outline == null) {
27547             return;
27548         }
27549         this._outline.geometry.dispose();
27550         this._outline.material.dispose();
27551         this._outline = null;
27552     };
27553     OutlineRenderTag.prototype._getLinePositions = function (points3d) {
27554         var length = points3d.length;
27555         var positions = new Float32Array(length * 3);
27556         for (var i = 0; i < length; ++i) {
27557             var index = 3 * i;
27558             var position = points3d[i];
27559             positions[index + 0] = position[0];
27560             positions[index + 1] = position[1];
27561             positions[index + 2] = position[2];
27562         }
27563         return positions;
27564     };
27565     OutlineRenderTag.prototype._getSpriteAlignment = function (index, alignment) {
27566         var horizontalAlignment = Viewer_1.SpriteAlignment.Center;
27567         var verticalAlignment = Viewer_1.SpriteAlignment.Center;
27568         if (alignment === Component_1.Alignment.Outer) {
27569             switch (index) {
27570                 case 0:
27571                     horizontalAlignment = Viewer_1.SpriteAlignment.End;
27572                     verticalAlignment = Viewer_1.SpriteAlignment.Start;
27573                     break;
27574                 case 1:
27575                     horizontalAlignment = Viewer_1.SpriteAlignment.End;
27576                     verticalAlignment = Viewer_1.SpriteAlignment.End;
27577                     break;
27578                 case 2:
27579                     horizontalAlignment = Viewer_1.SpriteAlignment.Start;
27580                     verticalAlignment = Viewer_1.SpriteAlignment.End;
27581                     break;
27582                 case 3:
27583                     horizontalAlignment = Viewer_1.SpriteAlignment.Start;
27584                     verticalAlignment = Viewer_1.SpriteAlignment.Start;
27585                     break;
27586                 default:
27587                     break;
27588             }
27589         }
27590         return [horizontalAlignment, verticalAlignment];
27591     };
27592     OutlineRenderTag.prototype._interact = function (operation, vertexIndex) {
27593         var _this = this;
27594         return function (e) {
27595             var offsetX = e.offsetX - e.target.offsetWidth / 2;
27596             var offsetY = e.offsetY - e.target.offsetHeight / 2;
27597             _this._interact$.next({
27598                 offsetX: offsetX,
27599                 offsetY: offsetY,
27600                 operation: operation,
27601                 tag: _this._tag,
27602                 vertexIndex: vertexIndex,
27603             });
27604         };
27605     };
27606     OutlineRenderTag.prototype._updateFillGeometry = function () {
27607         var triangles = this._tag.geometry.getTriangles3d(this._transform);
27608         var positions = new Float32Array(triangles);
27609         var geometry = this._fill.geometry;
27610         var attribute = geometry.getAttribute("position");
27611         if (attribute.array.length === positions.length) {
27612             attribute.set(positions);
27613             attribute.needsUpdate = true;
27614         }
27615         else {
27616             geometry.removeAttribute("position");
27617             geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
27618         }
27619         geometry.computeBoundingSphere();
27620     };
27621     OutlineRenderTag.prototype._updateFillMaterial = function () {
27622         var material = this._fill.material;
27623         material.color = new THREE.Color(this._tag.fillColor);
27624         material.opacity = this._tag.fillOpacity;
27625         material.needsUpdate = true;
27626     };
27627     OutlineRenderTag.prototype._updateHoleGeometries = function () {
27628         var polygonGeometry = this._tag.geometry;
27629         var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
27630         if (holes3d.length !== this._holes.length) {
27631             throw new Error("Changing the number of holes is not supported.");
27632         }
27633         for (var i = 0; i < this._holes.length; i++) {
27634             var holePoints3d = holes3d[i];
27635             var hole = this._holes[i];
27636             this._updateLine(hole, holePoints3d);
27637         }
27638     };
27639     OutlineRenderTag.prototype._updateHoleMaterials = function () {
27640         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
27641             var hole = _a[_i];
27642             var material = hole.material;
27643             this._updateLineBasicMaterial(material);
27644         }
27645     };
27646     OutlineRenderTag.prototype._updateLine = function (line, points3d) {
27647         var positions = this._getLinePositions(points3d);
27648         var geometry = line.geometry;
27649         var attribute = geometry.getAttribute("position");
27650         attribute.set(positions);
27651         attribute.needsUpdate = true;
27652         geometry.computeBoundingSphere();
27653     };
27654     OutlineRenderTag.prototype._updateOulineGeometry = function () {
27655         var points3d = this._tag.geometry.getPoints3d(this._transform);
27656         this._updateLine(this._outline, points3d);
27657     };
27658     OutlineRenderTag.prototype._updateOutlineMaterial = function () {
27659         var material = this._outline.material;
27660         this._updateLineBasicMaterial(material);
27661     };
27662     OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
27663         material.color = new THREE.Color(this._tag.lineColor);
27664         material.linewidth = Math.max(this._tag.lineWidth, 1);
27665         material.opacity = this._tag.lineWidth >= 1 ? 1 : 0;
27666         material.transparent = this._tag.lineWidth <= 0;
27667         material.needsUpdate = true;
27668     };
27669     return OutlineRenderTag;
27670 }(Component_1.RenderTag));
27671 exports.OutlineRenderTag = OutlineRenderTag;
27672
27673 },{"../../../Component":224,"../../../Viewer":234,"three":174,"virtual-dom":180}],292:[function(require,module,exports){
27674 "use strict";
27675 var __extends = (this && this.__extends) || function (d, b) {
27676     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
27677     function __() { this.constructor = d; }
27678     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27679 };
27680 var Subject_1 = require("rxjs/Subject");
27681 var Component_1 = require("../../../Component");
27682 /**
27683  * @class OutlineTag
27684  * @classdesc Tag holding properties for visualizing a geometry outline.
27685  */
27686 var OutlineTag = (function (_super) {
27687     __extends(OutlineTag, _super);
27688     /**
27689      * Create an outline tag.
27690      *
27691      * @override
27692      * @constructor
27693      * @param {string} id
27694      * @param {Geometry} geometry
27695      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
27696      * behavior of the outline tag.
27697      */
27698     function OutlineTag(id, geometry, options) {
27699         var _this = _super.call(this, id, geometry) || this;
27700         _this._editable = options.editable == null ? false : options.editable;
27701         _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
27702         _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
27703         _this._icon = options.icon === undefined ? null : options.icon;
27704         _this._iconAlignment = options.iconAlignment == null ? Component_1.Alignment.Outer : options.iconAlignment;
27705         _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
27706         _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
27707         _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
27708         _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
27709         _this._text = options.text === undefined ? null : options.text;
27710         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
27711         _this._click$ = new Subject_1.Subject();
27712         _this._click$
27713             .subscribe(function (t) {
27714             _this.fire(OutlineTag.click, _this);
27715         });
27716         return _this;
27717     }
27718     Object.defineProperty(OutlineTag.prototype, "click$", {
27719         /**
27720          * Click observable.
27721          *
27722          * @description An observable emitting the tag when the icon of the
27723          * tag has been clicked.
27724          *
27725          * @returns {Observable<Tag>}
27726          */
27727         get: function () {
27728             return this._click$;
27729         },
27730         enumerable: true,
27731         configurable: true
27732     });
27733     Object.defineProperty(OutlineTag.prototype, "editable", {
27734         /**
27735          * Get editable property.
27736          * @returns {boolean} Value indicating if tag is editable.
27737          */
27738         get: function () {
27739             return this._editable;
27740         },
27741         /**
27742          * Set editable property.
27743          * @param {boolean}
27744          *
27745          * @fires Tag#changed
27746          */
27747         set: function (value) {
27748             this._editable = value;
27749             this._notifyChanged$.next(this);
27750         },
27751         enumerable: true,
27752         configurable: true
27753     });
27754     Object.defineProperty(OutlineTag.prototype, "fillColor", {
27755         /**
27756          * Get fill color property.
27757          * @returns {number}
27758          */
27759         get: function () {
27760             return this._fillColor;
27761         },
27762         /**
27763          * Set fill color property.
27764          * @param {number}
27765          *
27766          * @fires Tag#changed
27767          */
27768         set: function (value) {
27769             this._fillColor = value;
27770             this._notifyChanged$.next(this);
27771         },
27772         enumerable: true,
27773         configurable: true
27774     });
27775     Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
27776         /**
27777          * Get fill opacity property.
27778          * @returns {number}
27779          */
27780         get: function () {
27781             return this._fillOpacity;
27782         },
27783         /**
27784          * Set fill opacity property.
27785          * @param {number}
27786          *
27787          * @fires Tag#changed
27788          */
27789         set: function (value) {
27790             this._fillOpacity = value;
27791             this._notifyChanged$.next(this);
27792         },
27793         enumerable: true,
27794         configurable: true
27795     });
27796     Object.defineProperty(OutlineTag.prototype, "geometry", {
27797         get: function () {
27798             return this._geometry;
27799         },
27800         enumerable: true,
27801         configurable: true
27802     });
27803     Object.defineProperty(OutlineTag.prototype, "icon", {
27804         /**
27805          * Get icon property.
27806          * @returns {string}
27807          */
27808         get: function () {
27809             return this._icon;
27810         },
27811         /**
27812          * Set icon property.
27813          * @param {string}
27814          *
27815          * @fires Tag#changed
27816          */
27817         set: function (value) {
27818             this._icon = value;
27819             this._notifyChanged$.next(this);
27820         },
27821         enumerable: true,
27822         configurable: true
27823     });
27824     Object.defineProperty(OutlineTag.prototype, "iconAlignment", {
27825         /**
27826          * Get icon alignment property.
27827          * @returns {Alignment}
27828          */
27829         get: function () {
27830             return this._iconAlignment;
27831         },
27832         /**
27833          * Set icon alignment property.
27834          * @param {Alignment}
27835          *
27836          * @fires Tag#changed
27837          */
27838         set: function (value) {
27839             this._iconAlignment = value;
27840             this._notifyChanged$.next(this);
27841         },
27842         enumerable: true,
27843         configurable: true
27844     });
27845     Object.defineProperty(OutlineTag.prototype, "iconIndex", {
27846         /**
27847          * Get icon index property.
27848          * @returns {number}
27849          */
27850         get: function () {
27851             return this._iconIndex;
27852         },
27853         /**
27854          * Set icon index property.
27855          * @param {number}
27856          *
27857          * @fires Tag#changed
27858          */
27859         set: function (value) {
27860             this._iconIndex = value;
27861             this._notifyChanged$.next(this);
27862         },
27863         enumerable: true,
27864         configurable: true
27865     });
27866     Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
27867         /**
27868          * Get indicate vertices property.
27869          * @returns {boolean} Value indicating if vertices should be indicated
27870          * when tag is editable.
27871          */
27872         get: function () {
27873             return this._indicateVertices;
27874         },
27875         /**
27876          * Set indicate vertices property.
27877          * @param {boolean}
27878          *
27879          * @fires Tag#changed
27880          */
27881         set: function (value) {
27882             this._indicateVertices = value;
27883             this._notifyChanged$.next(this);
27884         },
27885         enumerable: true,
27886         configurable: true
27887     });
27888     Object.defineProperty(OutlineTag.prototype, "lineColor", {
27889         /**
27890          * Get line color property.
27891          * @returns {number}
27892          */
27893         get: function () {
27894             return this._lineColor;
27895         },
27896         /**
27897          * Set line color property.
27898          * @param {number}
27899          *
27900          * @fires Tag#changed
27901          */
27902         set: function (value) {
27903             this._lineColor = value;
27904             this._notifyChanged$.next(this);
27905         },
27906         enumerable: true,
27907         configurable: true
27908     });
27909     Object.defineProperty(OutlineTag.prototype, "lineWidth", {
27910         /**
27911          * Get line width property.
27912          * @returns {number}
27913          */
27914         get: function () {
27915             return this._lineWidth;
27916         },
27917         /**
27918          * Set line width property.
27919          * @param {number}
27920          *
27921          * @fires Tag#changed
27922          */
27923         set: function (value) {
27924             this._lineWidth = value;
27925             this._notifyChanged$.next(this);
27926         },
27927         enumerable: true,
27928         configurable: true
27929     });
27930     Object.defineProperty(OutlineTag.prototype, "text", {
27931         /**
27932          * Get text property.
27933          * @returns {string}
27934          */
27935         get: function () {
27936             return this._text;
27937         },
27938         /**
27939          * Set text property.
27940          * @param {string}
27941          *
27942          * @fires Tag#changed
27943          */
27944         set: function (value) {
27945             this._text = value;
27946             this._notifyChanged$.next(this);
27947         },
27948         enumerable: true,
27949         configurable: true
27950     });
27951     Object.defineProperty(OutlineTag.prototype, "textColor", {
27952         /**
27953          * Get text color property.
27954          * @returns {number}
27955          */
27956         get: function () {
27957             return this._textColor;
27958         },
27959         /**
27960          * Set text color property.
27961          * @param {number}
27962          *
27963          * @fires Tag#changed
27964          */
27965         set: function (value) {
27966             this._textColor = value;
27967             this._notifyChanged$.next(this);
27968         },
27969         enumerable: true,
27970         configurable: true
27971     });
27972     /**
27973      * Set options for tag.
27974      *
27975      * @description Sets all the option properties provided and keps
27976      * the rest of the values as is.
27977      *
27978      * @param {IOutlineTagOptions} options - Outline tag options
27979      *
27980      * @fires {Tag#changed}
27981      */
27982     OutlineTag.prototype.setOptions = function (options) {
27983         this._editable = options.editable == null ? this._editable : options.editable;
27984         this._icon = options.icon === undefined ? this._icon : options.icon;
27985         this._iconAlignment = options.iconAlignment == null ? this._iconAlignment : options.iconAlignment;
27986         this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
27987         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
27988         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
27989         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
27990         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
27991         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
27992         this._text = options.text === undefined ? this._text : options.text;
27993         this._textColor = options.textColor == null ? this._textColor : options.textColor;
27994         this._notifyChanged$.next(this);
27995     };
27996     return OutlineTag;
27997 }(Component_1.Tag));
27998 /**
27999  * Event fired when the icon of the outline tag is clicked.
28000  *
28001  * @event OutlineTag#click
28002  * @type {OutlineTag} The tag instance that was clicked.
28003  */
28004 OutlineTag.click = "click";
28005 exports.OutlineTag = OutlineTag;
28006 Object.defineProperty(exports, "__esModule", { value: true });
28007 exports.default = OutlineTag;
28008
28009 },{"../../../Component":224,"rxjs/Subject":33}],293:[function(require,module,exports){
28010 /// <reference path="../../../../typings/index.d.ts" />
28011 "use strict";
28012 var THREE = require("three");
28013 var Subject_1 = require("rxjs/Subject");
28014 var RenderTag = (function () {
28015     function RenderTag(tag, transform) {
28016         this._tag = tag;
28017         this._transform = transform;
28018         this._glObjects = [];
28019         this._glObjectsChanged$ = new Subject_1.Subject();
28020         this._interact$ = new Subject_1.Subject();
28021     }
28022     Object.defineProperty(RenderTag.prototype, "glObjects", {
28023         /**
28024          * Get the GL objects for rendering of the tag.
28025          * @return {Array<Object3D>}
28026          */
28027         get: function () {
28028             return this._glObjects;
28029         },
28030         enumerable: true,
28031         configurable: true
28032     });
28033     Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
28034         get: function () {
28035             return this._glObjectsChanged$;
28036         },
28037         enumerable: true,
28038         configurable: true
28039     });
28040     Object.defineProperty(RenderTag.prototype, "interact$", {
28041         get: function () {
28042             return this._interact$;
28043         },
28044         enumerable: true,
28045         configurable: true
28046     });
28047     Object.defineProperty(RenderTag.prototype, "tag", {
28048         get: function () {
28049             return this._tag;
28050         },
28051         enumerable: true,
28052         configurable: true
28053     });
28054     RenderTag.prototype._projectToCanvas = function (point3d, projectionMatrix) {
28055         var projected = new THREE.Vector3(point3d.x, point3d.y, point3d.z)
28056             .applyProjection(projectionMatrix);
28057         return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
28058     };
28059     RenderTag.prototype._convertToCameraSpace = function (point3d, matrixWorldInverse) {
28060         return new THREE.Vector3(point3d[0], point3d[1], point3d[2]).applyMatrix4(matrixWorldInverse);
28061     };
28062     return RenderTag;
28063 }());
28064 exports.RenderTag = RenderTag;
28065 Object.defineProperty(exports, "__esModule", { value: true });
28066 exports.default = RenderTag;
28067
28068 },{"rxjs/Subject":33,"three":174}],294:[function(require,module,exports){
28069 /// <reference path="../../../../typings/index.d.ts" />
28070 "use strict";
28071 var __extends = (this && this.__extends) || function (d, b) {
28072     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28073     function __() { this.constructor = d; }
28074     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28075 };
28076 var vd = require("virtual-dom");
28077 var Component_1 = require("../../../Component");
28078 var Viewer_1 = require("../../../Viewer");
28079 /**
28080  * @class SpotRenderTag
28081  * @classdesc Tag visualizing the properties of a SpotTag.
28082  */
28083 var SpotRenderTag = (function (_super) {
28084     __extends(SpotRenderTag, _super);
28085     function SpotRenderTag() {
28086         return _super !== null && _super.apply(this, arguments) || this;
28087     }
28088     SpotRenderTag.prototype.dispose = function () { return; };
28089     SpotRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
28090         var _this = this;
28091         var vNodes = [];
28092         var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
28093         var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
28094         if (centroidCameraSpace.z < 0) {
28095             var centroidCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
28096             var centroidCss = centroidCanvas.map(function (coord) { return (100 * coord) + "%"; });
28097             var interactNone = function (e) {
28098                 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
28099             };
28100             if (this._tag.icon != null) {
28101                 if (atlas.loaded) {
28102                     var sprite = atlas.getDOMSprite(this._tag.icon, Viewer_1.SpriteAlignment.Center, Viewer_1.SpriteAlignment.End);
28103                     var properties = {
28104                         onmousedown: interactNone,
28105                         style: {
28106                             bottom: 100 * (1 - centroidCanvas[1]) + "%",
28107                             left: centroidCss[0],
28108                             pointerEvents: "all",
28109                             position: "absolute",
28110                             transform: "translate(0px, -8px)",
28111                         },
28112                     };
28113                     vNodes.push(vd.h("div", properties, [sprite]));
28114                 }
28115             }
28116             else if (this._tag.text != null) {
28117                 var properties = {
28118                     onmousedown: interactNone,
28119                     style: {
28120                         bottom: 100 * (1 - centroidCanvas[1]) + "%",
28121                         color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
28122                         left: centroidCss[0],
28123                         pointerEvents: "all",
28124                         position: "absolute",
28125                         transform: "translate(-50%, -7px)",
28126                     },
28127                     textContent: this._tag.text,
28128                 };
28129                 vNodes.push(vd.h("span.TagSymbol", properties, []));
28130             }
28131             var interact = this._interact(Component_1.TagOperation.Centroid);
28132             var background = "#" + ("000000" + this._tag.color.toString(16)).substr(-6);
28133             if (this._tag.editable) {
28134                 var interactorProperties = {
28135                     onmousedown: interact,
28136                     style: {
28137                         background: background,
28138                         left: centroidCss[0],
28139                         pointerEvents: "all",
28140                         position: "absolute",
28141                         top: centroidCss[1],
28142                     },
28143                 };
28144                 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
28145             }
28146             var pointProperties = {
28147                 style: {
28148                     background: background,
28149                     left: centroidCss[0],
28150                     position: "absolute",
28151                     top: centroidCss[1],
28152                 },
28153             };
28154             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
28155         }
28156         return vNodes;
28157     };
28158     SpotRenderTag.prototype._interact = function (operation, vertexIndex) {
28159         var _this = this;
28160         return function (e) {
28161             var offsetX = e.offsetX - e.target.offsetWidth / 2;
28162             var offsetY = e.offsetY - e.target.offsetHeight / 2;
28163             _this._interact$.next({
28164                 offsetX: offsetX,
28165                 offsetY: offsetY,
28166                 operation: operation,
28167                 tag: _this._tag,
28168                 vertexIndex: vertexIndex,
28169             });
28170         };
28171     };
28172     return SpotRenderTag;
28173 }(Component_1.RenderTag));
28174 exports.SpotRenderTag = SpotRenderTag;
28175
28176 },{"../../../Component":224,"../../../Viewer":234,"virtual-dom":180}],295:[function(require,module,exports){
28177 "use strict";
28178 var __extends = (this && this.__extends) || function (d, b) {
28179     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28180     function __() { this.constructor = d; }
28181     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28182 };
28183 var Component_1 = require("../../../Component");
28184 /**
28185  * @class SpotTag
28186  * @classdesc Tag holding properties for visualizing the centroid of a geometry.
28187  */
28188 var SpotTag = (function (_super) {
28189     __extends(SpotTag, _super);
28190     /**
28191      * Create a spot tag.
28192      *
28193      * @override
28194      * @constructor
28195      * @param {string} id
28196      * @param {Geometry} geometry
28197      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
28198      * behavior of the spot tag.
28199      */
28200     function SpotTag(id, geometry, options) {
28201         var _this = _super.call(this, id, geometry) || this;
28202         _this._color = options.color == null ? 0xFFFFFF : options.color;
28203         _this._editable = options.editable == null ? false : options.editable;
28204         _this._icon = options.icon === undefined ? null : options.icon;
28205         _this._text = options.text === undefined ? null : options.text;
28206         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
28207         return _this;
28208     }
28209     Object.defineProperty(SpotTag.prototype, "color", {
28210         /**
28211          * Get color property.
28212          * @returns {number} The color of the spot as a hexagonal number;
28213          */
28214         get: function () {
28215             return this._color;
28216         },
28217         /**
28218          * Set color property.
28219          * @param {number}
28220          *
28221          * @fires Tag#changed
28222          */
28223         set: function (value) {
28224             this._color = value;
28225             this._notifyChanged$.next(this);
28226         },
28227         enumerable: true,
28228         configurable: true
28229     });
28230     Object.defineProperty(SpotTag.prototype, "editable", {
28231         /**
28232          * Get editable property.
28233          * @returns {boolean} Value indicating if tag is editable.
28234          */
28235         get: function () {
28236             return this._editable;
28237         },
28238         /**
28239          * Set editable property.
28240          * @param {boolean}
28241          *
28242          * @fires Tag#changed
28243          */
28244         set: function (value) {
28245             this._editable = value;
28246             this._notifyChanged$.next(this);
28247         },
28248         enumerable: true,
28249         configurable: true
28250     });
28251     Object.defineProperty(SpotTag.prototype, "icon", {
28252         /**
28253          * Get icon property.
28254          * @returns {string}
28255          */
28256         get: function () {
28257             return this._icon;
28258         },
28259         /**
28260          * Set icon property.
28261          * @param {string}
28262          *
28263          * @fires Tag#changed
28264          */
28265         set: function (value) {
28266             this._icon = value;
28267             this._notifyChanged$.next(this);
28268         },
28269         enumerable: true,
28270         configurable: true
28271     });
28272     Object.defineProperty(SpotTag.prototype, "text", {
28273         /**
28274          * Get text property.
28275          * @returns {string}
28276          */
28277         get: function () {
28278             return this._text;
28279         },
28280         /**
28281          * Set text property.
28282          * @param {string}
28283          *
28284          * @fires Tag#changed
28285          */
28286         set: function (value) {
28287             this._text = value;
28288             this._notifyChanged$.next(this);
28289         },
28290         enumerable: true,
28291         configurable: true
28292     });
28293     Object.defineProperty(SpotTag.prototype, "textColor", {
28294         /**
28295          * Get text color property.
28296          * @returns {number}
28297          */
28298         get: function () {
28299             return this._textColor;
28300         },
28301         /**
28302          * Set text color property.
28303          * @param {number}
28304          *
28305          * @fires Tag#changed
28306          */
28307         set: function (value) {
28308             this._textColor = value;
28309             this._notifyChanged$.next(this);
28310         },
28311         enumerable: true,
28312         configurable: true
28313     });
28314     /**
28315      * Set options for tag.
28316      *
28317      * @description Sets all the option properties provided and keps
28318      * the rest of the values as is.
28319      *
28320      * @param {ISpotTagOptions} options - Spot tag options
28321      *
28322      * @fires {Tag#changed}
28323      */
28324     SpotTag.prototype.setOptions = function (options) {
28325         this._color = options.color == null ? this._color : options.color;
28326         this._editable = options.editable == null ? this._editable : options.editable;
28327         this._icon = options.icon === undefined ? this._icon : options.icon;
28328         this._text = options.text === undefined ? this._text : options.text;
28329         this._textColor = options.textColor == null ? this._textColor : options.textColor;
28330         this._notifyChanged$.next(this);
28331     };
28332     return SpotTag;
28333 }(Component_1.Tag));
28334 exports.SpotTag = SpotTag;
28335 Object.defineProperty(exports, "__esModule", { value: true });
28336 exports.default = SpotTag;
28337
28338 },{"../../../Component":224}],296:[function(require,module,exports){
28339 "use strict";
28340 var __extends = (this && this.__extends) || function (d, b) {
28341     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28342     function __() { this.constructor = d; }
28343     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28344 };
28345 var Subject_1 = require("rxjs/Subject");
28346 require("rxjs/add/operator/map");
28347 require("rxjs/add/operator/share");
28348 var Utils_1 = require("../../../Utils");
28349 /**
28350  * @class Tag
28351  * @abstract
28352  * @classdesc Abstract class representing the basic functionality of for a tag.
28353  */
28354 var Tag = (function (_super) {
28355     __extends(Tag, _super);
28356     /**
28357      * Create a tag.
28358      *
28359      * @constructor
28360      * @param {string} id
28361      * @param {Geometry} geometry
28362      */
28363     function Tag(id, geometry) {
28364         var _this = _super.call(this) || this;
28365         _this._id = id;
28366         _this._geometry = geometry;
28367         _this._notifyChanged$ = new Subject_1.Subject();
28368         _this._notifyChanged$
28369             .subscribe(function (t) {
28370             _this.fire(Tag.changed, _this);
28371         });
28372         _this._geometry.changed$
28373             .subscribe(function (g) {
28374             _this.fire(Tag.geometrychanged, _this);
28375         });
28376         return _this;
28377     }
28378     Object.defineProperty(Tag.prototype, "id", {
28379         /**
28380          * Get id property.
28381          * @returns {string}
28382          */
28383         get: function () {
28384             return this._id;
28385         },
28386         enumerable: true,
28387         configurable: true
28388     });
28389     Object.defineProperty(Tag.prototype, "geometry", {
28390         /**
28391          * Get geometry property.
28392          * @returns {Geometry}
28393          */
28394         get: function () {
28395             return this._geometry;
28396         },
28397         enumerable: true,
28398         configurable: true
28399     });
28400     Object.defineProperty(Tag.prototype, "changed$", {
28401         /**
28402          * Get changed observable.
28403          * @returns {Observable<Tag>}
28404          */
28405         get: function () {
28406             return this._notifyChanged$;
28407         },
28408         enumerable: true,
28409         configurable: true
28410     });
28411     Object.defineProperty(Tag.prototype, "geometryChanged$", {
28412         /**
28413          * Get geometry changed observable.
28414          * @returns {Observable<Tag>}
28415          */
28416         get: function () {
28417             var _this = this;
28418             return this._geometry.changed$
28419                 .map(function (geometry) {
28420                 return _this;
28421             })
28422                 .share();
28423         },
28424         enumerable: true,
28425         configurable: true
28426     });
28427     return Tag;
28428 }(Utils_1.EventEmitter));
28429 /**
28430  * Event fired when a property related to the visual appearance of the
28431  * tag has changed.
28432  *
28433  * @event Tag#changed
28434  * @type {Tag} The tag instance that has changed.
28435  */
28436 Tag.changed = "changed";
28437 /**
28438  * Event fired when the geometry of the tag has changed.
28439  *
28440  * @event Tag#geometrychanged
28441  * @type {Tag} The tag instance whose geometry has changed.
28442  */
28443 Tag.geometrychanged = "geometrychanged";
28444 exports.Tag = Tag;
28445 Object.defineProperty(exports, "__esModule", { value: true });
28446 exports.default = Tag;
28447
28448 },{"../../../Utils":233,"rxjs/Subject":33,"rxjs/add/operator/map":64,"rxjs/add/operator/share":73}],297:[function(require,module,exports){
28449 "use strict";
28450 var __extends = (this && this.__extends) || function (d, b) {
28451     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28452     function __() { this.constructor = d; }
28453     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28454 };
28455 var MapillaryError_1 = require("./MapillaryError");
28456 var ArgumentMapillaryError = (function (_super) {
28457     __extends(ArgumentMapillaryError, _super);
28458     function ArgumentMapillaryError(message) {
28459         var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
28460         _this.name = "ArgumentMapillaryError";
28461         return _this;
28462     }
28463     return ArgumentMapillaryError;
28464 }(MapillaryError_1.MapillaryError));
28465 exports.ArgumentMapillaryError = ArgumentMapillaryError;
28466 Object.defineProperty(exports, "__esModule", { value: true });
28467 exports.default = ArgumentMapillaryError;
28468
28469 },{"./MapillaryError":299}],298:[function(require,module,exports){
28470 "use strict";
28471 var __extends = (this && this.__extends) || function (d, b) {
28472     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28473     function __() { this.constructor = d; }
28474     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28475 };
28476 var MapillaryError_1 = require("./MapillaryError");
28477 var GraphMapillaryError = (function (_super) {
28478     __extends(GraphMapillaryError, _super);
28479     function GraphMapillaryError(message) {
28480         var _this = _super.call(this, message) || this;
28481         _this.name = "GraphMapillaryError";
28482         return _this;
28483     }
28484     return GraphMapillaryError;
28485 }(MapillaryError_1.MapillaryError));
28486 exports.GraphMapillaryError = GraphMapillaryError;
28487 Object.defineProperty(exports, "__esModule", { value: true });
28488 exports.default = GraphMapillaryError;
28489
28490 },{"./MapillaryError":299}],299:[function(require,module,exports){
28491 "use strict";
28492 var __extends = (this && this.__extends) || function (d, b) {
28493     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28494     function __() { this.constructor = d; }
28495     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28496 };
28497 var MapillaryError = (function (_super) {
28498     __extends(MapillaryError, _super);
28499     function MapillaryError(message) {
28500         var _this = _super.call(this, message) || this;
28501         _this.name = "MapillaryError";
28502         return _this;
28503     }
28504     return MapillaryError;
28505 }(Error));
28506 exports.MapillaryError = MapillaryError;
28507 Object.defineProperty(exports, "__esModule", { value: true });
28508 exports.default = MapillaryError;
28509
28510 },{}],300:[function(require,module,exports){
28511 /// <reference path="../../typings/index.d.ts" />
28512 "use strict";
28513 var THREE = require("three");
28514 /**
28515  * @class Camera
28516  *
28517  * @classdesc Holds information about a camera.
28518  */
28519 var Camera = (function () {
28520     /**
28521      * Create a new camera instance.
28522      * @param {Transform} [transform] - Optional transform instance.
28523      */
28524     function Camera(transform) {
28525         if (transform != null) {
28526             this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
28527             this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
28528             this._up = transform.upVector();
28529             this._focal = this._getFocal(transform);
28530         }
28531         else {
28532             this._position = new THREE.Vector3(0, 0, 0);
28533             this._lookat = new THREE.Vector3(0, 0, 1);
28534             this._up = new THREE.Vector3(0, -1, 0);
28535             this._focal = 1;
28536         }
28537     }
28538     Object.defineProperty(Camera.prototype, "position", {
28539         /**
28540          * Get position.
28541          * @returns {THREE.Vector3} The position vector.
28542          */
28543         get: function () {
28544             return this._position;
28545         },
28546         enumerable: true,
28547         configurable: true
28548     });
28549     Object.defineProperty(Camera.prototype, "lookat", {
28550         /**
28551          * Get lookat.
28552          * @returns {THREE.Vector3} The lookat vector.
28553          */
28554         get: function () {
28555             return this._lookat;
28556         },
28557         enumerable: true,
28558         configurable: true
28559     });
28560     Object.defineProperty(Camera.prototype, "up", {
28561         /**
28562          * Get up.
28563          * @returns {THREE.Vector3} The up vector.
28564          */
28565         get: function () {
28566             return this._up;
28567         },
28568         enumerable: true,
28569         configurable: true
28570     });
28571     Object.defineProperty(Camera.prototype, "focal", {
28572         /**
28573          * Get focal.
28574          * @returns {number} The focal length.
28575          */
28576         get: function () {
28577             return this._focal;
28578         },
28579         /**
28580          * Set focal.
28581          */
28582         set: function (value) {
28583             this._focal = value;
28584         },
28585         enumerable: true,
28586         configurable: true
28587     });
28588     /**
28589      * Update this camera to the linearly interpolated value of two other cameras.
28590      *
28591      * @param {Camera} a - First camera.
28592      * @param {Camera} b - Second camera.
28593      * @param {number} alpha - Interpolation value on the interval [0, 1].
28594      */
28595     Camera.prototype.lerpCameras = function (a, b, alpha) {
28596         this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
28597         this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
28598         this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
28599         this._focal = (1 - alpha) * a.focal + alpha * b.focal;
28600     };
28601     /**
28602      * Copy the properties of another camera to this camera.
28603      *
28604      * @param {Camera} other - Another camera.
28605      */
28606     Camera.prototype.copy = function (other) {
28607         this._position.copy(other.position);
28608         this._lookat.copy(other.lookat);
28609         this._up.copy(other.up);
28610         this._focal = other.focal;
28611     };
28612     /**
28613      * Clone this camera.
28614      *
28615      * @returns {Camera} A camera with cloned properties equal to this camera.
28616      */
28617     Camera.prototype.clone = function () {
28618         var camera = new Camera();
28619         camera.position.copy(this._position);
28620         camera.lookat.copy(this._lookat);
28621         camera.up.copy(this._up);
28622         camera.focal = this._focal;
28623         return camera;
28624     };
28625     /**
28626      * Determine the distance between this camera and another camera.
28627      *
28628      * @param {Camera} other - Another camera.
28629      * @returns {number} The distance between the cameras.
28630      */
28631     Camera.prototype.diff = function (other) {
28632         var pd = this._position.distanceToSquared(other.position);
28633         var ld = this._lookat.distanceToSquared(other.lookat);
28634         var ud = this._up.distanceToSquared(other.up);
28635         var fd = 100 * Math.abs(this._focal - other.focal);
28636         return Math.max(pd, ld, ud, fd);
28637     };
28638     /**
28639      * Get the focal length based on the transform.
28640      *
28641      * @description Returns the focal length of the transform if gpano info is not available.
28642      * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
28643      * the gpano information if available.
28644      *
28645      * @returns {number} Focal length.
28646      */
28647     Camera.prototype._getFocal = function (transform) {
28648         if (transform.gpano == null) {
28649             return transform.focal;
28650         }
28651         var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
28652         var focal = 0.5 / Math.tan(vFov / 2);
28653         return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
28654     };
28655     return Camera;
28656 }());
28657 exports.Camera = Camera;
28658
28659 },{"three":174}],301:[function(require,module,exports){
28660 "use strict";
28661 /**
28662  * @class GeoCoords
28663  *
28664  * @classdesc Converts coordinates between the geodetic (WGS84),
28665  * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
28666  * East, North, Up (ENU) reference frames.
28667  *
28668  * The WGS84 has latitude (degrees), longitude (degrees) and
28669  * altitude (meters) values.
28670  *
28671  * The ECEF Z-axis pierces the north pole and the
28672  * XY-axis defines the equatorial plane. The X-axis extends
28673  * from the geocenter to the intersection of the Equator and
28674  * the Greenwich Meridian. All values in meters.
28675  *
28676  * The WGS84 parameters are:
28677  *
28678  * a = 6378137
28679  * b = a * (1 - f)
28680  * f = 1 / 298.257223563
28681  * e = Math.sqrt((a^2 - b^2) / a^2)
28682  * e' = Math.sqrt((a^2 - b^2) / b^2)
28683  *
28684  * The WGS84 to ECEF conversion is performed using the following:
28685  *
28686  * X = (N - h) * cos(phi) * cos(lambda)
28687  * Y = (N + h) * cos(phi) * sin(lambda)
28688  * Z = (b^2 * N / a^2 + h) * sin(phi)
28689  *
28690  * where
28691  *
28692  * phi = latitude
28693  * lambda = longitude
28694  * h = height above ellipsoid (altitude)
28695  * N = Radius of curvature (meters)
28696  *   = a / Math.sqrt(1 - e^2 * sin(phi)^2)
28697  *
28698  * The ECEF to WGS84 conversion is performed using the following:
28699  *
28700  * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
28701  * lambda = arctan(Y / X)
28702  * h = p / cos(phi) - N
28703  *
28704  * where
28705  *
28706  * p = Math.sqrt(X^2 + Y^2)
28707  * theta = arctan(Z * a / p * b)
28708  *
28709  * In the ENU reference frame the x-axis points to the
28710  * East, the y-axis to the North and the z-axis Up. All values
28711  * in meters.
28712  *
28713  * The ECEF to ENU conversion is performed using the following:
28714  *
28715  * | x |   |       -sin(lambda_r)                cos(lambda_r)             0      | | X - X_r |
28716  * | y | = | -sin(phi_r) * cos(lambda_r)  -sin(phi_r) * sin(lambda_r)  cos(phi_r) | | Y - Y_r |
28717  * | z |   |  cos(phi_r) * cos(lambda_r)   cos(phi_r) * sin(lambda_r)  sin(phi_r) | | Z - Z_r |
28718  *
28719  * where
28720  *
28721  * phi_r = latitude of reference
28722  * lambda_r = longitude of reference
28723  * X_r, Y_r, Z_r = ECEF coordinates of reference
28724  *
28725  * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
28726  *
28727  * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
28728  * the first step for both conversions.
28729  */
28730 var GeoCoords = (function () {
28731     function GeoCoords() {
28732         this._wgs84a = 6378137.0;
28733         this._wgs84b = 6356752.31424518;
28734     }
28735     /**
28736      * Convert coordinates from geodetic (WGS84) reference to local topocentric
28737      * (ENU) reference.
28738      *
28739      * @param {number} lat Latitude in degrees.
28740      * @param {number} lon Longitude in degrees.
28741      * @param {number} alt Altitude in meters.
28742      * @param {number} refLat Reference latitude in degrees.
28743      * @param {number} refLon Reference longitude in degrees.
28744      * @param {number} refAlt Reference altitude in meters.
28745      * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
28746      */
28747     GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
28748         var ecef = this.geodeticToEcef(lat, lon, alt);
28749         return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
28750     };
28751     /**
28752      * Convert coordinates from local topocentric (ENU) reference to
28753      * geodetic (WGS84) reference.
28754      *
28755      * @param {number} x Topocentric ENU coordinate in East direction.
28756      * @param {number} y Topocentric ENU coordinate in North direction.
28757      * @param {number} z Topocentric ENU coordinate in Up direction.
28758      * @param {number} refLat Reference latitude in degrees.
28759      * @param {number} refLon Reference longitude in degrees.
28760      * @param {number} refAlt Reference altitude in meters.
28761      * @returns {Array<number>} The latitude and longitude in degrees
28762      *                          as well as altitude in meters.
28763      */
28764     GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
28765         var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
28766         return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
28767     };
28768     /**
28769      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
28770      * to local topocentric (ENU) reference.
28771      *
28772      * @param {number} X ECEF X-value.
28773      * @param {number} Y ECEF Y-value.
28774      * @param {number} Z ECEF Z-value.
28775      * @param {number} refLat Reference latitude in degrees.
28776      * @param {number} refLon Reference longitude in degrees.
28777      * @param {number} refAlt Reference altitude in meters.
28778      * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
28779      * and Up directions respectively.
28780      */
28781     GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
28782         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
28783         var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
28784         refLat = refLat * Math.PI / 180.0;
28785         refLon = refLon * Math.PI / 180.0;
28786         var cosLat = Math.cos(refLat);
28787         var sinLat = Math.sin(refLat);
28788         var cosLon = Math.cos(refLon);
28789         var sinLon = Math.sin(refLon);
28790         var x = -sinLon * V[0] + cosLon * V[1];
28791         var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
28792         var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
28793         return [x, y, z];
28794     };
28795     /**
28796      * Convert coordinates from local topocentric (ENU) reference
28797      * to Earth-Centered, Earth-Fixed (ECEF) reference.
28798      *
28799      * @param {number} x Topocentric ENU coordinate in East direction.
28800      * @param {number} y Topocentric ENU coordinate in North direction.
28801      * @param {number} z Topocentric ENU coordinate in Up direction.
28802      * @param {number} refLat Reference latitude in degrees.
28803      * @param {number} refLon Reference longitude in degrees.
28804      * @param {number} refAlt Reference altitude in meters.
28805      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
28806      */
28807     GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
28808         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
28809         refLat = refLat * Math.PI / 180.0;
28810         refLon = refLon * Math.PI / 180.0;
28811         var cosLat = Math.cos(refLat);
28812         var sinLat = Math.sin(refLat);
28813         var cosLon = Math.cos(refLon);
28814         var sinLon = Math.sin(refLon);
28815         var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
28816         var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
28817         var Z = cosLat * y + sinLat * z + refEcef[2];
28818         return [X, Y, Z];
28819     };
28820     /**
28821      * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
28822      * Earth-Fixed (ECEF) reference.
28823      *
28824      * @param {number} lat Latitude in degrees.
28825      * @param {number} lon Longitude in degrees.
28826      * @param {number} alt Altitude in meters.
28827      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
28828      */
28829     GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
28830         var a = this._wgs84a;
28831         var b = this._wgs84b;
28832         lat = lat * Math.PI / 180.0;
28833         lon = lon * Math.PI / 180.0;
28834         var cosLat = Math.cos(lat);
28835         var sinLat = Math.sin(lat);
28836         var cosLon = Math.cos(lon);
28837         var sinLon = Math.sin(lon);
28838         var a2 = a * a;
28839         var b2 = b * b;
28840         var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
28841         var nhcl = (a2 * L + alt) * cosLat;
28842         var X = nhcl * cosLon;
28843         var Y = nhcl * sinLon;
28844         var Z = (b2 * L + alt) * sinLat;
28845         return [X, Y, Z];
28846     };
28847     /**
28848      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
28849      * to geodetic reference (WGS84).
28850      *
28851      * @param {number} X ECEF X-value.
28852      * @param {number} Y ECEF Y-value.
28853      * @param {number} Z ECEF Z-value.
28854      * @returns {Array<number>} The latitude and longitude in degrees
28855      *                          as well as altitude in meters.
28856      */
28857     GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
28858         var a = this._wgs84a;
28859         var b = this._wgs84b;
28860         var a2 = a * a;
28861         var b2 = b * b;
28862         var a2mb2 = a2 - b2;
28863         var ea = Math.sqrt(a2mb2 / a2);
28864         var eb = Math.sqrt(a2mb2 / b2);
28865         var p = Math.sqrt(X * X + Y * Y);
28866         var theta = Math.atan2(Z * a, p * b);
28867         var sinTheta = Math.sin(theta);
28868         var cosTheta = Math.cos(theta);
28869         var lon = Math.atan2(Y, X);
28870         var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
28871         var sinLat = Math.sin(lat);
28872         var cosLat = Math.cos(lat);
28873         var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
28874         var alt = p / cosLat - N;
28875         return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
28876     };
28877     return GeoCoords;
28878 }());
28879 exports.GeoCoords = GeoCoords;
28880 Object.defineProperty(exports, "__esModule", { value: true });
28881 exports.default = GeoCoords;
28882
28883 },{}],302:[function(require,module,exports){
28884 /// <reference path="../../typings/index.d.ts" />
28885 "use strict";
28886 var THREE = require("three");
28887 /**
28888  * @class Spatial
28889  *
28890  * @classdesc Provides methods for scalar, vector and matrix calculations.
28891  */
28892 var Spatial = (function () {
28893     function Spatial() {
28894         this._epsilon = 1e-9;
28895     }
28896     /**
28897      * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
28898      * bearing (clockwise with origin at north or Y-axis).
28899      *
28900      * @param {number} phi - Azimuthal phi angle in radians.
28901      * @returns {number} Bearing in radians.
28902      */
28903     Spatial.prototype.azimuthalToBearing = function (phi) {
28904         return -phi + Math.PI / 2;
28905     };
28906     /**
28907      * Converts degrees to radians.
28908      *
28909      * @param {number} deg - Degrees.
28910      * @returns {number} Radians.
28911      */
28912     Spatial.prototype.degToRad = function (deg) {
28913         return Math.PI * deg / 180;
28914     };
28915     /**
28916      * Converts radians to degrees.
28917      *
28918      * @param {number} rad - Radians.
28919      * @returns {number} Degrees.
28920      */
28921     Spatial.prototype.radToDeg = function (rad) {
28922         return 180 * rad / Math.PI;
28923     };
28924     /**
28925      * Creates a rotation matrix from an angle-axis vector.
28926      *
28927      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
28928      * @returns {THREE.Matrix4} Rotation matrix.
28929      */
28930     Spatial.prototype.rotationMatrix = function (angleAxis) {
28931         var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
28932         var angle = axis.length();
28933         axis.normalize();
28934         return new THREE.Matrix4().makeRotationAxis(axis, angle);
28935     };
28936     /**
28937      * Rotates a vector according to a angle-axis rotation vector.
28938      *
28939      * @param {Array<number>} vector - Vector to rotate.
28940      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
28941      * @returns {THREE.Vector3} Rotated vector.
28942      */
28943     Spatial.prototype.rotate = function (vector, angleAxis) {
28944         var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
28945         var rotationMatrix = this.rotationMatrix(angleAxis);
28946         v.applyMatrix4(rotationMatrix);
28947         return v;
28948     };
28949     /**
28950      * Calculates the optical center from a rotation vector
28951      * on the angle-axis representation and a translation vector
28952      * according to C = -R^T t.
28953      *
28954      * @param {Array<number>} rotation - Angle-axis representation of a rotation.
28955      * @param {Array<number>} translation - Translation vector.
28956      * @returns {THREE.Vector3} Optical center.
28957      */
28958     Spatial.prototype.opticalCenter = function (rotation, translation) {
28959         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
28960         var vector = [-translation[0], -translation[1], -translation[2]];
28961         return this.rotate(vector, angleAxis);
28962     };
28963     /**
28964      * Calculates the viewing direction from a rotation vector
28965      * on the angle-axis representation.
28966      *
28967      * @param {number[]} rotation - Angle-axis representation of a rotation.
28968      * @returns {THREE.Vector3} Viewing direction.
28969      */
28970     Spatial.prototype.viewingDirection = function (rotation) {
28971         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
28972         return this.rotate([0, 0, 1], angleAxis);
28973     };
28974     /**
28975      * Wrap a number on the interval [min, max].
28976      *
28977      * @param {number} value - Value to wrap.
28978      * @param {number} min - Lower endpoint of interval.
28979      * @param {number} max - Upper endpoint of interval.
28980      * @returns {number} The wrapped number.
28981      */
28982     Spatial.prototype.wrap = function (value, min, max) {
28983         if (max < min) {
28984             throw new Error("Invalid arguments: max must be larger than min.");
28985         }
28986         var interval = (max - min);
28987         while (value > max || value < min) {
28988             if (value > max) {
28989                 value = value - interval;
28990             }
28991             else if (value < min) {
28992                 value = value + interval;
28993             }
28994         }
28995         return value;
28996     };
28997     /**
28998      * Wrap an angle on the interval [-Pi, Pi].
28999      *
29000      * @param {number} angle - Value to wrap.
29001      * @returns {number} Wrapped angle.
29002      */
29003     Spatial.prototype.wrapAngle = function (angle) {
29004         return this.wrap(angle, -Math.PI, Math.PI);
29005     };
29006     /**
29007      * Limit the value to the interval [min, max] by changing the value to
29008      * the nearest available one when it is outside the interval.
29009      *
29010      * @param {number} value - Value to clamp.
29011      * @param {number} min - Minimum of the interval.
29012      * @param {number} max - Maximum of the interval.
29013      * @returns {number} Clamped value.
29014      */
29015     Spatial.prototype.clamp = function (value, min, max) {
29016         if (value < min) {
29017             return min;
29018         }
29019         if (value > max) {
29020             return max;
29021         }
29022         return value;
29023     };
29024     /**
29025      * Calculates the counter-clockwise angle from the first
29026      * vector (x1, y1)^T to the second (x2, y2)^T.
29027      *
29028      * @param {number} x1 - X coordinate of first vector.
29029      * @param {number} y1 - Y coordinate of first vector.
29030      * @param {number} x2 - X coordinate of second vector.
29031      * @param {number} y2 - Y coordinate of second vector.
29032      * @returns {number} Counter clockwise angle between the vectors.
29033      */
29034     Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
29035         var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
29036         return this.wrapAngle(angle);
29037     };
29038     /**
29039      * Calculates the minimum (absolute) angle change for rotation
29040      * from one angle to another on the [-Pi, Pi] interval.
29041      *
29042      * @param {number} angle1 - Start angle.
29043      * @param {number} angle2 - Destination angle.
29044      * @returns {number} Absolute angle change between angles.
29045      */
29046     Spatial.prototype.angleDifference = function (angle1, angle2) {
29047         var angle = angle2 - angle1;
29048         return this.wrapAngle(angle);
29049     };
29050     /**
29051      * Calculates the relative rotation angle between two
29052      * angle-axis vectors.
29053      *
29054      * @param {number} rotation1 - First angle-axis vector.
29055      * @param {number} rotation2 - Second angle-axis vector.
29056      * @returns {number} Relative rotation angle.
29057      */
29058     Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
29059         var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
29060         var R2 = this.rotationMatrix(rotation2);
29061         var R = R1T.multiply(R2);
29062         var elements = R.elements;
29063         // from Tr(R) = 1 + 2*cos(theta)
29064         var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
29065         return theta;
29066     };
29067     /**
29068      * Calculates the angle from a vector to a plane.
29069      *
29070      * @param {Array<number>} vector - The vector.
29071      * @param {Array<number>} planeNormal - Normal of the plane.
29072      * @returns {number} Angle from between plane and vector.
29073      */
29074     Spatial.prototype.angleToPlane = function (vector, planeNormal) {
29075         var v = new THREE.Vector3().fromArray(vector);
29076         var norm = v.length();
29077         if (norm < this._epsilon) {
29078             return 0;
29079         }
29080         var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
29081         return Math.asin(projection / norm);
29082     };
29083     /**
29084      * Calculates the distance between two coordinates
29085      * (latitude longitude pairs) in meters according to
29086      * the haversine formula.
29087      *
29088      * @param {number} lat1 - Latitude of the first coordinate.
29089      * @param {number} lon1 - Longitude of the first coordinate.
29090      * @param {number} lat2 - Latitude of the second coordinate.
29091      * @param {number} lon2 - Longitude of the second coordinate.
29092      * @returns {number} Distance between lat lon positions.
29093      */
29094     Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
29095         var r = 6371000;
29096         var dLat = this.degToRad(lat2 - lat1);
29097         var dLon = this.degToRad(lon2 - lon1);
29098         var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
29099             Math.cos(lat1) * Math.cos(lat2) *
29100                 Math.sin(dLon / 2) * Math.sin(dLon / 2);
29101         var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
29102         return d;
29103     };
29104     return Spatial;
29105 }());
29106 exports.Spatial = Spatial;
29107 Object.defineProperty(exports, "__esModule", { value: true });
29108 exports.default = Spatial;
29109
29110 },{"three":174}],303:[function(require,module,exports){
29111 /// <reference path="../../typings/index.d.ts" />
29112 "use strict";
29113 var THREE = require("three");
29114 /**
29115  * @class Transform
29116  *
29117  * @classdesc Class used for calculating coordinate transformations
29118  * and projections.
29119  */
29120 var Transform = (function () {
29121     /**
29122      * Create a new transform instance.
29123      * @param {Node} apiNavImIm - Node properties.
29124      * @param {HTMLImageElement} image - Node image.
29125      * @param {Array<number>} translation - Node translation vector in three dimensions.
29126      */
29127     function Transform(node, image, translation) {
29128         this._orientation = this._getValue(node.orientation, 1);
29129         var imageWidth = image != null ? image.width : 4;
29130         var imageHeight = image != null ? image.height : 3;
29131         var keepOrientation = this._orientation < 5;
29132         this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
29133         this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
29134         this._basicAspect = keepOrientation ?
29135             this._width / this._height :
29136             this._height / this._width;
29137         this._basicWidth = keepOrientation ? node.width : node.height;
29138         this._basicHeight = keepOrientation ? node.height : node.width;
29139         this._focal = this._getValue(node.focal, 1);
29140         this._scale = this._getValue(node.scale, 0);
29141         this._gpano = node.gpano != null ? node.gpano : null;
29142         this._rt = this._getRt(node.rotation, translation);
29143         this._srt = this._getSrt(this._rt, this._scale);
29144     }
29145     Object.defineProperty(Transform.prototype, "basicAspect", {
29146         /**
29147          * Get basic aspect.
29148          * @returns {number} The orientation adjusted aspect ratio.
29149          */
29150         get: function () {
29151             return this._basicAspect;
29152         },
29153         enumerable: true,
29154         configurable: true
29155     });
29156     Object.defineProperty(Transform.prototype, "basicHeight", {
29157         /**
29158          * Get basic height.
29159          *
29160          * @description Does not fall back to node image height but
29161          * uses original value from API so can be faulty.
29162          *
29163          * @returns {number} The height of the basic version image
29164          * (adjusted for orientation).
29165          */
29166         get: function () {
29167             return this._basicHeight;
29168         },
29169         enumerable: true,
29170         configurable: true
29171     });
29172     Object.defineProperty(Transform.prototype, "basicWidth", {
29173         /**
29174          * Get basic width.
29175          *
29176          * @description Does not fall back to node image width but
29177          * uses original value from API so can be faulty.
29178          *
29179          * @returns {number} The width of the basic version image
29180          * (adjusted for orientation).
29181          */
29182         get: function () {
29183             return this._basicWidth;
29184         },
29185         enumerable: true,
29186         configurable: true
29187     });
29188     Object.defineProperty(Transform.prototype, "focal", {
29189         /**
29190          * Get focal.
29191          * @returns {number} The node focal length.
29192          */
29193         get: function () {
29194             return this._focal;
29195         },
29196         enumerable: true,
29197         configurable: true
29198     });
29199     Object.defineProperty(Transform.prototype, "fullPano", {
29200         /**
29201          * Get fullPano.
29202          *
29203          * @returns {boolean} Value indicating whether the node is a complete
29204          * 360 panorama.
29205          */
29206         get: function () {
29207             return this._gpano != null &&
29208                 this._gpano.CroppedAreaLeftPixels === 0 &&
29209                 this._gpano.CroppedAreaTopPixels === 0 &&
29210                 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
29211                 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
29212         },
29213         enumerable: true,
29214         configurable: true
29215     });
29216     Object.defineProperty(Transform.prototype, "gpano", {
29217         /**
29218          * Get gpano.
29219          * @returns {number} The node gpano information.
29220          */
29221         get: function () {
29222             return this._gpano;
29223         },
29224         enumerable: true,
29225         configurable: true
29226     });
29227     Object.defineProperty(Transform.prototype, "height", {
29228         /**
29229          * Get height.
29230          *
29231          * @description Falls back to the node image height if
29232          * the API data is faulty.
29233          *
29234          * @returns {number} The orientation adjusted image height.
29235          */
29236         get: function () {
29237             return this._height;
29238         },
29239         enumerable: true,
29240         configurable: true
29241     });
29242     Object.defineProperty(Transform.prototype, "orientation", {
29243         /**
29244          * Get orientation.
29245          * @returns {number} The image orientation.
29246          */
29247         get: function () {
29248             return this._orientation;
29249         },
29250         enumerable: true,
29251         configurable: true
29252     });
29253     Object.defineProperty(Transform.prototype, "rt", {
29254         /**
29255          * Get rt.
29256          * @returns {THREE.Matrix4} The extrinsic camera matrix.
29257          */
29258         get: function () {
29259             return this._rt;
29260         },
29261         enumerable: true,
29262         configurable: true
29263     });
29264     Object.defineProperty(Transform.prototype, "srt", {
29265         /**
29266          * Get srt.
29267          * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
29268          */
29269         get: function () {
29270             return this._srt;
29271         },
29272         enumerable: true,
29273         configurable: true
29274     });
29275     Object.defineProperty(Transform.prototype, "scale", {
29276         /**
29277          * Get scale.
29278          * @returns {number} The node atomic reconstruction scale.
29279          */
29280         get: function () {
29281             return this._scale;
29282         },
29283         enumerable: true,
29284         configurable: true
29285     });
29286     Object.defineProperty(Transform.prototype, "width", {
29287         /**
29288          * Get width.
29289          *
29290          * @description Falls back to the node image width if
29291          * the API data is faulty.
29292          *
29293          * @returns {number} The orientation adjusted image width.
29294          */
29295         get: function () {
29296             return this._width;
29297         },
29298         enumerable: true,
29299         configurable: true
29300     });
29301     /**
29302      * Calculate the up vector for the node transform.
29303      *
29304      * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
29305      */
29306     Transform.prototype.upVector = function () {
29307         var rte = this._rt.elements;
29308         switch (this._orientation) {
29309             case 1:
29310                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
29311             case 3:
29312                 return new THREE.Vector3(rte[1], rte[5], rte[9]);
29313             case 6:
29314                 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
29315             case 8:
29316                 return new THREE.Vector3(rte[0], rte[4], rte[8]);
29317             default:
29318                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
29319         }
29320     };
29321     /**
29322      * Calculate projector matrix for projecting 3D points to texture map
29323      * coordinates (u and v).
29324      *
29325      * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
29326      * map coordinate calculations.
29327      */
29328     Transform.prototype.projectorMatrix = function () {
29329         var projector = this._normalizedToTextureMatrix();
29330         var f = this._focal;
29331         var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
29332         projector.multiply(projection);
29333         projector.multiply(this._rt);
29334         return projector;
29335     };
29336     /**
29337      * Project 3D world coordinates to basic coordinates.
29338      *
29339      * @param {Array<number>} point3d - 3D world coordinates.
29340      * @return {Array<number>} 2D basic coordinates.
29341      */
29342     Transform.prototype.projectBasic = function (point3d) {
29343         var sfm = this.projectSfM(point3d);
29344         return this._sfmToBasic(sfm);
29345     };
29346     /**
29347      * Unproject basic coordinates to 3D world coordinates.
29348      *
29349      * @param {Array<number>} basic - 2D basic coordinates.
29350      * @param {Array<number>} distance - Depth to unproject from camera center.
29351      * @returns {Array<number>} Unprojected 3D world coordinates.
29352      */
29353     Transform.prototype.unprojectBasic = function (basic, distance) {
29354         var sfm = this._basicToSfm(basic);
29355         return this.unprojectSfM(sfm, distance);
29356     };
29357     /**
29358      * Project 3D world coordinates to SfM coordinates.
29359      *
29360      * @param {Array<number>} point3d - 3D world coordinates.
29361      * @return {Array<number>} 2D SfM coordinates.
29362      */
29363     Transform.prototype.projectSfM = function (point3d) {
29364         var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
29365         v.applyMatrix4(this._rt);
29366         return this._bearingToSfm([v.x, v.y, v.z]);
29367     };
29368     /**
29369      * Unproject SfM coordinates to a 3D world coordinates.
29370      *
29371      * @param {Array<number>} sfm - 2D SfM coordinates.
29372      * @param {Array<number>} distance - Depth to unproject from camera center.
29373      * @returns {Array<number>} Unprojected 3D world coordinates.
29374      */
29375     Transform.prototype.unprojectSfM = function (sfm, distance) {
29376         var bearing = this._sfmToBearing(sfm);
29377         var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
29378         v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
29379         return [v.x / v.w, v.y / v.w, v.z / v.w];
29380     };
29381     /**
29382      * Transform SfM coordinates to bearing vector (3D cartesian
29383      * coordinates on the unit sphere).
29384      *
29385      * @param {Array<number>} sfm - 2D SfM coordinates.
29386      * @returns {Array<number>} Bearing vector (3D cartesian coordinates
29387      * on the unit sphere).
29388      */
29389     Transform.prototype._sfmToBearing = function (sfm) {
29390         if (this._fullPano()) {
29391             var lon = sfm[0] * 2 * Math.PI;
29392             var lat = -sfm[1] * 2 * Math.PI;
29393             var x = Math.cos(lat) * Math.sin(lon);
29394             var y = -Math.sin(lat);
29395             var z = Math.cos(lat) * Math.cos(lon);
29396             return [x, y, z];
29397         }
29398         else if (this._gpano) {
29399             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
29400             var fullPanoPixel = [
29401                 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
29402                 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
29403             ];
29404             var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
29405             var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
29406             var x = Math.cos(lat) * Math.sin(lon);
29407             var y = -Math.sin(lat);
29408             var z = Math.cos(lat) * Math.cos(lon);
29409             return [x, y, z];
29410         }
29411         else {
29412             var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
29413             v.normalize();
29414             return [v.x, v.y, v.z];
29415         }
29416     };
29417     /**
29418      * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
29419      * SfM coordinates.
29420      *
29421      * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
29422      * unit sphere).
29423      * @returns {Array<number>} 2D SfM coordinates.
29424      */
29425     Transform.prototype._bearingToSfm = function (bearing) {
29426         if (this._fullPano()) {
29427             var x = bearing[0];
29428             var y = bearing[1];
29429             var z = bearing[2];
29430             var lon = Math.atan2(x, z);
29431             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
29432             return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
29433         }
29434         else if (this._gpano) {
29435             var x = bearing[0];
29436             var y = bearing[1];
29437             var z = bearing[2];
29438             var lon = Math.atan2(x, z);
29439             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
29440             var fullPanoPixel = [
29441                 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
29442                 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
29443             ];
29444             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
29445             return [
29446                 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
29447                 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
29448             ];
29449         }
29450         else {
29451             if (bearing[2] > 0) {
29452                 return [
29453                     bearing[0] * this._focal / bearing[2],
29454                     bearing[1] * this._focal / bearing[2],
29455                 ];
29456             }
29457             else {
29458                 return [
29459                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
29460                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
29461                 ];
29462             }
29463         }
29464     };
29465     /**
29466      * Convert basic coordinates to SfM coordinates.
29467      *
29468      * @param {Array<number>} basic - 2D basic coordinates.
29469      * @returns {Array<number>} 2D SfM coordinates.
29470      */
29471     Transform.prototype._basicToSfm = function (basic) {
29472         var rotatedX;
29473         var rotatedY;
29474         switch (this._orientation) {
29475             case 1:
29476                 rotatedX = basic[0];
29477                 rotatedY = basic[1];
29478                 break;
29479             case 3:
29480                 rotatedX = 1 - basic[0];
29481                 rotatedY = 1 - basic[1];
29482                 break;
29483             case 6:
29484                 rotatedX = basic[1];
29485                 rotatedY = 1 - basic[0];
29486                 break;
29487             case 8:
29488                 rotatedX = 1 - basic[1];
29489                 rotatedY = basic[0];
29490                 break;
29491             default:
29492                 rotatedX = basic[0];
29493                 rotatedY = basic[1];
29494                 break;
29495         }
29496         var w = this._width;
29497         var h = this._height;
29498         var s = Math.max(w, h);
29499         var sfmX = rotatedX * w / s - w / s / 2;
29500         var sfmY = rotatedY * h / s - h / s / 2;
29501         return [sfmX, sfmY];
29502     };
29503     /**
29504      * Convert SfM coordinates to basic coordinates.
29505      *
29506      * @param {Array<number>} sfm - 2D SfM coordinates.
29507      * @returns {Array<number>} 2D basic coordinates.
29508      */
29509     Transform.prototype._sfmToBasic = function (sfm) {
29510         var w = this._width;
29511         var h = this._height;
29512         var s = Math.max(w, h);
29513         var rotatedX = (sfm[0] + w / s / 2) / w * s;
29514         var rotatedY = (sfm[1] + h / s / 2) / h * s;
29515         var basicX;
29516         var basicY;
29517         switch (this._orientation) {
29518             case 1:
29519                 basicX = rotatedX;
29520                 basicY = rotatedY;
29521                 break;
29522             case 3:
29523                 basicX = 1 - rotatedX;
29524                 basicY = 1 - rotatedY;
29525                 break;
29526             case 6:
29527                 basicX = 1 - rotatedY;
29528                 basicY = rotatedX;
29529                 break;
29530             case 8:
29531                 basicX = rotatedY;
29532                 basicY = 1 - rotatedX;
29533                 break;
29534             default:
29535                 basicX = rotatedX;
29536                 basicY = rotatedY;
29537                 break;
29538         }
29539         return [basicX, basicY];
29540     };
29541     /**
29542      * Determines if the gpano information indicates a full panorama.
29543      *
29544      * @returns {boolean} Value determining if the gpano information indicates
29545      * a full panorama.
29546      */
29547     Transform.prototype._fullPano = function () {
29548         return this.gpano != null &&
29549             this.gpano.CroppedAreaLeftPixels === 0 &&
29550             this.gpano.CroppedAreaTopPixels === 0 &&
29551             this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
29552             this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
29553     };
29554     /**
29555      * Checks a value and returns it if it exists and is larger than 0.
29556      * Fallbacks if it is null.
29557      *
29558      * @param {number} value - Value to check.
29559      * @param {number} fallback - Value to fall back to.
29560      * @returns {number} The value or its fallback value if it is not defined or negative.
29561      */
29562     Transform.prototype._getValue = function (value, fallback) {
29563         return value != null && value > 0 ? value : fallback;
29564     };
29565     /**
29566      * Creates the extrinsic camera matrix [ R | t ].
29567      *
29568      * @param {Array<number>} rotation - Rotation vector in angle axis representation.
29569      * @param {Array<number>} translation - Translation vector.
29570      * @returns {THREE.Matrix4} Extrisic camera matrix.
29571      */
29572     Transform.prototype._getRt = function (rotation, translation) {
29573         var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
29574         var angle = axis.length();
29575         axis.normalize();
29576         var rt = new THREE.Matrix4();
29577         rt.makeRotationAxis(axis, angle);
29578         rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
29579         return rt;
29580     };
29581     /**
29582      * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
29583      *
29584      * @param {THREE.Matrix4} rt - Extrisic camera matrix.
29585      * @param {number} scale - Scale factor.
29586      * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
29587      */
29588     Transform.prototype._getSrt = function (rt, scale) {
29589         var srt = rt.clone();
29590         var elements = srt.elements;
29591         elements[12] = scale * elements[12];
29592         elements[13] = scale * elements[13];
29593         elements[14] = scale * elements[14];
29594         srt.scale(new THREE.Vector3(scale, scale, scale));
29595         return srt;
29596     };
29597     /**
29598      * Calculate a transformation matrix from normalized coordinates for
29599      * texture map coordinates.
29600      *
29601      * @returns {THREE.Matrix4} Normalized coordinates to texture map
29602      * coordinates transformation matrix.
29603      */
29604     Transform.prototype._normalizedToTextureMatrix = function () {
29605         var size = Math.max(this._width, this._height);
29606         var w = size / this._width;
29607         var h = size / this._height;
29608         switch (this._orientation) {
29609             case 1:
29610                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29611             case 3:
29612                 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29613             case 6:
29614                 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29615             case 8:
29616                 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29617             default:
29618                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29619         }
29620     };
29621     return Transform;
29622 }());
29623 exports.Transform = Transform;
29624
29625 },{"three":174}],304:[function(require,module,exports){
29626 /// <reference path="../../typings/index.d.ts" />
29627 "use strict";
29628 var THREE = require("three");
29629 /**
29630  * @class ViewportCoords
29631  *
29632  * @classdesc Provides methods for calculating 2D coordinate conversions
29633  * as well as 3D projection and unprojection.
29634  *
29635  * Basic coordinates are 2D coordinates on the [0, 1] interval and
29636  * have the origin point, (0, 0), at the top left corner and the
29637  * maximum value, (1, 1), at the bottom right corner of the original
29638  * photo.
29639  *
29640  * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
29641  * have the origin point in the center. The bottom left corner point is
29642  * (-1, -1) and the top right corner point is (1, 1).
29643  *
29644  * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
29645  * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
29646  * corner and the maximum value is (canvasWidth, canvasHeight) is in the
29647  * bottom right corner.
29648  *
29649  * 3D coordinates are in the topocentric world reference frame.
29650  */
29651 var ViewportCoords = (function () {
29652     function ViewportCoords() {
29653         this._unprojectDepth = 200;
29654     }
29655     /**
29656      * Convert basic coordinates to canvas coordinates.
29657      *
29658      * @description Transform origin and perspective camera position needs to be the
29659      * equal for reliable return value.
29660      *
29661      * @param {number} basicX - Basic X coordinate.
29662      * @param {number} basicY - Basic Y coordinate.
29663      * @param {HTMLElement} container - The viewer container.
29664      * @param {Transform} transform - Transform of the node to unproject from.
29665      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29666      * @returns {Array<number>} 2D canvas coordinates.
29667      */
29668     ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, perspectiveCamera) {
29669         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
29670         var canvas = this.projectToCanvas(point3d, container, perspectiveCamera);
29671         return canvas;
29672     };
29673     /**
29674      * Convert basic coordinates to viewport coordinates.
29675      *
29676      * @description Transform origin and perspective camera position needs to be the
29677      * equal for reliable return value.
29678      *
29679      * @param {number} basicX - Basic X coordinate.
29680      * @param {number} basicY - Basic Y coordinate.
29681      * @param {Transform} transform - Transform of the node to unproject from.
29682      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29683      * @returns {Array<number>} 2D viewport coordinates.
29684      */
29685     ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, perspectiveCamera) {
29686         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
29687         var viewport = this.projectToViewport(point3d, perspectiveCamera);
29688         return viewport;
29689     };
29690     /**
29691      * Get canvas pixel position from event.
29692      *
29693      * @param {Event} event - Event containing clientX and clientY properties.
29694      * @param {HTMLElement} element - HTML element.
29695      * @returns {Array<number>} 2D canvas coordinates.
29696      */
29697     ViewportCoords.prototype.canvasPosition = function (event, element) {
29698         var clientRect = element.getBoundingClientRect();
29699         var canvasX = event.clientX - clientRect.left - element.clientLeft;
29700         var canvasY = event.clientY - clientRect.top - element.clientTop;
29701         return [canvasX, canvasY];
29702     };
29703     /**
29704      * Convert canvas coordinates to basic coordinates.
29705      *
29706      * @description Transform origin and perspective camera position needs to be the
29707      * equal for reliable return value.
29708      *
29709      * @param {number} canvasX - Canvas X coordinate.
29710      * @param {number} canvasY - Canvas Y coordinate.
29711      * @param {HTMLElement} container - The viewer container.
29712      * @param {Transform} transform - Transform of the node to unproject from.
29713      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29714      * @returns {Array<number>} 2D basic coordinates.
29715      */
29716     ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, perspectiveCamera) {
29717         var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, perspectiveCamera)
29718             .toArray();
29719         var basic = transform.projectBasic(point3d);
29720         return basic;
29721     };
29722     /**
29723      * Convert canvas coordinates to viewport coordinates.
29724      *
29725      * @param {number} canvasX - Canvas X coordinate.
29726      * @param {number} canvasY - Canvas Y coordinate.
29727      * @param {HTMLElement} container - The viewer container.
29728      * @returns {Array<number>} 2D viewport coordinates.
29729      */
29730     ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
29731         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
29732         var viewportX = 2 * canvasX / canvasWidth - 1;
29733         var viewportY = 1 - 2 * canvasY / canvasHeight;
29734         return [viewportX, viewportY];
29735     };
29736     /**
29737      * Determines the width and height of the container in canvas coordinates.
29738      *
29739      * @param {HTMLElement} container - The viewer container.
29740      * @returns {Array<number>} 2D canvas coordinates.
29741      */
29742     ViewportCoords.prototype.containerToCanvas = function (container) {
29743         return [container.offsetWidth, container.offsetHeight];
29744     };
29745     /**
29746      * Determine basic distances from image to canvas corners.
29747      *
29748      * @description Transform origin and perspective camera position needs to be the
29749      * equal for reliable return value.
29750      *
29751      * Determines the smallest basic distance for every side of the canvas.
29752      *
29753      * @param {Transform} transform - Transform of the node to unproject from.
29754      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29755      * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
29756      */
29757     ViewportCoords.prototype.getBasicDistances = function (transform, perspectiveCamera) {
29758         var topLeftBasic = this.viewportToBasic(-1, 1, transform, perspectiveCamera);
29759         var topRightBasic = this.viewportToBasic(1, 1, transform, perspectiveCamera);
29760         var bottomRightBasic = this.viewportToBasic(1, -1, transform, perspectiveCamera);
29761         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, perspectiveCamera);
29762         var topBasicDistance = 0;
29763         var rightBasicDistance = 0;
29764         var bottomBasicDistance = 0;
29765         var leftBasicDistance = 0;
29766         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
29767             topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
29768                 -topLeftBasic[1] :
29769                 -topRightBasic[1];
29770         }
29771         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
29772             rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
29773                 topRightBasic[0] - 1 :
29774                 bottomRightBasic[0] - 1;
29775         }
29776         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
29777             bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
29778                 bottomRightBasic[1] - 1 :
29779                 bottomLeftBasic[1] - 1;
29780         }
29781         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
29782             leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
29783                 -bottomLeftBasic[0] :
29784                 -topLeftBasic[0];
29785         }
29786         return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
29787     };
29788     /**
29789      * Determine pixel distances from image to canvas corners.
29790      *
29791      * @description Transform origin and perspective camera position needs to be the
29792      * equal for reliable return value.
29793      *
29794      * Determines the smallest pixel distance for every side of the canvas.
29795      *
29796      * @param {HTMLElement} container - The viewer container.
29797      * @param {Transform} transform - Transform of the node to unproject from.
29798      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29799      * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
29800      */
29801     ViewportCoords.prototype.getPixelDistances = function (container, transform, perspectiveCamera) {
29802         var topLeftBasic = this.viewportToBasic(-1, 1, transform, perspectiveCamera);
29803         var topRightBasic = this.viewportToBasic(1, 1, transform, perspectiveCamera);
29804         var bottomRightBasic = this.viewportToBasic(1, -1, transform, perspectiveCamera);
29805         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, perspectiveCamera);
29806         var topPixelDistance = 0;
29807         var rightPixelDistance = 0;
29808         var bottomPixelDistance = 0;
29809         var leftPixelDistance = 0;
29810         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
29811         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
29812             var basicX = topLeftBasic[1] > topRightBasic[1] ?
29813                 topLeftBasic[0] :
29814                 topRightBasic[0];
29815             var canvas = this.basicToCanvas(basicX, 0, container, transform, perspectiveCamera);
29816             topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
29817         }
29818         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
29819             var basicY = topRightBasic[0] < bottomRightBasic[0] ?
29820                 topRightBasic[1] :
29821                 bottomRightBasic[1];
29822             var canvas = this.basicToCanvas(1, basicY, container, transform, perspectiveCamera);
29823             rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
29824         }
29825         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
29826             var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
29827                 bottomRightBasic[0] :
29828                 bottomLeftBasic[0];
29829             var canvas = this.basicToCanvas(basicX, 1, container, transform, perspectiveCamera);
29830             bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
29831         }
29832         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
29833             var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
29834                 bottomLeftBasic[1] :
29835                 topLeftBasic[1];
29836             var canvas = this.basicToCanvas(0, basicY, container, transform, perspectiveCamera);
29837             leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
29838         }
29839         return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
29840     };
29841     /**
29842      * Determine if an event occured inside an element.
29843      *
29844      * @param {Event} event - Event containing clientX and clientY properties.
29845      * @param {HTMLElement} element - HTML element.
29846      * @returns {boolean} Value indicating if the event occured inside the element or not.
29847      */
29848     ViewportCoords.prototype.insideElement = function (event, element) {
29849         var clientRect = element.getBoundingClientRect();
29850         var minX = clientRect.left + element.clientLeft;
29851         var maxX = minX + element.clientWidth;
29852         var minY = clientRect.top + element.clientTop;
29853         var maxY = minY + element.clientHeight;
29854         return event.clientX > minX &&
29855             event.clientX < maxX &&
29856             event.clientY > minY &&
29857             event.clientY < maxY;
29858     };
29859     /**
29860      * Project 3D world coordinates to canvas coordinates.
29861      *
29862      * @param {Array<number>} point3D - 3D world coordinates.
29863      * @param {HTMLElement} container - The viewer container.
29864      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29865      * @returns {Array<number>} 2D canvas coordinates.
29866      */
29867     ViewportCoords.prototype.projectToCanvas = function (point3d, container, perspectiveCamera) {
29868         var viewport = this.projectToViewport(point3d, perspectiveCamera);
29869         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
29870         return canvas;
29871     };
29872     /**
29873      * Project 3D world coordinates to viewport coordinates.
29874      *
29875      * @param {Array<number>} point3D - 3D world coordinates.
29876      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29877      * @returns {Array<number>} 2D viewport coordinates.
29878      */
29879     ViewportCoords.prototype.projectToViewport = function (point3d, perspectiveCamera) {
29880         var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
29881             .project(perspectiveCamera);
29882         return [viewport.x, viewport.y];
29883     };
29884     /**
29885      * Uproject canvas coordinates to 3D world coordinates.
29886      *
29887      * @param {number} canvasX - Canvas X coordinate.
29888      * @param {number} canvasY - Canvas Y coordinate.
29889      * @param {HTMLElement} container - The viewer container.
29890      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29891      * @returns {Array<number>} 3D world coordinates.
29892      */
29893     ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, perspectiveCamera) {
29894         var viewport = this.canvasToViewport(canvasX, canvasY, container);
29895         var point3d = this.unprojectFromViewport(viewport[0], viewport[1], perspectiveCamera);
29896         return point3d;
29897     };
29898     /**
29899      * Unproject viewport coordinates to 3D world coordinates.
29900      *
29901      * @param {number} viewportX - Viewport X coordinate.
29902      * @param {number} viewportY - Viewport Y coordinate.
29903      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29904      * @returns {Array<number>} 3D world coordinates.
29905      */
29906     ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, perspectiveCamera) {
29907         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
29908             .unproject(perspectiveCamera);
29909         return point3d;
29910     };
29911     /**
29912      * Convert viewport coordinates to basic coordinates.
29913      *
29914      * @description Transform origin and perspective camera position needs to be the
29915      * equal for reliable return value.
29916      *
29917      * @param {number} viewportX - Viewport X coordinate.
29918      * @param {number} viewportY - Viewport Y coordinate.
29919      * @param {Transform} transform - Transform of the node to unproject from.
29920      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
29921      * @returns {Array<number>} 2D basic coordinates.
29922      */
29923     ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, perspectiveCamera) {
29924         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
29925             .unproject(perspectiveCamera)
29926             .toArray();
29927         var basic = transform.projectBasic(point3d);
29928         return basic;
29929     };
29930     /**
29931      * Convert viewport coordinates to canvas coordinates.
29932      *
29933      * @param {number} viewportX - Viewport X coordinate.
29934      * @param {number} viewportY - Viewport Y coordinate.
29935      * @param {HTMLElement} container - The viewer container.
29936      * @returns {Array<number>} 2D canvas coordinates.
29937      */
29938     ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
29939         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
29940         var canvasX = canvasWidth * (viewportX + 1) / 2;
29941         var canvasY = -canvasHeight * (viewportY - 1) / 2;
29942         return [canvasX, canvasY];
29943     };
29944     return ViewportCoords;
29945 }());
29946 exports.ViewportCoords = ViewportCoords;
29947 Object.defineProperty(exports, "__esModule", { value: true });
29948 exports.default = ViewportCoords;
29949
29950 },{"three":174}],305:[function(require,module,exports){
29951 "use strict";
29952 /**
29953  * @class Filter
29954  *
29955  * @classdesc Represents a class for creating node filters. Implementation and
29956  * definitions based on https://github.com/mapbox/feature-filter.
29957  */
29958 var FilterCreator = (function () {
29959     function FilterCreator() {
29960     }
29961     /**
29962      * Create a filter from a filter expression.
29963      *
29964      * @description The following filters are supported:
29965      *
29966      * Comparison
29967      * `==`
29968      * `!=`
29969      * `<`
29970      * `<=`
29971      * `>`
29972      * `>=`
29973      *
29974      * Set membership
29975      * `in`
29976      * `!in`
29977      *
29978      * Combining
29979      * `all`
29980      *
29981      * @param {FilterExpression} filter - Comparison, set membership or combinding filter
29982      * expression.
29983      * @returns {FilterFunction} Function taking a node and returning a boolean that
29984      * indicates whether the node passed the test or not.
29985      */
29986     FilterCreator.prototype.createFilter = function (filter) {
29987         return new Function("node", "return " + this._compile(filter) + ";");
29988     };
29989     FilterCreator.prototype._compile = function (filter) {
29990         if (filter == null || filter.length <= 1) {
29991             return "true";
29992         }
29993         var operator = filter[0];
29994         var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
29995             operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
29996                 operator === ">" ||
29997                     operator === ">=" ||
29998                     operator === "<" ||
29999                     operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
30000                     operator === "in" ?
30001                         this._compileInOp(filter[1], filter.slice(2)) :
30002                         operator === "!in" ?
30003                             this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
30004                             operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
30005                                 "true";
30006         return "(" + operation + ")";
30007     };
30008     FilterCreator.prototype._compare = function (a, b) {
30009         return a < b ? -1 : a > b ? 1 : 0;
30010     };
30011     FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
30012         var left = this._compilePropertyReference(property);
30013         var right = JSON.stringify(value);
30014         return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
30015     };
30016     FilterCreator.prototype._compileInOp = function (property, values) {
30017         var compare = this._compare;
30018         var left = JSON.stringify(values.sort(compare));
30019         var right = this._compilePropertyReference(property);
30020         return left + ".indexOf(" + right + ")!==-1";
30021     };
30022     FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
30023         var compile = this._compile.bind(this);
30024         return filters.map(compile).join(operator);
30025     };
30026     FilterCreator.prototype._compileNegation = function (expression) {
30027         return "!(" + expression + ")";
30028     };
30029     FilterCreator.prototype._compilePropertyReference = function (property) {
30030         return "node[" + JSON.stringify(property) + "]";
30031     };
30032     return FilterCreator;
30033 }());
30034 exports.FilterCreator = FilterCreator;
30035 Object.defineProperty(exports, "__esModule", { value: true });
30036 exports.default = FilterCreator;
30037
30038 },{}],306:[function(require,module,exports){
30039 /// <reference path="../../typings/index.d.ts" />
30040 "use strict";
30041 var rbush = require("rbush");
30042 var Subject_1 = require("rxjs/Subject");
30043 require("rxjs/add/observable/from");
30044 require("rxjs/add/operator/catch");
30045 require("rxjs/add/operator/do");
30046 require("rxjs/add/operator/finally");
30047 require("rxjs/add/operator/map");
30048 require("rxjs/add/operator/publish");
30049 var Edge_1 = require("../Edge");
30050 var Error_1 = require("../Error");
30051 var Graph_1 = require("../Graph");
30052 /**
30053  * @class Graph
30054  *
30055  * @classdesc Represents a graph of nodes with edges.
30056  */
30057 var Graph = (function () {
30058     /**
30059      * Create a new graph instance.
30060      *
30061      * @param {APIv3} [apiV3] - API instance for retrieving data.
30062      * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
30063      * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
30064      * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
30065      * @param {FilterCreator} [filterCreator] - Instance for  filter creation.
30066      * @param {IGraphConfiguration} [configuration] - Configuration struct.
30067      */
30068     function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
30069         this._apiV3 = apiV3;
30070         this._cachedNodes = {};
30071         this._cachedNodeTiles = {};
30072         this._cachedSpatialEdges = {};
30073         this._cachedTiles = {};
30074         this._cachingFill$ = {};
30075         this._cachingFull$ = {};
30076         this._cachingSequences$ = {};
30077         this._cachingSpatialArea$ = {};
30078         this._cachingTiles$ = {};
30079         this._changed$ = new Subject_1.Subject();
30080         this._defaultAlt = 2;
30081         this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
30082         this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
30083         this._filter = this._filterCreator.createFilter(undefined);
30084         this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
30085         this._configuration = configuration != null ?
30086             configuration :
30087             {
30088                 maxSequences: 50,
30089                 maxUnusedNodes: 100,
30090                 maxUnusedTiles: 20,
30091             };
30092         this._nodes = {};
30093         this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
30094         this._nodeIndexTiles = {};
30095         this._nodeToTile = {};
30096         this._preStored = {};
30097         this._requiredNodeTiles = {};
30098         this._requiredSpatialArea = {};
30099         this._sequences = {};
30100         this._tilePrecision = 7;
30101         this._tileThreshold = 20;
30102     }
30103     Object.defineProperty(Graph.prototype, "changed$", {
30104         /**
30105          * Get changed$.
30106          *
30107          * @returns {Observable<Graph>} Observable emitting
30108          * the graph every time it has changed.
30109          */
30110         get: function () {
30111             return this._changed$;
30112         },
30113         enumerable: true,
30114         configurable: true
30115     });
30116     /**
30117      * Retrieve and cache node fill properties.
30118      *
30119      * @param {string} key - Key of node to fill.
30120      * @returns {Observable<Graph>} Observable emitting the graph
30121      * when the node has been updated.
30122      * @throws {GraphMapillaryError} When the operation is not valid on the
30123      * current graph.
30124      */
30125     Graph.prototype.cacheFill$ = function (key) {
30126         var _this = this;
30127         if (key in this._cachingFull$) {
30128             throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
30129         }
30130         if (!this.hasNode(key)) {
30131             throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
30132         }
30133         if (key in this._cachingFill$) {
30134             return this._cachingFill$[key];
30135         }
30136         var node = this.getNode(key);
30137         if (node.full) {
30138             throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
30139         }
30140         this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
30141             .do(function (imageByKeyFill) {
30142             if (!node.full) {
30143                 _this._makeFull(node, imageByKeyFill[key]);
30144             }
30145             delete _this._cachingFill$[key];
30146         })
30147             .map(function (imageByKeyFill) {
30148             return _this;
30149         })
30150             .finally(function () {
30151             if (key in _this._cachingFill$) {
30152                 delete _this._cachingFill$[key];
30153             }
30154             _this._changed$.next(_this);
30155         })
30156             .publish()
30157             .refCount();
30158         return this._cachingFill$[key];
30159     };
30160     /**
30161      * Retrieve and cache full node properties.
30162      *
30163      * @param {string} key - Key of node to fill.
30164      * @returns {Observable<Graph>} Observable emitting the graph
30165      * when the node has been updated.
30166      * @throws {GraphMapillaryError} When the operation is not valid on the
30167      * current graph.
30168      */
30169     Graph.prototype.cacheFull$ = function (key) {
30170         var _this = this;
30171         if (key in this._cachingFull$) {
30172             return this._cachingFull$[key];
30173         }
30174         if (this.hasNode(key)) {
30175             throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
30176         }
30177         this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
30178             .do(function (imageByKeyFull) {
30179             var fn = imageByKeyFull[key];
30180             if (_this.hasNode(key)) {
30181                 var node = _this.getNode(key);
30182                 if (!node.full) {
30183                     _this._makeFull(node, fn);
30184                 }
30185             }
30186             else {
30187                 if (fn.sequence == null || fn.sequence.key == null) {
30188                     throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
30189                 }
30190                 var node = new Graph_1.Node(fn);
30191                 _this._makeFull(node, fn);
30192                 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
30193                 _this._preStore(h, node);
30194                 _this._setNode(node);
30195                 delete _this._cachingFull$[key];
30196             }
30197         })
30198             .map(function (imageByKeyFull) {
30199             return _this;
30200         })
30201             .finally(function () {
30202             if (key in _this._cachingFull$) {
30203                 delete _this._cachingFull$[key];
30204             }
30205             _this._changed$.next(_this);
30206         })
30207             .publish()
30208             .refCount();
30209         return this._cachingFull$[key];
30210     };
30211     /**
30212      * Retrieve and cache a node sequence.
30213      *
30214      * @param {string} key - Key of node for which to retrieve sequence.
30215      * @returns {Observable<Graph>} Observable emitting the graph
30216      * when the sequence has been retrieved.
30217      * @throws {GraphMapillaryError} When the operation is not valid on the
30218      * current graph.
30219      */
30220     Graph.prototype.cacheNodeSequence$ = function (key) {
30221         if (!this.hasNode(key)) {
30222             throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
30223         }
30224         var node = this.getNode(key);
30225         if (node.sequenceKey in this._sequences) {
30226             throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
30227         }
30228         return this._cacheSequence$(node.sequenceKey);
30229     };
30230     /**
30231      * Retrieve and cache a sequence.
30232      *
30233      * @param {string} sequenceKey - Key of sequence to cache.
30234      * @returns {Observable<Graph>} Observable emitting the graph
30235      * when the sequence has been retrieved.
30236      * @throws {GraphMapillaryError} When the operation is not valid on the
30237      * current graph.
30238      */
30239     Graph.prototype.cacheSequence$ = function (sequenceKey) {
30240         if (sequenceKey in this._sequences) {
30241             throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
30242         }
30243         return this._cacheSequence$(sequenceKey);
30244     };
30245     /**
30246      * Cache sequence edges for a node.
30247      *
30248      * @param {string} key - Key of node.
30249      * @throws {GraphMapillaryError} When the operation is not valid on the
30250      * current graph.
30251      */
30252     Graph.prototype.cacheSequenceEdges = function (key) {
30253         var node = this.getNode(key);
30254         if (!(node.sequenceKey in this._sequences)) {
30255             throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
30256         }
30257         var sequence = this._sequences[node.sequenceKey].sequence;
30258         var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
30259         node.cacheSequenceEdges(edges);
30260     };
30261     /**
30262      * Retrieve and cache full nodes for a node spatial area.
30263      *
30264      * @param {string} key - Key of node for which to retrieve sequence.
30265      * @returns {Observable<Graph>} Observable emitting the graph
30266      * when the nodes in the spatial area has been made full.
30267      * @throws {GraphMapillaryError} When the operation is not valid on the
30268      * current graph.
30269      */
30270     Graph.prototype.cacheSpatialArea$ = function (key) {
30271         var _this = this;
30272         if (!this.hasNode(key)) {
30273             throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
30274         }
30275         if (key in this._cachedSpatialEdges) {
30276             throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
30277         }
30278         if (!(key in this._requiredSpatialArea)) {
30279             throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
30280         }
30281         var spatialArea = this._requiredSpatialArea[key];
30282         if (Object.keys(spatialArea.cacheNodes).length === 0) {
30283             throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
30284         }
30285         if (key in this._cachingSpatialArea$) {
30286             return this._cachingSpatialArea$[key];
30287         }
30288         var batches = [];
30289         while (spatialArea.cacheKeys.length > 0) {
30290             batches.push(spatialArea.cacheKeys.splice(0, 200));
30291         }
30292         var batchesToCache = batches.length;
30293         var spatialNodes$ = [];
30294         var _loop_1 = function (batch) {
30295             var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
30296                 .do(function (imageByKeyFill) {
30297                 for (var fillKey in imageByKeyFill) {
30298                     if (!imageByKeyFill.hasOwnProperty(fillKey)) {
30299                         continue;
30300                     }
30301                     var spatialNode = spatialArea.cacheNodes[fillKey];
30302                     if (spatialNode.full) {
30303                         delete spatialArea.cacheNodes[fillKey];
30304                         continue;
30305                     }
30306                     var fillNode = imageByKeyFill[fillKey];
30307                     _this._makeFull(spatialNode, fillNode);
30308                     delete spatialArea.cacheNodes[fillKey];
30309                 }
30310                 if (--batchesToCache === 0) {
30311                     delete _this._cachingSpatialArea$[key];
30312                 }
30313             })
30314                 .map(function (imageByKeyFill) {
30315                 return _this;
30316             })
30317                 .catch(function (error) {
30318                 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
30319                     var batchKey = batch_1[_i];
30320                     if (batchKey in spatialArea.all) {
30321                         delete spatialArea.all[batchKey];
30322                     }
30323                     if (batchKey in spatialArea.cacheNodes) {
30324                         delete spatialArea.cacheNodes[batchKey];
30325                     }
30326                 }
30327                 if (--batchesToCache === 0) {
30328                     delete _this._cachingSpatialArea$[key];
30329                 }
30330                 throw error;
30331             })
30332                 .finally(function () {
30333                 if (Object.keys(spatialArea.cacheNodes).length === 0) {
30334                     _this._changed$.next(_this);
30335                 }
30336             })
30337                 .publish()
30338                 .refCount();
30339             spatialNodes$.push(spatialNodeBatch$);
30340         };
30341         var this_1 = this;
30342         for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
30343             var batch = batches_1[_i];
30344             _loop_1(batch);
30345         }
30346         this._cachingSpatialArea$[key] = spatialNodes$;
30347         return spatialNodes$;
30348     };
30349     /**
30350      * Cache spatial edges for a node.
30351      *
30352      * @param {string} key - Key of node.
30353      * @throws {GraphMapillaryError} When the operation is not valid on the
30354      * current graph.
30355      */
30356     Graph.prototype.cacheSpatialEdges = function (key) {
30357         if (key in this._cachedSpatialEdges) {
30358             throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
30359         }
30360         var node = this.getNode(key);
30361         var sequence = this._sequences[node.sequenceKey].sequence;
30362         var fallbackKeys = [];
30363         var prevKey = sequence.findPrevKey(node.key);
30364         if (prevKey != null) {
30365             fallbackKeys.push(prevKey);
30366         }
30367         var nextKey = sequence.findNextKey(node.key);
30368         if (nextKey != null) {
30369             fallbackKeys.push(nextKey);
30370         }
30371         var allSpatialNodes = this._requiredSpatialArea[key].all;
30372         var potentialNodes = [];
30373         var filter = this._filter;
30374         for (var spatialNodeKey in allSpatialNodes) {
30375             if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
30376                 continue;
30377             }
30378             var spatialNode = allSpatialNodes[spatialNodeKey];
30379             if (filter(spatialNode)) {
30380                 potentialNodes.push(spatialNode);
30381             }
30382         }
30383         var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
30384         var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
30385         edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
30386         edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
30387         edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
30388         edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
30389         node.cacheSpatialEdges(edges);
30390         this._cachedSpatialEdges[key] = node;
30391         delete this._requiredSpatialArea[key];
30392         delete this._cachedNodeTiles[key];
30393     };
30394     /**
30395      * Retrieve and cache geohash tiles for a node.
30396      *
30397      * @param {string} key - Key of node for which to retrieve tiles.
30398      * @returns {Observable<Graph>} Observable emitting the graph
30399      * when the tiles required for the node has been cached.
30400      * @throws {GraphMapillaryError} When the operation is not valid on the
30401      * current graph.
30402      */
30403     Graph.prototype.cacheTiles$ = function (key) {
30404         var _this = this;
30405         if (key in this._cachedNodeTiles) {
30406             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
30407         }
30408         if (key in this._cachedSpatialEdges) {
30409             throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
30410         }
30411         if (!(key in this._requiredNodeTiles)) {
30412             throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
30413         }
30414         var nodeTiles = this._requiredNodeTiles[key];
30415         if (nodeTiles.cache.length === 0 &&
30416             nodeTiles.caching.length === 0) {
30417             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
30418         }
30419         if (!this.hasNode(key)) {
30420             throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
30421         }
30422         var hs = nodeTiles.cache.slice();
30423         nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
30424         nodeTiles.cache = [];
30425         var cacheTiles$ = [];
30426         var _loop_2 = function (h) {
30427             var cacheTile$ = null;
30428             if (h in this_2._cachingTiles$) {
30429                 cacheTile$ = this_2._cachingTiles$[h];
30430             }
30431             else {
30432                 cacheTile$ = this_2._apiV3.imagesByH$([h])
30433                     .do(function (imagesByH) {
30434                     var coreNodes = imagesByH[h];
30435                     if (h in _this._cachedTiles) {
30436                         return;
30437                     }
30438                     _this._nodeIndexTiles[h] = [];
30439                     _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
30440                     var hCache = _this._cachedTiles[h].nodes;
30441                     var preStored = _this._removeFromPreStore(h);
30442                     for (var index in coreNodes) {
30443                         if (!coreNodes.hasOwnProperty(index)) {
30444                             continue;
30445                         }
30446                         var coreNode = coreNodes[index];
30447                         if (coreNode == null) {
30448                             break;
30449                         }
30450                         if (coreNode.sequence == null ||
30451                             coreNode.sequence.key == null) {
30452                             console.warn("Sequence missing, discarding (" + coreNode.key + ")");
30453                             continue;
30454                         }
30455                         if (preStored != null && coreNode.key in preStored) {
30456                             var node_1 = preStored[coreNode.key];
30457                             delete preStored[coreNode.key];
30458                             hCache.push(node_1);
30459                             var nodeIndexItem_1 = {
30460                                 lat: node_1.latLon.lat,
30461                                 lon: node_1.latLon.lon,
30462                                 node: node_1,
30463                             };
30464                             _this._nodeIndex.insert(nodeIndexItem_1);
30465                             _this._nodeIndexTiles[h].push(nodeIndexItem_1);
30466                             _this._nodeToTile[node_1.key] = h;
30467                             continue;
30468                         }
30469                         var node = new Graph_1.Node(coreNode);
30470                         hCache.push(node);
30471                         var nodeIndexItem = {
30472                             lat: node.latLon.lat,
30473                             lon: node.latLon.lon,
30474                             node: node,
30475                         };
30476                         _this._nodeIndex.insert(nodeIndexItem);
30477                         _this._nodeIndexTiles[h].push(nodeIndexItem);
30478                         _this._nodeToTile[node.key] = h;
30479                         _this._setNode(node);
30480                     }
30481                     delete _this._cachingTiles$[h];
30482                 })
30483                     .map(function (imagesByH) {
30484                     return _this;
30485                 })
30486                     .catch(function (error) {
30487                     delete _this._cachingTiles$[h];
30488                     throw error;
30489                 })
30490                     .publish()
30491                     .refCount();
30492                 this_2._cachingTiles$[h] = cacheTile$;
30493             }
30494             cacheTiles$.push(cacheTile$
30495                 .do(function (graph) {
30496                 var index = nodeTiles.caching.indexOf(h);
30497                 if (index > -1) {
30498                     nodeTiles.caching.splice(index, 1);
30499                 }
30500                 if (nodeTiles.caching.length === 0 &&
30501                     nodeTiles.cache.length === 0) {
30502                     delete _this._requiredNodeTiles[key];
30503                     _this._cachedNodeTiles[key] = true;
30504                 }
30505             })
30506                 .catch(function (error) {
30507                 var index = nodeTiles.caching.indexOf(h);
30508                 if (index > -1) {
30509                     nodeTiles.caching.splice(index, 1);
30510                 }
30511                 if (nodeTiles.caching.length === 0 &&
30512                     nodeTiles.cache.length === 0) {
30513                     delete _this._requiredNodeTiles[key];
30514                     _this._cachedNodeTiles[key] = true;
30515                 }
30516                 throw error;
30517             })
30518                 .finally(function () {
30519                 _this._changed$.next(_this);
30520             })
30521                 .publish()
30522                 .refCount());
30523         };
30524         var this_2 = this;
30525         for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
30526             var h = _a[_i];
30527             _loop_2(h);
30528         }
30529         return cacheTiles$;
30530     };
30531     /**
30532      * Initialize the cache for a node.
30533      *
30534      * @param {string} key - Key of node.
30535      * @throws {GraphMapillaryError} When the operation is not valid on the
30536      * current graph.
30537      */
30538     Graph.prototype.initializeCache = function (key) {
30539         if (key in this._cachedNodes) {
30540             throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
30541         }
30542         var node = this.getNode(key);
30543         node.initializeCache(new Graph_1.NodeCache());
30544         var accessed = new Date().getTime();
30545         this._cachedNodes[key] = { accessed: accessed, node: node };
30546         this._updateCachedTileAccess(key, accessed);
30547     };
30548     /**
30549      * Get a value indicating if the graph is fill caching a node.
30550      *
30551      * @param {string} key - Key of node.
30552      * @returns {boolean} Value indicating if the node is being fill cached.
30553      */
30554     Graph.prototype.isCachingFill = function (key) {
30555         return key in this._cachingFill$;
30556     };
30557     /**
30558      * Get a value indicating if the graph is fully caching a node.
30559      *
30560      * @param {string} key - Key of node.
30561      * @returns {boolean} Value indicating if the node is being fully cached.
30562      */
30563     Graph.prototype.isCachingFull = function (key) {
30564         return key in this._cachingFull$;
30565     };
30566     /**
30567      * Get a value indicating if the graph is caching a sequence of a node.
30568      *
30569      * @param {string} key - Key of node.
30570      * @returns {boolean} Value indicating if the sequence of a node is
30571      * being cached.
30572      */
30573     Graph.prototype.isCachingNodeSequence = function (key) {
30574         var node = this.getNode(key);
30575         return node.sequenceKey in this._cachingSequences$;
30576     };
30577     /**
30578      * Get a value indicating if the graph is caching a sequence.
30579      *
30580      * @param {string} sequenceKey - Key of sequence.
30581      * @returns {boolean} Value indicating if the sequence is
30582      * being cached.
30583      */
30584     Graph.prototype.isCachingSequence = function (sequenceKey) {
30585         return sequenceKey in this._cachingSequences$;
30586     };
30587     /**
30588      * Get a value indicating if the graph is caching the tiles
30589      * required for calculating spatial edges of a node.
30590      *
30591      * @param {string} key - Key of node.
30592      * @returns {boolean} Value indicating if the tiles of
30593      * a node are being cached.
30594      */
30595     Graph.prototype.isCachingTiles = function (key) {
30596         return key in this._requiredNodeTiles &&
30597             this._requiredNodeTiles[key].cache.length === 0 &&
30598             this._requiredNodeTiles[key].caching.length > 0;
30599     };
30600     /**
30601      * Get a value indicating if the cache has been initialized
30602      * for a node.
30603      *
30604      * @param {string} key - Key of node.
30605      * @returns {boolean} Value indicating if the cache has been
30606      * initialized for a node.
30607      */
30608     Graph.prototype.hasInitializedCache = function (key) {
30609         return key in this._cachedNodes;
30610     };
30611     /**
30612      * Get a value indicating if a node exist in the graph.
30613      *
30614      * @param {string} key - Key of node.
30615      * @returns {boolean} Value indicating if a node exist in the graph.
30616      */
30617     Graph.prototype.hasNode = function (key) {
30618         var accessed = new Date().getTime();
30619         this._updateCachedNodeAccess(key, accessed);
30620         this._updateCachedTileAccess(key, accessed);
30621         return key in this._nodes;
30622     };
30623     /**
30624      * Get a value indicating if a node sequence exist in the graph.
30625      *
30626      * @param {string} key - Key of node.
30627      * @returns {boolean} Value indicating if a node sequence exist
30628      * in the graph.
30629      */
30630     Graph.prototype.hasNodeSequence = function (key) {
30631         var node = this.getNode(key);
30632         var sequenceKey = node.sequenceKey;
30633         var hasNodeSequence = sequenceKey in this._sequences;
30634         if (hasNodeSequence) {
30635             this._sequences[sequenceKey].accessed = new Date().getTime();
30636         }
30637         return hasNodeSequence;
30638     };
30639     /**
30640      * Get a value indicating if a sequence exist in the graph.
30641      *
30642      * @param {string} sequenceKey - Key of sequence.
30643      * @returns {boolean} Value indicating if a sequence exist
30644      * in the graph.
30645      */
30646     Graph.prototype.hasSequence = function (sequenceKey) {
30647         var hasSequence = sequenceKey in this._sequences;
30648         if (hasSequence) {
30649             this._sequences[sequenceKey].accessed = new Date().getTime();
30650         }
30651         return hasSequence;
30652     };
30653     /**
30654      * Get a value indicating if the graph has fully cached
30655      * all nodes in the spatial area of a node.
30656      *
30657      * @param {string} key - Key of node.
30658      * @returns {boolean} Value indicating if the spatial area
30659      * of a node has been cached.
30660      */
30661     Graph.prototype.hasSpatialArea = function (key) {
30662         if (!this.hasNode(key)) {
30663             throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
30664         }
30665         if (key in this._cachedSpatialEdges) {
30666             return true;
30667         }
30668         if (key in this._requiredSpatialArea) {
30669             return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
30670         }
30671         var node = this.getNode(key);
30672         var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
30673         var spatialItems = this._nodeIndex.search({
30674             maxX: bbox[1].lat,
30675             maxY: bbox[1].lon,
30676             minX: bbox[0].lat,
30677             minY: bbox[0].lon,
30678         });
30679         var spatialNodes = {
30680             all: {},
30681             cacheKeys: [],
30682             cacheNodes: {},
30683         };
30684         for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
30685             var spatialItem = spatialItems_1[_i];
30686             spatialNodes.all[spatialItem.node.key] = spatialItem.node;
30687             if (!spatialItem.node.full) {
30688                 spatialNodes.cacheKeys.push(spatialItem.node.key);
30689                 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
30690             }
30691         }
30692         this._requiredSpatialArea[key] = spatialNodes;
30693         return spatialNodes.cacheKeys.length === 0;
30694     };
30695     /**
30696      * Get a value indicating if the graph has a tiles required
30697      * for a node.
30698      *
30699      * @param {string} key - Key of node.
30700      * @returns {boolean} Value indicating if the the tiles required
30701      * by a node has been cached.
30702      */
30703     Graph.prototype.hasTiles = function (key) {
30704         var _this = this;
30705         if (key in this._cachedNodeTiles) {
30706             return true;
30707         }
30708         if (key in this._cachedSpatialEdges) {
30709             return true;
30710         }
30711         if (!this.hasNode(key)) {
30712             throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
30713         }
30714         var nodeTiles = { cache: [], caching: [] };
30715         if (!(key in this._requiredNodeTiles)) {
30716             var node = this.getNode(key);
30717             nodeTiles.cache = this._graphCalculator
30718                 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
30719                 .filter(function (h) {
30720                 return !(h in _this._cachedTiles);
30721             });
30722             if (nodeTiles.cache.length > 0) {
30723                 this._requiredNodeTiles[key] = nodeTiles;
30724             }
30725         }
30726         else {
30727             nodeTiles = this._requiredNodeTiles[key];
30728         }
30729         return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
30730     };
30731     /**
30732      * Get a node.
30733      *
30734      * @param {string} key - Key of node.
30735      * @returns {Node} Retrieved node.
30736      */
30737     Graph.prototype.getNode = function (key) {
30738         var accessed = new Date().getTime();
30739         this._updateCachedNodeAccess(key, accessed);
30740         this._updateCachedTileAccess(key, accessed);
30741         return this._nodes[key];
30742     };
30743     /**
30744      * Get a sequence.
30745      *
30746      * @param {string} sequenceKey - Key of sequence.
30747      * @returns {Node} Retrieved sequence.
30748      */
30749     Graph.prototype.getSequence = function (sequenceKey) {
30750         var sequenceAccess = this._sequences[sequenceKey];
30751         sequenceAccess.accessed = new Date().getTime();
30752         return sequenceAccess.sequence;
30753     };
30754     /**
30755      * Reset all spatial edges of the graph nodes.
30756      */
30757     Graph.prototype.resetSpatialEdges = function () {
30758         var cachedKeys = Object.keys(this._cachedSpatialEdges);
30759         for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
30760             var cachedKey = cachedKeys_1[_i];
30761             var node = this._cachedSpatialEdges[cachedKey];
30762             node.resetSpatialEdges();
30763             delete this._cachedSpatialEdges[cachedKey];
30764         }
30765     };
30766     /**
30767      * Reset the complete graph but keep the nodes corresponding
30768      * to the supplied keys. All other nodes will be disposed.
30769      *
30770      * @param {Array<string>} keepKeys - Keys for nodes to keep
30771      * in graph after reset.
30772      */
30773     Graph.prototype.reset = function (keepKeys) {
30774         var nodes = [];
30775         for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
30776             var key = keepKeys_1[_i];
30777             if (!this.hasNode(key)) {
30778                 throw new Error("Node does not exist " + key);
30779             }
30780             var node = this.getNode(key);
30781             node.resetSequenceEdges();
30782             node.resetSpatialEdges();
30783             nodes.push(node);
30784         }
30785         for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
30786             var cachedKey = _b[_a];
30787             if (keepKeys.indexOf(cachedKey) !== -1) {
30788                 continue;
30789             }
30790             this._cachedNodes[cachedKey].node.dispose();
30791             delete this._cachedNodes[cachedKey];
30792         }
30793         this._cachedNodeTiles = {};
30794         this._cachedSpatialEdges = {};
30795         this._cachedTiles = {};
30796         this._cachingFill$ = {};
30797         this._cachingFull$ = {};
30798         this._cachingSequences$ = {};
30799         this._cachingSpatialArea$ = {};
30800         this._cachingTiles$ = {};
30801         this._nodes = {};
30802         this._nodeToTile = {};
30803         this._preStored = {};
30804         for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
30805             var node = nodes_1[_c];
30806             this._nodes[node.key] = node;
30807             var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
30808             this._preStore(h, node);
30809         }
30810         this._requiredNodeTiles = {};
30811         this._requiredSpatialArea = {};
30812         this._sequences = {};
30813         this._nodeIndexTiles = {};
30814         this._nodeIndex.clear();
30815     };
30816     /**
30817      * Set the spatial node filter.
30818      *
30819      * @param {FilterExpression} filter - Filter expression to be applied
30820      * when calculating spatial edges.
30821      */
30822     Graph.prototype.setFilter = function (filter) {
30823         this._filter = this._filterCreator.createFilter(filter);
30824     };
30825     /**
30826      * Uncache the graph according to the graph configuration.
30827      *
30828      * @description Uncaches unused tiles, unused nodes and
30829      * sequences according to the numbers specified in the
30830      * graph configuration. Sequences does not have a direct
30831      * reference to either tiles or nodes and may be uncached
30832      * even if they are related to the nodes that should be kept.
30833      *
30834      * @param {Array<string>} keepKeys - Keys of nodes to keep in
30835      * graph unrelated to last access. Tiles related to those keys
30836      * will also be kept in graph.
30837      */
30838     Graph.prototype.uncache = function (keepKeys) {
30839         var keysInUse = {};
30840         this._addNewKeys(keysInUse, this._cachingFull$);
30841         this._addNewKeys(keysInUse, this._cachingFill$);
30842         this._addNewKeys(keysInUse, this._cachingTiles$);
30843         this._addNewKeys(keysInUse, this._cachingSpatialArea$);
30844         this._addNewKeys(keysInUse, this._requiredNodeTiles);
30845         this._addNewKeys(keysInUse, this._requiredSpatialArea);
30846         for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
30847             var key = keepKeys_2[_i];
30848             if (key in keysInUse) {
30849                 continue;
30850             }
30851             keysInUse[key] = true;
30852         }
30853         var keepHs = {};
30854         for (var key in keysInUse) {
30855             if (!keysInUse.hasOwnProperty(key)) {
30856                 continue;
30857             }
30858             var node = this._nodes[key];
30859             var nodeHs = this._graphCalculator.encodeHs(node.latLon);
30860             for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
30861                 var nodeH = nodeHs_1[_a];
30862                 if (!(nodeH in keepHs)) {
30863                     keepHs[nodeH] = true;
30864                 }
30865             }
30866         }
30867         var potentialHs = [];
30868         for (var h in this._cachedTiles) {
30869             if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
30870                 continue;
30871             }
30872             potentialHs.push([h, this._cachedTiles[h]]);
30873         }
30874         var uncacheHs = potentialHs
30875             .sort(function (h1, h2) {
30876             return h2[1].accessed - h1[1].accessed;
30877         })
30878             .slice(this._configuration.maxUnusedTiles)
30879             .map(function (h) {
30880             return h[0];
30881         });
30882         for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
30883             var uncacheH = uncacheHs_1[_b];
30884             this._uncacheTile(uncacheH);
30885         }
30886         var potentialNodes = [];
30887         for (var key in this._cachedNodes) {
30888             if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
30889                 continue;
30890             }
30891             potentialNodes.push(this._cachedNodes[key]);
30892         }
30893         var uncacheNodes = potentialNodes
30894             .sort(function (n1, n2) {
30895             return n2.accessed - n1.accessed;
30896         })
30897             .slice(this._configuration.maxUnusedNodes);
30898         for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
30899             var nodeAccess = uncacheNodes_1[_c];
30900             nodeAccess.node.uncache();
30901             var key = nodeAccess.node.key;
30902             delete this._cachedNodes[key];
30903             if (key in this._cachedNodeTiles) {
30904                 delete this._cachedNodeTiles[key];
30905             }
30906             if (key in this._cachedSpatialEdges) {
30907                 delete this._cachedSpatialEdges[key];
30908             }
30909         }
30910         var potentialSequences = [];
30911         for (var sequenceKey in this._sequences) {
30912             if (!this._sequences.hasOwnProperty(sequenceKey) ||
30913                 sequenceKey in this._cachingSequences$) {
30914                 continue;
30915             }
30916             potentialSequences.push(this._sequences[sequenceKey]);
30917         }
30918         var uncacheSequences = potentialSequences
30919             .sort(function (s1, s2) {
30920             return s2.accessed - s1.accessed;
30921         })
30922             .slice(this._configuration.maxSequences);
30923         for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
30924             var sequenceAccess = uncacheSequences_1[_d];
30925             var sequenceKey = sequenceAccess.sequence.key;
30926             delete this._sequences[sequenceKey];
30927             sequenceAccess.sequence.dispose();
30928         }
30929     };
30930     Graph.prototype._addNewKeys = function (keys, dict) {
30931         for (var key in dict) {
30932             if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
30933                 continue;
30934             }
30935             if (!(key in keys)) {
30936                 keys[key] = true;
30937             }
30938         }
30939     };
30940     Graph.prototype._cacheSequence$ = function (sequenceKey) {
30941         var _this = this;
30942         if (sequenceKey in this._cachingSequences$) {
30943             return this._cachingSequences$[sequenceKey];
30944         }
30945         this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
30946             .do(function (sequenceByKey) {
30947             if (!(sequenceKey in _this._sequences)) {
30948                 _this._sequences[sequenceKey] = {
30949                     accessed: new Date().getTime(),
30950                     sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
30951                 };
30952             }
30953             delete _this._cachingSequences$[sequenceKey];
30954         })
30955             .map(function (sequenceByKey) {
30956             return _this;
30957         })
30958             .finally(function () {
30959             if (sequenceKey in _this._cachingSequences$) {
30960                 delete _this._cachingSequences$[sequenceKey];
30961             }
30962             _this._changed$.next(_this);
30963         })
30964             .publish()
30965             .refCount();
30966         return this._cachingSequences$[sequenceKey];
30967     };
30968     Graph.prototype._makeFull = function (node, fillNode) {
30969         if (fillNode.calt == null) {
30970             fillNode.calt = this._defaultAlt;
30971         }
30972         if (fillNode.c_rotation == null) {
30973             fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
30974         }
30975         node.makeFull(fillNode);
30976     };
30977     Graph.prototype._preStore = function (h, node) {
30978         if (!(h in this._preStored)) {
30979             this._preStored[h] = {};
30980         }
30981         this._preStored[h][node.key] = node;
30982     };
30983     Graph.prototype._removeFromPreStore = function (h) {
30984         var preStored = null;
30985         if (h in this._preStored) {
30986             preStored = this._preStored[h];
30987             delete this._preStored[h];
30988         }
30989         return preStored;
30990     };
30991     Graph.prototype._setNode = function (node) {
30992         var key = node.key;
30993         if (this.hasNode(key)) {
30994             throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
30995         }
30996         this._nodes[key] = node;
30997     };
30998     Graph.prototype._uncacheTile = function (h) {
30999         for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
31000             var node = _a[_i];
31001             var key = node.key;
31002             delete this._nodes[key];
31003             delete this._nodeToTile[key];
31004             if (key in this._cachedNodes) {
31005                 delete this._cachedNodes[key];
31006             }
31007             if (key in this._cachedNodeTiles) {
31008                 delete this._cachedNodeTiles[key];
31009             }
31010             if (key in this._cachedSpatialEdges) {
31011                 delete this._cachedSpatialEdges[key];
31012             }
31013             node.dispose();
31014         }
31015         for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
31016             var nodeIndexItem = _c[_b];
31017             this._nodeIndex.remove(nodeIndexItem);
31018         }
31019         delete this._nodeIndexTiles[h];
31020         delete this._cachedTiles[h];
31021     };
31022     Graph.prototype._updateCachedTileAccess = function (key, accessed) {
31023         if (key in this._nodeToTile) {
31024             this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
31025         }
31026     };
31027     Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
31028         if (key in this._cachedNodes) {
31029             this._cachedNodes[key].accessed = accessed;
31030         }
31031     };
31032     return Graph;
31033 }());
31034 exports.Graph = Graph;
31035 Object.defineProperty(exports, "__esModule", { value: true });
31036 exports.default = Graph;
31037
31038 },{"../Edge":225,"../Error":226,"../Graph":228,"rbush":24,"rxjs/Subject":33,"rxjs/add/observable/from":40,"rxjs/add/operator/catch":51,"rxjs/add/operator/do":58,"rxjs/add/operator/finally":61,"rxjs/add/operator/map":64,"rxjs/add/operator/publish":70}],307:[function(require,module,exports){
31039 /// <reference path="../../typings/index.d.ts" />
31040 "use strict";
31041 var geohash = require("latlon-geohash");
31042 var THREE = require("three");
31043 var Geo_1 = require("../Geo");
31044 var GeoHashDirections = (function () {
31045     function GeoHashDirections() {
31046     }
31047     return GeoHashDirections;
31048 }());
31049 GeoHashDirections.n = "n";
31050 GeoHashDirections.nw = "nw";
31051 GeoHashDirections.w = "w";
31052 GeoHashDirections.sw = "sw";
31053 GeoHashDirections.s = "s";
31054 GeoHashDirections.se = "se";
31055 GeoHashDirections.e = "e";
31056 GeoHashDirections.ne = "ne";
31057 /**
31058  * @class GraphCalculator
31059  *
31060  * @classdesc Represents a calculator for graph entities.
31061  */
31062 var GraphCalculator = (function () {
31063     /**
31064      * Create a new graph calculator instance.
31065      *
31066      * @param {GeoCoords} geoCoords - Geo coords instance.
31067      */
31068     function GraphCalculator(geoCoords) {
31069         this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
31070     }
31071     /**
31072      * Encode the geohash tile for geodetic coordinates.
31073      *
31074      * @param {ILatLon} latlon - Latitude and longitude to encode.
31075      * @param {number} precision - Precision of the encoding.
31076      *
31077      * @returns {string} The geohash tile for the lat, lon and precision.
31078      */
31079     GraphCalculator.prototype.encodeH = function (latLon, precision) {
31080         if (precision === void 0) { precision = 7; }
31081         return geohash.encode(latLon.lat, latLon.lon, precision);
31082     };
31083     /**
31084      * Encode the geohash tiles within a threshold from a position
31085      * using Manhattan distance.
31086      *
31087      * @param {ILatLon} latlon - Latitude and longitude to encode.
31088      * @param {number} precision - Precision of the encoding.
31089      * @param {number} threshold - Threshold of the encoding in meters.
31090      *
31091      * @returns {string} The geohash tiles reachable within the threshold.
31092      */
31093     GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
31094         if (precision === void 0) { precision = 7; }
31095         if (threshold === void 0) { threshold = 20; }
31096         var h = geohash.encode(latLon.lat, latLon.lon, precision);
31097         var bounds = geohash.bounds(h);
31098         var ne = bounds.ne;
31099         var sw = bounds.sw;
31100         var neighbours = geohash.neighbours(h);
31101         var bl = [0, 0, 0];
31102         var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
31103         var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
31104         var left = position[0] - bl[0];
31105         var right = tr[0] - position[0];
31106         var bottom = position[1] - bl[1];
31107         var top = tr[1] - position[1];
31108         var l = left < threshold;
31109         var r = right < threshold;
31110         var b = bottom < threshold;
31111         var t = top < threshold;
31112         var hs = [h];
31113         if (t) {
31114             hs.push(neighbours[GeoHashDirections.n]);
31115         }
31116         if (t && l) {
31117             hs.push(neighbours[GeoHashDirections.nw]);
31118         }
31119         if (l) {
31120             hs.push(neighbours[GeoHashDirections.w]);
31121         }
31122         if (l && b) {
31123             hs.push(neighbours[GeoHashDirections.sw]);
31124         }
31125         if (b) {
31126             hs.push(neighbours[GeoHashDirections.s]);
31127         }
31128         if (b && r) {
31129             hs.push(neighbours[GeoHashDirections.se]);
31130         }
31131         if (r) {
31132             hs.push(neighbours[GeoHashDirections.e]);
31133         }
31134         if (r && t) {
31135             hs.push(neighbours[GeoHashDirections.ne]);
31136         }
31137         return hs;
31138     };
31139     /**
31140      * Get the bounding box corners for a circle with radius of a threshold
31141      * with center in a geodetic position.
31142      *
31143      * @param {ILatLon} latlon - Latitude and longitude to encode.
31144      * @param {number} threshold - Threshold distance from the position in meters.
31145      *
31146      * @returns {Array<ILatLon>} The south west and north east corners of the
31147      * bounding box.
31148      */
31149     GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
31150         var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
31151         var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
31152         return [
31153             { lat: bl[0], lon: bl[1] },
31154             { lat: tr[0], lon: tr[1] },
31155         ];
31156     };
31157     /**
31158      * Convert a compass angle to an angle axis rotation vector.
31159      *
31160      * @param {number} compassAngle - The compass angle in degrees.
31161      * @param {number} orientation - The orientation of the original image.
31162      *
31163      * @returns {Array<number>} Angle axis rotation vector.
31164      */
31165     GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
31166         var x = 0;
31167         var y = 0;
31168         var z = 0;
31169         switch (orientation) {
31170             case 1:
31171                 x = Math.PI / 2;
31172                 break;
31173             case 3:
31174                 x = -Math.PI / 2;
31175                 z = Math.PI;
31176                 break;
31177             case 6:
31178                 y = -Math.PI / 2;
31179                 z = -Math.PI / 2;
31180                 break;
31181             case 8:
31182                 y = Math.PI / 2;
31183                 z = Math.PI / 2;
31184                 break;
31185             default:
31186                 break;
31187         }
31188         var rz = new THREE.Matrix4().makeRotationZ(z);
31189         var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
31190         var re = new THREE.Matrix4().makeRotationFromEuler(euler);
31191         var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
31192         return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
31193     };
31194     return GraphCalculator;
31195 }());
31196 exports.GraphCalculator = GraphCalculator;
31197 Object.defineProperty(exports, "__esModule", { value: true });
31198 exports.default = GraphCalculator;
31199
31200 },{"../Geo":227,"latlon-geohash":20,"three":174}],308:[function(require,module,exports){
31201 "use strict";
31202 var Observable_1 = require("rxjs/Observable");
31203 var Subject_1 = require("rxjs/Subject");
31204 require("rxjs/add/operator/catch");
31205 require("rxjs/add/operator/concat");
31206 require("rxjs/add/operator/do");
31207 require("rxjs/add/operator/expand");
31208 require("rxjs/add/operator/finally");
31209 require("rxjs/add/operator/first");
31210 require("rxjs/add/operator/last");
31211 require("rxjs/add/operator/map");
31212 require("rxjs/add/operator/mergeMap");
31213 require("rxjs/add/operator/publishReplay");
31214 /**
31215  * @class GraphService
31216  *
31217  * @classdesc Represents a service for graph operations.
31218  */
31219 var GraphService = (function () {
31220     /**
31221      * Create a new graph service instance.
31222      *
31223      * @param {Graph} graph - Graph instance to be operated on.
31224      */
31225     function GraphService(graph, imageLoadingService) {
31226         this._graph$ = Observable_1.Observable
31227             .of(graph)
31228             .concat(graph.changed$)
31229             .publishReplay(1)
31230             .refCount();
31231         this._graph$.subscribe(function () { });
31232         this._imageLoadingService = imageLoadingService;
31233         this._firstGraphSubjects$ = [];
31234         this._initializeCacheSubscriptions = [];
31235         this._sequenceSubscriptions = [];
31236         this._spatialSubscriptions = [];
31237     }
31238     /**
31239      * Cache a node in the graph and retrieve it.
31240      *
31241      * @description When called, the full properties of
31242      * the node are retrieved and the node cache is initialized.
31243      * After that the node assets are cached and the node
31244      * is emitted to the observable when.
31245      * In parallel to caching the node assets, the sequence and
31246      * spatial edges of the node are cached. For this, the sequence
31247      * of the node and the required tiles and spatial nodes are
31248      * retrieved. The sequence and spatial edges may be set before
31249      * or after the node is returned.
31250      *
31251      * @param {string} key - Key of the node to cache.
31252      * @return {Observable<Node>} Observable emitting a single item,
31253      * the node, when it has been retrieved and its assets are cached.
31254      * @throws {Error} Propagates any IO node caching errors to the caller.
31255      */
31256     GraphService.prototype.cacheNode$ = function (key) {
31257         var _this = this;
31258         var firstGraphSubject$ = new Subject_1.Subject();
31259         this._firstGraphSubjects$.push(firstGraphSubject$);
31260         var firstGraph$ = firstGraphSubject$
31261             .publishReplay(1)
31262             .refCount();
31263         var node$ = firstGraph$
31264             .map(function (graph) {
31265             return graph.getNode(key);
31266         })
31267             .mergeMap(function (node) {
31268             return node.assetsCached ?
31269                 Observable_1.Observable.of(node) :
31270                 node.cacheAssets$();
31271         })
31272             .publishReplay(1)
31273             .refCount();
31274         node$.subscribe(function (node) {
31275             _this._imageLoadingService.loadnode$.next(node);
31276         }, function (error) {
31277             console.error("Failed to cache node (" + key + ")", error);
31278         });
31279         var initializeCacheSubscription = this._graph$
31280             .first()
31281             .mergeMap(function (graph) {
31282             if (graph.isCachingFull(key) || !graph.hasNode(key)) {
31283                 return graph.cacheFull$(key);
31284             }
31285             if (graph.isCachingFill(key) || !graph.getNode(key).full) {
31286                 return graph.cacheFill$(key);
31287             }
31288             return Observable_1.Observable.of(graph);
31289         })
31290             .do(function (graph) {
31291             if (!graph.hasInitializedCache(key)) {
31292                 graph.initializeCache(key);
31293             }
31294         })
31295             .finally(function () {
31296             if (initializeCacheSubscription == null) {
31297                 return;
31298             }
31299             _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
31300             _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
31301         })
31302             .subscribe(function (graph) {
31303             firstGraphSubject$.next(graph);
31304             firstGraphSubject$.complete();
31305         }, function (error) {
31306             firstGraphSubject$.error(error);
31307         });
31308         if (!initializeCacheSubscription.closed) {
31309             this._initializeCacheSubscriptions.push(initializeCacheSubscription);
31310         }
31311         var sequenceSubscription = firstGraph$
31312             .mergeMap(function (graph) {
31313             if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
31314                 return graph.cacheNodeSequence$(key);
31315             }
31316             return Observable_1.Observable.of(graph);
31317         })
31318             .do(function (graph) {
31319             if (!graph.getNode(key).sequenceEdges.cached) {
31320                 graph.cacheSequenceEdges(key);
31321             }
31322         })
31323             .finally(function () {
31324             if (sequenceSubscription == null) {
31325                 return;
31326             }
31327             _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
31328         })
31329             .subscribe(function (graph) { return; }, function (error) {
31330             console.error("Failed to cache sequence edges (" + key + ").", error);
31331         });
31332         if (!sequenceSubscription.closed) {
31333             this._sequenceSubscriptions.push(sequenceSubscription);
31334         }
31335         var spatialSubscription = firstGraph$
31336             .expand(function (graph) {
31337             if (graph.hasTiles(key)) {
31338                 return Observable_1.Observable.empty();
31339             }
31340             return Observable_1.Observable
31341                 .from(graph.cacheTiles$(key))
31342                 .mergeMap(function (graph$) {
31343                 return graph$
31344                     .mergeMap(function (g) {
31345                     if (g.isCachingTiles(key)) {
31346                         return Observable_1.Observable.empty();
31347                     }
31348                     return Observable_1.Observable.of(g);
31349                 })
31350                     .catch(function (error, caught$) {
31351                     console.error("Failed to cache tile data (" + key + ").", error);
31352                     return Observable_1.Observable.empty();
31353                 });
31354             });
31355         })
31356             .last()
31357             .mergeMap(function (graph) {
31358             if (graph.hasSpatialArea(key)) {
31359                 return Observable_1.Observable.of(graph);
31360             }
31361             return Observable_1.Observable
31362                 .from(graph.cacheSpatialArea$(key))
31363                 .mergeMap(function (graph$) {
31364                 return graph$
31365                     .catch(function (error, caught$) {
31366                     console.error("Failed to cache spatial nodes (" + key + ").", error);
31367                     return Observable_1.Observable.empty();
31368                 });
31369             });
31370         })
31371             .last()
31372             .mergeMap(function (graph) {
31373             return graph.hasNodeSequence(key) ?
31374                 Observable_1.Observable.of(graph) :
31375                 graph.cacheNodeSequence$(key);
31376         })
31377             .do(function (graph) {
31378             if (!graph.getNode(key).spatialEdges.cached) {
31379                 graph.cacheSpatialEdges(key);
31380             }
31381         })
31382             .finally(function () {
31383             if (spatialSubscription == null) {
31384                 return;
31385             }
31386             _this._removeFromArray(spatialSubscription, _this._spatialSubscriptions);
31387         })
31388             .subscribe(function (graph) { return; }, function (error) {
31389             console.error("Failed to cache spatial edges (" + key + ").", error);
31390         });
31391         if (!spatialSubscription.closed) {
31392             this._spatialSubscriptions.push(spatialSubscription);
31393         }
31394         return node$
31395             .first(function (node) {
31396             return node.assetsCached;
31397         });
31398     };
31399     /**
31400      * Cache a sequence in the graph and retrieve it.
31401      *
31402      * @param {string} sequenceKey - Sequence key.
31403      * @returns {Observable<Sequence>} Observable emitting a single item,
31404      * the sequence, when it has been retrieved and its assets are cached.
31405      * @throws {Error} Propagates any IO node caching errors to the caller.
31406      */
31407     GraphService.prototype.cacheSequence$ = function (sequenceKey) {
31408         return this._graph$
31409             .first()
31410             .mergeMap(function (graph) {
31411             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
31412                 return graph.cacheSequence$(sequenceKey);
31413             }
31414             return Observable_1.Observable.of(graph);
31415         })
31416             .map(function (graph) {
31417             return graph.getSequence(sequenceKey);
31418         });
31419     };
31420     /**
31421      * Set a spatial edge filter on the graph.
31422      *
31423      * @description Resets the spatial edges of all cached nodes.
31424      *
31425      * @param {FilterExpression} filter - Filter expression to be applied.
31426      * @return {Observable<Graph>} Observable emitting a single item,
31427      * the graph, when the spatial edges have been reset.
31428      */
31429     GraphService.prototype.setFilter$ = function (filter) {
31430         this._resetSubscriptions(this._spatialSubscriptions);
31431         return this._graph$
31432             .first()
31433             .do(function (graph) {
31434             graph.resetSpatialEdges();
31435             graph.setFilter(filter);
31436         });
31437     };
31438     /**
31439      * Reset the graph.
31440      *
31441      * @description Resets the graph but keeps the nodes of the
31442      * supplied keys.
31443      *
31444      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
31445      * @return {Observable<Node>} Observable emitting a single item,
31446      * the graph, when it has been reset.
31447      */
31448     GraphService.prototype.reset$ = function (keepKeys) {
31449         this._abortSubjects(this._firstGraphSubjects$);
31450         this._resetSubscriptions(this._initializeCacheSubscriptions);
31451         this._resetSubscriptions(this._sequenceSubscriptions);
31452         this._resetSubscriptions(this._spatialSubscriptions);
31453         return this._graph$
31454             .first()
31455             .do(function (graph) {
31456             graph.reset(keepKeys);
31457         });
31458     };
31459     /**
31460      * Uncache the graph.
31461      *
31462      * @description Uncaches the graph by removing tiles, nodes and
31463      * sequences. Keeps the nodes of the supplied keys and the tiles
31464      * related to those nodes.
31465      *
31466      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
31467      * @return {Observable<Graph>} Observable emitting a single item,
31468      * the graph, when the graph has been uncached.
31469      */
31470     GraphService.prototype.uncache$ = function (keepKeys) {
31471         return this._graph$
31472             .first()
31473             .do(function (graph) {
31474             graph.uncache(keepKeys);
31475         });
31476     };
31477     GraphService.prototype._abortSubjects = function (subjects) {
31478         for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
31479             var subject = _a[_i];
31480             this._removeFromArray(subject, subjects);
31481             subject.error(new Error("Cache node request was aborted."));
31482         }
31483     };
31484     GraphService.prototype._removeFromArray = function (object, objects) {
31485         var index = objects.indexOf(object);
31486         if (index !== -1) {
31487             objects.splice(index, 1);
31488         }
31489     };
31490     GraphService.prototype._resetSubscriptions = function (subscriptions) {
31491         for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
31492             var subscription = _a[_i];
31493             this._removeFromArray(subscription, subscriptions);
31494             if (!subscription.closed) {
31495                 subscription.unsubscribe();
31496             }
31497         }
31498     };
31499     return GraphService;
31500 }());
31501 exports.GraphService = GraphService;
31502 Object.defineProperty(exports, "__esModule", { value: true });
31503 exports.default = GraphService;
31504
31505 },{"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/catch":51,"rxjs/add/operator/concat":53,"rxjs/add/operator/do":58,"rxjs/add/operator/expand":59,"rxjs/add/operator/finally":61,"rxjs/add/operator/first":62,"rxjs/add/operator/last":63,"rxjs/add/operator/map":64,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/publishReplay":71}],309:[function(require,module,exports){
31506 /// <reference path="../../typings/index.d.ts" />
31507 "use strict";
31508 var Subject_1 = require("rxjs/Subject");
31509 var ImageLoadingService = (function () {
31510     function ImageLoadingService() {
31511         this._loadnode$ = new Subject_1.Subject();
31512         this._loadstatus$ = this._loadnode$
31513             .scan(function (nodes, node) {
31514             nodes[node.key] = node.loadStatus;
31515             return nodes;
31516         }, {})
31517             .publishReplay(1)
31518             .refCount();
31519         this._loadstatus$.subscribe(function () { });
31520     }
31521     Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
31522         get: function () {
31523             return this._loadnode$;
31524         },
31525         enumerable: true,
31526         configurable: true
31527     });
31528     Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
31529         get: function () {
31530             return this._loadstatus$;
31531         },
31532         enumerable: true,
31533         configurable: true
31534     });
31535     return ImageLoadingService;
31536 }());
31537 exports.ImageLoadingService = ImageLoadingService;
31538
31539 },{"rxjs/Subject":33}],310:[function(require,module,exports){
31540 /// <reference path="../../typings/index.d.ts" />
31541 "use strict";
31542 var Pbf = require("pbf");
31543 var MeshReader = (function () {
31544     function MeshReader() {
31545     }
31546     MeshReader.read = function (buffer) {
31547         var pbf = new Pbf(buffer);
31548         return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
31549     };
31550     MeshReader._readMeshField = function (tag, mesh, pbf) {
31551         if (tag === 1) {
31552             mesh.vertices.push(pbf.readFloat());
31553         }
31554         else if (tag === 2) {
31555             mesh.faces.push(pbf.readVarint());
31556         }
31557     };
31558     return MeshReader;
31559 }());
31560 exports.MeshReader = MeshReader;
31561
31562 },{"pbf":22}],311:[function(require,module,exports){
31563 "use strict";
31564 require("rxjs/add/observable/combineLatest");
31565 require("rxjs/add/operator/map");
31566 /**
31567  * @class Node
31568  *
31569  * @classdesc Represents a node in the navigation graph.
31570  */
31571 var Node = (function () {
31572     /**
31573      * Create a new node instance.
31574      *
31575      * @description Nodes are always created internally by the library.
31576      * Nodes can not be added to the library through any API method.
31577      *
31578      * @param {ICoreNode} coreNode - Raw core node data.
31579      */
31580     function Node(core) {
31581         this._cache = null;
31582         this._core = core;
31583         this._fill = null;
31584     }
31585     Object.defineProperty(Node.prototype, "assetsCached", {
31586         /**
31587          * Get assets cached.
31588          *
31589          * @description The assets that need to be cached for this property
31590          * to report true are the following: fill properties, image and mesh.
31591          * The library ensures that the current node will always have the
31592          * assets cached.
31593          *
31594          * @returns {boolean} Value indicating whether all assets have been
31595          * cached.
31596          */
31597         get: function () {
31598             return this._core != null &&
31599                 this._fill != null &&
31600                 this._cache != null &&
31601                 this._cache.image != null &&
31602                 this._cache.mesh != null;
31603         },
31604         enumerable: true,
31605         configurable: true
31606     });
31607     Object.defineProperty(Node.prototype, "alt", {
31608         /**
31609          * Get alt.
31610          *
31611          * @description If SfM has not been run the computed altitude is
31612          * set to a default value of two meters.
31613          *
31614          * @returns {number} Altitude, in meters.
31615          */
31616         get: function () {
31617             return this._fill.calt;
31618         },
31619         enumerable: true,
31620         configurable: true
31621     });
31622     Object.defineProperty(Node.prototype, "ca", {
31623         /**
31624          * Get ca.
31625          *
31626          * @description If the SfM computed compass angle exists it will
31627          * be returned, otherwise the original EXIF compass angle.
31628          *
31629          * @returns {number} Compass angle, measured in degrees.
31630          */
31631         get: function () {
31632             return this._fill.cca != null ? this._fill.cca : this._fill.ca;
31633         },
31634         enumerable: true,
31635         configurable: true
31636     });
31637     Object.defineProperty(Node.prototype, "capturedAt", {
31638         /**
31639          * Get capturedAt.
31640          *
31641          * @returns {number} Timestamp when the image was captured.
31642          */
31643         get: function () {
31644             return this._fill.captured_at;
31645         },
31646         enumerable: true,
31647         configurable: true
31648     });
31649     Object.defineProperty(Node.prototype, "computedCA", {
31650         /**
31651          * Get computedCA.
31652          *
31653          * @description Will not be set if SfM has not been run.
31654          *
31655          * @returns {number} SfM computed compass angle, measured in degrees.
31656          */
31657         get: function () {
31658             return this._fill.cca;
31659         },
31660         enumerable: true,
31661         configurable: true
31662     });
31663     Object.defineProperty(Node.prototype, "computedLatLon", {
31664         /**
31665          * Get computedLatLon.
31666          *
31667          * @description Will not be set if SfM has not been run.
31668          *
31669          * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
31670          * measured in degrees.
31671          */
31672         get: function () {
31673             return this._core.cl;
31674         },
31675         enumerable: true,
31676         configurable: true
31677     });
31678     Object.defineProperty(Node.prototype, "focal", {
31679         /**
31680          * Get focal.
31681          *
31682          * @description Will not be set if SfM has not been run.
31683          *
31684          * @returns {number} SfM computed focal length.
31685          */
31686         get: function () {
31687             return this._fill.cfocal;
31688         },
31689         enumerable: true,
31690         configurable: true
31691     });
31692     Object.defineProperty(Node.prototype, "full", {
31693         /**
31694          * Get full.
31695          *
31696          * @description The library ensures that the current node will
31697          * always be full.
31698          *
31699          * @returns {boolean} Value indicating whether the node has all
31700          * properties filled.
31701          */
31702         get: function () {
31703             return this._fill != null;
31704         },
31705         enumerable: true,
31706         configurable: true
31707     });
31708     Object.defineProperty(Node.prototype, "fullPano", {
31709         /**
31710          * Get fullPano.
31711          *
31712          * @returns {boolean} Value indicating whether the node is a complete
31713          * 360 panorama.
31714          */
31715         get: function () {
31716             return this._fill.gpano != null &&
31717                 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
31718                 this._fill.gpano.CroppedAreaTopPixels === 0 &&
31719                 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
31720                 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
31721         },
31722         enumerable: true,
31723         configurable: true
31724     });
31725     Object.defineProperty(Node.prototype, "gpano", {
31726         /**
31727          * Get gpano.
31728          *
31729          * @description Will not be set for non panoramic images.
31730          *
31731          * @returns {IGPano} Panorama information for panorama images.
31732          */
31733         get: function () {
31734             return this._fill.gpano;
31735         },
31736         enumerable: true,
31737         configurable: true
31738     });
31739     Object.defineProperty(Node.prototype, "height", {
31740         /**
31741          * Get height.
31742          *
31743          * @returns {number} Height of original image, not adjusted
31744          * for orientation.
31745          */
31746         get: function () {
31747             return this._fill.height;
31748         },
31749         enumerable: true,
31750         configurable: true
31751     });
31752     Object.defineProperty(Node.prototype, "image", {
31753         /**
31754          * Get image.
31755          *
31756          * @description The image will always be set on the current node.
31757          *
31758          * @returns {HTMLImageElement} Cached image element of the node.
31759          */
31760         get: function () {
31761             return this._cache.image;
31762         },
31763         enumerable: true,
31764         configurable: true
31765     });
31766     Object.defineProperty(Node.prototype, "key", {
31767         /**
31768          * Get key.
31769          *
31770          * @returns {string} Unique key of the node.
31771          */
31772         get: function () {
31773             return this._core.key;
31774         },
31775         enumerable: true,
31776         configurable: true
31777     });
31778     Object.defineProperty(Node.prototype, "latLon", {
31779         /**
31780          * Get latLon.
31781          *
31782          * @description If the SfM computed latitude longitude exist
31783          * it will be returned, otherwise the original EXIF latitude
31784          * longitude.
31785          *
31786          * @returns {ILatLon} Latitude longitude in WGS84 datum,
31787          * measured in degrees.
31788          */
31789         get: function () {
31790             return this._core.cl != null ? this._core.cl : this._core.l;
31791         },
31792         enumerable: true,
31793         configurable: true
31794     });
31795     Object.defineProperty(Node.prototype, "loadStatus", {
31796         /**
31797          * Get loadStatus.
31798          *
31799          * @returns {ILoadStatus} Value indicating the load status
31800          * of the mesh and image.
31801          */
31802         get: function () {
31803             return this._cache.loadStatus;
31804         },
31805         enumerable: true,
31806         configurable: true
31807     });
31808     Object.defineProperty(Node.prototype, "merged", {
31809         /**
31810          * Get merged.
31811          *
31812          * @returns {boolean} Value indicating whether SfM has been
31813          * run on the node and the node has been merged into a
31814          * connected component.
31815          */
31816         get: function () {
31817             return this._fill != null &&
31818                 this._fill.merge_version != null &&
31819                 this._fill.merge_version > 0;
31820         },
31821         enumerable: true,
31822         configurable: true
31823     });
31824     Object.defineProperty(Node.prototype, "mergeCC", {
31825         /**
31826          * Get mergeCC.
31827          *
31828          * @description Will not be set if SfM has not yet been run on
31829          * node.
31830          *
31831          * @returns {number} SfM connected component key to which
31832          * image belongs.
31833          */
31834         get: function () {
31835             return this._fill.merge_cc;
31836         },
31837         enumerable: true,
31838         configurable: true
31839     });
31840     Object.defineProperty(Node.prototype, "mergeVersion", {
31841         /**
31842          * Get mergeVersion.
31843          *
31844          * @returns {number} Version for which SfM was run and image was merged.
31845          */
31846         get: function () {
31847             return this._fill.merge_version;
31848         },
31849         enumerable: true,
31850         configurable: true
31851     });
31852     Object.defineProperty(Node.prototype, "mesh", {
31853         /**
31854          * Get mesh.
31855          *
31856          * @description The mesh will always be set on the current node.
31857          *
31858          * @returns {IMesh} SfM triangulated mesh of reconstructed
31859          * atomic 3D points.
31860          */
31861         get: function () {
31862             return this._cache.mesh;
31863         },
31864         enumerable: true,
31865         configurable: true
31866     });
31867     Object.defineProperty(Node.prototype, "orientation", {
31868         /**
31869          * Get orientation.
31870          *
31871          * @returns {number} EXIF orientation of original image.
31872          */
31873         get: function () {
31874             return this._fill.orientation;
31875         },
31876         enumerable: true,
31877         configurable: true
31878     });
31879     Object.defineProperty(Node.prototype, "originalCA", {
31880         /**
31881          * Get originalCA.
31882          *
31883          * @returns {number} Original EXIF compass angle, measured in
31884          * degrees.
31885          */
31886         get: function () {
31887             return this._fill.ca;
31888         },
31889         enumerable: true,
31890         configurable: true
31891     });
31892     Object.defineProperty(Node.prototype, "originalLatLon", {
31893         /**
31894          * Get originalLatLon.
31895          *
31896          * @returns {ILatLon} Original EXIF latitude longitude in
31897          * WGS84 datum, measured in degrees.
31898          */
31899         get: function () {
31900             return this._core.l;
31901         },
31902         enumerable: true,
31903         configurable: true
31904     });
31905     Object.defineProperty(Node.prototype, "pano", {
31906         /**
31907          * Get pano.
31908          *
31909          * @returns {boolean} Value indicating whether the node is a panorama.
31910          * It could be a cropped or full panorama.
31911          */
31912         get: function () {
31913             return this._fill.gpano != null &&
31914                 this._fill.gpano.FullPanoWidthPixels != null;
31915         },
31916         enumerable: true,
31917         configurable: true
31918     });
31919     Object.defineProperty(Node.prototype, "projectKey", {
31920         /**
31921          * Get projectKey.
31922          *
31923          * @returns {string} Unique key of the project to which
31924          * the node belongs.
31925          */
31926         get: function () {
31927             return this._fill.project != null ?
31928                 this._fill.project.key :
31929                 null;
31930         },
31931         enumerable: true,
31932         configurable: true
31933     });
31934     Object.defineProperty(Node.prototype, "rotation", {
31935         /**
31936          * Get rotation.
31937          *
31938          * @description Will not be set if SfM has not been run.
31939          *
31940          * @returns {Array<number>} Rotation vector in angle axis representation.
31941          */
31942         get: function () {
31943             return this._fill.c_rotation;
31944         },
31945         enumerable: true,
31946         configurable: true
31947     });
31948     Object.defineProperty(Node.prototype, "scale", {
31949         /**
31950          * Get scale.
31951          *
31952          * @description Will not be set if SfM has not been run.
31953          *
31954          * @returns {number} Scale of atomic reconstruction.
31955          */
31956         get: function () {
31957             return this._fill.atomic_scale;
31958         },
31959         enumerable: true,
31960         configurable: true
31961     });
31962     Object.defineProperty(Node.prototype, "sequenceKey", {
31963         /**
31964          * Get sequenceKey.
31965          *
31966          * @returns {string} Unique key of the sequence to which
31967          * the node belongs.
31968          */
31969         get: function () {
31970             return this._core.sequence.key;
31971         },
31972         enumerable: true,
31973         configurable: true
31974     });
31975     Object.defineProperty(Node.prototype, "sequenceEdges", {
31976         /**
31977          * Get sequenceEdges.
31978          *
31979          * @returns {IEdgeStatus} Value describing the status of the
31980          * sequence edges.
31981          */
31982         get: function () {
31983             return this._cache.sequenceEdges;
31984         },
31985         enumerable: true,
31986         configurable: true
31987     });
31988     Object.defineProperty(Node.prototype, "sequenceEdges$", {
31989         /**
31990          * Get sequenceEdges$.
31991          *
31992          * @returns {Observable<IEdgeStatus>} Observable emitting
31993          * values describing the status of the sequence edges.
31994          */
31995         get: function () {
31996             return this._cache.sequenceEdges$;
31997         },
31998         enumerable: true,
31999         configurable: true
32000     });
32001     Object.defineProperty(Node.prototype, "spatialEdges", {
32002         /**
32003          * Get spatialEdges.
32004          *
32005          * @returns {IEdgeStatus} Value describing the status of the
32006          * spatial edges.
32007          */
32008         get: function () {
32009             return this._cache.spatialEdges;
32010         },
32011         enumerable: true,
32012         configurable: true
32013     });
32014     Object.defineProperty(Node.prototype, "spatialEdges$", {
32015         /**
32016          * Get spatialEdges$.
32017          *
32018          * @returns {Observable<IEdgeStatus>} Observable emitting
32019          * values describing the status of the spatial edges.
32020          */
32021         get: function () {
32022             return this._cache.spatialEdges$;
32023         },
32024         enumerable: true,
32025         configurable: true
32026     });
32027     Object.defineProperty(Node.prototype, "userKey", {
32028         /**
32029          * Get userKey.
32030          *
32031          * @returns {string} Unique key of the user who uploaded
32032          * the image.
32033          */
32034         get: function () {
32035             return this._fill.user.key;
32036         },
32037         enumerable: true,
32038         configurable: true
32039     });
32040     Object.defineProperty(Node.prototype, "username", {
32041         /**
32042          * Get username.
32043          *
32044          * @returns {string} Username of the user who uploaded
32045          * the image.
32046          */
32047         get: function () {
32048             return this._fill.user.username;
32049         },
32050         enumerable: true,
32051         configurable: true
32052     });
32053     Object.defineProperty(Node.prototype, "width", {
32054         /**
32055          * Get width.
32056          *
32057          * @returns {number} Width of original image, not
32058          * adjusted for orientation.
32059          */
32060         get: function () {
32061             return this._fill.width;
32062         },
32063         enumerable: true,
32064         configurable: true
32065     });
32066     /**
32067      * Cache the image and mesh assets.
32068      *
32069      * @description The assets are always cached internally by the
32070      * library prior to setting a node as the current node.
32071      *
32072      * @returns {Observable<Node>} Observable emitting this node whenever the
32073      * load status has changed and when the mesh or image has been fully loaded.
32074      */
32075     Node.prototype.cacheAssets$ = function () {
32076         var _this = this;
32077         return this._cache.cacheAssets$(this.key, this.pano, this.merged)
32078             .map(function (cache) {
32079             return _this;
32080         });
32081     };
32082     Node.prototype.cacheImage$ = function (imageSize) {
32083         var _this = this;
32084         return this._cache.cacheImage$(this.key, imageSize)
32085             .map(function (cache) {
32086             return _this;
32087         });
32088     };
32089     /**
32090      * Cache the sequence edges.
32091      *
32092      * @description The sequence edges are cached asynchronously
32093      * internally by the library.
32094      *
32095      * @param {Array<IEdge>} edges - Sequence edges to cache.
32096      */
32097     Node.prototype.cacheSequenceEdges = function (edges) {
32098         this._cache.cacheSequenceEdges(edges);
32099     };
32100     /**
32101      * Cache the spatial edges.
32102      *
32103      * @description The spatial edges are cached asynchronously
32104      * internally by the library.
32105      *
32106      * @param {Array<IEdge>} edges - Spatial edges to cache.
32107      */
32108     Node.prototype.cacheSpatialEdges = function (edges) {
32109         this._cache.cacheSpatialEdges(edges);
32110     };
32111     /**
32112      * Dispose the node.
32113      *
32114      * @description Disposes all cached assets.
32115      */
32116     Node.prototype.dispose = function () {
32117         if (this._cache != null) {
32118             this._cache.dispose();
32119             this._cache = null;
32120         }
32121         this._core = null;
32122         this._fill = null;
32123     };
32124     /**
32125      * Initialize the node cache.
32126      *
32127      * @description The node cache is initialized internally by
32128      * the library.
32129      *
32130      * @param {NodeCache} cache - The node cache to set as cache.
32131      */
32132     Node.prototype.initializeCache = function (cache) {
32133         if (this._cache != null) {
32134             throw new Error("Node cache already initialized (" + this.key + ").");
32135         }
32136         this._cache = cache;
32137     };
32138     /**
32139      * Fill the node with all properties.
32140      *
32141      * @description The node is filled internally by
32142      * the library.
32143      *
32144      * @param {IFillNode} fill - The fill node struct.
32145      */
32146     Node.prototype.makeFull = function (fill) {
32147         if (fill == null) {
32148             throw new Error("Fill can not be null.");
32149         }
32150         this._fill = fill;
32151     };
32152     /**
32153      * Reset the sequence edges.
32154      */
32155     Node.prototype.resetSequenceEdges = function () {
32156         this._cache.resetSequenceEdges();
32157     };
32158     /**
32159      * Reset the spatial edges.
32160      */
32161     Node.prototype.resetSpatialEdges = function () {
32162         this._cache.resetSpatialEdges();
32163     };
32164     /**
32165      * Clears the image and mesh assets, aborts
32166      * any outstanding requests and resets edges.
32167      */
32168     Node.prototype.uncache = function () {
32169         if (this._cache == null) {
32170             return;
32171         }
32172         this._cache.dispose();
32173         this._cache = null;
32174     };
32175     return Node;
32176 }());
32177 exports.Node = Node;
32178 Object.defineProperty(exports, "__esModule", { value: true });
32179 exports.default = Node;
32180
32181 },{"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/map":64}],312:[function(require,module,exports){
32182 (function (Buffer){
32183 "use strict";
32184 var Subject_1 = require("rxjs/Subject");
32185 var Observable_1 = require("rxjs/Observable");
32186 require("rxjs/add/observable/combineLatest");
32187 require("rxjs/add/operator/publishReplay");
32188 var Graph_1 = require("../Graph");
32189 var Utils_1 = require("../Utils");
32190 /**
32191  * @class NodeCache
32192  *
32193  * @classdesc Represents the cached properties of a node.
32194  */
32195 var NodeCache = (function () {
32196     /**
32197      * Create a new node cache instance.
32198      */
32199     function NodeCache() {
32200         this._disposed = false;
32201         this._image = null;
32202         this._loadStatus = { loaded: 0, total: 0 };
32203         this._mesh = null;
32204         this._sequenceEdges = { cached: false, edges: [] };
32205         this._spatialEdges = { cached: false, edges: [] };
32206         this._sequenceEdgesChanged$ = new Subject_1.Subject();
32207         this._sequenceEdges$ = this._sequenceEdgesChanged$
32208             .startWith(this._sequenceEdges)
32209             .publishReplay(1)
32210             .refCount();
32211         this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
32212         this._spatialEdgesChanged$ = new Subject_1.Subject();
32213         this._spatialEdges$ = this._spatialEdgesChanged$
32214             .startWith(this._spatialEdges)
32215             .publishReplay(1)
32216             .refCount();
32217         this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
32218         this._cachingAssets$ = null;
32219     }
32220     Object.defineProperty(NodeCache.prototype, "image", {
32221         /**
32222          * Get image.
32223          *
32224          * @description Will not be set when assets have not been cached
32225          * or when the object has been disposed.
32226          *
32227          * @returns {HTMLImageElement} Cached image element of the node.
32228          */
32229         get: function () {
32230             return this._image;
32231         },
32232         enumerable: true,
32233         configurable: true
32234     });
32235     Object.defineProperty(NodeCache.prototype, "loadStatus", {
32236         /**
32237          * Get loadStatus.
32238          *
32239          * @returns {ILoadStatus} Value indicating the load status
32240          * of the mesh and image.
32241          */
32242         get: function () {
32243             return this._loadStatus;
32244         },
32245         enumerable: true,
32246         configurable: true
32247     });
32248     Object.defineProperty(NodeCache.prototype, "mesh", {
32249         /**
32250          * Get mesh.
32251          *
32252          * @description Will not be set when assets have not been cached
32253          * or when the object has been disposed.
32254          *
32255          * @returns {IMesh} SfM triangulated mesh of reconstructed
32256          * atomic 3D points.
32257          */
32258         get: function () {
32259             return this._mesh;
32260         },
32261         enumerable: true,
32262         configurable: true
32263     });
32264     Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
32265         /**
32266          * Get sequenceEdges.
32267          *
32268          * @returns {IEdgeStatus} Value describing the status of the
32269          * sequence edges.
32270          */
32271         get: function () {
32272             return this._sequenceEdges;
32273         },
32274         enumerable: true,
32275         configurable: true
32276     });
32277     Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
32278         /**
32279          * Get sequenceEdges$.
32280          *
32281          * @returns {Observable<IEdgeStatus>} Observable emitting
32282          * values describing the status of the sequence edges.
32283          */
32284         get: function () {
32285             return this._sequenceEdges$;
32286         },
32287         enumerable: true,
32288         configurable: true
32289     });
32290     Object.defineProperty(NodeCache.prototype, "spatialEdges", {
32291         /**
32292          * Get spatialEdges.
32293          *
32294          * @returns {IEdgeStatus} Value describing the status of the
32295          * spatial edges.
32296          */
32297         get: function () {
32298             return this._spatialEdges;
32299         },
32300         enumerable: true,
32301         configurable: true
32302     });
32303     Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
32304         /**
32305          * Get spatialEdges$.
32306          *
32307          * @returns {Observable<IEdgeStatus>} Observable emitting
32308          * values describing the status of the spatial edges.
32309          */
32310         get: function () {
32311             return this._spatialEdges$;
32312         },
32313         enumerable: true,
32314         configurable: true
32315     });
32316     /**
32317      * Cache the image and mesh assets.
32318      *
32319      * @param {string} key - Key of the node to cache.
32320      * @param {boolean} pano - Value indicating whether node is a panorama.
32321      * @param {boolean} merged - Value indicating whether node is merged.
32322      * @returns {Observable<NodeCache>} Observable emitting this node
32323      * cache whenever the load status has changed and when the mesh or image
32324      * has been fully loaded.
32325      */
32326     NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
32327         var _this = this;
32328         if (this._cachingAssets$ != null) {
32329             return this._cachingAssets$;
32330         }
32331         var imageSize = pano ?
32332             Utils_1.Settings.basePanoramaSize :
32333             Utils_1.Settings.baseImageSize;
32334         this._cachingAssets$ = Observable_1.Observable
32335             .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
32336             _this._loadStatus.loaded = 0;
32337             _this._loadStatus.total = 0;
32338             if (meshStatus) {
32339                 _this._mesh = meshStatus.object;
32340                 _this._loadStatus.loaded += meshStatus.loaded.loaded;
32341                 _this._loadStatus.total += meshStatus.loaded.total;
32342             }
32343             if (imageStatus) {
32344                 _this._image = imageStatus.object;
32345                 _this._loadStatus.loaded += imageStatus.loaded.loaded;
32346                 _this._loadStatus.total += imageStatus.loaded.total;
32347             }
32348             return _this;
32349         })
32350             .finally(function () {
32351             _this._cachingAssets$ = null;
32352         })
32353             .publishReplay(1)
32354             .refCount();
32355         return this._cachingAssets$;
32356     };
32357     /**
32358      * Cache an image with a higher resolution than the current one.
32359      *
32360      * @param {string} key - Key of the node to cache.
32361      * @param {ImageSize} imageSize - The size to cache.
32362      * @returns {Observable<NodeCache>} Observable emitting a single item,
32363      * the node cache, when the image has been cached. If supplied image
32364      * size is not larger than the current image size the node cache is
32365      * returned immediately.
32366      */
32367     NodeCache.prototype.cacheImage$ = function (key, imageSize) {
32368         var _this = this;
32369         if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
32370             return Observable_1.Observable.of(this);
32371         }
32372         return this._cacheImage$(key, imageSize)
32373             .first(function (status) {
32374             return status.object != null;
32375         })
32376             .do(function (status) {
32377             _this._disposeImage();
32378             _this._image = status.object;
32379         })
32380             .map(function (imageStatus) {
32381             return _this;
32382         });
32383     };
32384     /**
32385      * Cache the sequence edges.
32386      *
32387      * @param {Array<IEdge>} edges - Sequence edges to cache.
32388      */
32389     NodeCache.prototype.cacheSequenceEdges = function (edges) {
32390         this._sequenceEdges = { cached: true, edges: edges };
32391         this._sequenceEdgesChanged$.next(this._sequenceEdges);
32392     };
32393     /**
32394      * Cache the spatial edges.
32395      *
32396      * @param {Array<IEdge>} edges - Spatial edges to cache.
32397      */
32398     NodeCache.prototype.cacheSpatialEdges = function (edges) {
32399         this._spatialEdges = { cached: true, edges: edges };
32400         this._spatialEdgesChanged$.next(this._spatialEdges);
32401     };
32402     /**
32403      * Dispose the node cache.
32404      *
32405      * @description Disposes all cached assets and unsubscribes to
32406      * all streams.
32407      */
32408     NodeCache.prototype.dispose = function () {
32409         this._sequenceEdgesSubscription.unsubscribe();
32410         this._spatialEdgesSubscription.unsubscribe();
32411         this._disposeImage();
32412         this._mesh = null;
32413         this._loadStatus.loaded = 0;
32414         this._loadStatus.total = 0;
32415         this._sequenceEdges = { cached: false, edges: [] };
32416         this._spatialEdges = { cached: false, edges: [] };
32417         this._sequenceEdgesChanged$.next(this._sequenceEdges);
32418         this._spatialEdgesChanged$.next(this._spatialEdges);
32419         this._disposed = true;
32420         if (this._imageRequest != null) {
32421             this._imageRequest.abort();
32422         }
32423         if (this._meshRequest != null) {
32424             this._meshRequest.abort();
32425         }
32426     };
32427     /**
32428      * Reset the sequence edges.
32429      */
32430     NodeCache.prototype.resetSequenceEdges = function () {
32431         this._sequenceEdges = { cached: false, edges: [] };
32432         this._sequenceEdgesChanged$.next(this._sequenceEdges);
32433     };
32434     /**
32435      * Reset the spatial edges.
32436      */
32437     NodeCache.prototype.resetSpatialEdges = function () {
32438         this._spatialEdges = { cached: false, edges: [] };
32439         this._spatialEdgesChanged$.next(this._spatialEdges);
32440     };
32441     /**
32442      * Cache the image.
32443      *
32444      * @param {string} key - Key of the node to cache.
32445      * @param {boolean} pano - Value indicating whether node is a panorama.
32446      * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
32447      * emitting a load status object every time the load status changes
32448      * and completes when the image is fully loaded.
32449      */
32450     NodeCache.prototype._cacheImage$ = function (key, imageSize) {
32451         var _this = this;
32452         return Observable_1.Observable.create(function (subscriber) {
32453             var xmlHTTP = new XMLHttpRequest();
32454             xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
32455             xmlHTTP.responseType = "arraybuffer";
32456             xmlHTTP.timeout = 15000;
32457             xmlHTTP.onload = function (pe) {
32458                 if (xmlHTTP.status !== 200) {
32459                     _this._imageRequest = null;
32460                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
32461                     return;
32462                 }
32463                 var image = new Image();
32464                 image.crossOrigin = "Anonymous";
32465                 image.onload = function (e) {
32466                     _this._imageRequest = null;
32467                     if (_this._disposed) {
32468                         window.URL.revokeObjectURL(image.src);
32469                         subscriber.error(new Error("Image load was aborted (" + key + ")"));
32470                         return;
32471                     }
32472                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
32473                     subscriber.complete();
32474                 };
32475                 image.onerror = function (error) {
32476                     _this._imageRequest = null;
32477                     subscriber.error(new Error("Failed to load image (" + key + ")"));
32478                 };
32479                 var blob = new Blob([xmlHTTP.response]);
32480                 image.src = window.URL.createObjectURL(blob);
32481             };
32482             xmlHTTP.onprogress = function (pe) {
32483                 if (_this._disposed) {
32484                     return;
32485                 }
32486                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
32487             };
32488             xmlHTTP.onerror = function (error) {
32489                 _this._imageRequest = null;
32490                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
32491             };
32492             xmlHTTP.ontimeout = function (e) {
32493                 _this._imageRequest = null;
32494                 subscriber.error(new Error("Image request timed out (" + key + ")"));
32495             };
32496             xmlHTTP.onabort = function (event) {
32497                 _this._imageRequest = null;
32498                 subscriber.error(new Error("Image request was aborted (" + key + ")"));
32499             };
32500             _this._imageRequest = xmlHTTP;
32501             xmlHTTP.send(null);
32502         });
32503     };
32504     /**
32505      * Cache the mesh.
32506      *
32507      * @param {string} key - Key of the node to cache.
32508      * @param {boolean} merged - Value indicating whether node is merged.
32509      * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
32510      * a load status object every time the load status changes and completes
32511      * when the mesh is fully loaded.
32512      */
32513     NodeCache.prototype._cacheMesh$ = function (key, merged) {
32514         var _this = this;
32515         return Observable_1.Observable.create(function (subscriber) {
32516             if (!merged) {
32517                 subscriber.next(_this._createEmptyMeshLoadStatus());
32518                 subscriber.complete();
32519                 return;
32520             }
32521             var xmlHTTP = new XMLHttpRequest();
32522             xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
32523             xmlHTTP.responseType = "arraybuffer";
32524             xmlHTTP.timeout = 15000;
32525             xmlHTTP.onload = function (pe) {
32526                 _this._meshRequest = null;
32527                 if (_this._disposed) {
32528                     return;
32529                 }
32530                 var mesh = xmlHTTP.status === 200 ?
32531                     Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
32532                     { faces: [], vertices: [] };
32533                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
32534                 subscriber.complete();
32535             };
32536             xmlHTTP.onprogress = function (pe) {
32537                 if (_this._disposed) {
32538                     return;
32539                 }
32540                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
32541             };
32542             xmlHTTP.onerror = function (e) {
32543                 _this._meshRequest = null;
32544                 console.error("Failed to cache mesh (" + key + ")");
32545                 subscriber.next(_this._createEmptyMeshLoadStatus());
32546                 subscriber.complete();
32547             };
32548             xmlHTTP.ontimeout = function (e) {
32549                 _this._meshRequest = null;
32550                 console.error("Mesh request timed out (" + key + ")");
32551                 subscriber.next(_this._createEmptyMeshLoadStatus());
32552                 subscriber.complete();
32553             };
32554             xmlHTTP.onabort = function (e) {
32555                 _this._meshRequest = null;
32556                 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
32557             };
32558             _this._meshRequest = xmlHTTP;
32559             xmlHTTP.send(null);
32560         });
32561     };
32562     /**
32563      * Create a load status object with an empty mesh.
32564      *
32565      * @returns {ILoadStatusObject<IMesh>} Load status object
32566      * with empty mesh.
32567      */
32568     NodeCache.prototype._createEmptyMeshLoadStatus = function () {
32569         return {
32570             loaded: { loaded: 0, total: 0 },
32571             object: { faces: [], vertices: [] },
32572         };
32573     };
32574     NodeCache.prototype._disposeImage = function () {
32575         if (this._image != null) {
32576             window.URL.revokeObjectURL(this._image.src);
32577         }
32578         this._image = null;
32579     };
32580     return NodeCache;
32581 }());
32582 exports.NodeCache = NodeCache;
32583 Object.defineProperty(exports, "__esModule", { value: true });
32584 exports.default = NodeCache;
32585
32586 }).call(this,require("buffer").Buffer)
32587
32588 },{"../Graph":228,"../Utils":233,"buffer":5,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/publishReplay":71}],313:[function(require,module,exports){
32589 /// <reference path="../../typings/index.d.ts" />
32590 "use strict";
32591 var _ = require("underscore");
32592 /**
32593  * @class Sequence
32594  *
32595  * @classdesc Represents a sequence of ordered nodes.
32596  */
32597 var Sequence = (function () {
32598     /**
32599      * Create a new sequene instance.
32600      *
32601      * @param {ISequence} sequence - Raw sequence data.
32602      */
32603     function Sequence(sequence) {
32604         this._key = sequence.key;
32605         this._keys = sequence.keys;
32606     }
32607     Object.defineProperty(Sequence.prototype, "key", {
32608         /**
32609          * Get key.
32610          *
32611          * @returns {string} Unique sequence key.
32612          */
32613         get: function () {
32614             return this._key;
32615         },
32616         enumerable: true,
32617         configurable: true
32618     });
32619     Object.defineProperty(Sequence.prototype, "keys", {
32620         /**
32621          * Get keys.
32622          *
32623          * @returns {Array<string>} Array of ordered node keys in the sequence.
32624          */
32625         get: function () {
32626             return this._keys;
32627         },
32628         enumerable: true,
32629         configurable: true
32630     });
32631     /**
32632      * Dispose the sequence.
32633      *
32634      * @description Disposes all cached assets.
32635      */
32636     Sequence.prototype.dispose = function () {
32637         this._key = null;
32638         this._keys = null;
32639     };
32640     /**
32641      * Find the next node key in the sequence with respect to
32642      * the provided node key.
32643      *
32644      * @param {string} key - Reference node key.
32645      * @returns {string} Next key in sequence if it exists, null otherwise.
32646      */
32647     Sequence.prototype.findNextKey = function (key) {
32648         var i = _.indexOf(this._keys, key);
32649         if ((i + 1) >= this._keys.length || i === -1) {
32650             return null;
32651         }
32652         else {
32653             return this._keys[i + 1];
32654         }
32655     };
32656     /**
32657      * Find the previous node key in the sequence with respect to
32658      * the provided node key.
32659      *
32660      * @param {string} key - Reference node key.
32661      * @returns {string} Previous key in sequence if it exists, null otherwise.
32662      */
32663     Sequence.prototype.findPrevKey = function (key) {
32664         var i = _.indexOf(this._keys, key);
32665         if (i === 0 || i === -1) {
32666             return null;
32667         }
32668         else {
32669             return this._keys[i - 1];
32670         }
32671     };
32672     return Sequence;
32673 }());
32674 exports.Sequence = Sequence;
32675 Object.defineProperty(exports, "__esModule", { value: true });
32676 exports.default = Sequence;
32677
32678 },{"underscore":175}],314:[function(require,module,exports){
32679 /// <reference path="../../../typings/index.d.ts" />
32680 "use strict";
32681 var THREE = require("three");
32682 var Edge_1 = require("../../Edge");
32683 var Error_1 = require("../../Error");
32684 var Geo_1 = require("../../Geo");
32685 /**
32686  * @class EdgeCalculator
32687  *
32688  * @classdesc Represents a class for calculating node edges.
32689  */
32690 var EdgeCalculator = (function () {
32691     /**
32692      * Create a new edge calculator instance.
32693      *
32694      * @param {EdgeCalculatorSettings} settings - Settings struct.
32695      * @param {EdgeCalculatorDirections} directions - Directions struct.
32696      * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
32697      */
32698     function EdgeCalculator(settings, directions, coefficients) {
32699         this._spatial = new Geo_1.Spatial();
32700         this._geoCoords = new Geo_1.GeoCoords();
32701         this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
32702         this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
32703         this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
32704     }
32705     /**
32706      * Returns the potential edges to destination nodes for a set
32707      * of nodes with respect to a source node.
32708      *
32709      * @param {Node} node - Source node.
32710      * @param {Array<Node>} nodes - Potential destination nodes.
32711      * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
32712      * be returned even if they do not meet the criteria for a potential edge.
32713      * @throws {ArgumentMapillaryError} If node is not full.
32714      */
32715     EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
32716         if (!node.full) {
32717             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
32718         }
32719         if (!node.merged) {
32720             return [];
32721         }
32722         var currentDirection = this._spatial.viewingDirection(node.rotation);
32723         var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
32724         var potentialEdges = [];
32725         for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
32726             var potential = potentialNodes_1[_i];
32727             if (!potential.merged ||
32728                 potential.key === node.key) {
32729                 continue;
32730             }
32731             var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
32732             var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
32733             var distance = motion.length();
32734             if (distance > this._settings.maxDistance &&
32735                 fallbackKeys.indexOf(potential.key) < 0) {
32736                 continue;
32737             }
32738             var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
32739             var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
32740             var direction = this._spatial.viewingDirection(potential.rotation);
32741             var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
32742             var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
32743             var verticalDirectionChange = verticalDirection - currentVerticalDirection;
32744             var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
32745             var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
32746             var sameSequence = potential.sequenceKey != null &&
32747                 node.sequenceKey != null &&
32748                 potential.sequenceKey === node.sequenceKey;
32749             var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
32750                 potential.mergeCC === node.mergeCC;
32751             var sameUser = potential.userKey === node.userKey;
32752             var potentialEdge = {
32753                 capturedAt: potential.capturedAt,
32754                 directionChange: directionChange,
32755                 distance: distance,
32756                 fullPano: potential.fullPano,
32757                 key: potential.key,
32758                 motionChange: motionChange,
32759                 rotation: rotation,
32760                 sameMergeCC: sameMergeCC,
32761                 sameSequence: sameSequence,
32762                 sameUser: sameUser,
32763                 sequenceKey: potential.sequenceKey,
32764                 verticalDirectionChange: verticalDirectionChange,
32765                 verticalMotion: verticalMotion,
32766                 worldMotionAzimuth: worldMotionAzimuth,
32767             };
32768             potentialEdges.push(potentialEdge);
32769         }
32770         return potentialEdges;
32771     };
32772     /**
32773      * Computes the sequence edges for a node.
32774      *
32775      * @param {Node} node - Source node.
32776      * @throws {ArgumentMapillaryError} If node is not full.
32777      */
32778     EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
32779         if (!node.full) {
32780             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
32781         }
32782         if (node.sequenceKey !== sequence.key) {
32783             throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
32784         }
32785         var edges = [];
32786         var nextKey = sequence.findNextKey(node.key);
32787         if (nextKey != null) {
32788             edges.push({
32789                 data: {
32790                     direction: Edge_1.EdgeDirection.Next,
32791                     worldMotionAzimuth: Number.NaN,
32792                 },
32793                 from: node.key,
32794                 to: nextKey,
32795             });
32796         }
32797         var prevKey = sequence.findPrevKey(node.key);
32798         if (prevKey != null) {
32799             edges.push({
32800                 data: {
32801                     direction: Edge_1.EdgeDirection.Prev,
32802                     worldMotionAzimuth: Number.NaN,
32803                 },
32804                 from: node.key,
32805                 to: prevKey,
32806             });
32807         }
32808         return edges;
32809     };
32810     /**
32811      * Computes the similar edges for a node.
32812      *
32813      * @description Similar edges for perspective images and cropped panoramas
32814      * look roughly in the same direction and are positioned closed to the node.
32815      * Similar edges for full panoramas only target other full panoramas.
32816      *
32817      * @param {Node} node - Source node.
32818      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
32819      * @throws {ArgumentMapillaryError} If node is not full.
32820      */
32821     EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
32822         var _this = this;
32823         if (!node.full) {
32824             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
32825         }
32826         var nodeFullPano = node.fullPano;
32827         var sequenceGroups = {};
32828         for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
32829             var potentialEdge = potentialEdges_1[_i];
32830             if (potentialEdge.sequenceKey == null) {
32831                 continue;
32832             }
32833             if (potentialEdge.sameSequence ||
32834                 !potentialEdge.sameMergeCC) {
32835                 continue;
32836             }
32837             if (nodeFullPano) {
32838                 if (!potentialEdge.fullPano) {
32839                     continue;
32840                 }
32841             }
32842             else {
32843                 if (!potentialEdge.fullPano &&
32844                     Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
32845                     continue;
32846                 }
32847             }
32848             if (potentialEdge.distance > this._settings.similarMaxDistance) {
32849                 continue;
32850             }
32851             if (potentialEdge.sameUser &&
32852                 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
32853                     this._settings.similarMinTimeDifference) {
32854                 continue;
32855             }
32856             if (sequenceGroups[potentialEdge.sequenceKey] == null) {
32857                 sequenceGroups[potentialEdge.sequenceKey] = [];
32858             }
32859             sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
32860         }
32861         var similarEdges = [];
32862         var calculateScore = node.fullPano ?
32863             function (potentialEdge) {
32864                 return potentialEdge.distance;
32865             } :
32866             function (potentialEdge) {
32867                 return _this._coefficients.similarDistance * potentialEdge.distance +
32868                     _this._coefficients.similarRotation * potentialEdge.rotation;
32869             };
32870         for (var sequenceKey in sequenceGroups) {
32871             if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
32872                 continue;
32873             }
32874             var lowestScore = Number.MAX_VALUE;
32875             var similarEdge = null;
32876             for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
32877                 var potentialEdge = _b[_a];
32878                 var score = calculateScore(potentialEdge);
32879                 if (score < lowestScore) {
32880                     lowestScore = score;
32881                     similarEdge = potentialEdge;
32882                 }
32883             }
32884             if (similarEdge == null) {
32885                 continue;
32886             }
32887             similarEdges.push(similarEdge);
32888         }
32889         return similarEdges
32890             .map(function (potentialEdge) {
32891             return {
32892                 data: {
32893                     direction: Edge_1.EdgeDirection.Similar,
32894                     worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
32895                 },
32896                 from: node.key,
32897                 to: potentialEdge.key,
32898             };
32899         });
32900     };
32901     /**
32902      * Computes the step edges for a perspective node.
32903      *
32904      * @param {Node} node - Source node.
32905      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
32906      * @param {string} prevKey - Key of previous node in sequence.
32907      * @param {string} prevKey - Key of next node in sequence.
32908      * @throws {ArgumentMapillaryError} If node is not full.
32909      */
32910     EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
32911         if (!node.full) {
32912             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
32913         }
32914         var edges = [];
32915         if (node.fullPano) {
32916             return edges;
32917         }
32918         for (var k in this._directions.steps) {
32919             if (!this._directions.steps.hasOwnProperty(k)) {
32920                 continue;
32921             }
32922             var step = this._directions.steps[k];
32923             var lowestScore = Number.MAX_VALUE;
32924             var edge = null;
32925             var fallback = null;
32926             for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
32927                 var potential = potentialEdges_2[_i];
32928                 if (potential.fullPano) {
32929                     continue;
32930                 }
32931                 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
32932                     continue;
32933                 }
32934                 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
32935                 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
32936                 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
32937                 if (Math.abs(drift) > this._settings.stepMaxDrift) {
32938                     continue;
32939                 }
32940                 var potentialKey = potential.key;
32941                 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
32942                     fallback = potential;
32943                 }
32944                 if (potential.distance > this._settings.stepMaxDistance) {
32945                     continue;
32946                 }
32947                 motionDifference = Math.sqrt(motionDifference * motionDifference +
32948                     potential.verticalMotion * potential.verticalMotion);
32949                 var score = this._coefficients.stepPreferredDistance *
32950                     Math.abs(potential.distance - this._settings.stepPreferredDistance) /
32951                     this._settings.stepMaxDistance +
32952                     this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
32953                     this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
32954                     this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
32955                     this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
32956                 if (score < lowestScore) {
32957                     lowestScore = score;
32958                     edge = potential;
32959                 }
32960             }
32961             edge = edge == null ? fallback : edge;
32962             if (edge != null) {
32963                 edges.push({
32964                     data: {
32965                         direction: step.direction,
32966                         worldMotionAzimuth: edge.worldMotionAzimuth,
32967                     },
32968                     from: node.key,
32969                     to: edge.key,
32970                 });
32971             }
32972         }
32973         return edges;
32974     };
32975     /**
32976      * Computes the turn edges for a perspective node.
32977      *
32978      * @param {Node} node - Source node.
32979      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
32980      * @throws {ArgumentMapillaryError} If node is not full.
32981      */
32982     EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
32983         if (!node.full) {
32984             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
32985         }
32986         var edges = [];
32987         if (node.fullPano) {
32988             return edges;
32989         }
32990         for (var k in this._directions.turns) {
32991             if (!this._directions.turns.hasOwnProperty(k)) {
32992                 continue;
32993             }
32994             var turn = this._directions.turns[k];
32995             var lowestScore = Number.MAX_VALUE;
32996             var edge = null;
32997             for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
32998                 var potential = potentialEdges_3[_i];
32999                 if (potential.fullPano) {
33000                     continue;
33001                 }
33002                 if (potential.distance > this._settings.turnMaxDistance) {
33003                     continue;
33004                 }
33005                 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
33006                     potential.distance < this._settings.turnMaxRigDistance &&
33007                     Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
33008                 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
33009                 var score = void 0;
33010                 if (rig &&
33011                     potential.directionChange * turn.directionChange > 0 &&
33012                     Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
33013                     score = -Math.PI / 2 + Math.abs(potential.directionChange);
33014                 }
33015                 else {
33016                     if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
33017                         continue;
33018                     }
33019                     var motionDifference = turn.motionChange ?
33020                         this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
33021                     motionDifference = Math.sqrt(motionDifference * motionDifference +
33022                         potential.verticalMotion * potential.verticalMotion);
33023                     score =
33024                         this._coefficients.turnDistance * potential.distance /
33025                             this._settings.turnMaxDistance +
33026                             this._coefficients.turnMotion * motionDifference / Math.PI +
33027                             this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
33028                             this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
33029                 }
33030                 if (score < lowestScore) {
33031                     lowestScore = score;
33032                     edge = potential;
33033                 }
33034             }
33035             if (edge != null) {
33036                 edges.push({
33037                     data: {
33038                         direction: turn.direction,
33039                         worldMotionAzimuth: edge.worldMotionAzimuth,
33040                     },
33041                     from: node.key,
33042                     to: edge.key,
33043                 });
33044             }
33045         }
33046         return edges;
33047     };
33048     /**
33049      * Computes the pano edges for a perspective node.
33050      *
33051      * @param {Node} node - Source node.
33052      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
33053      * @throws {ArgumentMapillaryError} If node is not full.
33054      */
33055     EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
33056         if (!node.full) {
33057             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33058         }
33059         if (node.fullPano) {
33060             return [];
33061         }
33062         var lowestScore = Number.MAX_VALUE;
33063         var edge = null;
33064         for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
33065             var potential = potentialEdges_4[_i];
33066             if (!potential.fullPano) {
33067                 continue;
33068             }
33069             var score = this._coefficients.panoPreferredDistance *
33070                 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
33071                 this._settings.panoMaxDistance +
33072                 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
33073                 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
33074             if (score < lowestScore) {
33075                 lowestScore = score;
33076                 edge = potential;
33077             }
33078         }
33079         if (edge == null) {
33080             return [];
33081         }
33082         return [
33083             {
33084                 data: {
33085                     direction: Edge_1.EdgeDirection.Pano,
33086                     worldMotionAzimuth: edge.worldMotionAzimuth,
33087                 },
33088                 from: node.key,
33089                 to: edge.key,
33090             },
33091         ];
33092     };
33093     /**
33094      * Computes the pano and step edges for a pano node.
33095      *
33096      * @param {Node} node - Source node.
33097      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
33098      * @throws {ArgumentMapillaryError} If node is not full.
33099      */
33100     EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
33101         if (!node.full) {
33102             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33103         }
33104         if (!node.fullPano) {
33105             return [];
33106         }
33107         var panoEdges = [];
33108         var potentialPanos = [];
33109         var potentialSteps = [];
33110         for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
33111             var potential = potentialEdges_5[_i];
33112             if (potential.distance > this._settings.panoMaxDistance) {
33113                 continue;
33114             }
33115             if (potential.fullPano) {
33116                 if (potential.distance < this._settings.panoMinDistance) {
33117                     continue;
33118                 }
33119                 potentialPanos.push(potential);
33120             }
33121             else {
33122                 for (var k in this._directions.panos) {
33123                     if (!this._directions.panos.hasOwnProperty(k)) {
33124                         continue;
33125                     }
33126                     var pano = this._directions.panos[k];
33127                     var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
33128                     var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
33129                     if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
33130                         continue;
33131                     }
33132                     potentialSteps.push([pano.direction, potential]);
33133                     // break if step direction found
33134                     break;
33135                 }
33136             }
33137         }
33138         var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
33139         var occupiedAngles = [];
33140         var stepAngles = [];
33141         for (var index = 0; index < this._settings.panoMaxItems; index++) {
33142             var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
33143             var lowestScore = Number.MAX_VALUE;
33144             var edge = null;
33145             for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
33146                 var potential = potentialPanos_1[_a];
33147                 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
33148                 if (Math.abs(motionDifference) > maxRotationDifference) {
33149                     continue;
33150                 }
33151                 var occupiedDifference = Number.MAX_VALUE;
33152                 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
33153                     var occupiedAngle = occupiedAngles_1[_b];
33154                     var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
33155                     if (difference < occupiedDifference) {
33156                         occupiedDifference = difference;
33157                     }
33158                 }
33159                 if (occupiedDifference <= maxRotationDifference) {
33160                     continue;
33161                 }
33162                 var score = this._coefficients.panoPreferredDistance *
33163                     Math.abs(potential.distance - this._settings.panoPreferredDistance) /
33164                     this._settings.panoMaxDistance +
33165                     this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
33166                     this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
33167                     this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
33168                 if (score < lowestScore) {
33169                     lowestScore = score;
33170                     edge = potential;
33171                 }
33172             }
33173             if (edge != null) {
33174                 occupiedAngles.push(edge.motionChange);
33175                 panoEdges.push({
33176                     data: {
33177                         direction: Edge_1.EdgeDirection.Pano,
33178                         worldMotionAzimuth: edge.worldMotionAzimuth,
33179                     },
33180                     from: node.key,
33181                     to: edge.key,
33182                 });
33183             }
33184             else {
33185                 stepAngles.push(rotation);
33186             }
33187         }
33188         var occupiedStepAngles = {};
33189         occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
33190         occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
33191         occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
33192         occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
33193         occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
33194         for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
33195             var stepAngle = stepAngles_1[_c];
33196             var occupations = [];
33197             for (var k in this._directions.panos) {
33198                 if (!this._directions.panos.hasOwnProperty(k)) {
33199                     continue;
33200                 }
33201                 var pano = this._directions.panos[k];
33202                 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
33203                     .concat(occupiedStepAngles[pano.direction])
33204                     .concat(occupiedStepAngles[pano.prev])
33205                     .concat(occupiedStepAngles[pano.next]);
33206                 var lowestScore = Number.MAX_VALUE;
33207                 var edge = null;
33208                 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
33209                     var potential = potentialSteps_1[_d];
33210                     if (potential[0] !== pano.direction) {
33211                         continue;
33212                     }
33213                     var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
33214                     if (Math.abs(motionChange) > maxRotationDifference) {
33215                         continue;
33216                     }
33217                     var minOccupiedDifference = Number.MAX_VALUE;
33218                     for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
33219                         var occupiedAngle = allOccupiedAngles_1[_e];
33220                         var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
33221                         if (occupiedDifference < minOccupiedDifference) {
33222                             minOccupiedDifference = occupiedDifference;
33223                         }
33224                     }
33225                     if (minOccupiedDifference <= maxRotationDifference) {
33226                         continue;
33227                     }
33228                     var score = this._coefficients.panoPreferredDistance *
33229                         Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
33230                         this._settings.panoMaxDistance +
33231                         this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
33232                         this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
33233                     if (score < lowestScore) {
33234                         lowestScore = score;
33235                         edge = potential;
33236                     }
33237                 }
33238                 if (edge != null) {
33239                     occupations.push(edge);
33240                     panoEdges.push({
33241                         data: {
33242                             direction: edge[0],
33243                             worldMotionAzimuth: edge[1].worldMotionAzimuth,
33244                         },
33245                         from: node.key,
33246                         to: edge[1].key,
33247                     });
33248                 }
33249             }
33250             for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
33251                 var occupation = occupations_1[_f];
33252                 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
33253             }
33254         }
33255         return panoEdges;
33256     };
33257     return EdgeCalculator;
33258 }());
33259 exports.EdgeCalculator = EdgeCalculator;
33260 Object.defineProperty(exports, "__esModule", { value: true });
33261 exports.default = EdgeCalculator;
33262
33263 },{"../../Edge":225,"../../Error":226,"../../Geo":227,"three":174}],315:[function(require,module,exports){
33264 "use strict";
33265 var EdgeCalculatorCoefficients = (function () {
33266     function EdgeCalculatorCoefficients() {
33267         this.panoPreferredDistance = 2;
33268         this.panoMotion = 2;
33269         this.panoSequencePenalty = 1;
33270         this.panoMergeCCPenalty = 4;
33271         this.stepPreferredDistance = 4;
33272         this.stepMotion = 3;
33273         this.stepRotation = 4;
33274         this.stepSequencePenalty = 2;
33275         this.stepMergeCCPenalty = 6;
33276         this.similarDistance = 2;
33277         this.similarRotation = 3;
33278         this.turnDistance = 4;
33279         this.turnMotion = 2;
33280         this.turnSequencePenalty = 1;
33281         this.turnMergeCCPenalty = 4;
33282     }
33283     return EdgeCalculatorCoefficients;
33284 }());
33285 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
33286 Object.defineProperty(exports, "__esModule", { value: true });
33287 exports.default = EdgeCalculatorCoefficients;
33288
33289 },{}],316:[function(require,module,exports){
33290 "use strict";
33291 var Edge_1 = require("../../Edge");
33292 var EdgeCalculatorDirections = (function () {
33293     function EdgeCalculatorDirections() {
33294         this.steps = {};
33295         this.turns = {};
33296         this.panos = {};
33297         this.steps[Edge_1.EdgeDirection.StepForward] = {
33298             direction: Edge_1.EdgeDirection.StepForward,
33299             motionChange: 0,
33300             useFallback: true,
33301         };
33302         this.steps[Edge_1.EdgeDirection.StepBackward] = {
33303             direction: Edge_1.EdgeDirection.StepBackward,
33304             motionChange: Math.PI,
33305             useFallback: true,
33306         };
33307         this.steps[Edge_1.EdgeDirection.StepLeft] = {
33308             direction: Edge_1.EdgeDirection.StepLeft,
33309             motionChange: Math.PI / 2,
33310             useFallback: false,
33311         };
33312         this.steps[Edge_1.EdgeDirection.StepRight] = {
33313             direction: Edge_1.EdgeDirection.StepRight,
33314             motionChange: -Math.PI / 2,
33315             useFallback: false,
33316         };
33317         this.turns[Edge_1.EdgeDirection.TurnLeft] = {
33318             direction: Edge_1.EdgeDirection.TurnLeft,
33319             directionChange: Math.PI / 2,
33320             motionChange: Math.PI / 4,
33321         };
33322         this.turns[Edge_1.EdgeDirection.TurnRight] = {
33323             direction: Edge_1.EdgeDirection.TurnRight,
33324             directionChange: -Math.PI / 2,
33325             motionChange: -Math.PI / 4,
33326         };
33327         this.turns[Edge_1.EdgeDirection.TurnU] = {
33328             direction: Edge_1.EdgeDirection.TurnU,
33329             directionChange: Math.PI,
33330             motionChange: null,
33331         };
33332         this.panos[Edge_1.EdgeDirection.StepForward] = {
33333             direction: Edge_1.EdgeDirection.StepForward,
33334             directionChange: 0,
33335             next: Edge_1.EdgeDirection.StepLeft,
33336             prev: Edge_1.EdgeDirection.StepRight,
33337         };
33338         this.panos[Edge_1.EdgeDirection.StepBackward] = {
33339             direction: Edge_1.EdgeDirection.StepBackward,
33340             directionChange: Math.PI,
33341             next: Edge_1.EdgeDirection.StepRight,
33342             prev: Edge_1.EdgeDirection.StepLeft,
33343         };
33344         this.panos[Edge_1.EdgeDirection.StepLeft] = {
33345             direction: Edge_1.EdgeDirection.StepLeft,
33346             directionChange: Math.PI / 2,
33347             next: Edge_1.EdgeDirection.StepBackward,
33348             prev: Edge_1.EdgeDirection.StepForward,
33349         };
33350         this.panos[Edge_1.EdgeDirection.StepRight] = {
33351             direction: Edge_1.EdgeDirection.StepRight,
33352             directionChange: -Math.PI / 2,
33353             next: Edge_1.EdgeDirection.StepForward,
33354             prev: Edge_1.EdgeDirection.StepBackward,
33355         };
33356     }
33357     return EdgeCalculatorDirections;
33358 }());
33359 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
33360
33361 },{"../../Edge":225}],317:[function(require,module,exports){
33362 "use strict";
33363 var EdgeCalculatorSettings = (function () {
33364     function EdgeCalculatorSettings() {
33365         this.panoMinDistance = 0.1;
33366         this.panoMaxDistance = 20;
33367         this.panoPreferredDistance = 5;
33368         this.panoMaxItems = 4;
33369         this.panoMaxStepTurnChange = Math.PI / 8;
33370         this.rotationMaxDistance = this.turnMaxRigDistance;
33371         this.rotationMaxDirectionChange = Math.PI / 6;
33372         this.rotationMaxVerticalDirectionChange = Math.PI / 8;
33373         this.similarMaxDirectionChange = Math.PI / 8;
33374         this.similarMaxDistance = 12;
33375         this.similarMinTimeDifference = 12 * 3600 * 1000;
33376         this.stepMaxDistance = 20;
33377         this.stepMaxDirectionChange = Math.PI / 6;
33378         this.stepMaxDrift = Math.PI / 6;
33379         this.stepPreferredDistance = 4;
33380         this.turnMaxDistance = 15;
33381         this.turnMaxDirectionChange = 2 * Math.PI / 9;
33382         this.turnMaxRigDistance = 0.65;
33383         this.turnMinRigDirectionChange = Math.PI / 6;
33384     }
33385     Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
33386         get: function () {
33387             return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
33388         },
33389         enumerable: true,
33390         configurable: true
33391     });
33392     return EdgeCalculatorSettings;
33393 }());
33394 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
33395 Object.defineProperty(exports, "__esModule", { value: true });
33396 exports.default = EdgeCalculatorSettings;
33397
33398 },{}],318:[function(require,module,exports){
33399 "use strict";
33400 /**
33401  * Enumeration for edge directions
33402  * @enum {number}
33403  * @readonly
33404  * @description Directions for edges in node graph describing
33405  * sequence, spatial and node type relations between nodes.
33406  */
33407 var EdgeDirection;
33408 (function (EdgeDirection) {
33409     /**
33410      * Next node in the sequence.
33411      */
33412     EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
33413     /**
33414      * Previous node in the sequence.
33415      */
33416     EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
33417     /**
33418      * Step to the left keeping viewing direction.
33419      */
33420     EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
33421     /**
33422      * Step to the right keeping viewing direction.
33423      */
33424     EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
33425     /**
33426      * Step forward keeping viewing direction.
33427      */
33428     EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
33429     /**
33430      * Step backward keeping viewing direction.
33431      */
33432     EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
33433     /**
33434      * Turn 90 degrees counter clockwise.
33435      */
33436     EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
33437     /**
33438      * Turn 90 degrees clockwise.
33439      */
33440     EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
33441     /**
33442      * Turn 180 degrees.
33443      */
33444     EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
33445     /**
33446      * Panorama in general direction.
33447      */
33448     EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
33449     /**
33450      * Looking in roughly the same direction at rougly the same position.
33451      */
33452     EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
33453 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
33454 ;
33455
33456 },{}],319:[function(require,module,exports){
33457 /// <reference path="../../typings/index.d.ts" />
33458 "use strict";
33459 var _ = require("underscore");
33460 var vd = require("virtual-dom");
33461 var Subject_1 = require("rxjs/Subject");
33462 require("rxjs/add/operator/combineLatest");
33463 require("rxjs/add/operator/distinctUntilChanged");
33464 require("rxjs/add/operator/filter");
33465 require("rxjs/add/operator/map");
33466 require("rxjs/add/operator/pluck");
33467 require("rxjs/add/operator/scan");
33468 var Render_1 = require("../Render");
33469 var DOMRenderer = (function () {
33470     function DOMRenderer(element, renderService, currentFrame$) {
33471         this._adaptiveOperation$ = new Subject_1.Subject();
33472         this._render$ = new Subject_1.Subject();
33473         this._renderAdaptive$ = new Subject_1.Subject();
33474         this._renderService = renderService;
33475         this._currentFrame$ = currentFrame$;
33476         var rootNode = vd.create(vd.h("div.domRenderer", []));
33477         element.appendChild(rootNode);
33478         this._offset$ = this._adaptiveOperation$
33479             .scan(function (adaptive, operation) {
33480             return operation(adaptive);
33481         }, {
33482             elementHeight: element.offsetHeight,
33483             elementWidth: element.offsetWidth,
33484             imageAspect: 0,
33485             renderMode: Render_1.RenderMode.Fill,
33486         })
33487             .filter(function (adaptive) {
33488             return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
33489         })
33490             .map(function (adaptive) {
33491             var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
33492             var ratio = adaptive.imageAspect / elementAspect;
33493             var verticalOffset = 0;
33494             var horizontalOffset = 0;
33495             if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
33496                 if (adaptive.imageAspect > elementAspect) {
33497                     verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
33498                 }
33499                 else {
33500                     horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
33501                 }
33502             }
33503             else {
33504                 if (adaptive.imageAspect > elementAspect) {
33505                     horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
33506                 }
33507                 else {
33508                     verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
33509                 }
33510             }
33511             return {
33512                 bottom: verticalOffset,
33513                 left: horizontalOffset,
33514                 right: horizontalOffset,
33515                 top: verticalOffset,
33516             };
33517         });
33518         this._currentFrame$
33519             .filter(function (frame) {
33520             return frame.state.currentNode != null;
33521         })
33522             .distinctUntilChanged(function (k1, k2) {
33523             return k1 === k2;
33524         }, function (frame) {
33525             return frame.state.currentNode.key;
33526         })
33527             .map(function (frame) {
33528             return frame.state.currentTransform.basicAspect;
33529         })
33530             .map(function (aspect) {
33531             return function (adaptive) {
33532                 adaptive.imageAspect = aspect;
33533                 return adaptive;
33534             };
33535         })
33536             .subscribe(this._adaptiveOperation$);
33537         this._renderAdaptive$
33538             .scan(function (vNodeHashes, vNodeHash) {
33539             if (vNodeHash.vnode == null) {
33540                 delete vNodeHashes[vNodeHash.name];
33541             }
33542             else {
33543                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
33544             }
33545             return vNodeHashes;
33546         }, {})
33547             .combineLatest(this._offset$)
33548             .map(function (vo) {
33549             var vNodes = _.values(vo[0]);
33550             var offset = vo[1];
33551             var properties = {
33552                 style: {
33553                     bottom: offset.bottom + "px",
33554                     left: offset.left + "px",
33555                     "pointer-events": "none",
33556                     position: "absolute",
33557                     right: offset.right + "px",
33558                     top: offset.top + "px",
33559                 },
33560             };
33561             return {
33562                 name: "adaptiveDomRenderer",
33563                 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
33564             };
33565         })
33566             .subscribe(this._render$);
33567         this._vNode$ = this._render$
33568             .scan(function (vNodeHashes, vNodeHash) {
33569             if (vNodeHash.vnode == null) {
33570                 delete vNodeHashes[vNodeHash.name];
33571             }
33572             else {
33573                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
33574             }
33575             return vNodeHashes;
33576         }, {})
33577             .map(function (vNodeHashes) {
33578             var vNodes = _.values(vNodeHashes);
33579             return vd.h("div.domRenderer", vNodes);
33580         });
33581         this._vPatch$ = this._vNode$
33582             .scan(function (nodePatch, vNode) {
33583             nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
33584             nodePatch.vnode = vNode;
33585             return nodePatch;
33586         }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
33587             .pluck("vpatch");
33588         this._element$ = this._vPatch$
33589             .scan(function (oldElement, vPatch) {
33590             return vd.patch(oldElement, vPatch);
33591         }, rootNode)
33592             .publishReplay(1)
33593             .refCount();
33594         this._element$.subscribe(function () { });
33595         this._renderService.size$
33596             .map(function (size) {
33597             return function (adaptive) {
33598                 adaptive.elementWidth = size.width;
33599                 adaptive.elementHeight = size.height;
33600                 return adaptive;
33601             };
33602         })
33603             .subscribe(this._adaptiveOperation$);
33604         this._renderService.renderMode$
33605             .map(function (renderMode) {
33606             return function (adaptive) {
33607                 adaptive.renderMode = renderMode;
33608                 return adaptive;
33609             };
33610         })
33611             .subscribe(this._adaptiveOperation$);
33612     }
33613     Object.defineProperty(DOMRenderer.prototype, "element$", {
33614         get: function () {
33615             return this._element$;
33616         },
33617         enumerable: true,
33618         configurable: true
33619     });
33620     Object.defineProperty(DOMRenderer.prototype, "render$", {
33621         get: function () {
33622             return this._render$;
33623         },
33624         enumerable: true,
33625         configurable: true
33626     });
33627     Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
33628         get: function () {
33629             return this._renderAdaptive$;
33630         },
33631         enumerable: true,
33632         configurable: true
33633     });
33634     DOMRenderer.prototype.clear = function (name) {
33635         this._renderAdaptive$.next({ name: name, vnode: null });
33636         this._render$.next({ name: name, vnode: null });
33637     };
33638     return DOMRenderer;
33639 }());
33640 exports.DOMRenderer = DOMRenderer;
33641 Object.defineProperty(exports, "__esModule", { value: true });
33642 exports.default = DOMRenderer;
33643
33644 },{"../Render":230,"rxjs/Subject":33,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/pluck":69,"rxjs/add/operator/scan":72,"underscore":175,"virtual-dom":180}],320:[function(require,module,exports){
33645 "use strict";
33646 var GLRenderStage;
33647 (function (GLRenderStage) {
33648     GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
33649     GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
33650 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
33651 Object.defineProperty(exports, "__esModule", { value: true });
33652 exports.default = GLRenderStage;
33653
33654 },{}],321:[function(require,module,exports){
33655 /// <reference path="../../typings/index.d.ts" />
33656 "use strict";
33657 var THREE = require("three");
33658 var Observable_1 = require("rxjs/Observable");
33659 var Subject_1 = require("rxjs/Subject");
33660 require("rxjs/add/observable/combineLatest");
33661 require("rxjs/add/operator/distinctUntilChanged");
33662 require("rxjs/add/operator/filter");
33663 require("rxjs/add/operator/first");
33664 require("rxjs/add/operator/map");
33665 require("rxjs/add/operator/merge");
33666 require("rxjs/add/operator/mergeMap");
33667 require("rxjs/add/operator/scan");
33668 require("rxjs/add/operator/share");
33669 require("rxjs/add/operator/startWith");
33670 var Render_1 = require("../Render");
33671 var GLRenderer = (function () {
33672     function GLRenderer(canvasContainer, renderService) {
33673         var _this = this;
33674         this._renderFrame$ = new Subject_1.Subject();
33675         this._renderCameraOperation$ = new Subject_1.Subject();
33676         this._render$ = new Subject_1.Subject();
33677         this._clear$ = new Subject_1.Subject();
33678         this._renderOperation$ = new Subject_1.Subject();
33679         this._rendererOperation$ = new Subject_1.Subject();
33680         this._eraserOperation$ = new Subject_1.Subject();
33681         this._renderService = renderService;
33682         this._renderer$ = this._rendererOperation$
33683             .scan(function (renderer, operation) {
33684             return operation(renderer);
33685         }, { needsRender: false, renderer: null });
33686         this._renderCollection$ = this._renderOperation$
33687             .scan(function (hashes, operation) {
33688             return operation(hashes);
33689         }, {})
33690             .share();
33691         this._renderCamera$ = this._renderCameraOperation$
33692             .scan(function (rc, operation) {
33693             return operation(rc);
33694         }, { frameId: -1, needsRender: false, perspective: null });
33695         this._eraser$ = this._eraserOperation$
33696             .startWith(function (eraser) {
33697             return eraser;
33698         })
33699             .scan(function (eraser, operation) {
33700             return operation(eraser);
33701         }, { needsRender: false });
33702         Observable_1.Observable
33703             .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
33704             var renders = Object.keys(hashes)
33705                 .map(function (key) {
33706                 return hashes[key];
33707             });
33708             return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
33709         })
33710             .filter(function (co) {
33711             var needsRender = co.renderer.needsRender ||
33712                 co.camera.needsRender ||
33713                 co.eraser.needsRender;
33714             var frameId = co.camera.frameId;
33715             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
33716                 var render = _a[_i];
33717                 if (render.frameId !== frameId) {
33718                     return false;
33719                 }
33720                 needsRender = needsRender || render.needsRender;
33721             }
33722             return needsRender;
33723         })
33724             .distinctUntilChanged(function (n1, n2) {
33725             return n1 === n2;
33726         }, function (co) {
33727             return co.eraser.needsRender ? -1 : co.camera.frameId;
33728         })
33729             .subscribe(function (co) {
33730             co.renderer.needsRender = false;
33731             co.camera.needsRender = false;
33732             co.eraser.needsRender = false;
33733             var perspectiveCamera = co.camera.perspective;
33734             var backgroundRenders = [];
33735             var foregroundRenders = [];
33736             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
33737                 var render = _a[_i];
33738                 if (render.stage === Render_1.GLRenderStage.Background) {
33739                     backgroundRenders.push(render.render);
33740                 }
33741                 else if (render.stage === Render_1.GLRenderStage.Foreground) {
33742                     foregroundRenders.push(render.render);
33743                 }
33744             }
33745             var renderer = co.renderer.renderer;
33746             renderer.clear();
33747             for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
33748                 var render = backgroundRenders_1[_b];
33749                 render(perspectiveCamera, renderer);
33750             }
33751             renderer.clearDepth();
33752             for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
33753                 var render = foregroundRenders_1[_c];
33754                 render(perspectiveCamera, renderer);
33755             }
33756         });
33757         this._renderFrame$
33758             .map(function (rc) {
33759             return function (irc) {
33760                 irc.frameId = rc.frameId;
33761                 irc.perspective = rc.perspective;
33762                 if (rc.changed === true) {
33763                     irc.needsRender = true;
33764                 }
33765                 return irc;
33766             };
33767         })
33768             .subscribe(this._renderCameraOperation$);
33769         this._renderFrameSubscribe();
33770         var renderHash$ = this._render$
33771             .map(function (hash) {
33772             return function (hashes) {
33773                 hashes[hash.name] = hash.render;
33774                 return hashes;
33775             };
33776         });
33777         var clearHash$ = this._clear$
33778             .map(function (name) {
33779             return function (hashes) {
33780                 delete hashes[name];
33781                 return hashes;
33782             };
33783         });
33784         Observable_1.Observable
33785             .merge(renderHash$, clearHash$)
33786             .subscribe(this._renderOperation$);
33787         this._webGLRenderer$ = this._render$
33788             .first()
33789             .map(function (hash) {
33790             var element = renderService.element;
33791             var webGLRenderer = new THREE.WebGLRenderer();
33792             webGLRenderer.setPixelRatio(window.devicePixelRatio);
33793             webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
33794             webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
33795             webGLRenderer.autoClear = false;
33796             webGLRenderer.domElement.style.position = "absolute";
33797             canvasContainer.appendChild(webGLRenderer.domElement);
33798             return webGLRenderer;
33799         })
33800             .publishReplay(1)
33801             .refCount();
33802         this._webGLRenderer$.subscribe(function () { });
33803         var createRenderer$ = this._webGLRenderer$
33804             .first()
33805             .map(function (webGLRenderer) {
33806             return function (renderer) {
33807                 renderer.needsRender = true;
33808                 renderer.renderer = webGLRenderer;
33809                 return renderer;
33810             };
33811         });
33812         var resizeRenderer$ = this._renderService.size$
33813             .map(function (size) {
33814             return function (renderer) {
33815                 if (renderer.renderer == null) {
33816                     return renderer;
33817                 }
33818                 renderer.renderer.setSize(size.width, size.height);
33819                 renderer.needsRender = true;
33820                 return renderer;
33821             };
33822         });
33823         var clearRenderer$ = this._clear$
33824             .map(function (name) {
33825             return function (renderer) {
33826                 if (renderer.renderer == null) {
33827                     return renderer;
33828                 }
33829                 renderer.needsRender = true;
33830                 return renderer;
33831             };
33832         });
33833         Observable_1.Observable
33834             .merge(createRenderer$, resizeRenderer$, clearRenderer$)
33835             .subscribe(this._rendererOperation$);
33836         var renderCollectionEmpty$ = this._renderCollection$
33837             .filter(function (hashes) {
33838             return Object.keys(hashes).length === 0;
33839         })
33840             .share();
33841         renderCollectionEmpty$
33842             .subscribe(function (hashes) {
33843             if (_this._renderFrameSubscription == null) {
33844                 return;
33845             }
33846             _this._renderFrameSubscription.unsubscribe();
33847             _this._renderFrameSubscription = null;
33848             _this._renderFrameSubscribe();
33849         });
33850         renderCollectionEmpty$
33851             .map(function (hashes) {
33852             return function (eraser) {
33853                 eraser.needsRender = true;
33854                 return eraser;
33855             };
33856         })
33857             .subscribe(this._eraserOperation$);
33858     }
33859     Object.defineProperty(GLRenderer.prototype, "render$", {
33860         get: function () {
33861             return this._render$;
33862         },
33863         enumerable: true,
33864         configurable: true
33865     });
33866     Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
33867         get: function () {
33868             return this._webGLRenderer$;
33869         },
33870         enumerable: true,
33871         configurable: true
33872     });
33873     GLRenderer.prototype.clear = function (name) {
33874         this._clear$.next(name);
33875     };
33876     GLRenderer.prototype._renderFrameSubscribe = function () {
33877         var _this = this;
33878         this._render$
33879             .first()
33880             .map(function (renderHash) {
33881             return function (irc) {
33882                 irc.needsRender = true;
33883                 return irc;
33884             };
33885         })
33886             .subscribe(function (operation) {
33887             _this._renderCameraOperation$.next(operation);
33888         });
33889         this._renderFrameSubscription = this._render$
33890             .first()
33891             .mergeMap(function (hash) {
33892             return _this._renderService.renderCameraFrame$;
33893         })
33894             .subscribe(this._renderFrame$);
33895     };
33896     return GLRenderer;
33897 }());
33898 exports.GLRenderer = GLRenderer;
33899 Object.defineProperty(exports, "__esModule", { value: true });
33900 exports.default = GLRenderer;
33901
33902 },{"../Render":230,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73,"rxjs/add/operator/startWith":77,"three":174}],322:[function(require,module,exports){
33903 /// <reference path="../../typings/index.d.ts" />
33904 "use strict";
33905 var THREE = require("three");
33906 var Geo_1 = require("../Geo");
33907 var Render_1 = require("../Render");
33908 var RenderCamera = (function () {
33909     function RenderCamera(perspectiveCameraAspect, renderMode) {
33910         this.alpha = -1;
33911         this.zoom = 0;
33912         this._frameId = -1;
33913         this._changed = false;
33914         this._changedForFrame = -1;
33915         this.currentAspect = 1;
33916         this.currentPano = false;
33917         this.previousAspect = 1;
33918         this.previousPano = false;
33919         this.renderMode = renderMode;
33920         this._spatial = new Geo_1.Spatial();
33921         this._camera = new Geo_1.Camera();
33922         this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
33923         this._perspective.matrixAutoUpdate = false;
33924         this._rotation = { phi: 0, theta: 0 };
33925     }
33926     Object.defineProperty(RenderCamera.prototype, "camera", {
33927         get: function () {
33928             return this._camera;
33929         },
33930         enumerable: true,
33931         configurable: true
33932     });
33933     Object.defineProperty(RenderCamera.prototype, "changed", {
33934         get: function () {
33935             return this.frameId === this._changedForFrame;
33936         },
33937         enumerable: true,
33938         configurable: true
33939     });
33940     Object.defineProperty(RenderCamera.prototype, "frameId", {
33941         get: function () {
33942             return this._frameId;
33943         },
33944         set: function (value) {
33945             this._frameId = value;
33946             if (this._changed) {
33947                 this._changed = false;
33948                 this._changedForFrame = value;
33949             }
33950         },
33951         enumerable: true,
33952         configurable: true
33953     });
33954     Object.defineProperty(RenderCamera.prototype, "perspective", {
33955         get: function () {
33956             return this._perspective;
33957         },
33958         enumerable: true,
33959         configurable: true
33960     });
33961     Object.defineProperty(RenderCamera.prototype, "rotation", {
33962         get: function () {
33963             return this._rotation;
33964         },
33965         enumerable: true,
33966         configurable: true
33967     });
33968     RenderCamera.prototype.updateProjection = function () {
33969         var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
33970         var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
33971         var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
33972         var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
33973         this._perspective.fov = verticalFov;
33974         this._perspective.updateProjectionMatrix();
33975         this._changed = true;
33976     };
33977     RenderCamera.prototype.updatePerspective = function (camera) {
33978         this._perspective.up.copy(camera.up);
33979         this._perspective.position.copy(camera.position);
33980         this._perspective.lookAt(camera.lookat);
33981         this._perspective.updateMatrix();
33982         this._perspective.updateMatrixWorld(false);
33983         this._changed = true;
33984     };
33985     RenderCamera.prototype.updateRotation = function (camera) {
33986         this._rotation = this._getRotation(camera);
33987     };
33988     RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
33989         return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
33990     };
33991     RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
33992         if (pano) {
33993             return 1;
33994         }
33995         var coeff = Math.max(1, 1 / nodeAspect);
33996         var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
33997             nodeAspect > perspectiveCameraAspect :
33998             nodeAspect < perspectiveCameraAspect;
33999         var aspect = usePerspective ?
34000             coeff * perspectiveCameraAspect :
34001             coeff * nodeAspect;
34002         return aspect;
34003     };
34004     RenderCamera.prototype._getRotation = function (camera) {
34005         var direction = camera.lookat.clone().sub(camera.position);
34006         var up = camera.up.clone();
34007         var upProjection = direction.clone().dot(up);
34008         var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
34009         var phi = Math.atan2(planeProjection.y, planeProjection.x);
34010         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
34011         return { phi: phi, theta: theta };
34012     };
34013     return RenderCamera;
34014 }());
34015 exports.RenderCamera = RenderCamera;
34016 Object.defineProperty(exports, "__esModule", { value: true });
34017 exports.default = RenderCamera;
34018
34019 },{"../Geo":227,"../Render":230,"three":174}],323:[function(require,module,exports){
34020 "use strict";
34021 /**
34022  * Enumeration for render mode
34023  * @enum {number}
34024  * @readonly
34025  * @description Modes for specifying how rendering is done
34026  * in the viewer. All modes preserves the original aspect
34027  * ratio of the images.
34028  */
34029 var RenderMode;
34030 (function (RenderMode) {
34031     /**
34032      * Displays all content within the viewer.
34033      *
34034      * @description Black bars shown on both
34035      * sides of the content. Bars are shown
34036      * either below and above or to the left
34037      * and right of the content depending on
34038      * the aspect ratio relation between the
34039      * image and the viewer.
34040      */
34041     RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
34042     /**
34043      * Fills the viewer by cropping content.
34044      *
34045      * @description Cropping is done either
34046      * in horizontal or vertical direction
34047      * depending on the aspect ratio relation
34048      * between the image and the viewer.
34049      */
34050     RenderMode[RenderMode["Fill"] = 1] = "Fill";
34051 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
34052 Object.defineProperty(exports, "__esModule", { value: true });
34053 exports.default = RenderMode;
34054
34055 },{}],324:[function(require,module,exports){
34056 /// <reference path="../../typings/index.d.ts" />
34057 "use strict";
34058 var Subject_1 = require("rxjs/Subject");
34059 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
34060 require("rxjs/add/observable/combineLatest");
34061 require("rxjs/add/operator/do");
34062 require("rxjs/add/operator/filter");
34063 require("rxjs/add/operator/map");
34064 require("rxjs/add/operator/publishReplay");
34065 require("rxjs/add/operator/scan");
34066 require("rxjs/add/operator/skip");
34067 require("rxjs/add/operator/startWith");
34068 require("rxjs/add/operator/withLatestFrom");
34069 var Geo_1 = require("../Geo");
34070 var Render_1 = require("../Render");
34071 var RenderService = (function () {
34072     function RenderService(element, currentFrame$, renderMode) {
34073         var _this = this;
34074         this._element = element;
34075         this._currentFrame$ = currentFrame$;
34076         this._spatial = new Geo_1.Spatial();
34077         renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
34078         this._resize$ = new Subject_1.Subject();
34079         this._renderCameraOperation$ = new Subject_1.Subject();
34080         this._size$ =
34081             new BehaviorSubject_1.BehaviorSubject({
34082                 height: this._element.offsetHeight,
34083                 width: this._element.offsetWidth,
34084             });
34085         this._resize$
34086             .map(function () {
34087             return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
34088         })
34089             .subscribe(this._size$);
34090         this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
34091         this._renderCameraHolder$ = this._renderCameraOperation$
34092             .startWith(function (rc) {
34093             return rc;
34094         })
34095             .scan(function (rc, operation) {
34096             return operation(rc);
34097         }, new Render_1.RenderCamera(this._element.offsetWidth / this._element.offsetHeight, renderMode))
34098             .publishReplay(1)
34099             .refCount();
34100         this._renderCameraFrame$ = this._currentFrame$
34101             .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
34102             return [frame, renderCamera];
34103         })
34104             .do(function (args) {
34105             var frame = args[0];
34106             var rc = args[1];
34107             var camera = frame.state.camera;
34108             if (rc.alpha !== frame.state.alpha ||
34109                 rc.zoom !== frame.state.zoom ||
34110                 rc.camera.diff(camera) > 1e-9) {
34111                 var currentTransform = frame.state.currentTransform;
34112                 var previousTransform = frame.state.previousTransform != null ?
34113                     frame.state.previousTransform :
34114                     frame.state.currentTransform;
34115                 var previousNode = frame.state.previousNode != null ?
34116                     frame.state.previousNode :
34117                     frame.state.currentNode;
34118                 rc.currentAspect = currentTransform.basicAspect;
34119                 rc.currentPano = frame.state.currentNode.pano;
34120                 rc.previousAspect = previousTransform.basicAspect;
34121                 rc.previousPano = previousNode.pano;
34122                 rc.alpha = frame.state.alpha;
34123                 rc.zoom = frame.state.zoom;
34124                 rc.camera.copy(camera);
34125                 rc.updatePerspective(camera);
34126                 rc.updateRotation(camera);
34127                 rc.updateProjection();
34128             }
34129             rc.frameId = frame.id;
34130         })
34131             .map(function (args) {
34132             return args[1];
34133         })
34134             .publishReplay(1)
34135             .refCount();
34136         this._renderCamera$ = this._renderCameraFrame$
34137             .filter(function (rc) {
34138             return rc.changed;
34139         })
34140             .publishReplay(1)
34141             .refCount();
34142         this._bearing$ = this._renderCamera$
34143             .map(function (renderCamera) {
34144             var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
34145             return _this._spatial.wrap(bearing, 0, 360);
34146         })
34147             .publishReplay(1)
34148             .refCount();
34149         this._size$
34150             .skip(1)
34151             .map(function (size) {
34152             return function (rc) {
34153                 rc.perspective.aspect = size.width / size.height;
34154                 rc.updateProjection();
34155                 return rc;
34156             };
34157         })
34158             .subscribe(this._renderCameraOperation$);
34159         this._renderMode$
34160             .skip(1)
34161             .map(function (rm) {
34162             return function (rc) {
34163                 rc.renderMode = rm;
34164                 rc.updateProjection();
34165                 return rc;
34166             };
34167         })
34168             .subscribe(this._renderCameraOperation$);
34169         this._bearing$.subscribe(function () { });
34170         this._renderCameraHolder$.subscribe(function () { });
34171         this._size$.subscribe(function () { });
34172         this._renderMode$.subscribe(function () { });
34173         this._renderCamera$.subscribe(function () { });
34174         this._renderCameraFrame$.subscribe(function () { });
34175     }
34176     Object.defineProperty(RenderService.prototype, "bearing$", {
34177         get: function () {
34178             return this._bearing$;
34179         },
34180         enumerable: true,
34181         configurable: true
34182     });
34183     Object.defineProperty(RenderService.prototype, "element", {
34184         get: function () {
34185             return this._element;
34186         },
34187         enumerable: true,
34188         configurable: true
34189     });
34190     Object.defineProperty(RenderService.prototype, "resize$", {
34191         get: function () {
34192             return this._resize$;
34193         },
34194         enumerable: true,
34195         configurable: true
34196     });
34197     Object.defineProperty(RenderService.prototype, "size$", {
34198         get: function () {
34199             return this._size$;
34200         },
34201         enumerable: true,
34202         configurable: true
34203     });
34204     Object.defineProperty(RenderService.prototype, "renderMode$", {
34205         get: function () {
34206             return this._renderMode$;
34207         },
34208         enumerable: true,
34209         configurable: true
34210     });
34211     Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
34212         get: function () {
34213             return this._renderCameraFrame$;
34214         },
34215         enumerable: true,
34216         configurable: true
34217     });
34218     Object.defineProperty(RenderService.prototype, "renderCamera$", {
34219         get: function () {
34220             return this._renderCamera$;
34221         },
34222         enumerable: true,
34223         configurable: true
34224     });
34225     return RenderService;
34226 }());
34227 exports.RenderService = RenderService;
34228 Object.defineProperty(exports, "__esModule", { value: true });
34229 exports.default = RenderService;
34230
34231 },{"../Geo":227,"../Render":230,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/do":58,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/skip":74,"rxjs/add/operator/startWith":77,"rxjs/add/operator/withLatestFrom":82}],325:[function(require,module,exports){
34232 "use strict";
34233 var State;
34234 (function (State) {
34235     State[State["Traversing"] = 0] = "Traversing";
34236     State[State["Waiting"] = 1] = "Waiting";
34237 })(State = exports.State || (exports.State = {}));
34238 Object.defineProperty(exports, "__esModule", { value: true });
34239 exports.default = State;
34240
34241 },{}],326:[function(require,module,exports){
34242 "use strict";
34243 var State_1 = require("../State");
34244 var Geo_1 = require("../Geo");
34245 var StateContext = (function () {
34246     function StateContext() {
34247         this._state = new State_1.TraversingState({
34248             alpha: 1,
34249             camera: new Geo_1.Camera(),
34250             currentIndex: -1,
34251             reference: { alt: 0, lat: 0, lon: 0 },
34252             trajectory: [],
34253             zoom: 0,
34254         });
34255     }
34256     StateContext.prototype.traverse = function () {
34257         this._state = this._state.traverse();
34258     };
34259     StateContext.prototype.wait = function () {
34260         this._state = this._state.wait();
34261     };
34262     Object.defineProperty(StateContext.prototype, "state", {
34263         get: function () {
34264             if (this._state instanceof State_1.TraversingState) {
34265                 return State_1.State.Traversing;
34266             }
34267             else if (this._state instanceof State_1.WaitingState) {
34268                 return State_1.State.Waiting;
34269             }
34270             throw new Error("Invalid state");
34271         },
34272         enumerable: true,
34273         configurable: true
34274     });
34275     Object.defineProperty(StateContext.prototype, "reference", {
34276         get: function () {
34277             return this._state.reference;
34278         },
34279         enumerable: true,
34280         configurable: true
34281     });
34282     Object.defineProperty(StateContext.prototype, "alpha", {
34283         get: function () {
34284             return this._state.alpha;
34285         },
34286         enumerable: true,
34287         configurable: true
34288     });
34289     Object.defineProperty(StateContext.prototype, "camera", {
34290         get: function () {
34291             return this._state.camera;
34292         },
34293         enumerable: true,
34294         configurable: true
34295     });
34296     Object.defineProperty(StateContext.prototype, "zoom", {
34297         get: function () {
34298             return this._state.zoom;
34299         },
34300         enumerable: true,
34301         configurable: true
34302     });
34303     Object.defineProperty(StateContext.prototype, "currentNode", {
34304         get: function () {
34305             return this._state.currentNode;
34306         },
34307         enumerable: true,
34308         configurable: true
34309     });
34310     Object.defineProperty(StateContext.prototype, "previousNode", {
34311         get: function () {
34312             return this._state.previousNode;
34313         },
34314         enumerable: true,
34315         configurable: true
34316     });
34317     Object.defineProperty(StateContext.prototype, "currentCamera", {
34318         get: function () {
34319             return this._state.currentCamera;
34320         },
34321         enumerable: true,
34322         configurable: true
34323     });
34324     Object.defineProperty(StateContext.prototype, "currentTransform", {
34325         get: function () {
34326             return this._state.currentTransform;
34327         },
34328         enumerable: true,
34329         configurable: true
34330     });
34331     Object.defineProperty(StateContext.prototype, "previousTransform", {
34332         get: function () {
34333             return this._state.previousTransform;
34334         },
34335         enumerable: true,
34336         configurable: true
34337     });
34338     Object.defineProperty(StateContext.prototype, "trajectory", {
34339         get: function () {
34340             return this._state.trajectory;
34341         },
34342         enumerable: true,
34343         configurable: true
34344     });
34345     Object.defineProperty(StateContext.prototype, "currentIndex", {
34346         get: function () {
34347             return this._state.currentIndex;
34348         },
34349         enumerable: true,
34350         configurable: true
34351     });
34352     Object.defineProperty(StateContext.prototype, "lastNode", {
34353         get: function () {
34354             return this._state.trajectory[this._state.trajectory.length - 1];
34355         },
34356         enumerable: true,
34357         configurable: true
34358     });
34359     Object.defineProperty(StateContext.prototype, "nodesAhead", {
34360         get: function () {
34361             return this._state.trajectory.length - 1 - this._state.currentIndex;
34362         },
34363         enumerable: true,
34364         configurable: true
34365     });
34366     Object.defineProperty(StateContext.prototype, "motionless", {
34367         get: function () {
34368             return this._state.motionless;
34369         },
34370         enumerable: true,
34371         configurable: true
34372     });
34373     StateContext.prototype.getCenter = function () {
34374         return this._state.getCenter();
34375     };
34376     StateContext.prototype.setCenter = function (center) {
34377         this._state.setCenter(center);
34378     };
34379     StateContext.prototype.setZoom = function (zoom) {
34380         this._state.setZoom(zoom);
34381     };
34382     StateContext.prototype.update = function (fps) {
34383         this._state.update(fps);
34384     };
34385     StateContext.prototype.append = function (nodes) {
34386         this._state.append(nodes);
34387     };
34388     StateContext.prototype.prepend = function (nodes) {
34389         this._state.prepend(nodes);
34390     };
34391     StateContext.prototype.remove = function (n) {
34392         this._state.remove(n);
34393     };
34394     StateContext.prototype.clear = function () {
34395         this._state.clear();
34396     };
34397     StateContext.prototype.clearPrior = function () {
34398         this._state.clearPrior();
34399     };
34400     StateContext.prototype.cut = function () {
34401         this._state.cut();
34402     };
34403     StateContext.prototype.set = function (nodes) {
34404         this._state.set(nodes);
34405     };
34406     StateContext.prototype.rotate = function (delta) {
34407         this._state.rotate(delta);
34408     };
34409     StateContext.prototype.rotateBasic = function (basicRotation) {
34410         this._state.rotateBasic(basicRotation);
34411     };
34412     StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
34413         this._state.rotateBasicUnbounded(basicRotation);
34414     };
34415     StateContext.prototype.rotateToBasic = function (basic) {
34416         this._state.rotateToBasic(basic);
34417     };
34418     StateContext.prototype.move = function (delta) {
34419         this._state.move(delta);
34420     };
34421     StateContext.prototype.moveTo = function (delta) {
34422         this._state.moveTo(delta);
34423     };
34424     StateContext.prototype.zoomIn = function (delta, reference) {
34425         this._state.zoomIn(delta, reference);
34426     };
34427     return StateContext;
34428 }());
34429 exports.StateContext = StateContext;
34430
34431 },{"../Geo":227,"../State":231}],327:[function(require,module,exports){
34432 "use strict";
34433 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
34434 var Subject_1 = require("rxjs/Subject");
34435 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
34436 require("rxjs/add/operator/bufferCount");
34437 require("rxjs/add/operator/distinctUntilChanged");
34438 require("rxjs/add/operator/do");
34439 require("rxjs/add/operator/filter");
34440 require("rxjs/add/operator/first");
34441 require("rxjs/add/operator/map");
34442 require("rxjs/add/operator/pairwise");
34443 require("rxjs/add/operator/publishReplay");
34444 require("rxjs/add/operator/scan");
34445 require("rxjs/add/operator/startWith");
34446 require("rxjs/add/operator/switchMap");
34447 require("rxjs/add/operator/withLatestFrom");
34448 var State_1 = require("../State");
34449 var StateService = (function () {
34450     function StateService() {
34451         var _this = this;
34452         this._appendNode$ = new Subject_1.Subject();
34453         this._start$ = new Subject_1.Subject();
34454         this._frame$ = new Subject_1.Subject();
34455         this._fpsSampleRate = 30;
34456         this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
34457             return context;
34458         });
34459         this._context$ = this._contextOperation$
34460             .scan(function (context, operation) {
34461             return operation(context);
34462         }, new State_1.StateContext())
34463             .publishReplay(1)
34464             .refCount();
34465         this._state$ = this._context$
34466             .map(function (context) {
34467             return context.state;
34468         })
34469             .distinctUntilChanged()
34470             .publishReplay(1)
34471             .refCount();
34472         this._fps$ = this._start$
34473             .switchMap(function () {
34474             return _this._frame$
34475                 .bufferCount(1, _this._fpsSampleRate)
34476                 .map(function (frameIds) {
34477                 return new Date().getTime();
34478             })
34479                 .pairwise()
34480                 .map(function (times) {
34481                 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
34482             })
34483                 .startWith(60);
34484         })
34485             .share();
34486         this._currentState$ = this._frame$
34487             .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
34488             return [frameId, fps, context];
34489         })
34490             .filter(function (fc) {
34491             return fc[2].currentNode != null;
34492         })
34493             .do(function (fc) {
34494             fc[2].update(fc[1]);
34495         })
34496             .map(function (fc) {
34497             return { fps: fc[1], id: fc[0], state: fc[2] };
34498         })
34499             .share();
34500         this._lastState$ = this._currentState$
34501             .publishReplay(1)
34502             .refCount();
34503         var nodeChanged$ = this._currentState$
34504             .distinctUntilChanged(undefined, function (f) {
34505             return f.state.currentNode.key;
34506         })
34507             .publishReplay(1)
34508             .refCount();
34509         var nodeChangedSubject$ = new Subject_1.Subject();
34510         nodeChanged$
34511             .subscribe(nodeChangedSubject$);
34512         this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
34513         nodeChangedSubject$
34514             .map(function (f) {
34515             return f.state.currentNode.key;
34516         })
34517             .subscribe(this._currentKey$);
34518         this._currentNode$ = nodeChangedSubject$
34519             .map(function (f) {
34520             return f.state.currentNode;
34521         })
34522             .publishReplay(1)
34523             .refCount();
34524         this._currentCamera$ = nodeChangedSubject$
34525             .map(function (f) {
34526             return f.state.currentCamera;
34527         })
34528             .publishReplay(1)
34529             .refCount();
34530         this._currentTransform$ = nodeChangedSubject$
34531             .map(function (f) {
34532             return f.state.currentTransform;
34533         })
34534             .publishReplay(1)
34535             .refCount();
34536         this._reference$ = nodeChangedSubject$
34537             .map(function (f) {
34538             return f.state.reference;
34539         })
34540             .distinctUntilChanged(function (r1, r2) {
34541             return r1.lat === r2.lat && r1.lon === r2.lon;
34542         }, function (reference) {
34543             return { lat: reference.lat, lon: reference.lon };
34544         })
34545             .publishReplay(1)
34546             .refCount();
34547         this._currentNodeExternal$ = nodeChanged$
34548             .map(function (f) {
34549             return f.state.currentNode;
34550         })
34551             .publishReplay(1)
34552             .refCount();
34553         this._appendNode$
34554             .map(function (node) {
34555             return function (context) {
34556                 context.append([node]);
34557                 return context;
34558             };
34559         })
34560             .subscribe(this._contextOperation$);
34561         this._inMotionOperation$ = new Subject_1.Subject();
34562         nodeChanged$
34563             .map(function (frame) {
34564             return true;
34565         })
34566             .subscribe(this._inMotionOperation$);
34567         this._inMotionOperation$
34568             .distinctUntilChanged()
34569             .filter(function (moving) {
34570             return moving;
34571         })
34572             .switchMap(function (moving) {
34573             return _this._currentState$
34574                 .filter(function (frame) {
34575                 return frame.state.nodesAhead === 0;
34576             })
34577                 .map(function (frame) {
34578                 return [frame.state.camera.clone(), frame.state.zoom];
34579             })
34580                 .pairwise()
34581                 .map(function (pair) {
34582                 var c1 = pair[0][0];
34583                 var c2 = pair[1][0];
34584                 var z1 = pair[0][1];
34585                 var z2 = pair[1][1];
34586                 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
34587             })
34588                 .first(function (changed) {
34589                 return !changed;
34590             });
34591         })
34592             .subscribe(this._inMotionOperation$);
34593         this._inMotion$ = this._inMotionOperation$
34594             .distinctUntilChanged()
34595             .publishReplay(1)
34596             .refCount();
34597         this._inTranslationOperation$ = new Subject_1.Subject();
34598         nodeChanged$
34599             .map(function (frame) {
34600             return true;
34601         })
34602             .subscribe(this._inTranslationOperation$);
34603         this._inTranslationOperation$
34604             .distinctUntilChanged()
34605             .filter(function (inTranslation) {
34606             return inTranslation;
34607         })
34608             .switchMap(function (inTranslation) {
34609             return _this._currentState$
34610                 .filter(function (frame) {
34611                 return frame.state.nodesAhead === 0;
34612             })
34613                 .map(function (frame) {
34614                 return frame.state.camera.position.clone();
34615             })
34616                 .pairwise()
34617                 .map(function (pair) {
34618                 return pair[0].distanceToSquared(pair[1]) !== 0;
34619             })
34620                 .first(function (changed) {
34621                 return !changed;
34622             });
34623         })
34624             .subscribe(this._inTranslationOperation$);
34625         this._inTranslation$ = this._inTranslationOperation$
34626             .distinctUntilChanged()
34627             .publishReplay(1)
34628             .refCount();
34629         this._state$.subscribe(function () { });
34630         this._currentNode$.subscribe(function () { });
34631         this._currentCamera$.subscribe(function () { });
34632         this._currentTransform$.subscribe(function () { });
34633         this._reference$.subscribe(function () { });
34634         this._currentNodeExternal$.subscribe(function () { });
34635         this._lastState$.subscribe(function () { });
34636         this._inMotion$.subscribe(function () { });
34637         this._inTranslation$.subscribe(function () { });
34638         this._frameId = null;
34639         this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
34640     }
34641     Object.defineProperty(StateService.prototype, "currentState$", {
34642         get: function () {
34643             return this._currentState$;
34644         },
34645         enumerable: true,
34646         configurable: true
34647     });
34648     Object.defineProperty(StateService.prototype, "currentNode$", {
34649         get: function () {
34650             return this._currentNode$;
34651         },
34652         enumerable: true,
34653         configurable: true
34654     });
34655     Object.defineProperty(StateService.prototype, "currentKey$", {
34656         get: function () {
34657             return this._currentKey$;
34658         },
34659         enumerable: true,
34660         configurable: true
34661     });
34662     Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
34663         get: function () {
34664             return this._currentNodeExternal$;
34665         },
34666         enumerable: true,
34667         configurable: true
34668     });
34669     Object.defineProperty(StateService.prototype, "currentCamera$", {
34670         get: function () {
34671             return this._currentCamera$;
34672         },
34673         enumerable: true,
34674         configurable: true
34675     });
34676     Object.defineProperty(StateService.prototype, "currentTransform$", {
34677         get: function () {
34678             return this._currentTransform$;
34679         },
34680         enumerable: true,
34681         configurable: true
34682     });
34683     Object.defineProperty(StateService.prototype, "state$", {
34684         get: function () {
34685             return this._state$;
34686         },
34687         enumerable: true,
34688         configurable: true
34689     });
34690     Object.defineProperty(StateService.prototype, "reference$", {
34691         get: function () {
34692             return this._reference$;
34693         },
34694         enumerable: true,
34695         configurable: true
34696     });
34697     Object.defineProperty(StateService.prototype, "inMotion$", {
34698         get: function () {
34699             return this._inMotion$;
34700         },
34701         enumerable: true,
34702         configurable: true
34703     });
34704     Object.defineProperty(StateService.prototype, "inTranslation$", {
34705         get: function () {
34706             return this._inTranslation$;
34707         },
34708         enumerable: true,
34709         configurable: true
34710     });
34711     Object.defineProperty(StateService.prototype, "appendNode$", {
34712         get: function () {
34713             return this._appendNode$;
34714         },
34715         enumerable: true,
34716         configurable: true
34717     });
34718     StateService.prototype.traverse = function () {
34719         this._inMotionOperation$.next(true);
34720         this._invokeContextOperation(function (context) { context.traverse(); });
34721     };
34722     StateService.prototype.wait = function () {
34723         this._invokeContextOperation(function (context) { context.wait(); });
34724     };
34725     StateService.prototype.appendNodes = function (nodes) {
34726         this._invokeContextOperation(function (context) { context.append(nodes); });
34727     };
34728     StateService.prototype.prependNodes = function (nodes) {
34729         this._invokeContextOperation(function (context) { context.prepend(nodes); });
34730     };
34731     StateService.prototype.removeNodes = function (n) {
34732         this._invokeContextOperation(function (context) { context.remove(n); });
34733     };
34734     StateService.prototype.clearNodes = function () {
34735         this._invokeContextOperation(function (context) { context.clear(); });
34736     };
34737     StateService.prototype.clearPriorNodes = function () {
34738         this._invokeContextOperation(function (context) { context.clearPrior(); });
34739     };
34740     StateService.prototype.cutNodes = function () {
34741         this._invokeContextOperation(function (context) { context.cut(); });
34742     };
34743     StateService.prototype.setNodes = function (nodes) {
34744         this._invokeContextOperation(function (context) { context.set(nodes); });
34745     };
34746     StateService.prototype.rotate = function (delta) {
34747         this._inMotionOperation$.next(true);
34748         this._invokeContextOperation(function (context) { context.rotate(delta); });
34749     };
34750     StateService.prototype.rotateBasic = function (basicRotation) {
34751         this._inMotionOperation$.next(true);
34752         this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
34753     };
34754     StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
34755         this._inMotionOperation$.next(true);
34756         this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
34757     };
34758     StateService.prototype.rotateToBasic = function (basic) {
34759         this._inMotionOperation$.next(true);
34760         this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
34761     };
34762     StateService.prototype.move = function (delta) {
34763         this._inMotionOperation$.next(true);
34764         this._invokeContextOperation(function (context) { context.move(delta); });
34765     };
34766     StateService.prototype.moveTo = function (position) {
34767         this._inMotionOperation$.next(true);
34768         this._invokeContextOperation(function (context) { context.moveTo(position); });
34769     };
34770     /**
34771      * Change zoom level while keeping the reference point position approximately static.
34772      *
34773      * @parameter {number} delta - Change in zoom level.
34774      * @parameter {Array<number>} reference - Reference point in basic coordinates.
34775      */
34776     StateService.prototype.zoomIn = function (delta, reference) {
34777         this._inMotionOperation$.next(true);
34778         this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
34779     };
34780     StateService.prototype.getCenter = function () {
34781         return this._lastState$
34782             .first()
34783             .map(function (frame) {
34784             return frame.state.getCenter();
34785         });
34786     };
34787     StateService.prototype.getZoom = function () {
34788         return this._lastState$
34789             .first()
34790             .map(function (frame) {
34791             return frame.state.zoom;
34792         });
34793     };
34794     StateService.prototype.setCenter = function (center) {
34795         this._inMotionOperation$.next(true);
34796         this._invokeContextOperation(function (context) { context.setCenter(center); });
34797     };
34798     StateService.prototype.setZoom = function (zoom) {
34799         this._inMotionOperation$.next(true);
34800         this._invokeContextOperation(function (context) { context.setZoom(zoom); });
34801     };
34802     StateService.prototype.start = function () {
34803         if (this._frameId == null) {
34804             this._start$.next(null);
34805             this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
34806             this._frame$.next(this._frameId);
34807         }
34808     };
34809     StateService.prototype.stop = function () {
34810         if (this._frameId != null) {
34811             this._frameGenerator.cancelAnimationFrame(this._frameId);
34812             this._frameId = null;
34813         }
34814     };
34815     StateService.prototype._invokeContextOperation = function (action) {
34816         this._contextOperation$
34817             .next(function (context) {
34818             action(context);
34819             return context;
34820         });
34821     };
34822     StateService.prototype._frame = function (time) {
34823         this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
34824         this._frame$.next(this._frameId);
34825     };
34826     return StateService;
34827 }());
34828 exports.StateService = StateService;
34829
34830 },{"../State":231,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/bufferCount":49,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/do":58,"rxjs/add/operator/filter":60,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/pairwise":68,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/startWith":77,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/withLatestFrom":82,"rxjs/util/AnimationFrame":155}],328:[function(require,module,exports){
34831 /// <reference path="../../../typings/index.d.ts" />
34832 "use strict";
34833 var Error_1 = require("../../Error");
34834 var Geo_1 = require("../../Geo");
34835 var StateBase = (function () {
34836     function StateBase(state) {
34837         this._spatial = new Geo_1.Spatial();
34838         this._geoCoords = new Geo_1.GeoCoords();
34839         this._referenceThreshold = 0.01;
34840         this._reference = state.reference;
34841         this._alpha = state.alpha;
34842         this._camera = state.camera.clone();
34843         this._zoom = state.zoom;
34844         this._currentIndex = state.currentIndex;
34845         this._trajectory = state.trajectory.slice();
34846         this._trajectoryTransforms = [];
34847         this._trajectoryCameras = [];
34848         for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
34849             var node = _a[_i];
34850             var translation = this._nodeToTranslation(node);
34851             var transform = new Geo_1.Transform(node, node.image, translation);
34852             this._trajectoryTransforms.push(transform);
34853             this._trajectoryCameras.push(new Geo_1.Camera(transform));
34854         }
34855         this._currentNode = this._trajectory.length > 0 ?
34856             this._trajectory[this._currentIndex] :
34857             null;
34858         this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
34859             this._trajectory[this._currentIndex - 1] :
34860             null;
34861         this._currentCamera = this._trajectoryCameras.length > 0 ?
34862             this._trajectoryCameras[this._currentIndex].clone() :
34863             new Geo_1.Camera();
34864         this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
34865             this._trajectoryCameras[this._currentIndex - 1].clone() :
34866             this._currentCamera.clone();
34867     }
34868     Object.defineProperty(StateBase.prototype, "reference", {
34869         get: function () {
34870             return this._reference;
34871         },
34872         enumerable: true,
34873         configurable: true
34874     });
34875     Object.defineProperty(StateBase.prototype, "alpha", {
34876         get: function () {
34877             return this._getAlpha();
34878         },
34879         enumerable: true,
34880         configurable: true
34881     });
34882     Object.defineProperty(StateBase.prototype, "camera", {
34883         get: function () {
34884             return this._camera;
34885         },
34886         enumerable: true,
34887         configurable: true
34888     });
34889     Object.defineProperty(StateBase.prototype, "zoom", {
34890         get: function () {
34891             return this._zoom;
34892         },
34893         enumerable: true,
34894         configurable: true
34895     });
34896     Object.defineProperty(StateBase.prototype, "trajectory", {
34897         get: function () {
34898             return this._trajectory;
34899         },
34900         enumerable: true,
34901         configurable: true
34902     });
34903     Object.defineProperty(StateBase.prototype, "currentIndex", {
34904         get: function () {
34905             return this._currentIndex;
34906         },
34907         enumerable: true,
34908         configurable: true
34909     });
34910     Object.defineProperty(StateBase.prototype, "currentNode", {
34911         get: function () {
34912             return this._currentNode;
34913         },
34914         enumerable: true,
34915         configurable: true
34916     });
34917     Object.defineProperty(StateBase.prototype, "previousNode", {
34918         get: function () {
34919             return this._previousNode;
34920         },
34921         enumerable: true,
34922         configurable: true
34923     });
34924     Object.defineProperty(StateBase.prototype, "currentCamera", {
34925         get: function () {
34926             return this._currentCamera;
34927         },
34928         enumerable: true,
34929         configurable: true
34930     });
34931     Object.defineProperty(StateBase.prototype, "currentTransform", {
34932         get: function () {
34933             return this._trajectoryTransforms.length > 0 ?
34934                 this._trajectoryTransforms[this.currentIndex] : null;
34935         },
34936         enumerable: true,
34937         configurable: true
34938     });
34939     Object.defineProperty(StateBase.prototype, "previousTransform", {
34940         get: function () {
34941             return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
34942                 this._trajectoryTransforms[this.currentIndex - 1] : null;
34943         },
34944         enumerable: true,
34945         configurable: true
34946     });
34947     Object.defineProperty(StateBase.prototype, "motionless", {
34948         get: function () {
34949             return this._motionless;
34950         },
34951         enumerable: true,
34952         configurable: true
34953     });
34954     StateBase.prototype.append = function (nodes) {
34955         if (nodes.length < 1) {
34956             throw Error("Trajectory can not be empty");
34957         }
34958         if (this._currentIndex < 0) {
34959             this.set(nodes);
34960         }
34961         else {
34962             this._trajectory = this._trajectory.concat(nodes);
34963             this._appendToTrajectories(nodes);
34964         }
34965     };
34966     StateBase.prototype.prepend = function (nodes) {
34967         if (nodes.length < 1) {
34968             throw Error("Trajectory can not be empty");
34969         }
34970         this._trajectory = nodes.slice().concat(this._trajectory);
34971         this._currentIndex += nodes.length;
34972         this._setCurrentNode();
34973         var referenceReset = this._setReference(this._currentNode);
34974         if (referenceReset) {
34975             this._setTrajectories();
34976         }
34977         else {
34978             this._prependToTrajectories(nodes);
34979         }
34980         this._setCurrentCamera();
34981     };
34982     StateBase.prototype.remove = function (n) {
34983         if (n < 0) {
34984             throw Error("n must be a positive integer");
34985         }
34986         if (this._currentIndex - 1 < n) {
34987             throw Error("Current and previous nodes can not be removed");
34988         }
34989         for (var i = 0; i < n; i++) {
34990             this._trajectory.shift();
34991             this._trajectoryTransforms.shift();
34992             this._trajectoryCameras.shift();
34993             this._currentIndex--;
34994         }
34995         this._setCurrentNode();
34996     };
34997     StateBase.prototype.clearPrior = function () {
34998         if (this._currentIndex > 0) {
34999             this.remove(this._currentIndex - 1);
35000         }
35001     };
35002     StateBase.prototype.clear = function () {
35003         this.cut();
35004         if (this._currentIndex > 0) {
35005             this.remove(this._currentIndex - 1);
35006         }
35007     };
35008     StateBase.prototype.cut = function () {
35009         while (this._trajectory.length - 1 > this._currentIndex) {
35010             this._trajectory.pop();
35011             this._trajectoryTransforms.pop();
35012             this._trajectoryCameras.pop();
35013         }
35014     };
35015     StateBase.prototype.set = function (nodes) {
35016         this._setTrajectory(nodes);
35017         this._setCurrentNode();
35018         this._setReference(this._currentNode);
35019         this._setTrajectories();
35020         this._setCurrentCamera();
35021     };
35022     StateBase.prototype.getCenter = function () {
35023         return this._currentNode != null ?
35024             this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
35025             [0.5, 0.5];
35026     };
35027     StateBase.prototype._setCurrent = function () {
35028         this._setCurrentNode();
35029         var referenceReset = this._setReference(this._currentNode);
35030         if (referenceReset) {
35031             this._setTrajectories();
35032         }
35033         this._setCurrentCamera();
35034     };
35035     StateBase.prototype._setCurrentCamera = function () {
35036         this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
35037         this._previousCamera = this._currentIndex > 0 ?
35038             this._trajectoryCameras[this._currentIndex - 1].clone() :
35039             this._currentCamera.clone();
35040     };
35041     StateBase.prototype._motionlessTransition = function () {
35042         var nodesSet = this._currentNode != null && this._previousNode != null;
35043         return nodesSet && !(this._currentNode.merged &&
35044             this._previousNode.merged &&
35045             this._withinOriginalDistance() &&
35046             this._sameConnectedComponent());
35047     };
35048     StateBase.prototype._setReference = function (node) {
35049         // do not reset reference if node is within threshold distance
35050         if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
35051             Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
35052             return false;
35053         }
35054         // do not reset reference if previous node exist and transition is with motion
35055         if (this._previousNode != null && !this._motionlessTransition()) {
35056             return false;
35057         }
35058         this._reference.lat = node.latLon.lat;
35059         this._reference.lon = node.latLon.lon;
35060         this._reference.alt = node.alt;
35061         return true;
35062     };
35063     StateBase.prototype._setCurrentNode = function () {
35064         this._currentNode = this._trajectory.length > 0 ?
35065             this._trajectory[this._currentIndex] :
35066             null;
35067         this._previousNode = this._currentIndex > 0 ?
35068             this._trajectory[this._currentIndex - 1] :
35069             null;
35070     };
35071     StateBase.prototype._setTrajectory = function (nodes) {
35072         if (nodes.length < 1) {
35073             throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
35074         }
35075         if (this._currentNode != null) {
35076             this._trajectory = [this._currentNode].concat(nodes);
35077             this._currentIndex = 1;
35078         }
35079         else {
35080             this._trajectory = nodes.slice();
35081             this._currentIndex = 0;
35082         }
35083     };
35084     StateBase.prototype._setTrajectories = function () {
35085         this._trajectoryTransforms.length = 0;
35086         this._trajectoryCameras.length = 0;
35087         this._appendToTrajectories(this._trajectory);
35088     };
35089     StateBase.prototype._appendToTrajectories = function (nodes) {
35090         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
35091             var node = nodes_1[_i];
35092             if (!node.assetsCached) {
35093                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
35094             }
35095             var translation = this._nodeToTranslation(node);
35096             var transform = new Geo_1.Transform(node, node.image, translation);
35097             this._trajectoryTransforms.push(transform);
35098             this._trajectoryCameras.push(new Geo_1.Camera(transform));
35099         }
35100     };
35101     StateBase.prototype._prependToTrajectories = function (nodes) {
35102         for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
35103             var node = _a[_i];
35104             if (!node.assetsCached) {
35105                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
35106             }
35107             var translation = this._nodeToTranslation(node);
35108             var transform = new Geo_1.Transform(node, node.image, translation);
35109             this._trajectoryTransforms.unshift(transform);
35110             this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
35111         }
35112     };
35113     StateBase.prototype._nodeToTranslation = function (node) {
35114         var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
35115         var RC = this._spatial.rotate(C, node.rotation);
35116         return [-RC.x, -RC.y, -RC.z];
35117     };
35118     StateBase.prototype._sameConnectedComponent = function () {
35119         var current = this._currentNode;
35120         var previous = this._previousNode;
35121         if (!current ||
35122             !current.mergeCC ||
35123             !previous ||
35124             !previous.mergeCC) {
35125             return true;
35126         }
35127         return current.mergeCC === previous.mergeCC;
35128     };
35129     StateBase.prototype._withinOriginalDistance = function () {
35130         var current = this._currentNode;
35131         var previous = this._previousNode;
35132         if (!current || !previous) {
35133             return true;
35134         }
35135         // 50 km/h moves 28m in 2s
35136         var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
35137         return distance < 25;
35138     };
35139     return StateBase;
35140 }());
35141 exports.StateBase = StateBase;
35142
35143 },{"../../Error":226,"../../Geo":227}],329:[function(require,module,exports){
35144 /// <reference path="../../../typings/index.d.ts" />
35145 "use strict";
35146 var __extends = (this && this.__extends) || function (d, b) {
35147     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
35148     function __() { this.constructor = d; }
35149     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35150 };
35151 var THREE = require("three");
35152 var UnitBezier = require("unitbezier");
35153 var State_1 = require("../../State");
35154 var RotationDelta = (function () {
35155     function RotationDelta(phi, theta) {
35156         this._phi = phi;
35157         this._theta = theta;
35158     }
35159     Object.defineProperty(RotationDelta.prototype, "phi", {
35160         get: function () {
35161             return this._phi;
35162         },
35163         set: function (value) {
35164             this._phi = value;
35165         },
35166         enumerable: true,
35167         configurable: true
35168     });
35169     Object.defineProperty(RotationDelta.prototype, "theta", {
35170         get: function () {
35171             return this._theta;
35172         },
35173         set: function (value) {
35174             this._theta = value;
35175         },
35176         enumerable: true,
35177         configurable: true
35178     });
35179     Object.defineProperty(RotationDelta.prototype, "isZero", {
35180         get: function () {
35181             return this._phi === 0 && this._theta === 0;
35182         },
35183         enumerable: true,
35184         configurable: true
35185     });
35186     RotationDelta.prototype.copy = function (delta) {
35187         this._phi = delta.phi;
35188         this._theta = delta.theta;
35189     };
35190     RotationDelta.prototype.lerp = function (other, alpha) {
35191         this._phi = (1 - alpha) * this._phi + alpha * other.phi;
35192         this._theta = (1 - alpha) * this._theta + alpha * other.theta;
35193     };
35194     RotationDelta.prototype.multiply = function (value) {
35195         this._phi *= value;
35196         this._theta *= value;
35197     };
35198     RotationDelta.prototype.threshold = function (value) {
35199         this._phi = Math.abs(this._phi) > value ? this._phi : 0;
35200         this._theta = Math.abs(this._theta) > value ? this._theta : 0;
35201     };
35202     RotationDelta.prototype.lengthSquared = function () {
35203         return this._phi * this._phi + this._theta * this._theta;
35204     };
35205     RotationDelta.prototype.reset = function () {
35206         this._phi = 0;
35207         this._theta = 0;
35208     };
35209     return RotationDelta;
35210 }());
35211 var TraversingState = (function (_super) {
35212     __extends(TraversingState, _super);
35213     function TraversingState(state) {
35214         var _this = _super.call(this, state) || this;
35215         _this._adjustCameras();
35216         _this._motionless = _this._motionlessTransition();
35217         _this._baseAlpha = _this._alpha;
35218         _this._animationSpeed = 0.025;
35219         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
35220         _this._useBezier = false;
35221         _this._rotationDelta = new RotationDelta(0, 0);
35222         _this._requestedRotationDelta = null;
35223         _this._basicRotation = [0, 0];
35224         _this._requestedBasicRotation = null;
35225         _this._requestedBasicRotationUnbounded = null;
35226         _this._rotationAcceleration = 0.86;
35227         _this._rotationIncreaseAlpha = 0.97;
35228         _this._rotationDecreaseAlpha = 0.9;
35229         _this._rotationThreshold = 1e-3;
35230         _this._unboundedRotationAlpha = 0.8;
35231         _this._desiredZoom = state.zoom;
35232         _this._minZoom = 0;
35233         _this._maxZoom = 3;
35234         _this._lookatDepth = 10;
35235         _this._desiredLookat = null;
35236         _this._desiredCenter = null;
35237         return _this;
35238     }
35239     TraversingState.prototype.traverse = function () {
35240         throw new Error("Not implemented");
35241     };
35242     TraversingState.prototype.wait = function () {
35243         return new State_1.WaitingState(this);
35244     };
35245     TraversingState.prototype.append = function (nodes) {
35246         var emptyTrajectory = this._trajectory.length === 0;
35247         if (emptyTrajectory) {
35248             this._resetTransition();
35249         }
35250         _super.prototype.append.call(this, nodes);
35251         if (emptyTrajectory) {
35252             this._setDesiredCenter();
35253             this._setDesiredZoom();
35254         }
35255     };
35256     TraversingState.prototype.prepend = function (nodes) {
35257         var emptyTrajectory = this._trajectory.length === 0;
35258         if (emptyTrajectory) {
35259             this._resetTransition();
35260         }
35261         _super.prototype.prepend.call(this, nodes);
35262         if (emptyTrajectory) {
35263             this._setDesiredCenter();
35264             this._setDesiredZoom();
35265         }
35266     };
35267     TraversingState.prototype.set = function (nodes) {
35268         _super.prototype.set.call(this, nodes);
35269         this._desiredLookat = null;
35270         this._resetTransition();
35271         this._clearRotation();
35272         this._setDesiredCenter();
35273         this._setDesiredZoom();
35274         if (this._trajectory.length < 3) {
35275             this._useBezier = true;
35276         }
35277     };
35278     TraversingState.prototype.move = function (delta) {
35279         throw new Error("Not implemented");
35280     };
35281     TraversingState.prototype.moveTo = function (delta) {
35282         throw new Error("Not implemented");
35283     };
35284     TraversingState.prototype.rotate = function (rotationDelta) {
35285         if (this._currentNode == null) {
35286             return;
35287         }
35288         this._desiredZoom = this._zoom;
35289         this._desiredLookat = null;
35290         this._requestedBasicRotation = null;
35291         if (this._requestedRotationDelta != null) {
35292             this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
35293             this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
35294         }
35295         else {
35296             this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
35297         }
35298     };
35299     TraversingState.prototype.rotateBasic = function (basicRotation) {
35300         if (this._currentNode == null) {
35301             return;
35302         }
35303         this._desiredZoom = this._zoom;
35304         this._desiredLookat = null;
35305         this._requestedRotationDelta = null;
35306         if (this._requestedBasicRotation != null) {
35307             this._requestedBasicRotation[0] += basicRotation[0];
35308             this._requestedBasicRotation[1] += basicRotation[1];
35309             var threshold = 0.05 / Math.pow(2, this._zoom);
35310             this._requestedBasicRotation[0] =
35311                 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
35312             this._requestedBasicRotation[1] =
35313                 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
35314         }
35315         else {
35316             this._requestedBasicRotation = basicRotation.slice();
35317         }
35318     };
35319     TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
35320         if (this._currentNode == null) {
35321             return;
35322         }
35323         if (this._requestedBasicRotationUnbounded != null) {
35324             this._requestedBasicRotationUnbounded[0] += basicRotation[0];
35325             this._requestedBasicRotationUnbounded[1] += basicRotation[1];
35326         }
35327         else {
35328             this._requestedBasicRotationUnbounded = basicRotation.slice();
35329         }
35330     };
35331     TraversingState.prototype.rotateToBasic = function (basic) {
35332         if (this._currentNode == null) {
35333             return;
35334         }
35335         this._desiredZoom = this._zoom;
35336         this._desiredLookat = null;
35337         basic[0] = this._spatial.clamp(basic[0], 0, 1);
35338         basic[1] = this._spatial.clamp(basic[1], 0, 1);
35339         var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
35340         this._currentCamera.lookat.fromArray(lookat);
35341     };
35342     TraversingState.prototype.zoomIn = function (delta, reference) {
35343         if (this._currentNode == null) {
35344             return;
35345         }
35346         this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
35347         var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
35348         var currentCenterX = currentCenter[0];
35349         var currentCenterY = currentCenter[1];
35350         var zoom0 = Math.pow(2, this._zoom);
35351         var zoom1 = Math.pow(2, this._desiredZoom);
35352         var refX = reference[0];
35353         var refY = reference[1];
35354         if (this.currentTransform.gpano != null &&
35355             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
35356             if (refX - currentCenterX > 0.5) {
35357                 refX = refX - 1;
35358             }
35359             else if (currentCenterX - refX > 0.5) {
35360                 refX = 1 + refX;
35361             }
35362         }
35363         var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
35364         var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
35365         var gpano = this.currentTransform.gpano;
35366         if (this._currentNode.fullPano) {
35367             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
35368             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
35369         }
35370         else if (gpano != null &&
35371             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
35372             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
35373             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
35374         }
35375         else {
35376             newCenterX = this._spatial.clamp(newCenterX, 0, 1);
35377             newCenterY = this._spatial.clamp(newCenterY, 0, 1);
35378         }
35379         this._desiredLookat = new THREE.Vector3()
35380             .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
35381     };
35382     TraversingState.prototype.setCenter = function (center) {
35383         this._desiredLookat = null;
35384         this._requestedRotationDelta = null;
35385         this._requestedBasicRotation = null;
35386         this._desiredZoom = this._zoom;
35387         var clamped = [
35388             this._spatial.clamp(center[0], 0, 1),
35389             this._spatial.clamp(center[1], 0, 1),
35390         ];
35391         if (this._currentNode == null) {
35392             this._desiredCenter = clamped;
35393             return;
35394         }
35395         this._desiredCenter = null;
35396         var currentLookat = new THREE.Vector3()
35397             .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
35398         var previousTransform = this.previousTransform != null ?
35399             this.previousTransform :
35400             this.currentTransform;
35401         var previousLookat = new THREE.Vector3()
35402             .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
35403         this._currentCamera.lookat.copy(currentLookat);
35404         this._previousCamera.lookat.copy(previousLookat);
35405     };
35406     TraversingState.prototype.setZoom = function (zoom) {
35407         this._desiredLookat = null;
35408         this._requestedRotationDelta = null;
35409         this._requestedBasicRotation = null;
35410         this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
35411         this._desiredZoom = this._zoom;
35412     };
35413     TraversingState.prototype.update = function (fps) {
35414         if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
35415             this._currentIndex += 1;
35416             this._useBezier = this._trajectory.length < 3 &&
35417                 this._currentIndex + 1 === this._trajectory.length;
35418             this._setCurrent();
35419             this._resetTransition();
35420             this._clearRotation();
35421             this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
35422             this._desiredLookat = null;
35423         }
35424         var animationSpeed = this._animationSpeed * (60 / fps);
35425         this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed);
35426         if (this._useBezier) {
35427             this._alpha = this._unitBezier.solve(this._baseAlpha);
35428         }
35429         else {
35430             this._alpha = this._baseAlpha;
35431         }
35432         this._updateRotation();
35433         if (!this._rotationDelta.isZero) {
35434             this._applyRotation(this._previousCamera);
35435             this._applyRotation(this._currentCamera);
35436         }
35437         this._updateRotationBasic();
35438         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
35439             this._applyRotationBasic();
35440         }
35441         this._updateZoom(animationSpeed);
35442         this._updateLookat(animationSpeed);
35443         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
35444     };
35445     TraversingState.prototype._getAlpha = function () {
35446         return this._motionless ? Math.ceil(this._alpha) : this._alpha;
35447     };
35448     TraversingState.prototype._setCurrentCamera = function () {
35449         _super.prototype._setCurrentCamera.call(this);
35450         this._adjustCameras();
35451     };
35452     TraversingState.prototype._adjustCameras = function () {
35453         if (this._previousNode == null) {
35454             return;
35455         }
35456         var lookat = this._camera.lookat.clone().sub(this._camera.position);
35457         this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
35458         if (this._currentNode.fullPano) {
35459             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
35460         }
35461     };
35462     TraversingState.prototype._resetTransition = function () {
35463         this._alpha = 0;
35464         this._baseAlpha = 0;
35465         this._motionless = this._motionlessTransition();
35466     };
35467     TraversingState.prototype._applyRotation = function (camera) {
35468         if (camera == null) {
35469             return;
35470         }
35471         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
35472         var qInverse = q.clone().inverse();
35473         var offset = new THREE.Vector3();
35474         offset.copy(camera.lookat).sub(camera.position);
35475         offset.applyQuaternion(q);
35476         var length = offset.length();
35477         var phi = Math.atan2(offset.y, offset.x);
35478         phi += this._rotationDelta.phi;
35479         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
35480         theta += this._rotationDelta.theta;
35481         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
35482         offset.x = Math.sin(theta) * Math.cos(phi);
35483         offset.y = Math.sin(theta) * Math.sin(phi);
35484         offset.z = Math.cos(theta);
35485         offset.applyQuaternion(qInverse);
35486         camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
35487     };
35488     TraversingState.prototype._applyRotationBasic = function () {
35489         var currentNode = this._currentNode;
35490         var previousNode = this._previousNode != null ?
35491             this.previousNode :
35492             this.currentNode;
35493         var currentCamera = this._currentCamera;
35494         var previousCamera = this._previousCamera;
35495         var currentTransform = this.currentTransform;
35496         var previousTransform = this.previousTransform != null ?
35497             this.previousTransform :
35498             this.currentTransform;
35499         var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
35500         var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
35501         var currentGPano = currentTransform.gpano;
35502         var previousGPano = previousTransform.gpano;
35503         if (currentNode.fullPano) {
35504             currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
35505             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0.05, 0.95);
35506         }
35507         else if (currentGPano != null &&
35508             currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
35509             currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
35510             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
35511         }
35512         else {
35513             currentBasic[0] = this._spatial.clamp(currentBasic[0] + this._basicRotation[0], 0, 1);
35514             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
35515         }
35516         if (previousNode.fullPano) {
35517             previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
35518             previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0.05, 0.95);
35519         }
35520         else if (previousGPano != null &&
35521             previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
35522             previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
35523             previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0, 1);
35524         }
35525         else {
35526             previousBasic[0] = this._spatial.clamp(previousBasic[0] + this._basicRotation[0], 0, 1);
35527             previousBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
35528         }
35529         var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
35530         currentCamera.lookat.fromArray(currentLookat);
35531         var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
35532         previousCamera.lookat.fromArray(previousLookat);
35533     };
35534     TraversingState.prototype._updateZoom = function (animationSpeed) {
35535         var diff = this._desiredZoom - this._zoom;
35536         var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
35537         if (diff === 0) {
35538             return;
35539         }
35540         else if (Math.abs(diff) < 2e-3) {
35541             this._zoom = this._desiredZoom;
35542             if (this._desiredLookat != null) {
35543                 this._desiredLookat = null;
35544             }
35545         }
35546         else {
35547             this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
35548         }
35549     };
35550     TraversingState.prototype._updateLookat = function (animationSpeed) {
35551         if (this._desiredLookat === null) {
35552             return;
35553         }
35554         var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
35555         if (Math.abs(diff) < 1e-6) {
35556             this._currentCamera.lookat.copy(this._desiredLookat);
35557             this._desiredLookat = null;
35558         }
35559         else {
35560             this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
35561         }
35562     };
35563     TraversingState.prototype._updateRotation = function () {
35564         if (this._requestedRotationDelta != null) {
35565             var length_1 = this._rotationDelta.lengthSquared();
35566             var requestedLength = this._requestedRotationDelta.lengthSquared();
35567             if (requestedLength > length_1) {
35568                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
35569             }
35570             else {
35571                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
35572             }
35573             this._requestedRotationDelta = null;
35574             return;
35575         }
35576         if (this._rotationDelta.isZero) {
35577             return;
35578         }
35579         this._rotationDelta.multiply(this._rotationAcceleration);
35580         this._rotationDelta.threshold(this._rotationThreshold);
35581     };
35582     TraversingState.prototype._updateRotationBasic = function () {
35583         if (this._requestedBasicRotation != null) {
35584             var x = this._basicRotation[0];
35585             var y = this._basicRotation[1];
35586             var reqX = this._requestedBasicRotation[0];
35587             var reqY = this._requestedBasicRotation[1];
35588             if (Math.abs(reqX) > Math.abs(x)) {
35589                 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
35590             }
35591             else {
35592                 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
35593             }
35594             if (Math.abs(reqY) > Math.abs(y)) {
35595                 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
35596             }
35597             else {
35598                 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
35599             }
35600             this._requestedBasicRotation = null;
35601             return;
35602         }
35603         if (this._requestedBasicRotationUnbounded != null) {
35604             var reqX = this._requestedBasicRotationUnbounded[0];
35605             var reqY = this._requestedBasicRotationUnbounded[1];
35606             if (Math.abs(reqX) > 0) {
35607                 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
35608             }
35609             if (Math.abs(reqY) > 0) {
35610                 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
35611             }
35612             if (this._desiredLookat != null) {
35613                 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
35614                 desiredBasicLookat[0] += reqX;
35615                 desiredBasicLookat[1] += reqY;
35616                 this._desiredLookat = new THREE.Vector3()
35617                     .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
35618             }
35619             this._requestedBasicRotationUnbounded = null;
35620         }
35621         if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
35622             return;
35623         }
35624         this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
35625         this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
35626         if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
35627             Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
35628             this._basicRotation = [0, 0];
35629         }
35630     };
35631     TraversingState.prototype._clearRotation = function () {
35632         if (this._currentNode.fullPano) {
35633             return;
35634         }
35635         if (this._requestedRotationDelta != null) {
35636             this._requestedRotationDelta = null;
35637         }
35638         if (!this._rotationDelta.isZero) {
35639             this._rotationDelta.reset();
35640         }
35641         if (this._requestedBasicRotation != null) {
35642             this._requestedBasicRotation = null;
35643         }
35644         if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
35645             this._basicRotation = [0, 0];
35646         }
35647     };
35648     TraversingState.prototype._setDesiredCenter = function () {
35649         if (this._desiredCenter == null) {
35650             return;
35651         }
35652         var lookatDirection = new THREE.Vector3()
35653             .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
35654             .sub(this._currentCamera.position);
35655         this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
35656         this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
35657         this._desiredCenter = null;
35658     };
35659     TraversingState.prototype._setDesiredZoom = function () {
35660         this._desiredZoom =
35661             this._currentNode.fullPano || this._previousNode == null ?
35662                 this._zoom : 0;
35663     };
35664     return TraversingState;
35665 }(State_1.StateBase));
35666 exports.TraversingState = TraversingState;
35667
35668 },{"../../State":231,"three":174,"unitbezier":176}],330:[function(require,module,exports){
35669 "use strict";
35670 var __extends = (this && this.__extends) || function (d, b) {
35671     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
35672     function __() { this.constructor = d; }
35673     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35674 };
35675 var State_1 = require("../../State");
35676 var WaitingState = (function (_super) {
35677     __extends(WaitingState, _super);
35678     function WaitingState(state) {
35679         var _this = _super.call(this, state) || this;
35680         _this._adjustCameras();
35681         _this._motionless = _this._motionlessTransition();
35682         return _this;
35683     }
35684     WaitingState.prototype.traverse = function () {
35685         return new State_1.TraversingState(this);
35686     };
35687     WaitingState.prototype.wait = function () {
35688         throw new Error("Not implemented");
35689     };
35690     WaitingState.prototype.prepend = function (nodes) {
35691         _super.prototype.prepend.call(this, nodes);
35692         this._motionless = this._motionlessTransition();
35693     };
35694     WaitingState.prototype.set = function (nodes) {
35695         _super.prototype.set.call(this, nodes);
35696         this._motionless = this._motionlessTransition();
35697     };
35698     WaitingState.prototype.rotate = function (delta) { return; };
35699     WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
35700     WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
35701     WaitingState.prototype.rotateToBasic = function (basic) { return; };
35702     WaitingState.prototype.zoomIn = function (delta, reference) { return; };
35703     WaitingState.prototype.move = function (delta) {
35704         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
35705     };
35706     WaitingState.prototype.moveTo = function (position) {
35707         this._alpha = Math.max(0, Math.min(1, position));
35708     };
35709     WaitingState.prototype.update = function (fps) {
35710         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
35711     };
35712     WaitingState.prototype.setCenter = function (center) { return; };
35713     WaitingState.prototype.setZoom = function (zoom) { return; };
35714     WaitingState.prototype._getAlpha = function () {
35715         return this._motionless ? Math.round(this._alpha) : this._alpha;
35716     };
35717     ;
35718     WaitingState.prototype._setCurrentCamera = function () {
35719         _super.prototype._setCurrentCamera.call(this);
35720         this._adjustCameras();
35721     };
35722     WaitingState.prototype._adjustCameras = function () {
35723         if (this._previousNode == null) {
35724             return;
35725         }
35726         if (this._currentNode.fullPano) {
35727             var lookat = this._camera.lookat.clone().sub(this._camera.position);
35728             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
35729         }
35730         if (this._previousNode.fullPano) {
35731             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
35732             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
35733         }
35734     };
35735     return WaitingState;
35736 }(State_1.StateBase));
35737 exports.WaitingState = WaitingState;
35738
35739 },{"../../State":231}],331:[function(require,module,exports){
35740 "use strict";
35741 var Observable_1 = require("rxjs/Observable");
35742 /**
35743  * @class ImageTileLoader
35744  *
35745  * @classdesc Represents a loader of image tiles.
35746  */
35747 var ImageTileLoader = (function () {
35748     /**
35749      * Create a new node image tile loader instance.
35750      *
35751      * @param {string} scheme - The URI scheme.
35752      * @param {string} host - The URI host.
35753      * @param {string} [origin] - The origin query param.
35754      */
35755     function ImageTileLoader(scheme, host, origin) {
35756         this._scheme = scheme;
35757         this._host = host;
35758         this._origin = origin != null ? "?origin=" + origin : "";
35759     }
35760     /**
35761      * Retrieve an image tile.
35762      *
35763      * @description Retrieve an image tile by specifying the area
35764      * as well as the scaled size.
35765      *
35766      * @param {string} identifier - The identifier of the image.
35767      * @param {number} x - The top left x pixel coordinate for the tile
35768      * in the original image.
35769      * @param {number} y - The top left y pixel coordinate for the tile
35770      * in the original image.
35771      * @param {number} w - The pixel width of the tile in the original image.
35772      * @param {number} h - The pixel height of the tile in the original image.
35773      * @param {number} scaledW - The scaled width of the returned tile.
35774      * @param {number} scaledH - The scaled height of the returned tile.
35775      */
35776     ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
35777         var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
35778         var url = this._scheme +
35779             "://" +
35780             this._host +
35781             characteristics +
35782             this._origin;
35783         var xmlHTTP = null;
35784         return [Observable_1.Observable.create(function (subscriber) {
35785                 xmlHTTP = new XMLHttpRequest();
35786                 xmlHTTP.open("GET", url, true);
35787                 xmlHTTP.responseType = "arraybuffer";
35788                 xmlHTTP.timeout = 15000;
35789                 xmlHTTP.onload = function (event) {
35790                     if (xmlHTTP.status !== 200) {
35791                         subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
35792                             ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
35793                         return;
35794                     }
35795                     var image = new Image();
35796                     image.crossOrigin = "Anonymous";
35797                     image.onload = function (e) {
35798                         subscriber.next(image);
35799                         subscriber.complete();
35800                     };
35801                     image.onerror = function (error) {
35802                         subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
35803                     };
35804                     var blob = new Blob([xmlHTTP.response]);
35805                     image.src = window.URL.createObjectURL(blob);
35806                 };
35807                 xmlHTTP.onerror = function (error) {
35808                     subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
35809                 };
35810                 xmlHTTP.ontimeout = function (error) {
35811                     subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
35812                 };
35813                 xmlHTTP.onabort = function (event) {
35814                     subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
35815                 };
35816                 xmlHTTP.send(null);
35817             }),
35818             function () {
35819                 if (xmlHTTP != null) {
35820                     xmlHTTP.abort();
35821                 }
35822             },
35823         ];
35824     };
35825     return ImageTileLoader;
35826 }());
35827 exports.ImageTileLoader = ImageTileLoader;
35828 Object.defineProperty(exports, "__esModule", { value: true });
35829 exports.default = ImageTileLoader;
35830
35831 },{"rxjs/Observable":28}],332:[function(require,module,exports){
35832 "use strict";
35833 /**
35834  * @class ImageTileStore
35835  *
35836  * @classdesc Represents a store for image tiles.
35837  */
35838 var ImageTileStore = (function () {
35839     /**
35840      * Create a new node image tile store instance.
35841      */
35842     function ImageTileStore() {
35843         this._images = {};
35844     }
35845     /**
35846      * Add an image tile to the store.
35847      *
35848      * @param {HTMLImageElement} image - The image tile.
35849      * @param {string} key - The identifier for the tile.
35850      * @param {number} level - The level of the tile.
35851      */
35852     ImageTileStore.prototype.addImage = function (image, key, level) {
35853         if (!(level in this._images)) {
35854             this._images[level] = {};
35855         }
35856         this._images[level][key] = image;
35857     };
35858     /**
35859      * Dispose the store.
35860      *
35861      * @description Disposes all cached assets.
35862      */
35863     ImageTileStore.prototype.dispose = function () {
35864         for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
35865             var level = _a[_i];
35866             var levelImages = this._images[level];
35867             for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
35868                 var key = _c[_b];
35869                 window.URL.revokeObjectURL(levelImages[key].src);
35870                 delete levelImages[key];
35871             }
35872             delete this._images[level];
35873         }
35874     };
35875     /**
35876      * Get an image tile from the store.
35877      *
35878      * @param {string} key - The identifier for the tile.
35879      * @param {number} level - The level of the tile.
35880      */
35881     ImageTileStore.prototype.getImage = function (key, level) {
35882         return this._images[level][key];
35883     };
35884     /**
35885      * Check if an image tile exist in the store.
35886      *
35887      * @param {string} key - The identifier for the tile.
35888      * @param {number} level - The level of the tile.
35889      */
35890     ImageTileStore.prototype.hasImage = function (key, level) {
35891         return level in this._images && key in this._images[level];
35892     };
35893     return ImageTileStore;
35894 }());
35895 exports.ImageTileStore = ImageTileStore;
35896 Object.defineProperty(exports, "__esModule", { value: true });
35897 exports.default = ImageTileStore;
35898
35899 },{}],333:[function(require,module,exports){
35900 /// <reference path="../../typings/index.d.ts" />
35901 "use strict";
35902 var Geo_1 = require("../Geo");
35903 /**
35904  * @class RegionOfInterestCalculator
35905  *
35906  * @classdesc Represents a calculator for regions of interest.
35907  */
35908 var RegionOfInterestCalculator = (function () {
35909     function RegionOfInterestCalculator() {
35910         this._viewportCoords = new Geo_1.ViewportCoords();
35911     }
35912     /**
35913      * Compute a region of interest based on the current render camera
35914      * and the viewport size.
35915      *
35916      * @param {RenderCamera} renderCamera - Render camera used for unprojections.
35917      * @param {ISize} size - Viewport size in pixels.
35918      * @param {Transform} transform - Transform used for projections.
35919      *
35920      * @returns {IRegionOfInterest} A region of interest.
35921      */
35922     RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
35923         var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
35924         var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
35925         this._clipBoundingBox(bbox);
35926         var viewportPixelWidth = 2 / size.width;
35927         var viewportPixelHeight = 2 / size.height;
35928         var centralViewportPixel = [
35929             [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
35930             [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
35931             [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
35932             [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
35933         ];
35934         var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
35935         return {
35936             bbox: bbox,
35937             pixelHeight: cpbox.maxY - cpbox.minY,
35938             pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
35939         };
35940     };
35941     RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
35942         var points = [];
35943         var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
35944         var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
35945         for (var side = 0; side < 4; ++side) {
35946             var o = os[side];
35947             var d = ds[side];
35948             for (var i = 0; i < pointsPerSide; ++i) {
35949                 points.push([o[0] + d[0] * i / pointsPerSide,
35950                     o[1] + d[1] * i / pointsPerSide]);
35951             }
35952         }
35953         return points;
35954     };
35955     RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
35956         var _this = this;
35957         var basicPoints = viewportPoints
35958             .map(function (point) {
35959             return _this._viewportCoords
35960                 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
35961         });
35962         if (transform.gpano != null) {
35963             return this._boundingBoxPano(basicPoints);
35964         }
35965         else {
35966             return this._boundingBox(basicPoints);
35967         }
35968     };
35969     RegionOfInterestCalculator.prototype._boundingBox = function (points) {
35970         var bbox = {
35971             maxX: Number.NEGATIVE_INFINITY,
35972             maxY: Number.NEGATIVE_INFINITY,
35973             minX: Number.POSITIVE_INFINITY,
35974             minY: Number.POSITIVE_INFINITY,
35975         };
35976         for (var i = 0; i < points.length; ++i) {
35977             bbox.minX = Math.min(bbox.minX, points[i][0]);
35978             bbox.maxX = Math.max(bbox.maxX, points[i][0]);
35979             bbox.minY = Math.min(bbox.minY, points[i][1]);
35980             bbox.maxY = Math.max(bbox.maxY, points[i][1]);
35981         }
35982         return bbox;
35983     };
35984     RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
35985         var _this = this;
35986         var xs = [];
35987         var ys = [];
35988         for (var i = 0; i < points.length; ++i) {
35989             xs.push(points[i][0]);
35990             ys.push(points[i][1]);
35991         }
35992         xs.sort(function (a, b) { return _this._sign(a - b); });
35993         ys.sort(function (a, b) { return _this._sign(a - b); });
35994         var intervalX = this._intervalPano(xs);
35995         return {
35996             maxX: intervalX[1],
35997             maxY: ys[ys.length - 1],
35998             minX: intervalX[0],
35999             minY: ys[0],
36000         };
36001     };
36002     /**
36003      * Find the max interval between consecutive numbers.
36004      * Assumes numbers are between 0 and 1, sorted and that
36005      * x is equivalent to x + 1.
36006      */
36007     RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
36008         var maxdx = 0;
36009         var maxi = -1;
36010         for (var i = 0; i < xs.length - 1; ++i) {
36011             var dx = xs[i + 1] - xs[i];
36012             if (dx > maxdx) {
36013                 maxdx = dx;
36014                 maxi = i;
36015             }
36016         }
36017         var loopdx = xs[0] + 1 - xs[xs.length - 1];
36018         if (loopdx > maxdx) {
36019             return [xs[0], xs[xs.length - 1]];
36020         }
36021         else {
36022             return [xs[maxi + 1], xs[maxi]];
36023         }
36024     };
36025     RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
36026         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
36027         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
36028         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
36029         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
36030     };
36031     RegionOfInterestCalculator.prototype._sign = function (n) {
36032         return n > 0 ? 1 : n < 0 ? -1 : 0;
36033     };
36034     return RegionOfInterestCalculator;
36035 }());
36036 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
36037 Object.defineProperty(exports, "__esModule", { value: true });
36038 exports.default = RegionOfInterestCalculator;
36039
36040 },{"../Geo":227}],334:[function(require,module,exports){
36041 /// <reference path="../../typings/index.d.ts" />
36042 "use strict";
36043 var THREE = require("three");
36044 var Subject_1 = require("rxjs/Subject");
36045 /**
36046  * @class TextureProvider
36047  *
36048  * @classdesc Represents a provider of textures.
36049  */
36050 var TextureProvider = (function () {
36051     /**
36052      * Create a new node texture provider instance.
36053      *
36054      * @param {string} key - The identifier of the image for which to request tiles.
36055      * @param {number} width - The full width of the original image.
36056      * @param {number} height - The full height of the original image.
36057      * @param {number} tileSize - The size used when requesting tiles.
36058      * @param {HTMLImageElement} background - Image to use as background.
36059      * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
36060      * @param {ImageTileStore} imageTileStore - Store for saving tiles.
36061      * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
36062      */
36063     function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
36064         this._disposed = false;
36065         this._key = key;
36066         if (width <= 0 || height <= 0) {
36067             console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
36068         }
36069         this._width = width;
36070         this._height = height;
36071         this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
36072         this._currentLevel = -1;
36073         this._tileSize = tileSize;
36074         this._updated$ = new Subject_1.Subject();
36075         this._createdSubject$ = new Subject_1.Subject();
36076         this._created$ = this._createdSubject$
36077             .publishReplay(1)
36078             .refCount();
36079         this._createdSubscription = this._created$.subscribe(function () { });
36080         this._hasSubject$ = new Subject_1.Subject();
36081         this._has$ = this._hasSubject$
36082             .startWith(false)
36083             .publishReplay(1)
36084             .refCount();
36085         this._hasSubscription = this._has$.subscribe(function () { });
36086         this._abortFunctions = [];
36087         this._tileSubscriptions = {};
36088         this._renderedCurrentLevelTiles = {};
36089         this._renderedTiles = {};
36090         this._background = background;
36091         this._camera = null;
36092         this._imageTileLoader = imageTileLoader;
36093         this._imageTileStore = imageTileStore;
36094         this._renderer = renderer;
36095         this._renderTarget = null;
36096         this._roi = null;
36097     }
36098     Object.defineProperty(TextureProvider.prototype, "disposed", {
36099         /**
36100          * Get disposed.
36101          *
36102          * @returns {boolean} Value indicating whether provider has
36103          * been disposed.
36104          */
36105         get: function () {
36106             return this._disposed;
36107         },
36108         enumerable: true,
36109         configurable: true
36110     });
36111     Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
36112         /**
36113          * Get hasTexture$.
36114          *
36115          * @returns {Observable<boolean>} Observable emitting
36116          * values indicating when the existance of a texture
36117          * changes.
36118          */
36119         get: function () {
36120             return this._has$;
36121         },
36122         enumerable: true,
36123         configurable: true
36124     });
36125     Object.defineProperty(TextureProvider.prototype, "key", {
36126         /**
36127          * Get key.
36128          *
36129          * @returns {boolean} The identifier of the image for
36130          * which to render textures.
36131          */
36132         get: function () {
36133             return this._key;
36134         },
36135         enumerable: true,
36136         configurable: true
36137     });
36138     Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
36139         /**
36140          * Get textureUpdated$.
36141          *
36142          * @returns {Observable<boolean>} Observable emitting
36143          * values when an existing texture has been updated.
36144          */
36145         get: function () {
36146             return this._updated$;
36147         },
36148         enumerable: true,
36149         configurable: true
36150     });
36151     Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
36152         /**
36153          * Get textureCreated$.
36154          *
36155          * @returns {Observable<boolean>} Observable emitting
36156          * values when a new texture has been created.
36157          */
36158         get: function () {
36159             return this._created$;
36160         },
36161         enumerable: true,
36162         configurable: true
36163     });
36164     /**
36165      * Abort all outstanding image tile requests.
36166      */
36167     TextureProvider.prototype.abort = function () {
36168         for (var key in this._tileSubscriptions) {
36169             if (!this._tileSubscriptions.hasOwnProperty(key)) {
36170                 continue;
36171             }
36172             this._tileSubscriptions[key].unsubscribe();
36173         }
36174         this._tileSubscriptions = {};
36175         for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
36176             var abort = _a[_i];
36177             abort();
36178         }
36179         this._abortFunctions = [];
36180     };
36181     /**
36182      * Dispose the provider.
36183      *
36184      * @description Disposes all cached assets and
36185      * aborts all outstanding image tile requests.
36186      */
36187     TextureProvider.prototype.dispose = function () {
36188         if (this._disposed) {
36189             console.warn("Texture already disposed (" + this._key + ")");
36190             return;
36191         }
36192         this.abort();
36193         if (this._renderTarget != null) {
36194             this._renderTarget.dispose();
36195             this._renderTarget = null;
36196         }
36197         this._imageTileStore.dispose();
36198         this._imageTileStore = null;
36199         this._background = null;
36200         this._camera = null;
36201         this._imageTileLoader = null;
36202         this._renderer = null;
36203         this._roi = null;
36204         this._createdSubscription.unsubscribe();
36205         this._hasSubscription.unsubscribe();
36206         this._disposed = true;
36207     };
36208     /**
36209      * Set the region of interest.
36210      *
36211      * @description When the region of interest is set the
36212      * the tile level is determined and tiles for the region
36213      * are fetched from the store or the loader and renderedLevel
36214      * to the texture.
36215      *
36216      * @param {IRegionOfInterest} roi - Spatial edges to cache.
36217      */
36218     TextureProvider.prototype.setRegionOfInterest = function (roi) {
36219         if (this._width <= 0 || this._height <= 0) {
36220             return;
36221         }
36222         this._roi = roi;
36223         var width = 1 / this._roi.pixelWidth;
36224         var height = 1 / this._roi.pixelHeight;
36225         var size = Math.max(height, width);
36226         var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.round(Math.log(size) / Math.log(2))));
36227         if (currentLevel !== this._currentLevel) {
36228             this.abort();
36229             this._currentLevel = currentLevel;
36230             if (!(this._currentLevel in this._renderedTiles)) {
36231                 this._renderedTiles[this._currentLevel] = [];
36232             }
36233             this._renderedCurrentLevelTiles = {};
36234             for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
36235                 var tile = _a[_i];
36236                 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
36237             }
36238         }
36239         var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
36240         var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
36241         var tiles = this._getTiles(topLeft, bottomRight);
36242         if (this._camera == null) {
36243             this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
36244             this._camera.position.z = 1;
36245             var gl = this._renderer.getContext();
36246             var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
36247             var backgroundSize = Math.max(this._width, this._height);
36248             var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
36249             var targetWidth = Math.floor(scale * this._width);
36250             var targetHeight = Math.floor(scale * this._height);
36251             this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
36252                 depthBuffer: false,
36253                 format: THREE.RGBFormat,
36254                 magFilter: THREE.LinearFilter,
36255                 minFilter: THREE.LinearFilter,
36256                 stencilBuffer: false,
36257             });
36258             this._renderToTarget(0, 0, this._width, this._height, this._background);
36259             this._createdSubject$.next(this._renderTarget.texture);
36260             this._hasSubject$.next(true);
36261         }
36262         this._fetchTiles(tiles);
36263     };
36264     /**
36265      * Update the image used as background for the texture.
36266      *
36267      * @param {HTMLImageElement} background - The background image.
36268      */
36269     TextureProvider.prototype.updateBackground = function (background) {
36270         this._background = background;
36271     };
36272     /**
36273      * Retrieve an image tile.
36274      *
36275      * @description Retrieve an image tile and render it to the
36276      * texture. Add the tile to the store and emit to the updated
36277      * observable.
36278      *
36279      * @param {Array<number>} tile - The tile coordinates.
36280      * @param {number} level - The tile level.
36281      * @param {number} x - The top left x pixel coordinate of the tile.
36282      * @param {number} y - The top left y pixel coordinate of the tile.
36283      * @param {number} w - The pixel width of the tile.
36284      * @param {number} h - The pixel height of the tile.
36285      * @param {number} scaledW - The scaled width of the returned tile.
36286      * @param {number} scaledH - The scaled height of the returned tile.
36287      */
36288     TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
36289         var _this = this;
36290         var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
36291         var tile$ = getTile[0];
36292         var abort = getTile[1];
36293         this._abortFunctions.push(abort);
36294         var tileKey = this._tileKey(tile);
36295         var subscription = tile$
36296             .subscribe(function (image) {
36297             _this._renderToTarget(x, y, w, h, image);
36298             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
36299             _this._removeFromArray(abort, _this._abortFunctions);
36300             _this._setTileRendered(tile, _this._currentLevel);
36301             _this._imageTileStore.addImage(image, tileKey, level);
36302             _this._updated$.next(true);
36303         }, function (error) {
36304             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
36305             _this._removeFromArray(abort, _this._abortFunctions);
36306             console.error(error);
36307         });
36308         if (!subscription.closed) {
36309             this._tileSubscriptions[tileKey] = subscription;
36310         }
36311     };
36312     /**
36313      * Retrieve image tiles.
36314      *
36315      * @description Retrieve a image tiles and render them to the
36316      * texture. Retrieve from store if it exists, otherwise Retrieve
36317      * from loader.
36318      *
36319      * @param {Array<Array<number>>} tiles - Array of tile coordinates to
36320      * retrieve.
36321      */
36322     TextureProvider.prototype._fetchTiles = function (tiles) {
36323         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
36324         for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
36325             var tile = tiles_1[_i];
36326             var tileKey = this._tileKey(tile);
36327             if (tileKey in this._renderedCurrentLevelTiles ||
36328                 tileKey in this._tileSubscriptions) {
36329                 continue;
36330             }
36331             var tileX = tileSize * tile[0];
36332             var tileY = tileSize * tile[1];
36333             var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
36334             var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
36335             if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
36336                 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
36337                 this._setTileRendered(tile, this._currentLevel);
36338                 this._updated$.next(true);
36339                 continue;
36340             }
36341             var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
36342             var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
36343             this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
36344         }
36345     };
36346     /**
36347      * Get tile coordinates for a point using the current level.
36348      *
36349      * @param {Array<number>} point - Point in basic coordinates.
36350      *
36351      * @returns {Array<number>} x and y tile coodinates.
36352      */
36353     TextureProvider.prototype._getTileCoords = function (point) {
36354         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
36355         var maxX = Math.ceil(this._width / tileSize) - 1;
36356         var maxY = Math.ceil(this._height / tileSize) - 1;
36357         return [
36358             Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
36359             Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
36360         ];
36361     };
36362     /**
36363      * Get tile coordinates for all tiles contained in a bounding
36364      * box.
36365      *
36366      * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
36367      * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
36368      *
36369      * @returns {Array<Array<number>>} Array of x, y tile coodinates.
36370      */
36371     TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
36372         var xs = [];
36373         if (topLeft[0] > bottomRight[0]) {
36374             var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
36375             var maxX = Math.ceil(this._width / tileSize) - 1;
36376             for (var x = topLeft[0]; x <= maxX; x++) {
36377                 xs.push(x);
36378             }
36379             for (var x = 0; x <= bottomRight[0]; x++) {
36380                 xs.push(x);
36381             }
36382         }
36383         else {
36384             for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
36385                 xs.push(x);
36386             }
36387         }
36388         var tiles = [];
36389         for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
36390             var x = xs_1[_i];
36391             for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
36392                 tiles.push([x, y]);
36393             }
36394         }
36395         return tiles;
36396     };
36397     /**
36398      * Remove an item from an array if it exists in array.
36399      *
36400      * @param {T} item - Item to remove.
36401      * @param {Array<T>} array - Array from which item should be removed.
36402      */
36403     TextureProvider.prototype._removeFromArray = function (item, array) {
36404         var index = array.indexOf(item);
36405         if (index !== -1) {
36406             array.splice(index, 1);
36407         }
36408     };
36409     /**
36410      * Remove an item from a dictionary.
36411      *
36412      * @param {string} key - Key of the item to remove.
36413      * @param {Object} dict - Dictionary from which item should be removed.
36414      */
36415     TextureProvider.prototype._removeFromDictionary = function (key, dict) {
36416         if (key in dict) {
36417             delete dict[key];
36418         }
36419     };
36420     /**
36421      * Render an image tile to the target texture.
36422      *
36423      * @param {number} x - The top left x pixel coordinate of the tile.
36424      * @param {number} y - The top left y pixel coordinate of the tile.
36425      * @param {number} w - The pixel width of the tile.
36426      * @param {number} h - The pixel height of the tile.
36427      * @param {HTMLImageElement} background - The image tile to render.
36428      */
36429     TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
36430         var texture = new THREE.Texture(image);
36431         texture.minFilter = THREE.LinearFilter;
36432         texture.needsUpdate = true;
36433         var geometry = new THREE.PlaneGeometry(w, h);
36434         var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
36435         var mesh = new THREE.Mesh(geometry, material);
36436         mesh.position.x = -this._width / 2 + x + w / 2;
36437         mesh.position.y = this._height / 2 - y - h / 2;
36438         var scene = new THREE.Scene();
36439         scene.add(mesh);
36440         this._renderer.render(scene, this._camera, this._renderTarget);
36441         this._renderer.setRenderTarget(undefined);
36442         scene.remove(mesh);
36443         geometry.dispose();
36444         material.dispose();
36445         texture.dispose();
36446     };
36447     /**
36448      * Mark a tile as rendered.
36449      *
36450      * @description Clears tiles marked as rendered in other
36451      * levels of the tile pyramid  if they were rendered on
36452      * top of or below the tile.
36453      *
36454      * @param {Arrary<number>} tile - The tile coordinates.
36455      * @param {number} level - Tile level of the tile coordinates.
36456      */
36457     TextureProvider.prototype._setTileRendered = function (tile, level) {
36458         var otherLevels = Object.keys(this._renderedTiles)
36459             .map(function (key) {
36460             return parseInt(key, 10);
36461         })
36462             .filter(function (renderedLevel) {
36463             return renderedLevel !== level;
36464         });
36465         for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
36466             var otherLevel = otherLevels_1[_i];
36467             var scale = Math.pow(2, otherLevel - level);
36468             if (otherLevel < level) {
36469                 var x = Math.floor(scale * tile[0]);
36470                 var y = Math.floor(scale * tile[1]);
36471                 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
36472                     var otherTile = _b[_a];
36473                     if (otherTile[0] === x && otherTile[1] === y) {
36474                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
36475                         this._renderedTiles[otherLevel].splice(index, 1);
36476                     }
36477                 }
36478             }
36479             else {
36480                 var startX = scale * tile[0];
36481                 var endX = startX + scale - 1;
36482                 var startY = scale * tile[1];
36483                 var endY = startY + scale - 1;
36484                 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
36485                     var otherTile = _d[_c];
36486                     if (otherTile[0] >= startX && otherTile[0] <= endX &&
36487                         otherTile[1] >= startY && otherTile[1] <= endY) {
36488                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
36489                         this._renderedTiles[otherLevel].splice(index, 1);
36490                     }
36491                 }
36492             }
36493             if (this._renderedTiles[otherLevel].length === 0) {
36494                 delete this._renderedTiles[otherLevel];
36495             }
36496         }
36497         this._renderedTiles[level].push(tile);
36498         this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
36499     };
36500     /**
36501      * Create a tile key from a tile coordinates.
36502      *
36503      * @description Tile keys are used as a hash for
36504      * storing the tile in a dictionary.
36505      *
36506      * @param {Arrary<number>} tile - The tile coordinates.
36507      */
36508     TextureProvider.prototype._tileKey = function (tile) {
36509         return tile[0] + "-" + tile[1];
36510     };
36511     return TextureProvider;
36512 }());
36513 exports.TextureProvider = TextureProvider;
36514 Object.defineProperty(exports, "__esModule", { value: true });
36515 exports.default = TextureProvider;
36516
36517 },{"rxjs/Subject":33,"three":174}],335:[function(require,module,exports){
36518 "use strict";
36519 var EventEmitter = (function () {
36520     function EventEmitter() {
36521         this._events = {};
36522     }
36523     /**
36524      * Subscribe to an event by its name.
36525      * @param {string }eventType - The name of the event to subscribe to.
36526      * @param {any} fn - The handler called when the event occurs.
36527      */
36528     EventEmitter.prototype.on = function (eventType, fn) {
36529         this._events[eventType] = this._events[eventType] || [];
36530         this._events[eventType].push(fn);
36531         return;
36532     };
36533     /**
36534      * Unsubscribe from an event by its name.
36535      * @param {string} eventType - The name of the event to subscribe to.
36536      * @param {any} fn - The handler to remove.
36537      */
36538     EventEmitter.prototype.off = function (eventType, fn) {
36539         if (!eventType) {
36540             this._events = {};
36541             return;
36542         }
36543         if (!this._listens(eventType)) {
36544             var idx = this._events[eventType].indexOf(fn);
36545             if (idx >= 0) {
36546                 this._events[eventType].splice(idx, 1);
36547             }
36548             if (this._events[eventType].length) {
36549                 delete this._events[eventType];
36550             }
36551         }
36552         else {
36553             delete this._events[eventType];
36554         }
36555         return;
36556     };
36557     EventEmitter.prototype.fire = function (eventType, data) {
36558         if (!this._listens(eventType)) {
36559             return;
36560         }
36561         for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
36562             var fn = _a[_i];
36563             fn.call(this, data);
36564         }
36565         return;
36566     };
36567     EventEmitter.prototype._listens = function (eventType) {
36568         return !!(this._events && this._events[eventType]);
36569     };
36570     return EventEmitter;
36571 }());
36572 exports.EventEmitter = EventEmitter;
36573 Object.defineProperty(exports, "__esModule", { value: true });
36574 exports.default = EventEmitter;
36575
36576 },{}],336:[function(require,module,exports){
36577 "use strict";
36578 var Viewer_1 = require("../Viewer");
36579 var Settings = (function () {
36580     function Settings() {
36581     }
36582     Settings.setOptions = function (options) {
36583         Settings._baseImageSize = options.baseImageSize != null ?
36584             options.baseImageSize :
36585             Viewer_1.ImageSize.Size640;
36586         Settings._basePanoramaSize = options.basePanoramaSize != null ?
36587             options.basePanoramaSize :
36588             Viewer_1.ImageSize.Size2048;
36589         Settings._maxImageSize = options.maxImageSize != null ?
36590             options.maxImageSize :
36591             Viewer_1.ImageSize.Size2048;
36592     };
36593     Object.defineProperty(Settings, "baseImageSize", {
36594         get: function () {
36595             return Settings._baseImageSize;
36596         },
36597         enumerable: true,
36598         configurable: true
36599     });
36600     Object.defineProperty(Settings, "basePanoramaSize", {
36601         get: function () {
36602             return Settings._basePanoramaSize;
36603         },
36604         enumerable: true,
36605         configurable: true
36606     });
36607     Object.defineProperty(Settings, "maxImageSize", {
36608         get: function () {
36609             return Settings._maxImageSize;
36610         },
36611         enumerable: true,
36612         configurable: true
36613     });
36614     return Settings;
36615 }());
36616 exports.Settings = Settings;
36617 Object.defineProperty(exports, "__esModule", { value: true });
36618 exports.default = Settings;
36619
36620 },{"../Viewer":234}],337:[function(require,module,exports){
36621 "use strict";
36622 var Urls = (function () {
36623     function Urls() {
36624     }
36625     Object.defineProperty(Urls, "tileScheme", {
36626         get: function () {
36627             return "https";
36628         },
36629         enumerable: true,
36630         configurable: true
36631     });
36632     Object.defineProperty(Urls, "tileDomain", {
36633         get: function () {
36634             return "d2qb1440i7l50o.cloudfront.net";
36635         },
36636         enumerable: true,
36637         configurable: true
36638     });
36639     Object.defineProperty(Urls, "origin", {
36640         get: function () {
36641             return "mapillary.webgl";
36642         },
36643         enumerable: true,
36644         configurable: true
36645     });
36646     Urls.thumbnail = function (key, size) {
36647         return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=" + this.origin;
36648     };
36649     Urls.falcorModel = function (clientId) {
36650         return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
36651     };
36652     Urls.protoMesh = function (key) {
36653         return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
36654     };
36655     return Urls;
36656 }());
36657 exports.Urls = Urls;
36658 Object.defineProperty(exports, "__esModule", { value: true });
36659 exports.default = Urls;
36660
36661 },{}],338:[function(require,module,exports){
36662 "use strict";
36663 require("rxjs/add/operator/bufferCount");
36664 require("rxjs/add/operator/delay");
36665 require("rxjs/add/operator/distinctUntilChanged");
36666 require("rxjs/add/operator/map");
36667 require("rxjs/add/operator/switchMap");
36668 var CacheService = (function () {
36669     function CacheService(graphService, stateService) {
36670         this._graphService = graphService;
36671         this._stateService = stateService;
36672         this._started = false;
36673     }
36674     Object.defineProperty(CacheService.prototype, "started", {
36675         get: function () {
36676             return this._started;
36677         },
36678         enumerable: true,
36679         configurable: true
36680     });
36681     CacheService.prototype.start = function () {
36682         var _this = this;
36683         if (this._started) {
36684             return;
36685         }
36686         this._uncacheSubscription = this._stateService.currentState$
36687             .distinctUntilChanged(undefined, function (frame) {
36688             return frame.state.currentNode.key;
36689         })
36690             .map(function (frame) {
36691             return frame.state.trajectory
36692                 .map(function (n) {
36693                 return n.key;
36694             });
36695         })
36696             .bufferCount(1, 5)
36697             .switchMap(function (keepKeysBuffer) {
36698             var keepKeys = keepKeysBuffer[0];
36699             return _this._graphService.uncache$(keepKeys);
36700         })
36701             .subscribe(function () { });
36702         this._started = true;
36703     };
36704     CacheService.prototype.stop = function () {
36705         if (!this._started) {
36706             return;
36707         }
36708         this._uncacheSubscription.unsubscribe();
36709         this._uncacheSubscription = null;
36710         this._started = false;
36711     };
36712     return CacheService;
36713 }());
36714 exports.CacheService = CacheService;
36715 Object.defineProperty(exports, "__esModule", { value: true });
36716 exports.default = CacheService;
36717
36718 },{"rxjs/add/operator/bufferCount":49,"rxjs/add/operator/delay":55,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/map":64,"rxjs/add/operator/switchMap":78}],339:[function(require,module,exports){
36719 "use strict";
36720 var Component_1 = require("../Component");
36721 var ComponentController = (function () {
36722     function ComponentController(container, navigator, observer, key, options) {
36723         var _this = this;
36724         this._container = container;
36725         this._observer = observer;
36726         this._navigator = navigator;
36727         this._options = options != null ? options : {};
36728         this._key = key;
36729         this._componentService = new Component_1.ComponentService(this._container, this._navigator);
36730         this._coverComponent = this._componentService.getCover();
36731         this._initializeComponents();
36732         if (key) {
36733             this._initilizeCoverComponent();
36734             this._subscribeCoverComponent();
36735         }
36736         else {
36737             this._navigator.movedToKey$
36738                 .first(function (k) {
36739                 return k != null;
36740             })
36741                 .subscribe(function (k) {
36742                 _this._key = k;
36743                 _this._componentService.deactivateCover();
36744                 _this._coverComponent.configure({ key: _this._key, loading: false, visible: false });
36745                 _this._subscribeCoverComponent();
36746                 _this._navigator.stateService.start();
36747                 _this._observer.startEmit();
36748             });
36749         }
36750     }
36751     ComponentController.prototype.get = function (name) {
36752         return this._componentService.get(name);
36753     };
36754     ComponentController.prototype.activate = function (name) {
36755         this._componentService.activate(name);
36756     };
36757     ComponentController.prototype.activateCover = function () {
36758         this._coverComponent.configure({ loading: false, visible: true });
36759     };
36760     ComponentController.prototype.deactivate = function (name) {
36761         this._componentService.deactivate(name);
36762     };
36763     ComponentController.prototype.deactivateCover = function () {
36764         this._coverComponent.configure({ loading: true, visible: true });
36765     };
36766     ComponentController.prototype.resize = function () {
36767         this._componentService.resize();
36768     };
36769     ComponentController.prototype._initializeComponents = function () {
36770         var options = this._options;
36771         this._uFalse(options.background, "background");
36772         this._uFalse(options.debug, "debug");
36773         this._uFalse(options.image, "image");
36774         this._uFalse(options.marker, "marker");
36775         this._uFalse(options.navigation, "navigation");
36776         this._uFalse(options.route, "route");
36777         this._uFalse(options.slider, "slider");
36778         this._uFalse(options.tag, "tag");
36779         this._uTrue(options.attribution, "attribution");
36780         this._uTrue(options.bearing, "bearing");
36781         this._uTrue(options.cache, "cache");
36782         this._uTrue(options.direction, "direction");
36783         this._uTrue(options.imagePlane, "imagePlane");
36784         this._uTrue(options.keyboard, "keyboard");
36785         this._uTrue(options.loading, "loading");
36786         this._uTrue(options.mouse, "mouse");
36787         this._uTrue(options.sequence, "sequence");
36788         this._uTrue(options.stats, "stats");
36789     };
36790     ComponentController.prototype._initilizeCoverComponent = function () {
36791         var options = this._options;
36792         this._coverComponent.configure({ key: this._key });
36793         if (options.cover === undefined || options.cover) {
36794             this.activateCover();
36795         }
36796         else {
36797             this.deactivateCover();
36798         }
36799     };
36800     ComponentController.prototype._subscribeCoverComponent = function () {
36801         var _this = this;
36802         this._coverComponent.configuration$.subscribe(function (conf) {
36803             if (conf.loading) {
36804                 _this._navigator.stateService.currentKey$
36805                     .first()
36806                     .switchMap(function (key) {
36807                     return key == null || key !== conf.key ?
36808                         _this._navigator.moveToKey$(conf.key) :
36809                         _this._navigator.stateService.currentNode$
36810                             .first();
36811                 })
36812                     .subscribe(function (node) {
36813                     _this._navigator.stateService.start();
36814                     _this._observer.startEmit();
36815                     _this._coverComponent.configure({ loading: false, visible: false });
36816                     _this._componentService.deactivateCover();
36817                 }, function (error) {
36818                     console.error("Failed to deactivate cover.", error);
36819                     _this._coverComponent.configure({ loading: false, visible: true });
36820                 });
36821             }
36822             else if (conf.visible) {
36823                 _this._observer.stopEmit();
36824                 _this._navigator.stateService.stop();
36825                 _this._componentService.activateCover();
36826             }
36827         });
36828     };
36829     ComponentController.prototype._uFalse = function (option, name) {
36830         if (option === undefined) {
36831             this._componentService.deactivate(name);
36832             return;
36833         }
36834         if (typeof option === "boolean") {
36835             if (option) {
36836                 this._componentService.activate(name);
36837             }
36838             else {
36839                 this._componentService.deactivate(name);
36840             }
36841             return;
36842         }
36843         this._componentService.configure(name, option);
36844         this._componentService.activate(name);
36845     };
36846     ComponentController.prototype._uTrue = function (option, name) {
36847         if (option === undefined) {
36848             this._componentService.activate(name);
36849             return;
36850         }
36851         if (typeof option === "boolean") {
36852             if (option) {
36853                 this._componentService.activate(name);
36854             }
36855             else {
36856                 this._componentService.deactivate(name);
36857             }
36858             return;
36859         }
36860         this._componentService.configure(name, option);
36861         this._componentService.activate(name);
36862     };
36863     return ComponentController;
36864 }());
36865 exports.ComponentController = ComponentController;
36866
36867 },{"../Component":224}],340:[function(require,module,exports){
36868 "use strict";
36869 var Render_1 = require("../Render");
36870 var Viewer_1 = require("../Viewer");
36871 var Container = (function () {
36872     function Container(id, stateService, options) {
36873         this.id = id;
36874         this._container = document.getElementById(id);
36875         this._container.classList.add("mapillary-js");
36876         this._canvasContainer = document.createElement("div");
36877         this._canvasContainer.className = "mapillary-js-interactive";
36878         this._container.appendChild(this._canvasContainer);
36879         this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
36880         this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService);
36881         this.domRenderer = new Render_1.DOMRenderer(this._container, this.renderService, stateService.currentState$);
36882         this.mouseService = new Viewer_1.MouseService(this._canvasContainer, this._container);
36883         this.touchService = new Viewer_1.TouchService(this._canvasContainer);
36884         this.spriteService = new Viewer_1.SpriteService(options.sprite);
36885     }
36886     Object.defineProperty(Container.prototype, "element", {
36887         get: function () {
36888             return this._container;
36889         },
36890         enumerable: true,
36891         configurable: true
36892     });
36893     Object.defineProperty(Container.prototype, "canvasContainer", {
36894         get: function () {
36895             return this.canvasContainer;
36896         },
36897         enumerable: true,
36898         configurable: true
36899     });
36900     return Container;
36901 }());
36902 exports.Container = Container;
36903 Object.defineProperty(exports, "__esModule", { value: true });
36904 exports.default = Container;
36905
36906 },{"../Render":230,"../Viewer":234}],341:[function(require,module,exports){
36907 "use strict";
36908 /**
36909  * Enumeration for image sizes
36910  * @enum {number}
36911  * @readonly
36912  * @description Image sizes in pixels for the long side of the image.
36913  */
36914 var ImageSize;
36915 (function (ImageSize) {
36916     /**
36917      * 320 pixels image size
36918      */
36919     ImageSize[ImageSize["Size320"] = 320] = "Size320";
36920     /**
36921      * 640 pixels image size
36922      */
36923     ImageSize[ImageSize["Size640"] = 640] = "Size640";
36924     /**
36925      * 1024 pixels image size
36926      */
36927     ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
36928     /**
36929      * 2048 pixels image size
36930      */
36931     ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
36932 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
36933
36934 },{}],342:[function(require,module,exports){
36935 /// <reference path="../../typings/index.d.ts" />
36936 "use strict";
36937 var _ = require("underscore");
36938 var Subject_1 = require("rxjs/Subject");
36939 require("rxjs/add/operator/debounceTime");
36940 require("rxjs/add/operator/distinctUntilChanged");
36941 require("rxjs/add/operator/map");
36942 require("rxjs/add/operator/publishReplay");
36943 require("rxjs/add/operator/scan");
36944 require("rxjs/add/operator/startWith");
36945 var LoadingService = (function () {
36946     function LoadingService() {
36947         this._loadersSubject$ = new Subject_1.Subject();
36948         this._loaders$ = this._loadersSubject$
36949             .scan(function (loaders, loader) {
36950             if (loader.task !== undefined) {
36951                 loaders[loader.task] = loader.loading;
36952             }
36953             return loaders;
36954         }, {})
36955             .startWith({})
36956             .publishReplay(1)
36957             .refCount();
36958     }
36959     Object.defineProperty(LoadingService.prototype, "loading$", {
36960         get: function () {
36961             return this._loaders$
36962                 .map(function (loaders) {
36963                 return _.reduce(loaders, function (loader, acc) {
36964                     return (loader || acc);
36965                 }, false);
36966             })
36967                 .debounceTime(100)
36968                 .distinctUntilChanged();
36969         },
36970         enumerable: true,
36971         configurable: true
36972     });
36973     LoadingService.prototype.taskLoading$ = function (task) {
36974         return this._loaders$
36975             .map(function (loaders) {
36976             return !!loaders[task];
36977         })
36978             .debounceTime(100)
36979             .distinctUntilChanged();
36980     };
36981     LoadingService.prototype.startLoading = function (task) {
36982         this._loadersSubject$.next({ loading: true, task: task });
36983     };
36984     LoadingService.prototype.stopLoading = function (task) {
36985         this._loadersSubject$.next({ loading: false, task: task });
36986     };
36987     return LoadingService;
36988 }());
36989 exports.LoadingService = LoadingService;
36990 Object.defineProperty(exports, "__esModule", { value: true });
36991 exports.default = LoadingService;
36992
36993 },{"rxjs/Subject":33,"rxjs/add/operator/debounceTime":54,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/map":64,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/startWith":77,"underscore":175}],343:[function(require,module,exports){
36994 "use strict";
36995 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
36996 var Observable_1 = require("rxjs/Observable");
36997 var Subject_1 = require("rxjs/Subject");
36998 require("rxjs/add/observable/fromEvent");
36999 require("rxjs/add/operator/distinctUntilChanged");
37000 require("rxjs/add/operator/filter");
37001 require("rxjs/add/operator/map");
37002 require("rxjs/add/operator/merge");
37003 require("rxjs/add/operator/mergeMap");
37004 require("rxjs/add/operator/publishReplay");
37005 require("rxjs/add/operator/scan");
37006 require("rxjs/add/operator/switchMap");
37007 require("rxjs/add/operator/withLatestFrom");
37008 var Geo_1 = require("../Geo");
37009 var MouseService = (function () {
37010     function MouseService(canvasContainer, container, viewportCoords) {
37011         var _this = this;
37012         this._canvasContainer = canvasContainer;
37013         this._container = container;
37014         this._viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
37015         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
37016         this._active$ = this._activeSubject$
37017             .distinctUntilChanged()
37018             .publishReplay(1)
37019             .refCount();
37020         this._claimMouse$ = new Subject_1.Subject();
37021         this._documentMouseDown$ = Observable_1.Observable.fromEvent(document, "mousedown")
37022             .filter(function (event) {
37023             return _this._viewportCoords.insideElement(event, _this._container);
37024         })
37025             .share();
37026         this._documentMouseMove$ = Observable_1.Observable.fromEvent(document, "mousemove");
37027         this._documentMouseUp$ = Observable_1.Observable.fromEvent(document, "mouseup");
37028         this._documentCanvasMouseMove$ = this._documentMouseMove$
37029             .filter(function (event) {
37030             return _this._viewportCoords.insideElement(event, _this._container);
37031         })
37032             .share();
37033         this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
37034         this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
37035         this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
37036         this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
37037         this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
37038         this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
37039         this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
37040         this._dblClick$ = Observable_1.Observable.fromEvent(canvasContainer, "dblclick");
37041         this._dblClick$
37042             .subscribe(function (event) {
37043             event.preventDefault();
37044         });
37045         this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
37046         this._contextMenu$
37047             .subscribe(function (event) {
37048             event.preventDefault();
37049         });
37050         this._mouseWheel$ = Observable_1.Observable.fromEvent(document, "wheel")
37051             .filter(function (event) {
37052             return _this._viewportCoords.insideElement(event, _this._container);
37053         })
37054             .share();
37055         this._consistentContextMenu$ = Observable_1.Observable
37056             .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
37057             .bufferCount(3, 1)
37058             .filter(function (events) {
37059             // fire context menu on mouse up both on mac and windows
37060             return events[0].type === "mousedown" &&
37061                 events[1].type === "contextmenu" &&
37062                 events[2].type === "mouseup";
37063         })
37064             .map(function (events) {
37065             return events[1];
37066         })
37067             .share();
37068         var dragStop$ = Observable_1.Observable
37069             .merge(this._documentMouseUp$.filter(function (e) {
37070             return e.button === 0;
37071         }))
37072             .share();
37073         var leftButtonDown$ = this._mouseDown$
37074             .filter(function (e) {
37075             return e.button === 0;
37076         })
37077             .share();
37078         this._mouseDragStart$ = leftButtonDown$
37079             .mergeMap(function (e) {
37080             return _this._documentMouseMove$
37081                 .takeUntil(dragStop$)
37082                 .take(1);
37083         });
37084         this._mouseDrag$ = leftButtonDown$
37085             .mergeMap(function (e) {
37086             return _this._documentMouseMove$
37087                 .skip(1)
37088                 .takeUntil(dragStop$);
37089         });
37090         this._mouseDragEnd$ = this._mouseDragStart$
37091             .mergeMap(function (e) {
37092             return dragStop$.first();
37093         });
37094         this._documentCanvasMouseDown$ = this._documentMouseDown$
37095             .filter(function (e) {
37096             return _this._viewportCoords.insideElement(e, _this._container);
37097         })
37098             .share();
37099         var documentCanvasLeftButtonDown$ = this._documentCanvasMouseDown$
37100             .filter(function (e) {
37101             return e.button === 0;
37102         })
37103             .share();
37104         this._documentCanvasMouseDragStart$ = documentCanvasLeftButtonDown$
37105             .mergeMap(function (e) {
37106             return _this._documentCanvasMouseMove$
37107                 .takeUntil(dragStop$)
37108                 .take(1);
37109         });
37110         this._documentCanvasMouseDrag$ = documentCanvasLeftButtonDown$
37111             .mergeMap(function (e) {
37112             return _this._documentCanvasMouseMove$
37113                 .skip(1)
37114                 .takeUntil(dragStop$);
37115         });
37116         this._documentCanvasMouseDragEnd$ = this._documentCanvasMouseDragStart$
37117             .mergeMap(function (e) {
37118             return dragStop$.first();
37119         });
37120         this._staticClick$ = this._mouseDown$
37121             .switchMap(function (e) {
37122             return _this._click$
37123                 .takeUntil(_this._mouseMove$)
37124                 .take(1);
37125         });
37126         this._mouseOwner$ = this._claimMouse$
37127             .scan(function (claims, mouseClaim) {
37128             if (mouseClaim.zindex == null) {
37129                 delete claims[mouseClaim.name];
37130             }
37131             else {
37132                 claims[mouseClaim.name] = mouseClaim.zindex;
37133             }
37134             return claims;
37135         }, {})
37136             .map(function (claims) {
37137             var owner = null;
37138             var curZ = -1;
37139             for (var name_1 in claims) {
37140                 if (claims.hasOwnProperty(name_1)) {
37141                     if (claims[name_1] > curZ) {
37142                         curZ = claims[name_1];
37143                         owner = name_1;
37144                     }
37145                 }
37146             }
37147             return owner;
37148         })
37149             .publishReplay(1)
37150             .refCount();
37151         this._mouseOwner$.subscribe(function () { });
37152     }
37153     Object.defineProperty(MouseService.prototype, "active$", {
37154         get: function () {
37155             return this._active$;
37156         },
37157         enumerable: true,
37158         configurable: true
37159     });
37160     Object.defineProperty(MouseService.prototype, "activate$", {
37161         get: function () {
37162             return this._activeSubject$;
37163         },
37164         enumerable: true,
37165         configurable: true
37166     });
37167     Object.defineProperty(MouseService.prototype, "documentCanvasMouseDown$", {
37168         get: function () {
37169             return this._documentCanvasMouseDown$;
37170         },
37171         enumerable: true,
37172         configurable: true
37173     });
37174     Object.defineProperty(MouseService.prototype, "documentCanvasMouseMove$", {
37175         get: function () {
37176             return this._documentCanvasMouseMove$;
37177         },
37178         enumerable: true,
37179         configurable: true
37180     });
37181     Object.defineProperty(MouseService.prototype, "documentCanvasMouseDragStart$", {
37182         get: function () {
37183             return this._documentCanvasMouseDragStart$;
37184         },
37185         enumerable: true,
37186         configurable: true
37187     });
37188     Object.defineProperty(MouseService.prototype, "documentCanvasMouseDrag$", {
37189         get: function () {
37190             return this._documentCanvasMouseDrag$;
37191         },
37192         enumerable: true,
37193         configurable: true
37194     });
37195     Object.defineProperty(MouseService.prototype, "documentCanvasMouseDragEnd$", {
37196         get: function () {
37197             return this._documentCanvasMouseDragEnd$;
37198         },
37199         enumerable: true,
37200         configurable: true
37201     });
37202     Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
37203         get: function () {
37204             return this._documentMouseMove$;
37205         },
37206         enumerable: true,
37207         configurable: true
37208     });
37209     Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
37210         get: function () {
37211             return this._documentMouseUp$;
37212         },
37213         enumerable: true,
37214         configurable: true
37215     });
37216     Object.defineProperty(MouseService.prototype, "mouseOwner$", {
37217         get: function () {
37218             return this._mouseOwner$;
37219         },
37220         enumerable: true,
37221         configurable: true
37222     });
37223     Object.defineProperty(MouseService.prototype, "mouseDown$", {
37224         get: function () {
37225             return this._mouseDown$;
37226         },
37227         enumerable: true,
37228         configurable: true
37229     });
37230     Object.defineProperty(MouseService.prototype, "mouseMove$", {
37231         get: function () {
37232             return this._mouseMove$;
37233         },
37234         enumerable: true,
37235         configurable: true
37236     });
37237     Object.defineProperty(MouseService.prototype, "mouseLeave$", {
37238         get: function () {
37239             return this._mouseLeave$;
37240         },
37241         enumerable: true,
37242         configurable: true
37243     });
37244     Object.defineProperty(MouseService.prototype, "mouseOut$", {
37245         get: function () {
37246             return this._mouseOut$;
37247         },
37248         enumerable: true,
37249         configurable: true
37250     });
37251     Object.defineProperty(MouseService.prototype, "mouseOver$", {
37252         get: function () {
37253             return this._mouseOver$;
37254         },
37255         enumerable: true,
37256         configurable: true
37257     });
37258     Object.defineProperty(MouseService.prototype, "mouseUp$", {
37259         get: function () {
37260             return this._mouseUp$;
37261         },
37262         enumerable: true,
37263         configurable: true
37264     });
37265     Object.defineProperty(MouseService.prototype, "click$", {
37266         get: function () {
37267             return this._click$;
37268         },
37269         enumerable: true,
37270         configurable: true
37271     });
37272     Object.defineProperty(MouseService.prototype, "dblClick$", {
37273         get: function () {
37274             return this._dblClick$;
37275         },
37276         enumerable: true,
37277         configurable: true
37278     });
37279     Object.defineProperty(MouseService.prototype, "contextMenu$", {
37280         get: function () {
37281             return this._consistentContextMenu$;
37282         },
37283         enumerable: true,
37284         configurable: true
37285     });
37286     Object.defineProperty(MouseService.prototype, "mouseWheel$", {
37287         get: function () {
37288             return this._mouseWheel$;
37289         },
37290         enumerable: true,
37291         configurable: true
37292     });
37293     Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
37294         get: function () {
37295             return this._mouseDragStart$;
37296         },
37297         enumerable: true,
37298         configurable: true
37299     });
37300     Object.defineProperty(MouseService.prototype, "mouseDrag$", {
37301         get: function () {
37302             return this._mouseDrag$;
37303         },
37304         enumerable: true,
37305         configurable: true
37306     });
37307     Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
37308         get: function () {
37309             return this._mouseDragEnd$;
37310         },
37311         enumerable: true,
37312         configurable: true
37313     });
37314     Object.defineProperty(MouseService.prototype, "staticClick$", {
37315         get: function () {
37316             return this._staticClick$;
37317         },
37318         enumerable: true,
37319         configurable: true
37320     });
37321     MouseService.prototype.claimMouse = function (name, zindex) {
37322         this._claimMouse$.next({ name: name, zindex: zindex });
37323     };
37324     MouseService.prototype.unclaimMouse = function (name) {
37325         this._claimMouse$.next({ name: name, zindex: null });
37326     };
37327     MouseService.prototype.filtered$ = function (name, observable$) {
37328         return observable$
37329             .withLatestFrom(this.mouseOwner$, function (event, owner) {
37330             return [event, owner];
37331         })
37332             .filter(function (eo) {
37333             return eo[1] === name;
37334         })
37335             .map(function (eo) {
37336             return eo[0];
37337         });
37338     };
37339     return MouseService;
37340 }());
37341 exports.MouseService = MouseService;
37342 Object.defineProperty(exports, "__esModule", { value: true });
37343 exports.default = MouseService;
37344
37345 },{"../Geo":227,"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/withLatestFrom":82}],344:[function(require,module,exports){
37346 /// <reference path="../../typings/index.d.ts" />
37347 "use strict";
37348 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
37349 var Observable_1 = require("rxjs/Observable");
37350 require("rxjs/add/observable/throw");
37351 require("rxjs/add/operator/do");
37352 require("rxjs/add/operator/finally");
37353 require("rxjs/add/operator/first");
37354 require("rxjs/add/operator/map");
37355 require("rxjs/add/operator/mergeMap");
37356 var API_1 = require("../API");
37357 var Graph_1 = require("../Graph");
37358 var Edge_1 = require("../Edge");
37359 var State_1 = require("../State");
37360 var Viewer_1 = require("../Viewer");
37361 var Navigator = (function () {
37362     function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService) {
37363         this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
37364         this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
37365         this._graphService = graphService != null ?
37366             graphService :
37367             new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
37368         this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
37369         this._loadingName = "navigator";
37370         this._stateService = stateService != null ? stateService : new State_1.StateService();
37371         this._cacheService = cacheService != null ?
37372             cacheService :
37373             new Viewer_1.CacheService(this._graphService, this._stateService);
37374         this._cacheService.start();
37375         this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
37376         this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
37377         this._dirRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
37378         this._latLonRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
37379     }
37380     Object.defineProperty(Navigator.prototype, "apiV3", {
37381         get: function () {
37382             return this._apiV3;
37383         },
37384         enumerable: true,
37385         configurable: true
37386     });
37387     Object.defineProperty(Navigator.prototype, "graphService", {
37388         get: function () {
37389             return this._graphService;
37390         },
37391         enumerable: true,
37392         configurable: true
37393     });
37394     Object.defineProperty(Navigator.prototype, "imageLoadingService", {
37395         get: function () {
37396             return this._imageLoadingService;
37397         },
37398         enumerable: true,
37399         configurable: true
37400     });
37401     Object.defineProperty(Navigator.prototype, "keyRequested$", {
37402         get: function () {
37403             return this._keyRequested$;
37404         },
37405         enumerable: true,
37406         configurable: true
37407     });
37408     Object.defineProperty(Navigator.prototype, "loadingService", {
37409         get: function () {
37410             return this._loadingService;
37411         },
37412         enumerable: true,
37413         configurable: true
37414     });
37415     Object.defineProperty(Navigator.prototype, "movedToKey$", {
37416         get: function () {
37417             return this._movedToKey$;
37418         },
37419         enumerable: true,
37420         configurable: true
37421     });
37422     Object.defineProperty(Navigator.prototype, "stateService", {
37423         get: function () {
37424             return this._stateService;
37425         },
37426         enumerable: true,
37427         configurable: true
37428     });
37429     Navigator.prototype.moveToKey$ = function (key) {
37430         var _this = this;
37431         this.loadingService.startLoading(this._loadingName);
37432         this._keyRequested$.next(key);
37433         return this._graphService.cacheNode$(key)
37434             .do(function (node) {
37435             _this.stateService.setNodes([node]);
37436             _this._movedToKey$.next(node.key);
37437         })
37438             .finally(function () {
37439             _this.loadingService.stopLoading(_this._loadingName);
37440         });
37441     };
37442     Navigator.prototype.moveDir$ = function (direction) {
37443         var _this = this;
37444         this.loadingService.startLoading(this._loadingName);
37445         this._dirRequested$.next(direction);
37446         return this.stateService.currentNode$
37447             .first()
37448             .mergeMap(function (node) {
37449             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
37450                 node.sequenceEdges$ :
37451                 node.spatialEdges$)
37452                 .first()
37453                 .map(function (status) {
37454                 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
37455                     var edge = _a[_i];
37456                     if (edge.data.direction === direction) {
37457                         return edge.to;
37458                     }
37459                 }
37460                 return null;
37461             });
37462         })
37463             .mergeMap(function (directionKey) {
37464             if (directionKey == null) {
37465                 _this.loadingService.stopLoading(_this._loadingName);
37466                 return Observable_1.Observable
37467                     .throw(new Error("Direction (" + direction + ") does not exist for current node."));
37468             }
37469             return _this.moveToKey$(directionKey);
37470         });
37471     };
37472     Navigator.prototype.moveCloseTo$ = function (lat, lon) {
37473         var _this = this;
37474         this.loadingService.startLoading(this._loadingName);
37475         this._latLonRequested$.next({ lat: lat, lon: lon });
37476         return this.apiV3.imageCloseTo$(lat, lon)
37477             .mergeMap(function (fullNode) {
37478             if (fullNode == null) {
37479                 _this.loadingService.stopLoading(_this._loadingName);
37480                 return Observable_1.Observable
37481                     .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
37482             }
37483             return _this.moveToKey$(fullNode.key);
37484         });
37485     };
37486     Navigator.prototype.setFilter$ = function (filter) {
37487         var _this = this;
37488         this._stateService.clearNodes();
37489         return this._movedToKey$
37490             .first()
37491             .mergeMap(function (key) {
37492             if (key != null) {
37493                 return _this._trajectoryKeys$()
37494                     .mergeMap(function (keys) {
37495                     return _this._graphService.setFilter$(filter)
37496                         .mergeMap(function (graph) {
37497                         return _this._cacheKeys$(keys);
37498                     });
37499                 })
37500                     .last();
37501             }
37502             return _this._keyRequested$
37503                 .mergeMap(function (requestedKey) {
37504                 if (requestedKey != null) {
37505                     return _this._graphService.setFilter$(filter)
37506                         .mergeMap(function (graph) {
37507                         return _this._graphService.cacheNode$(requestedKey);
37508                     });
37509                 }
37510                 return _this._graphService.setFilter$(filter)
37511                     .map(function (graph) {
37512                     return undefined;
37513                 });
37514             });
37515         })
37516             .map(function (node) {
37517             return undefined;
37518         });
37519     };
37520     Navigator.prototype.setToken$ = function (token) {
37521         var _this = this;
37522         this._stateService.clearNodes();
37523         return this._movedToKey$
37524             .first()
37525             .do(function (key) {
37526             _this._apiV3.setToken(token);
37527         })
37528             .mergeMap(function (key) {
37529             return key == null ?
37530                 _this._graphService.reset$([])
37531                     .map(function (graph) {
37532                     return undefined;
37533                 }) :
37534                 _this._trajectoryKeys$()
37535                     .mergeMap(function (keys) {
37536                     return _this._graphService.reset$(keys)
37537                         .mergeMap(function (graph) {
37538                         return _this._cacheKeys$(keys);
37539                     });
37540                 })
37541                     .last()
37542                     .map(function (node) {
37543                     return undefined;
37544                 });
37545         });
37546     };
37547     Navigator.prototype._cacheKeys$ = function (keys) {
37548         var _this = this;
37549         var cacheNodes$ = keys
37550             .map(function (key) {
37551             return _this._graphService.cacheNode$(key);
37552         });
37553         return Observable_1.Observable
37554             .from(cacheNodes$)
37555             .mergeAll();
37556     };
37557     Navigator.prototype._trajectoryKeys$ = function () {
37558         return this._stateService.currentState$
37559             .first()
37560             .map(function (frame) {
37561             return frame.state.trajectory
37562                 .map(function (node) {
37563                 return node.key;
37564             });
37565         });
37566     };
37567     return Navigator;
37568 }());
37569 exports.Navigator = Navigator;
37570 Object.defineProperty(exports, "__esModule", { value: true });
37571 exports.default = Navigator;
37572
37573 },{"../API":223,"../Edge":225,"../Graph":228,"../State":231,"../Viewer":234,"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/add/observable/throw":45,"rxjs/add/operator/do":58,"rxjs/add/operator/finally":61,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/mergeMap":67}],345:[function(require,module,exports){
37574 "use strict";
37575 var Observable_1 = require("rxjs/Observable");
37576 require("rxjs/add/observable/combineLatest");
37577 require("rxjs/add/operator/distinctUntilChanged");
37578 require("rxjs/add/operator/map");
37579 require("rxjs/add/operator/throttleTime");
37580 var Viewer_1 = require("../Viewer");
37581 var Observer = (function () {
37582     function Observer(eventEmitter, navigator, container) {
37583         this._container = container;
37584         this._eventEmitter = eventEmitter;
37585         this._navigator = navigator;
37586         this._projection = new Viewer_1.Projection();
37587         this._started = false;
37588     }
37589     Object.defineProperty(Observer.prototype, "started", {
37590         get: function () {
37591             return this._started;
37592         },
37593         enumerable: true,
37594         configurable: true
37595     });
37596     Observer.prototype.startEmit = function () {
37597         var _this = this;
37598         if (this._started) {
37599             return;
37600         }
37601         this._started = true;
37602         this._loadingSubscription = this._navigator.loadingService.loading$
37603             .subscribe(function (loading) {
37604             _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
37605         });
37606         this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
37607             .subscribe(function (node) {
37608             _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
37609         });
37610         this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
37611             .switchMap(function (node) {
37612             return node.sequenceEdges$;
37613         })
37614             .subscribe(function (status) {
37615             _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
37616         });
37617         this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
37618             .switchMap(function (node) {
37619             return node.spatialEdges$;
37620         })
37621             .subscribe(function (status) {
37622             _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
37623         });
37624         this._moveSubscription = Observable_1.Observable
37625             .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
37626             .map(function (values) {
37627             return values[0] || values[1] || values[2];
37628         })
37629             .distinctUntilChanged()
37630             .subscribe(function (started) {
37631             if (started) {
37632                 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
37633             }
37634             else {
37635                 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
37636             }
37637         });
37638         this._bearingSubscription = this._container.renderService.bearing$
37639             .throttleTime(100)
37640             .distinctUntilChanged(function (b1, b2) {
37641             return Math.abs(b2 - b1) < 1;
37642         })
37643             .subscribe(function (bearing) {
37644             _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
37645         });
37646         var mouseMove$ = this._container.mouseService.active$
37647             .switchMap(function (active) {
37648             return active ?
37649                 Observable_1.Observable.empty() :
37650                 _this._container.mouseService.mouseMove$;
37651         });
37652         this._viewerMouseEventSubscription = Observable_1.Observable
37653             .merge(this._mapMouseEvent$(Viewer_1.Viewer.click, this._container.mouseService.staticClick$), this._mapMouseEvent$(Viewer_1.Viewer.contextmenu, this._container.mouseService.contextMenu$), this._mapMouseEvent$(Viewer_1.Viewer.dblclick, this._container.mouseService.dblClick$), this._mapMouseEvent$(Viewer_1.Viewer.mousedown, this._container.mouseService.mouseDown$), this._mapMouseEvent$(Viewer_1.Viewer.mousemove, mouseMove$), this._mapMouseEvent$(Viewer_1.Viewer.mouseout, this._container.mouseService.mouseOut$), this._mapMouseEvent$(Viewer_1.Viewer.mouseover, this._container.mouseService.mouseOver$), this._mapMouseEvent$(Viewer_1.Viewer.mouseup, this._container.mouseService.mouseUp$))
37654             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
37655             .map(function (_a) {
37656             var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
37657             var unprojection = _this._projection.unprojectFromEvent(event, _this._container.element, render, reference, transform);
37658             return {
37659                 basicPoint: unprojection.basicPoint,
37660                 latLon: unprojection.latLon,
37661                 originalEvent: event,
37662                 pixelPoint: unprojection.pixelPoint,
37663                 target: _this._eventEmitter,
37664                 type: type,
37665             };
37666         })
37667             .subscribe(function (event) {
37668             _this._eventEmitter.fire(event.type, event);
37669         });
37670     };
37671     Observer.prototype.stopEmit = function () {
37672         if (!this.started) {
37673             return;
37674         }
37675         this._started = false;
37676         this._bearingSubscription.unsubscribe();
37677         this._loadingSubscription.unsubscribe();
37678         this._currentNodeSubscription.unsubscribe();
37679         this._moveSubscription.unsubscribe();
37680         this._sequenceEdgesSubscription.unsubscribe();
37681         this._spatialEdgesSubscription.unsubscribe();
37682         this._viewerMouseEventSubscription.unsubscribe();
37683         this._bearingSubscription = null;
37684         this._loadingSubscription = null;
37685         this._currentNodeSubscription = null;
37686         this._moveSubscription = null;
37687         this._sequenceEdgesSubscription = null;
37688         this._spatialEdgesSubscription = null;
37689         this._viewerMouseEventSubscription = null;
37690     };
37691     Observer.prototype.unproject$ = function (pixelPoint) {
37692         var _this = this;
37693         return Observable_1.Observable
37694             .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
37695             .first()
37696             .map(function (_a) {
37697             var render = _a[0], reference = _a[1], transform = _a[2];
37698             var unprojection = _this._projection.unprojectFromCanvas(pixelPoint, _this._container.element, render, reference, transform);
37699             return unprojection.latLon;
37700         });
37701     };
37702     Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
37703         return mouseEvent$.map(function (event) {
37704             return [type, event];
37705         });
37706     };
37707     return Observer;
37708 }());
37709 exports.Observer = Observer;
37710 Object.defineProperty(exports, "__esModule", { value: true });
37711 exports.default = Observer;
37712
37713 },{"../Viewer":234,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/map":64,"rxjs/add/operator/throttleTime":81}],346:[function(require,module,exports){
37714 /// <reference path="../../typings/index.d.ts" />
37715 "use strict";
37716 var THREE = require("three");
37717 var Geo_1 = require("../Geo");
37718 var Projection = (function () {
37719     function Projection(geoCoords, viewportCoords) {
37720         this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
37721         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
37722     }
37723     Projection.prototype.unprojectFromEvent = function (event, container, renderCamera, reference, transform) {
37724         var pixelPoint = this._viewportCoords.canvasPosition(event, container);
37725         return this.unprojectFromCanvas(pixelPoint, container, renderCamera, reference, transform);
37726     };
37727     Projection.prototype.unprojectFromCanvas = function (pixelPoint, container, render, reference, transform) {
37728         var canvasX = pixelPoint[0];
37729         var canvasY = pixelPoint[1];
37730         var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
37731         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
37732             .unproject(render.perspective);
37733         var basicPoint = transform.projectBasic(point3d.toArray());
37734         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
37735             basicPoint = null;
37736         }
37737         var direction3d = point3d.clone().sub(render.camera.position).normalize();
37738         var dist = -2 / direction3d.z;
37739         var latLon = null;
37740         if (dist > 0 && dist < 100 && !!basicPoint) {
37741             var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
37742             var latLonArray = this._geoCoords
37743                 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
37744                 .slice(0, 2);
37745             latLon = { lat: latLonArray[0], lon: latLonArray[1] };
37746         }
37747         var unprojection = {
37748             basicPoint: basicPoint,
37749             latLon: latLon,
37750             pixelPoint: [canvasX, canvasY],
37751         };
37752         return unprojection;
37753     };
37754     return Projection;
37755 }());
37756 exports.Projection = Projection;
37757 Object.defineProperty(exports, "__esModule", { value: true });
37758 exports.default = Projection;
37759
37760 },{"../Geo":227,"three":174}],347:[function(require,module,exports){
37761 "use strict";
37762 var SpriteAlignment;
37763 (function (SpriteAlignment) {
37764     SpriteAlignment[SpriteAlignment["Center"] = 0] = "Center";
37765     SpriteAlignment[SpriteAlignment["Start"] = 1] = "Start";
37766     SpriteAlignment[SpriteAlignment["End"] = 2] = "End";
37767 })(SpriteAlignment = exports.SpriteAlignment || (exports.SpriteAlignment = {}));
37768 Object.defineProperty(exports, "__esModule", { value: true });
37769 exports.default = SpriteAlignment;
37770
37771 },{}],348:[function(require,module,exports){
37772 /// <reference path="../../typings/index.d.ts" />
37773 "use strict";
37774 var THREE = require("three");
37775 var vd = require("virtual-dom");
37776 var Subject_1 = require("rxjs/Subject");
37777 require("rxjs/add/operator/publishReplay");
37778 require("rxjs/add/operator/scan");
37779 require("rxjs/add/operator/startWith");
37780 var Viewer_1 = require("../Viewer");
37781 var SpriteAtlas = (function () {
37782     function SpriteAtlas() {
37783     }
37784     Object.defineProperty(SpriteAtlas.prototype, "json", {
37785         set: function (value) {
37786             this._json = value;
37787         },
37788         enumerable: true,
37789         configurable: true
37790     });
37791     Object.defineProperty(SpriteAtlas.prototype, "image", {
37792         set: function (value) {
37793             this._image = value;
37794             this._texture = new THREE.Texture(this._image);
37795             this._texture.minFilter = THREE.NearestFilter;
37796         },
37797         enumerable: true,
37798         configurable: true
37799     });
37800     Object.defineProperty(SpriteAtlas.prototype, "loaded", {
37801         get: function () {
37802             return !!(this._image && this._json);
37803         },
37804         enumerable: true,
37805         configurable: true
37806     });
37807     SpriteAtlas.prototype.getGLSprite = function (name) {
37808         if (!this.loaded) {
37809             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
37810         }
37811         var definition = this._json[name];
37812         if (!definition) {
37813             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
37814             return new THREE.Object3D();
37815         }
37816         var texture = this._texture.clone();
37817         texture.needsUpdate = true;
37818         var width = this._image.width;
37819         var height = this._image.height;
37820         texture.offset.x = definition.x / width;
37821         texture.offset.y = (height - definition.y - definition.height) / height;
37822         texture.repeat.x = definition.width / width;
37823         texture.repeat.y = definition.height / height;
37824         var material = new THREE.SpriteMaterial({ map: texture });
37825         return new THREE.Sprite(material);
37826     };
37827     SpriteAtlas.prototype.getDOMSprite = function (name, horizontalAlign, verticalAlign) {
37828         if (!this.loaded) {
37829             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
37830         }
37831         if (horizontalAlign == null) {
37832             horizontalAlign = Viewer_1.SpriteAlignment.Start;
37833         }
37834         if (verticalAlign == null) {
37835             verticalAlign = Viewer_1.SpriteAlignment.Start;
37836         }
37837         var definition = this._json[name];
37838         if (!definition) {
37839             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
37840             return vd.h("div", {}, []);
37841         }
37842         var clipTop = definition.y;
37843         var clipRigth = definition.x + definition.width;
37844         var clipBottom = definition.y + definition.height;
37845         var clipLeft = definition.x;
37846         var left = -definition.x;
37847         var top = -definition.y;
37848         var height = this._image.height;
37849         var width = this._image.width;
37850         switch (horizontalAlign) {
37851             case Viewer_1.SpriteAlignment.Center:
37852                 left -= definition.width / 2;
37853                 break;
37854             case Viewer_1.SpriteAlignment.End:
37855                 left -= definition.width;
37856                 break;
37857             case Viewer_1.SpriteAlignment.Start:
37858                 break;
37859             default:
37860                 break;
37861         }
37862         switch (verticalAlign) {
37863             case Viewer_1.SpriteAlignment.Center:
37864                 top -= definition.height / 2;
37865                 break;
37866             case Viewer_1.SpriteAlignment.End:
37867                 top -= definition.height;
37868                 break;
37869             case Viewer_1.SpriteAlignment.Start:
37870                 break;
37871             default:
37872                 break;
37873         }
37874         var pixelRatioInverse = 1 / definition.pixelRatio;
37875         clipTop *= pixelRatioInverse;
37876         clipRigth *= pixelRatioInverse;
37877         clipBottom *= pixelRatioInverse;
37878         clipLeft *= pixelRatioInverse;
37879         left *= pixelRatioInverse;
37880         top *= pixelRatioInverse;
37881         height *= pixelRatioInverse;
37882         width *= pixelRatioInverse;
37883         var properties = {
37884             src: this._image.src,
37885             style: {
37886                 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
37887                 height: height + "px",
37888                 left: left + "px",
37889                 position: "absolute",
37890                 top: top + "px",
37891                 width: width + "px",
37892             },
37893         };
37894         return vd.h("img", properties, []);
37895     };
37896     return SpriteAtlas;
37897 }());
37898 var SpriteService = (function () {
37899     function SpriteService(sprite) {
37900         var _this = this;
37901         this._retina = window.devicePixelRatio > 1;
37902         this._spriteAtlasOperation$ = new Subject_1.Subject();
37903         this._spriteAtlas$ = this._spriteAtlasOperation$
37904             .startWith(function (atlas) {
37905             return atlas;
37906         })
37907             .scan(function (atlas, operation) {
37908             return operation(atlas);
37909         }, new SpriteAtlas())
37910             .publishReplay(1)
37911             .refCount();
37912         this._spriteAtlas$.subscribe(function () { });
37913         if (sprite == null) {
37914             return;
37915         }
37916         var format = this._retina ? "@2x" : "";
37917         var imageXmlHTTP = new XMLHttpRequest();
37918         imageXmlHTTP.open("GET", sprite + format + ".png", true);
37919         imageXmlHTTP.responseType = "arraybuffer";
37920         imageXmlHTTP.onload = function () {
37921             var image = new Image();
37922             image.onload = function () {
37923                 _this._spriteAtlasOperation$.next(function (atlas) {
37924                     atlas.image = image;
37925                     return atlas;
37926                 });
37927             };
37928             var blob = new Blob([imageXmlHTTP.response]);
37929             image.src = window.URL.createObjectURL(blob);
37930         };
37931         imageXmlHTTP.onerror = function (error) {
37932             console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
37933         };
37934         imageXmlHTTP.send();
37935         var jsonXmlHTTP = new XMLHttpRequest();
37936         jsonXmlHTTP.open("GET", sprite + format + ".json", true);
37937         jsonXmlHTTP.responseType = "text";
37938         jsonXmlHTTP.onload = function () {
37939             var json = JSON.parse(jsonXmlHTTP.response);
37940             _this._spriteAtlasOperation$.next(function (atlas) {
37941                 atlas.json = json;
37942                 return atlas;
37943             });
37944         };
37945         jsonXmlHTTP.onerror = function (error) {
37946             console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
37947         };
37948         jsonXmlHTTP.send();
37949     }
37950     Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
37951         get: function () {
37952             return this._spriteAtlas$;
37953         },
37954         enumerable: true,
37955         configurable: true
37956     });
37957     return SpriteService;
37958 }());
37959 exports.SpriteService = SpriteService;
37960 Object.defineProperty(exports, "__esModule", { value: true });
37961 exports.default = SpriteService;
37962
37963 },{"../Viewer":234,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/startWith":77,"three":174,"virtual-dom":180}],349:[function(require,module,exports){
37964 "use strict";
37965 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
37966 var Observable_1 = require("rxjs/Observable");
37967 var Subject_1 = require("rxjs/Subject");
37968 require("rxjs/add/observable/timer");
37969 require("rxjs/add/operator/bufferWhen");
37970 require("rxjs/add/operator/filter");
37971 require("rxjs/add/operator/map");
37972 require("rxjs/add/operator/merge");
37973 require("rxjs/add/operator/scan");
37974 require("rxjs/add/operator/switchMap");
37975 var TouchService = (function () {
37976     function TouchService(element) {
37977         var _this = this;
37978         this._element = element;
37979         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
37980         this._active$ = this._activeSubject$
37981             .distinctUntilChanged()
37982             .publishReplay(1)
37983             .refCount();
37984         this._touchStart$ = Observable_1.Observable.fromEvent(element, "touchstart");
37985         this._touchMove$ = Observable_1.Observable.fromEvent(element, "touchmove");
37986         this._touchEnd$ = Observable_1.Observable.fromEvent(element, "touchend");
37987         this._touchCancel$ = Observable_1.Observable.fromEvent(element, "touchcancel");
37988         var tapStart$ = this._touchStart$
37989             .filter(function (te) {
37990             return te.touches.length === 1 && te.targetTouches.length === 1;
37991         })
37992             .share();
37993         this._doubleTap$ = tapStart$
37994             .bufferWhen(function () {
37995             return tapStart$
37996                 .first()
37997                 .switchMap(function (event) {
37998                 return Observable_1.Observable
37999                     .timer(300)
38000                     .merge(tapStart$)
38001                     .take(1);
38002             });
38003         })
38004             .filter(function (events) {
38005             return events.length === 2;
38006         })
38007             .map(function (events) {
38008             return events[events.length - 1];
38009         })
38010             .share();
38011         this._doubleTap$
38012             .subscribe(function (event) {
38013             event.preventDefault();
38014         });
38015         this._singleTouchMove$ = this._touchMove$
38016             .filter(function (te) {
38017             return te.touches.length === 1 && te.targetTouches.length === 1;
38018         })
38019             .share();
38020         var singleTouchStart$ = Observable_1.Observable
38021             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
38022             .filter(function (te) {
38023             return te.touches.length === 1 && te.targetTouches.length === 1;
38024         });
38025         var multipleTouchStart$ = Observable_1.Observable
38026             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
38027             .filter(function (te) {
38028             return te.touches.length >= 1;
38029         });
38030         var touchStop$ = Observable_1.Observable
38031             .merge(this._touchEnd$, this._touchCancel$)
38032             .filter(function (te) {
38033             return te.touches.length === 0;
38034         });
38035         this._singleTouchDragStart$ = singleTouchStart$
38036             .mergeMap(function (e) {
38037             return _this._singleTouchMove$
38038                 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
38039                 .take(1);
38040         });
38041         this._singleTouchDragEnd$ = singleTouchStart$
38042             .mergeMap(function (e) {
38043             return Observable_1.Observable
38044                 .merge(touchStop$, multipleTouchStart$)
38045                 .first();
38046         });
38047         this._singleTouchDrag$ = singleTouchStart$
38048             .switchMap(function (te) {
38049             return _this._singleTouchMove$
38050                 .skip(1)
38051                 .takeUntil(Observable_1.Observable
38052                 .merge(multipleTouchStart$, touchStop$));
38053         });
38054         var touchesChanged$ = Observable_1.Observable
38055             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
38056         this._pinchStart$ = touchesChanged$
38057             .filter(function (te) {
38058             return te.touches.length === 2 && te.targetTouches.length === 2;
38059         });
38060         this._pinchEnd$ = touchesChanged$
38061             .filter(function (te) {
38062             return te.touches.length !== 2 || te.targetTouches.length !== 2;
38063         });
38064         this._pinchOperation$ = new Subject_1.Subject();
38065         this._pinch$ = this._pinchOperation$
38066             .scan(function (pinch, operation) {
38067             return operation(pinch);
38068         }, {
38069             changeX: 0,
38070             changeY: 0,
38071             clientX: 0,
38072             clientY: 0,
38073             distance: 0,
38074             distanceChange: 0,
38075             distanceX: 0,
38076             distanceY: 0,
38077             originalEvent: null,
38078             pageX: 0,
38079             pageY: 0,
38080             screenX: 0,
38081             screenY: 0,
38082             touch1: null,
38083             touch2: null,
38084         });
38085         this._touchMove$
38086             .filter(function (te) {
38087             return te.touches.length === 2 && te.targetTouches.length === 2;
38088         })
38089             .map(function (te) {
38090             return function (previous) {
38091                 var touch1 = te.touches[0];
38092                 var touch2 = te.touches[1];
38093                 var minX = Math.min(touch1.clientX, touch2.clientX);
38094                 var maxX = Math.max(touch1.clientX, touch2.clientX);
38095                 var minY = Math.min(touch1.clientY, touch2.clientY);
38096                 var maxY = Math.max(touch1.clientY, touch2.clientY);
38097                 var centerClientX = minX + (maxX - minX) / 2;
38098                 var centerClientY = minY + (maxY - minY) / 2;
38099                 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
38100                 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
38101                 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
38102                 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
38103                 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
38104                 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
38105                 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
38106                 var distanceChange = distance - previous.distance;
38107                 var changeX = distanceX - previous.distanceX;
38108                 var changeY = distanceY - previous.distanceY;
38109                 var current = {
38110                     changeX: changeX,
38111                     changeY: changeY,
38112                     clientX: centerClientX,
38113                     clientY: centerClientY,
38114                     distance: distance,
38115                     distanceChange: distanceChange,
38116                     distanceX: distanceX,
38117                     distanceY: distanceY,
38118                     originalEvent: te,
38119                     pageX: centerPageX,
38120                     pageY: centerPageY,
38121                     screenX: centerScreenX,
38122                     screenY: centerScreenY,
38123                     touch1: touch1,
38124                     touch2: touch2,
38125                 };
38126                 return current;
38127             };
38128         })
38129             .subscribe(this._pinchOperation$);
38130         this._pinchChange$ = this._pinchStart$
38131             .switchMap(function (te) {
38132             return _this._pinch$
38133                 .skip(1)
38134                 .takeUntil(_this._pinchEnd$);
38135         });
38136     }
38137     Object.defineProperty(TouchService.prototype, "active$", {
38138         get: function () {
38139             return this._active$;
38140         },
38141         enumerable: true,
38142         configurable: true
38143     });
38144     Object.defineProperty(TouchService.prototype, "activate$", {
38145         get: function () {
38146             return this._activeSubject$;
38147         },
38148         enumerable: true,
38149         configurable: true
38150     });
38151     Object.defineProperty(TouchService.prototype, "doubleTap$", {
38152         get: function () {
38153             return this._doubleTap$;
38154         },
38155         enumerable: true,
38156         configurable: true
38157     });
38158     Object.defineProperty(TouchService.prototype, "touchStart$", {
38159         get: function () {
38160             return this._touchStart$;
38161         },
38162         enumerable: true,
38163         configurable: true
38164     });
38165     Object.defineProperty(TouchService.prototype, "touchMove$", {
38166         get: function () {
38167             return this._touchMove$;
38168         },
38169         enumerable: true,
38170         configurable: true
38171     });
38172     Object.defineProperty(TouchService.prototype, "touchEnd$", {
38173         get: function () {
38174             return this._touchEnd$;
38175         },
38176         enumerable: true,
38177         configurable: true
38178     });
38179     Object.defineProperty(TouchService.prototype, "touchCancel$", {
38180         get: function () {
38181             return this._touchCancel$;
38182         },
38183         enumerable: true,
38184         configurable: true
38185     });
38186     Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
38187         get: function () {
38188             return this._singleTouchDragStart$;
38189         },
38190         enumerable: true,
38191         configurable: true
38192     });
38193     Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
38194         get: function () {
38195             return this._singleTouchDrag$;
38196         },
38197         enumerable: true,
38198         configurable: true
38199     });
38200     Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
38201         get: function () {
38202             return this._singleTouchDragEnd$;
38203         },
38204         enumerable: true,
38205         configurable: true
38206     });
38207     Object.defineProperty(TouchService.prototype, "pinch$", {
38208         get: function () {
38209             return this._pinchChange$;
38210         },
38211         enumerable: true,
38212         configurable: true
38213     });
38214     Object.defineProperty(TouchService.prototype, "pinchStart$", {
38215         get: function () {
38216             return this._pinchStart$;
38217         },
38218         enumerable: true,
38219         configurable: true
38220     });
38221     Object.defineProperty(TouchService.prototype, "pinchEnd$", {
38222         get: function () {
38223             return this._pinchEnd$;
38224         },
38225         enumerable: true,
38226         configurable: true
38227     });
38228     return TouchService;
38229 }());
38230 exports.TouchService = TouchService;
38231
38232 },{"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/timer":46,"rxjs/add/operator/bufferWhen":50,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/scan":72,"rxjs/add/operator/switchMap":78}],350:[function(require,module,exports){
38233 /// <reference path="../../typings/index.d.ts" />
38234 "use strict";
38235 var __extends = (this && this.__extends) || function (d, b) {
38236     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
38237     function __() { this.constructor = d; }
38238     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
38239 };
38240 var when = require("when");
38241 var Viewer_1 = require("../Viewer");
38242 var Utils_1 = require("../Utils");
38243 /**
38244  * @class Viewer
38245  *
38246  * @classdesc The Viewer object represents the navigable photo viewer.
38247  * Create a Viewer by specifying a container, client ID, photo key and
38248  * other options. The viewer exposes methods and events for programmatic
38249  * interaction.
38250  */
38251 var Viewer = (function (_super) {
38252     __extends(Viewer, _super);
38253     /**
38254      * Create a new viewer instance.
38255      *
38256      * @param {string} id - Required `id` of a DOM element which will
38257      * be transformed into the viewer.
38258      * @param {string} clientId - Required `Mapillary API ClientID`. Can
38259      * be obtained from https://www.mapillary.com/app/settings/developers.
38260      * @param {string} [key] - Optional `photoId` to start from, can be any
38261      * Mapillary photo, if null no image is loaded.
38262      * @param {IViewerOptions} [options] - Optional configuration object
38263      * specifing Viewer's initial setup.
38264      * @param {string} [token] - Optional bearer token for API requests of
38265      * protected resources.
38266      *
38267      * @example
38268      * ```
38269      * var viewer = new Viewer("<element-id>", "<client-id>", "<my key>");
38270      * ```
38271      */
38272     function Viewer(id, clientId, key, options, token) {
38273         var _this = _super.call(this) || this;
38274         options = options != null ? options : {};
38275         Utils_1.Settings.setOptions(options);
38276         _this._navigator = new Viewer_1.Navigator(clientId, token);
38277         _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
38278         _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
38279         _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
38280         return _this;
38281     }
38282     /**
38283      * Activate a component.
38284      *
38285      * @param {string} name - Name of the component which will become active.
38286      *
38287      * @example
38288      * ```
38289      * viewer.activateComponent("mouse");
38290      * ```
38291      */
38292     Viewer.prototype.activateComponent = function (name) {
38293         this._componentController.activate(name);
38294     };
38295     /**
38296      * Activate the cover (deactivates all other components).
38297      */
38298     Viewer.prototype.activateCover = function () {
38299         this._componentController.activateCover();
38300     };
38301     /**
38302      * Deactivate a component.
38303      *
38304      * @param {string} name - Name of component which become inactive.
38305      *
38306      * @example
38307      * ```
38308      * viewer.deactivateComponent("mouse");
38309      * ```
38310      */
38311     Viewer.prototype.deactivateComponent = function (name) {
38312         this._componentController.deactivate(name);
38313     };
38314     /**
38315      * Deactivate the cover (activates all components marked as active).
38316      */
38317     Viewer.prototype.deactivateCover = function () {
38318         this._componentController.deactivateCover();
38319     };
38320     /**
38321      * Get the bearing of the current viewer camera.
38322      *
38323      * @description The bearing depends on how the camera
38324      * is currently rotated and does not correspond
38325      * to the compass angle of the current node if the view
38326      * has been panned.
38327      *
38328      * Bearing is measured in degrees clockwise with respect to
38329      * north.
38330      *
38331      * @returns {Promise<number>} Promise to the bearing
38332      * of the current viewer camera.
38333      *
38334      * @example
38335      * ```
38336      * viewer.getBearing().then((b) => { console.log(b); });
38337      * ```
38338      */
38339     Viewer.prototype.getBearing = function () {
38340         var _this = this;
38341         return when.promise(function (resolve, reject) {
38342             _this._container.renderService.bearing$
38343                 .first()
38344                 .subscribe(function (bearing) {
38345                 resolve(bearing);
38346             }, function (error) {
38347                 reject(error);
38348             });
38349         });
38350     };
38351     /**
38352      * Get the basic coordinates of the current photo that is
38353      * at the center of the viewport.
38354      *
38355      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
38356      * and have the origin point, (0, 0), at the top left corner and the
38357      * maximum value, (1, 1), at the bottom right corner of the original
38358      * photo.
38359      *
38360      * @returns {Promise<number[]>} Promise to the basic coordinates
38361      * of the current photo at the center for the viewport.
38362      *
38363      * @example
38364      * ```
38365      * viewer.getCenter().then((c) => { console.log(c); });
38366      * ```
38367      */
38368     Viewer.prototype.getCenter = function () {
38369         var _this = this;
38370         return when.promise(function (resolve, reject) {
38371             _this._navigator.stateService.getCenter()
38372                 .subscribe(function (center) {
38373                 resolve(center);
38374             }, function (error) {
38375                 reject(error);
38376             });
38377         });
38378     };
38379     /**
38380      * Get a component.
38381      *
38382      * @param {string} name - Name of component.
38383      * @returns {Component} The requested component.
38384      *
38385      * @example
38386      * ```
38387      * var mouseComponent = viewer.getComponent("mouse");
38388      * ```
38389      */
38390     Viewer.prototype.getComponent = function (name) {
38391         return this._componentController.get(name);
38392     };
38393     /**
38394      * Get the photo's current zoom level.
38395      *
38396      * @returns {Promise<number>} Promise to the viewers's current
38397      * zoom level.
38398      *
38399      * @example
38400      * ```
38401      * viewer.getZoom().then((z) => { console.log(z); });
38402      * ```
38403      */
38404     Viewer.prototype.getZoom = function () {
38405         var _this = this;
38406         return when.promise(function (resolve, reject) {
38407             _this._navigator.stateService.getZoom()
38408                 .subscribe(function (zoom) {
38409                 resolve(zoom);
38410             }, function (error) {
38411                 reject(error);
38412             });
38413         });
38414     };
38415     /**
38416      * Move close to given latitude and longitude.
38417      *
38418      * @description Because the method propagates IO errors, these potential errors
38419      * need to be handled by the method caller (see example).
38420      *
38421      * @param {Number} lat - Latitude, in degrees.
38422      * @param {Number} lon - Longitude, in degrees.
38423      * @returns {Promise<Node>} Promise to the node that was navigated to.
38424      * @throws {Error} If no nodes exist close to provided latitude
38425      * longitude.
38426      * @throws {Error} Propagates any IO errors to the caller.
38427      *
38428      * @example
38429      * ```
38430      * viewer.moveCloseTo(0, 0).then(
38431      *     (n) => { console.log(n); },
38432      *     (e) => { console.error(e); });
38433      * ```
38434      */
38435     Viewer.prototype.moveCloseTo = function (lat, lon) {
38436         var _this = this;
38437         return when.promise(function (resolve, reject) {
38438             _this._navigator.moveCloseTo$(lat, lon).subscribe(function (node) {
38439                 resolve(node);
38440             }, function (error) {
38441                 reject(error);
38442             });
38443         });
38444     };
38445     /**
38446      * Navigate in a given direction.
38447      *
38448      * @description This method has to be called through EdgeDirection enumeration as in the example.
38449      *
38450      * @param {EdgeDirection} dir - Direction in which which to move.
38451      * @returns {Promise<Node>} Promise to the node that was navigated to.
38452      * @throws {Error} If the current node does not have the edge direction
38453      * or the edges has not yet been cached.
38454      * @throws {Error} Propagates any IO errors to the caller.
38455      *
38456      * @example
38457      * ```
38458      * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
38459      *     (n) => { console.log(n); },
38460      *     (e) => { console.error(e); });
38461      * ```
38462      */
38463     Viewer.prototype.moveDir = function (dir) {
38464         var _this = this;
38465         return when.promise(function (resolve, reject) {
38466             _this._navigator.moveDir$(dir).subscribe(function (node) {
38467                 resolve(node);
38468             }, function (error) {
38469                 reject(error);
38470             });
38471         });
38472     };
38473     /**
38474      * Navigate to a given photo key.
38475      *
38476      * @param {string} key - A valid Mapillary photo key.
38477      * @returns {Promise<Node>} Promise to the node that was navigated to.
38478      * @throws {Error} Propagates any IO errors to the caller.
38479      *
38480      * @example
38481      * ```
38482      * viewer.moveToKey("<my key>").then(
38483      *     (n) => { console.log(n); },
38484      *     (e) => { console.error(e); });
38485      * ```
38486      */
38487     Viewer.prototype.moveToKey = function (key) {
38488         var _this = this;
38489         return when.promise(function (resolve, reject) {
38490             _this._navigator.moveToKey$(key).subscribe(function (node) {
38491                 resolve(node);
38492             }, function (error) {
38493                 reject(error);
38494             });
38495         });
38496     };
38497     /**
38498      * Detect the viewer's new width and height and resize it.
38499      *
38500      * @description The components will also detect the viewer's
38501      * new size and resize their rendered elements if needed.
38502      *
38503      * @example
38504      * ```
38505      * viewer.resize();
38506      * ```
38507      */
38508     Viewer.prototype.resize = function () {
38509         this._container.renderService.resize$.next(null);
38510         this._componentController.resize();
38511     };
38512     /**
38513      * Set a bearer token for authenticated API requests of
38514      * protected resources.
38515      *
38516      * @description When the supplied token is null or undefined,
38517      * any previously set bearer token will be cleared and the
38518      * viewer will make unauthenticated requests.
38519      *
38520      * Calling setAuthToken aborts all outstanding move requests.
38521      * The promises of those move requests will be rejected and
38522      * the rejections need to be caught.
38523      *
38524      * @param {string} [token] token - Bearer token.
38525      * @returns {Promise<void>} Promise that resolves after token
38526      * is set.
38527      *
38528      * @example
38529      * ```
38530      * viewer.setAuthToken("<my token>")
38531      *     .then(() => { console.log("token set"); });
38532      * ```
38533      */
38534     Viewer.prototype.setAuthToken = function (token) {
38535         var _this = this;
38536         return when.promise(function (resolve, reject) {
38537             _this._navigator.setToken$(token)
38538                 .subscribe(function () {
38539                 resolve(undefined);
38540             }, function (error) {
38541                 reject(error);
38542             });
38543         });
38544     };
38545     /**
38546      * Set the basic coordinates of the current photo to be in the
38547      * center of the viewport.
38548      *
38549      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
38550      * and has the origin point, (0, 0), at the top left corner and the
38551      * maximum value, (1, 1), at the bottom right corner of the original
38552      * photo.
38553      *
38554      * @param {number[]} The basic coordinates of the current
38555      * photo to be at the center for the viewport.
38556      *
38557      * @example
38558      * ```
38559      * viewer.setCenter([0.5, 0.5]);
38560      * ```
38561      */
38562     Viewer.prototype.setCenter = function (center) {
38563         this._navigator.stateService.setCenter(center);
38564     };
38565     /**
38566      * Set the filter selecting nodes to use when calculating
38567      * the spatial edges.
38568      *
38569      * @description The following filter types are supported:
38570      *
38571      * Comparison
38572      *
38573      * `["==", key, value]` equality: `node[key] = value`
38574      *
38575      * `["!=", key, value]` inequality: `node[key] ≠ value`
38576      *
38577      * `["<", key, value]` less than: `node[key] < value`
38578      *
38579      * `["<=", key, value]` less than or equal: `node[key] ≤ value`
38580      *
38581      * `[">", key, value]` greater than: `node[key] > value`
38582      *
38583      * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
38584      *
38585      * Set membership
38586      *
38587      * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
38588      *
38589      * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
38590      *
38591      * Combining
38592      *
38593      * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
38594      *
38595      * A key must be a string that identifies a node property name. A value must be
38596      * a string, number, or boolean. Strictly-typed comparisons are used. The values
38597      * `f0, ..., fn` of the combining filter must be filter expressions.
38598      *
38599      * Clear the filter by setting it to null or empty array.
38600      *
38601      * @param {FilterExpression} filter - The filter expression.
38602      * @returns {Promise<void>} Promise that resolves after filter is applied.
38603      *
38604      * @example
38605      * ```
38606      * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
38607      * ```
38608      */
38609     Viewer.prototype.setFilter = function (filter) {
38610         var _this = this;
38611         return when.promise(function (resolve, reject) {
38612             _this._navigator.setFilter$(filter)
38613                 .subscribe(function () {
38614                 resolve(undefined);
38615             }, function (error) {
38616                 reject(error);
38617             });
38618         });
38619     };
38620     /**
38621      * Set the viewer's render mode.
38622      *
38623      * @param {RenderMode} renderMode - Render mode.
38624      *
38625      * @example
38626      * ```
38627      * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
38628      * ```
38629      */
38630     Viewer.prototype.setRenderMode = function (renderMode) {
38631         this._container.renderService.renderMode$.next(renderMode);
38632     };
38633     /**
38634      * Set the photo's current zoom level.
38635      *
38636      * @description Possible zoom level values are on the [0, 3] interval.
38637      * Zero means zooming out to fit the photo to the view whereas three
38638      * shows the highest level of detail.
38639      *
38640      * @param {number} The photo's current zoom level.
38641      *
38642      * @example
38643      * ```
38644      * viewer.setZoom(2);
38645      * ```
38646      */
38647     Viewer.prototype.setZoom = function (zoom) {
38648         this._navigator.stateService.setZoom(zoom);
38649     };
38650     /**
38651      *
38652      * Returns an ILatLon representing geographical coordinates that correspond
38653      * to the specified pixel coordinates.
38654      *
38655      * @description The pixel point may not always correspond to geographical
38656      * coordinates. In the case of no correspondence the returned value will
38657      * be `null`.
38658      *
38659      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
38660      * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
38661      *
38662      * @example
38663      * ```
38664      * viewer.unproject([100, 100])
38665      *     .then((latLon) => { console.log(latLon); });
38666      * ```
38667      */
38668     Viewer.prototype.unproject = function (pixelPoint) {
38669         var _this = this;
38670         return when.promise(function (resolve, reject) {
38671             _this._observer.unproject$(pixelPoint)
38672                 .subscribe(function (latLon) {
38673                 resolve(latLon);
38674             }, function (error) {
38675                 reject(error);
38676             });
38677         });
38678     };
38679     return Viewer;
38680 }(Utils_1.EventEmitter));
38681 /**
38682  * Fired when the viewing direction of the camera changes.
38683  * @event
38684  * @type {number} bearing - Value indicating the current bearing
38685  * measured in degrees clockwise with respect to north.
38686  */
38687 Viewer.bearingchanged = "bearingchanged";
38688 /**
38689  * Fired when a pointing device (usually a mouse) is pressed and released at
38690  * the same point in the viewer.
38691  * @event
38692  * @type {IViewerMouseEvent} event - Viewer mouse event data.
38693  */
38694 Viewer.click = "click";
38695 /**
38696  * Fired when the right button of the mouse is clicked within the viewer.
38697  * @event
38698  * @type {IViewerMouseEvent} event - Viewer mouse event data.
38699  */
38700 Viewer.contextmenu = "contextmenu";
38701 /**
38702  * Fired when a pointing device (usually a mouse) is clicked twice at
38703  * the same point in the viewer.
38704  * @event
38705  * @type {IViewerMouseEvent} event - Viewer mouse event data.
38706  */
38707 Viewer.dblclick = "dblclick";
38708 /**
38709  * Fired when the viewer is loading more data.
38710  * @event
38711  * @type {boolean} loading - Value indicating whether the viewer is loading.
38712  */
38713 Viewer.loadingchanged = "loadingchanged";
38714 /**
38715  * Fired when a pointing device (usually a mouse) is pressed within the viewer.
38716  * @event
38717  * @type {IViewerMouseEvent} event - Viewer mouse event data.
38718  */
38719 Viewer.mousedown = "mousedown";
38720 /**
38721  * Fired when a pointing device (usually a mouse) is moved within the viewer.
38722  * @description Will not fire when the mouse is actively used, e.g. for drag pan.
38723  * @event
38724  * @type {IViewerMouseEvent} event - Viewer mouse event data.
38725  */
38726 Viewer.mousemove = "mousemove";
38727 /**
38728  * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
38729  * @event
38730  * @type {IViewerMouseEvent} event - Viewer mouse event data.
38731  */
38732 Viewer.mouseout = "mouseout";
38733 /**
38734  * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
38735  * @event
38736  * @type {IViewerMouseEvent} event - Viewer mouse event data.
38737  */
38738 Viewer.mouseover = "mouseover";
38739 /**
38740  * Fired when a pointing device (usually a mouse) is released within the viewer.
38741  * @event
38742  * @type {IViewerMouseEvent} event - Viewer mouse event data.
38743  */
38744 Viewer.mouseup = "mouseup";
38745 /**
38746  * Fired when the viewer motion stops and it is in a fixed
38747  * position with a fixed point of view.
38748  * @event
38749  */
38750 Viewer.moveend = "moveend";
38751 /**
38752  * Fired when the motion from one view to another start,
38753  * either by changing the position (e.g. when changing node) or
38754  * when changing point of view (e.g. by interaction such as pan and zoom).
38755  * @event
38756  */
38757 Viewer.movestart = "movestart";
38758 /**
38759  * Fired every time the viewer navigates to a new node.
38760  * @event
38761  * @type {Node} node - Current node.
38762  */
38763 Viewer.nodechanged = "nodechanged";
38764 /**
38765  * Fired every time the sequence edges of the current node changes.
38766  * @event
38767  * @type {IEdgeStatus} status - The edge status object.
38768  */
38769 Viewer.sequenceedgeschanged = "sequenceedgeschanged";
38770 /**
38771  * Fired every time the spatial edges of the current node changes.
38772  * @event
38773  * @type {IEdgeStatus} status - The edge status object.
38774  */
38775 Viewer.spatialedgeschanged = "spatialedgeschanged";
38776 exports.Viewer = Viewer;
38777
38778 },{"../Utils":233,"../Viewer":234,"when":221}]},{},[229])(229)
38779 });
38780 //# sourceMappingURL=mapillary.js.map