]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/iD/iD/mapillary-js/mapillary.js
fb7fe80e2d5bac1c8723486979117bb7ca19dd6c
[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":153}],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._subscribe(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     /**
5438      * @method forEach
5439      * @param {Function} next a handler for each value emitted by the observable
5440      * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5441      * @return {Promise} a promise that either resolves on observable completion or
5442      *  rejects with the handled error
5443      */
5444     Observable.prototype.forEach = function (next, PromiseCtor) {
5445         var _this = this;
5446         if (!PromiseCtor) {
5447             if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5448                 PromiseCtor = root_1.root.Rx.config.Promise;
5449             }
5450             else if (root_1.root.Promise) {
5451                 PromiseCtor = root_1.root.Promise;
5452             }
5453         }
5454         if (!PromiseCtor) {
5455             throw new Error('no Promise impl found');
5456         }
5457         return new PromiseCtor(function (resolve, reject) {
5458             var subscription = _this.subscribe(function (value) {
5459                 if (subscription) {
5460                     // if there is a subscription, then we can surmise
5461                     // the next handling is asynchronous. Any errors thrown
5462                     // need to be rejected explicitly and unsubscribe must be
5463                     // called manually
5464                     try {
5465                         next(value);
5466                     }
5467                     catch (err) {
5468                         reject(err);
5469                         subscription.unsubscribe();
5470                     }
5471                 }
5472                 else {
5473                     // if there is NO subscription, then we're getting a nexted
5474                     // value synchronously during subscription. We can just call it.
5475                     // If it errors, Observable's `subscribe` will ensure the
5476                     // unsubscription logic is called, then synchronously rethrow the error.
5477                     // After that, Promise will trap the error and send it
5478                     // down the rejection path.
5479                     next(value);
5480                 }
5481             }, reject, resolve);
5482         });
5483     };
5484     Observable.prototype._subscribe = function (subscriber) {
5485         return this.source.subscribe(subscriber);
5486     };
5487     /**
5488      * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5489      * @method Symbol.observable
5490      * @return {Observable} this instance of the observable
5491      */
5492     Observable.prototype[observable_1.$$observable] = function () {
5493         return this;
5494     };
5495     // HACK: Since TypeScript inherits static properties too, we have to
5496     // fight against TypeScript here so Subject can have a different static create signature
5497     /**
5498      * Creates a new cold Observable by calling the Observable constructor
5499      * @static true
5500      * @owner Observable
5501      * @method create
5502      * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5503      * @return {Observable} a new cold observable
5504      */
5505     Observable.create = function (subscribe) {
5506         return new Observable(subscribe);
5507     };
5508     return Observable;
5509 }());
5510 exports.Observable = Observable;
5511
5512 },{"./symbol/observable":148,"./util/root":163,"./util/toSubscriber":165}],29:[function(require,module,exports){
5513 "use strict";
5514 exports.empty = {
5515     closed: true,
5516     next: function (value) { },
5517     error: function (err) { throw err; },
5518     complete: function () { }
5519 };
5520
5521 },{}],30:[function(require,module,exports){
5522 "use strict";
5523 var __extends = (this && this.__extends) || function (d, b) {
5524     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5525     function __() { this.constructor = d; }
5526     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5527 };
5528 var Subscriber_1 = require('./Subscriber');
5529 /**
5530  * We need this JSDoc comment for affecting ESDoc.
5531  * @ignore
5532  * @extends {Ignored}
5533  */
5534 var OuterSubscriber = (function (_super) {
5535     __extends(OuterSubscriber, _super);
5536     function OuterSubscriber() {
5537         _super.apply(this, arguments);
5538     }
5539     OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5540         this.destination.next(innerValue);
5541     };
5542     OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5543         this.destination.error(error);
5544     };
5545     OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5546         this.destination.complete();
5547     };
5548     return OuterSubscriber;
5549 }(Subscriber_1.Subscriber));
5550 exports.OuterSubscriber = OuterSubscriber;
5551
5552 },{"./Subscriber":35}],31:[function(require,module,exports){
5553 "use strict";
5554 var __extends = (this && this.__extends) || function (d, b) {
5555     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5556     function __() { this.constructor = d; }
5557     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5558 };
5559 var Subject_1 = require('./Subject');
5560 var queue_1 = require('./scheduler/queue');
5561 var Subscription_1 = require('./Subscription');
5562 var observeOn_1 = require('./operator/observeOn');
5563 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5564 var SubjectSubscription_1 = require('./SubjectSubscription');
5565 /**
5566  * @class ReplaySubject<T>
5567  */
5568 var ReplaySubject = (function (_super) {
5569     __extends(ReplaySubject, _super);
5570     function ReplaySubject(bufferSize, windowTime, scheduler) {
5571         if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5572         if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5573         _super.call(this);
5574         this.scheduler = scheduler;
5575         this._events = [];
5576         this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5577         this._windowTime = windowTime < 1 ? 1 : windowTime;
5578     }
5579     ReplaySubject.prototype.next = function (value) {
5580         var now = this._getNow();
5581         this._events.push(new ReplayEvent(now, value));
5582         this._trimBufferThenGetEvents();
5583         _super.prototype.next.call(this, value);
5584     };
5585     ReplaySubject.prototype._subscribe = function (subscriber) {
5586         var _events = this._trimBufferThenGetEvents();
5587         var scheduler = this.scheduler;
5588         var subscription;
5589         if (this.closed) {
5590             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5591         }
5592         else if (this.hasError) {
5593             subscription = Subscription_1.Subscription.EMPTY;
5594         }
5595         else if (this.isStopped) {
5596             subscription = Subscription_1.Subscription.EMPTY;
5597         }
5598         else {
5599             this.observers.push(subscriber);
5600             subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5601         }
5602         if (scheduler) {
5603             subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5604         }
5605         var len = _events.length;
5606         for (var i = 0; i < len && !subscriber.closed; i++) {
5607             subscriber.next(_events[i].value);
5608         }
5609         if (this.hasError) {
5610             subscriber.error(this.thrownError);
5611         }
5612         else if (this.isStopped) {
5613             subscriber.complete();
5614         }
5615         return subscription;
5616     };
5617     ReplaySubject.prototype._getNow = function () {
5618         return (this.scheduler || queue_1.queue).now();
5619     };
5620     ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5621         var now = this._getNow();
5622         var _bufferSize = this._bufferSize;
5623         var _windowTime = this._windowTime;
5624         var _events = this._events;
5625         var eventsCount = _events.length;
5626         var spliceCount = 0;
5627         // Trim events that fall out of the time window.
5628         // Start at the front of the list. Break early once
5629         // we encounter an event that falls within the window.
5630         while (spliceCount < eventsCount) {
5631             if ((now - _events[spliceCount].time) < _windowTime) {
5632                 break;
5633             }
5634             spliceCount++;
5635         }
5636         if (eventsCount > _bufferSize) {
5637             spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5638         }
5639         if (spliceCount > 0) {
5640             _events.splice(0, spliceCount);
5641         }
5642         return _events;
5643     };
5644     return ReplaySubject;
5645 }(Subject_1.Subject));
5646 exports.ReplaySubject = ReplaySubject;
5647 var ReplayEvent = (function () {
5648     function ReplayEvent(time, value) {
5649         this.time = time;
5650         this.value = value;
5651     }
5652     return ReplayEvent;
5653 }());
5654
5655 },{"./Subject":33,"./SubjectSubscription":34,"./Subscription":36,"./operator/observeOn":123,"./scheduler/queue":146,"./util/ObjectUnsubscribedError":153}],32:[function(require,module,exports){
5656 "use strict";
5657 /**
5658  * An execution context and a data structure to order tasks and schedule their
5659  * execution. Provides a notion of (potentially virtual) time, through the
5660  * `now()` getter method.
5661  *
5662  * Each unit of work in a Scheduler is called an {@link Action}.
5663  *
5664  * ```ts
5665  * class Scheduler {
5666  *   now(): number;
5667  *   schedule(work, delay?, state?): Subscription;
5668  * }
5669  * ```
5670  *
5671  * @class Scheduler
5672  */
5673 var Scheduler = (function () {
5674     function Scheduler(SchedulerAction, now) {
5675         if (now === void 0) { now = Scheduler.now; }
5676         this.SchedulerAction = SchedulerAction;
5677         this.now = now;
5678     }
5679     /**
5680      * Schedules a function, `work`, for execution. May happen at some point in
5681      * the future, according to the `delay` parameter, if specified. May be passed
5682      * some context object, `state`, which will be passed to the `work` function.
5683      *
5684      * The given arguments will be processed an stored as an Action object in a
5685      * queue of actions.
5686      *
5687      * @param {function(state: ?T): ?Subscription} work A function representing a
5688      * task, or some unit of work to be executed by the Scheduler.
5689      * @param {number} [delay] Time to wait before executing the work, where the
5690      * time unit is implicit and defined by the Scheduler itself.
5691      * @param {T} [state] Some contextual data that the `work` function uses when
5692      * called by the Scheduler.
5693      * @return {Subscription} A subscription in order to be able to unsubscribe
5694      * the scheduled work.
5695      */
5696     Scheduler.prototype.schedule = function (work, delay, state) {
5697         if (delay === void 0) { delay = 0; }
5698         return new this.SchedulerAction(this, work).schedule(state, delay);
5699     };
5700     Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
5701     return Scheduler;
5702 }());
5703 exports.Scheduler = Scheduler;
5704
5705 },{}],33:[function(require,module,exports){
5706 "use strict";
5707 var __extends = (this && this.__extends) || function (d, b) {
5708     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5709     function __() { this.constructor = d; }
5710     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5711 };
5712 var Observable_1 = require('./Observable');
5713 var Subscriber_1 = require('./Subscriber');
5714 var Subscription_1 = require('./Subscription');
5715 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5716 var SubjectSubscription_1 = require('./SubjectSubscription');
5717 var rxSubscriber_1 = require('./symbol/rxSubscriber');
5718 /**
5719  * @class SubjectSubscriber<T>
5720  */
5721 var SubjectSubscriber = (function (_super) {
5722     __extends(SubjectSubscriber, _super);
5723     function SubjectSubscriber(destination) {
5724         _super.call(this, destination);
5725         this.destination = destination;
5726     }
5727     return SubjectSubscriber;
5728 }(Subscriber_1.Subscriber));
5729 exports.SubjectSubscriber = SubjectSubscriber;
5730 /**
5731  * @class Subject<T>
5732  */
5733 var Subject = (function (_super) {
5734     __extends(Subject, _super);
5735     function Subject() {
5736         _super.call(this);
5737         this.observers = [];
5738         this.closed = false;
5739         this.isStopped = false;
5740         this.hasError = false;
5741         this.thrownError = null;
5742     }
5743     Subject.prototype[rxSubscriber_1.$$rxSubscriber] = function () {
5744         return new SubjectSubscriber(this);
5745     };
5746     Subject.prototype.lift = function (operator) {
5747         var subject = new AnonymousSubject(this, this);
5748         subject.operator = operator;
5749         return subject;
5750     };
5751     Subject.prototype.next = function (value) {
5752         if (this.closed) {
5753             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5754         }
5755         if (!this.isStopped) {
5756             var observers = this.observers;
5757             var len = observers.length;
5758             var copy = observers.slice();
5759             for (var i = 0; i < len; i++) {
5760                 copy[i].next(value);
5761             }
5762         }
5763     };
5764     Subject.prototype.error = function (err) {
5765         if (this.closed) {
5766             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5767         }
5768         this.hasError = true;
5769         this.thrownError = err;
5770         this.isStopped = true;
5771         var observers = this.observers;
5772         var len = observers.length;
5773         var copy = observers.slice();
5774         for (var i = 0; i < len; i++) {
5775             copy[i].error(err);
5776         }
5777         this.observers.length = 0;
5778     };
5779     Subject.prototype.complete = function () {
5780         if (this.closed) {
5781             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5782         }
5783         this.isStopped = true;
5784         var observers = this.observers;
5785         var len = observers.length;
5786         var copy = observers.slice();
5787         for (var i = 0; i < len; i++) {
5788             copy[i].complete();
5789         }
5790         this.observers.length = 0;
5791     };
5792     Subject.prototype.unsubscribe = function () {
5793         this.isStopped = true;
5794         this.closed = true;
5795         this.observers = null;
5796     };
5797     Subject.prototype._subscribe = function (subscriber) {
5798         if (this.closed) {
5799             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5800         }
5801         else if (this.hasError) {
5802             subscriber.error(this.thrownError);
5803             return Subscription_1.Subscription.EMPTY;
5804         }
5805         else if (this.isStopped) {
5806             subscriber.complete();
5807             return Subscription_1.Subscription.EMPTY;
5808         }
5809         else {
5810             this.observers.push(subscriber);
5811             return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5812         }
5813     };
5814     Subject.prototype.asObservable = function () {
5815         var observable = new Observable_1.Observable();
5816         observable.source = this;
5817         return observable;
5818     };
5819     Subject.create = function (destination, source) {
5820         return new AnonymousSubject(destination, source);
5821     };
5822     return Subject;
5823 }(Observable_1.Observable));
5824 exports.Subject = Subject;
5825 /**
5826  * @class AnonymousSubject<T>
5827  */
5828 var AnonymousSubject = (function (_super) {
5829     __extends(AnonymousSubject, _super);
5830     function AnonymousSubject(destination, source) {
5831         _super.call(this);
5832         this.destination = destination;
5833         this.source = source;
5834     }
5835     AnonymousSubject.prototype.next = function (value) {
5836         var destination = this.destination;
5837         if (destination && destination.next) {
5838             destination.next(value);
5839         }
5840     };
5841     AnonymousSubject.prototype.error = function (err) {
5842         var destination = this.destination;
5843         if (destination && destination.error) {
5844             this.destination.error(err);
5845         }
5846     };
5847     AnonymousSubject.prototype.complete = function () {
5848         var destination = this.destination;
5849         if (destination && destination.complete) {
5850             this.destination.complete();
5851         }
5852     };
5853     AnonymousSubject.prototype._subscribe = function (subscriber) {
5854         var source = this.source;
5855         if (source) {
5856             return this.source.subscribe(subscriber);
5857         }
5858         else {
5859             return Subscription_1.Subscription.EMPTY;
5860         }
5861     };
5862     return AnonymousSubject;
5863 }(Subject));
5864 exports.AnonymousSubject = AnonymousSubject;
5865
5866 },{"./Observable":28,"./SubjectSubscription":34,"./Subscriber":35,"./Subscription":36,"./symbol/rxSubscriber":149,"./util/ObjectUnsubscribedError":153}],34:[function(require,module,exports){
5867 "use strict";
5868 var __extends = (this && this.__extends) || function (d, b) {
5869     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5870     function __() { this.constructor = d; }
5871     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5872 };
5873 var Subscription_1 = require('./Subscription');
5874 /**
5875  * We need this JSDoc comment for affecting ESDoc.
5876  * @ignore
5877  * @extends {Ignored}
5878  */
5879 var SubjectSubscription = (function (_super) {
5880     __extends(SubjectSubscription, _super);
5881     function SubjectSubscription(subject, subscriber) {
5882         _super.call(this);
5883         this.subject = subject;
5884         this.subscriber = subscriber;
5885         this.closed = false;
5886     }
5887     SubjectSubscription.prototype.unsubscribe = function () {
5888         if (this.closed) {
5889             return;
5890         }
5891         this.closed = true;
5892         var subject = this.subject;
5893         var observers = subject.observers;
5894         this.subject = null;
5895         if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
5896             return;
5897         }
5898         var subscriberIndex = observers.indexOf(this.subscriber);
5899         if (subscriberIndex !== -1) {
5900             observers.splice(subscriberIndex, 1);
5901         }
5902     };
5903     return SubjectSubscription;
5904 }(Subscription_1.Subscription));
5905 exports.SubjectSubscription = SubjectSubscription;
5906
5907 },{"./Subscription":36}],35:[function(require,module,exports){
5908 "use strict";
5909 var __extends = (this && this.__extends) || function (d, b) {
5910     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5911     function __() { this.constructor = d; }
5912     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5913 };
5914 var isFunction_1 = require('./util/isFunction');
5915 var Subscription_1 = require('./Subscription');
5916 var Observer_1 = require('./Observer');
5917 var rxSubscriber_1 = require('./symbol/rxSubscriber');
5918 /**
5919  * Implements the {@link Observer} interface and extends the
5920  * {@link Subscription} class. While the {@link Observer} is the public API for
5921  * consuming the values of an {@link Observable}, all Observers get converted to
5922  * a Subscriber, in order to provide Subscription-like capabilities such as
5923  * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
5924  * implementing operators, but it is rarely used as a public API.
5925  *
5926  * @class Subscriber<T>
5927  */
5928 var Subscriber = (function (_super) {
5929     __extends(Subscriber, _super);
5930     /**
5931      * @param {Observer|function(value: T): void} [destinationOrNext] A partially
5932      * defined Observer or a `next` callback function.
5933      * @param {function(e: ?any): void} [error] The `error` callback of an
5934      * Observer.
5935      * @param {function(): void} [complete] The `complete` callback of an
5936      * Observer.
5937      */
5938     function Subscriber(destinationOrNext, error, complete) {
5939         _super.call(this);
5940         this.syncErrorValue = null;
5941         this.syncErrorThrown = false;
5942         this.syncErrorThrowable = false;
5943         this.isStopped = false;
5944         switch (arguments.length) {
5945             case 0:
5946                 this.destination = Observer_1.empty;
5947                 break;
5948             case 1:
5949                 if (!destinationOrNext) {
5950                     this.destination = Observer_1.empty;
5951                     break;
5952                 }
5953                 if (typeof destinationOrNext === 'object') {
5954                     if (destinationOrNext instanceof Subscriber) {
5955                         this.destination = destinationOrNext;
5956                         this.destination.add(this);
5957                     }
5958                     else {
5959                         this.syncErrorThrowable = true;
5960                         this.destination = new SafeSubscriber(this, destinationOrNext);
5961                     }
5962                     break;
5963                 }
5964             default:
5965                 this.syncErrorThrowable = true;
5966                 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
5967                 break;
5968         }
5969     }
5970     Subscriber.prototype[rxSubscriber_1.$$rxSubscriber] = function () { return this; };
5971     /**
5972      * A static factory for a Subscriber, given a (potentially partial) definition
5973      * of an Observer.
5974      * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
5975      * @param {function(e: ?any): void} [error] The `error` callback of an
5976      * Observer.
5977      * @param {function(): void} [complete] The `complete` callback of an
5978      * Observer.
5979      * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
5980      * Observer represented by the given arguments.
5981      */
5982     Subscriber.create = function (next, error, complete) {
5983         var subscriber = new Subscriber(next, error, complete);
5984         subscriber.syncErrorThrowable = false;
5985         return subscriber;
5986     };
5987     /**
5988      * The {@link Observer} callback to receive notifications of type `next` from
5989      * the Observable, with a value. The Observable may call this method 0 or more
5990      * times.
5991      * @param {T} [value] The `next` value.
5992      * @return {void}
5993      */
5994     Subscriber.prototype.next = function (value) {
5995         if (!this.isStopped) {
5996             this._next(value);
5997         }
5998     };
5999     /**
6000      * The {@link Observer} callback to receive notifications of type `error` from
6001      * the Observable, with an attached {@link Error}. Notifies the Observer that
6002      * the Observable has experienced an error condition.
6003      * @param {any} [err] The `error` exception.
6004      * @return {void}
6005      */
6006     Subscriber.prototype.error = function (err) {
6007         if (!this.isStopped) {
6008             this.isStopped = true;
6009             this._error(err);
6010         }
6011     };
6012     /**
6013      * The {@link Observer} callback to receive a valueless notification of type
6014      * `complete` from the Observable. Notifies the Observer that the Observable
6015      * has finished sending push-based notifications.
6016      * @return {void}
6017      */
6018     Subscriber.prototype.complete = function () {
6019         if (!this.isStopped) {
6020             this.isStopped = true;
6021             this._complete();
6022         }
6023     };
6024     Subscriber.prototype.unsubscribe = function () {
6025         if (this.closed) {
6026             return;
6027         }
6028         this.isStopped = true;
6029         _super.prototype.unsubscribe.call(this);
6030     };
6031     Subscriber.prototype._next = function (value) {
6032         this.destination.next(value);
6033     };
6034     Subscriber.prototype._error = function (err) {
6035         this.destination.error(err);
6036         this.unsubscribe();
6037     };
6038     Subscriber.prototype._complete = function () {
6039         this.destination.complete();
6040         this.unsubscribe();
6041     };
6042     return Subscriber;
6043 }(Subscription_1.Subscription));
6044 exports.Subscriber = Subscriber;
6045 /**
6046  * We need this JSDoc comment for affecting ESDoc.
6047  * @ignore
6048  * @extends {Ignored}
6049  */
6050 var SafeSubscriber = (function (_super) {
6051     __extends(SafeSubscriber, _super);
6052     function SafeSubscriber(_parent, observerOrNext, error, complete) {
6053         _super.call(this);
6054         this._parent = _parent;
6055         var next;
6056         var context = this;
6057         if (isFunction_1.isFunction(observerOrNext)) {
6058             next = observerOrNext;
6059         }
6060         else if (observerOrNext) {
6061             context = observerOrNext;
6062             next = observerOrNext.next;
6063             error = observerOrNext.error;
6064             complete = observerOrNext.complete;
6065             if (isFunction_1.isFunction(context.unsubscribe)) {
6066                 this.add(context.unsubscribe.bind(context));
6067             }
6068             context.unsubscribe = this.unsubscribe.bind(this);
6069         }
6070         this._context = context;
6071         this._next = next;
6072         this._error = error;
6073         this._complete = complete;
6074     }
6075     SafeSubscriber.prototype.next = function (value) {
6076         if (!this.isStopped && this._next) {
6077             var _parent = this._parent;
6078             if (!_parent.syncErrorThrowable) {
6079                 this.__tryOrUnsub(this._next, value);
6080             }
6081             else if (this.__tryOrSetError(_parent, this._next, value)) {
6082                 this.unsubscribe();
6083             }
6084         }
6085     };
6086     SafeSubscriber.prototype.error = function (err) {
6087         if (!this.isStopped) {
6088             var _parent = this._parent;
6089             if (this._error) {
6090                 if (!_parent.syncErrorThrowable) {
6091                     this.__tryOrUnsub(this._error, err);
6092                     this.unsubscribe();
6093                 }
6094                 else {
6095                     this.__tryOrSetError(_parent, this._error, err);
6096                     this.unsubscribe();
6097                 }
6098             }
6099             else if (!_parent.syncErrorThrowable) {
6100                 this.unsubscribe();
6101                 throw err;
6102             }
6103             else {
6104                 _parent.syncErrorValue = err;
6105                 _parent.syncErrorThrown = true;
6106                 this.unsubscribe();
6107             }
6108         }
6109     };
6110     SafeSubscriber.prototype.complete = function () {
6111         if (!this.isStopped) {
6112             var _parent = this._parent;
6113             if (this._complete) {
6114                 if (!_parent.syncErrorThrowable) {
6115                     this.__tryOrUnsub(this._complete);
6116                     this.unsubscribe();
6117                 }
6118                 else {
6119                     this.__tryOrSetError(_parent, this._complete);
6120                     this.unsubscribe();
6121                 }
6122             }
6123             else {
6124                 this.unsubscribe();
6125             }
6126         }
6127     };
6128     SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6129         try {
6130             fn.call(this._context, value);
6131         }
6132         catch (err) {
6133             this.unsubscribe();
6134             throw err;
6135         }
6136     };
6137     SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6138         try {
6139             fn.call(this._context, value);
6140         }
6141         catch (err) {
6142             parent.syncErrorValue = err;
6143             parent.syncErrorThrown = true;
6144             return true;
6145         }
6146         return false;
6147     };
6148     SafeSubscriber.prototype._unsubscribe = function () {
6149         var _parent = this._parent;
6150         this._context = null;
6151         this._parent = null;
6152         _parent.unsubscribe();
6153     };
6154     return SafeSubscriber;
6155 }(Subscriber));
6156
6157 },{"./Observer":29,"./Subscription":36,"./symbol/rxSubscriber":149,"./util/isFunction":159}],36:[function(require,module,exports){
6158 "use strict";
6159 var __extends = (this && this.__extends) || function (d, b) {
6160     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6161     function __() { this.constructor = d; }
6162     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6163 };
6164 var isArray_1 = require('./util/isArray');
6165 var isObject_1 = require('./util/isObject');
6166 var isFunction_1 = require('./util/isFunction');
6167 var tryCatch_1 = require('./util/tryCatch');
6168 var errorObject_1 = require('./util/errorObject');
6169 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6170 /**
6171  * Represents a disposable resource, such as the execution of an Observable. A
6172  * Subscription has one important method, `unsubscribe`, that takes no argument
6173  * and just disposes the resource held by the subscription.
6174  *
6175  * Additionally, subscriptions may be grouped together through the `add()`
6176  * method, which will attach a child Subscription to the current Subscription.
6177  * When a Subscription is unsubscribed, all its children (and its grandchildren)
6178  * will be unsubscribed as well.
6179  *
6180  * @class Subscription
6181  */
6182 var Subscription = (function () {
6183     /**
6184      * @param {function(): void} [unsubscribe] A function describing how to
6185      * perform the disposal of resources when the `unsubscribe` method is called.
6186      */
6187     function Subscription(unsubscribe) {
6188         /**
6189          * A flag to indicate whether this Subscription has already been unsubscribed.
6190          * @type {boolean}
6191          */
6192         this.closed = false;
6193         if (unsubscribe) {
6194             this._unsubscribe = unsubscribe;
6195         }
6196     }
6197     /**
6198      * Disposes the resources held by the subscription. May, for instance, cancel
6199      * an ongoing Observable execution or cancel any other type of work that
6200      * started when the Subscription was created.
6201      * @return {void}
6202      */
6203     Subscription.prototype.unsubscribe = function () {
6204         var hasErrors = false;
6205         var errors;
6206         if (this.closed) {
6207             return;
6208         }
6209         this.closed = true;
6210         var _a = this, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6211         this._subscriptions = null;
6212         if (isFunction_1.isFunction(_unsubscribe)) {
6213             var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6214             if (trial === errorObject_1.errorObject) {
6215                 hasErrors = true;
6216                 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6217                     flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6218             }
6219         }
6220         if (isArray_1.isArray(_subscriptions)) {
6221             var index = -1;
6222             var len = _subscriptions.length;
6223             while (++index < len) {
6224                 var sub = _subscriptions[index];
6225                 if (isObject_1.isObject(sub)) {
6226                     var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6227                     if (trial === errorObject_1.errorObject) {
6228                         hasErrors = true;
6229                         errors = errors || [];
6230                         var err = errorObject_1.errorObject.e;
6231                         if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6232                             errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6233                         }
6234                         else {
6235                             errors.push(err);
6236                         }
6237                     }
6238                 }
6239             }
6240         }
6241         if (hasErrors) {
6242             throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6243         }
6244     };
6245     /**
6246      * Adds a tear down to be called during the unsubscribe() of this
6247      * Subscription.
6248      *
6249      * If the tear down being added is a subscription that is already
6250      * unsubscribed, is the same reference `add` is being called on, or is
6251      * `Subscription.EMPTY`, it will not be added.
6252      *
6253      * If this subscription is already in an `closed` state, the passed
6254      * tear down logic will be executed immediately.
6255      *
6256      * @param {TeardownLogic} teardown The additional logic to execute on
6257      * teardown.
6258      * @return {Subscription} Returns the Subscription used or created to be
6259      * added to the inner subscriptions list. This Subscription can be used with
6260      * `remove()` to remove the passed teardown logic from the inner subscriptions
6261      * list.
6262      */
6263     Subscription.prototype.add = function (teardown) {
6264         if (!teardown || (teardown === Subscription.EMPTY)) {
6265             return Subscription.EMPTY;
6266         }
6267         if (teardown === this) {
6268             return this;
6269         }
6270         var sub = teardown;
6271         switch (typeof teardown) {
6272             case 'function':
6273                 sub = new Subscription(teardown);
6274             case 'object':
6275                 if (sub.closed || typeof sub.unsubscribe !== 'function') {
6276                     return sub;
6277                 }
6278                 else if (this.closed) {
6279                     sub.unsubscribe();
6280                     return sub;
6281                 }
6282                 break;
6283             default:
6284                 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6285         }
6286         var childSub = new ChildSubscription(sub, this);
6287         this._subscriptions = this._subscriptions || [];
6288         this._subscriptions.push(childSub);
6289         return childSub;
6290     };
6291     /**
6292      * Removes a Subscription from the internal list of subscriptions that will
6293      * unsubscribe during the unsubscribe process of this Subscription.
6294      * @param {Subscription} subscription The subscription to remove.
6295      * @return {void}
6296      */
6297     Subscription.prototype.remove = function (subscription) {
6298         // HACK: This might be redundant because of the logic in `add()`
6299         if (subscription == null || (subscription === this) || (subscription === Subscription.EMPTY)) {
6300             return;
6301         }
6302         var subscriptions = this._subscriptions;
6303         if (subscriptions) {
6304             var subscriptionIndex = subscriptions.indexOf(subscription);
6305             if (subscriptionIndex !== -1) {
6306                 subscriptions.splice(subscriptionIndex, 1);
6307             }
6308         }
6309     };
6310     Subscription.EMPTY = (function (empty) {
6311         empty.closed = true;
6312         return empty;
6313     }(new Subscription()));
6314     return Subscription;
6315 }());
6316 exports.Subscription = Subscription;
6317 var ChildSubscription = (function (_super) {
6318     __extends(ChildSubscription, _super);
6319     function ChildSubscription(_innerSub, _parent) {
6320         _super.call(this);
6321         this._innerSub = _innerSub;
6322         this._parent = _parent;
6323     }
6324     ChildSubscription.prototype._unsubscribe = function () {
6325         var _a = this, _innerSub = _a._innerSub, _parent = _a._parent;
6326         _parent.remove(this);
6327         _innerSub.unsubscribe();
6328     };
6329     return ChildSubscription;
6330 }(Subscription));
6331 exports.ChildSubscription = ChildSubscription;
6332 function flattenUnsubscriptionErrors(errors) {
6333     return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6334 }
6335
6336 },{"./util/UnsubscriptionError":155,"./util/errorObject":156,"./util/isArray":157,"./util/isFunction":159,"./util/isObject":160,"./util/tryCatch":166}],37:[function(require,module,exports){
6337 "use strict";
6338 var Observable_1 = require('../../Observable');
6339 var combineLatest_1 = require('../../observable/combineLatest');
6340 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6341
6342 },{"../../Observable":28,"../../observable/combineLatest":93}],38:[function(require,module,exports){
6343 "use strict";
6344 var Observable_1 = require('../../Observable');
6345 var defer_1 = require('../../observable/defer');
6346 Observable_1.Observable.defer = defer_1.defer;
6347
6348 },{"../../Observable":28,"../../observable/defer":94}],39:[function(require,module,exports){
6349 "use strict";
6350 var Observable_1 = require('../../Observable');
6351 var empty_1 = require('../../observable/empty');
6352 Observable_1.Observable.empty = empty_1.empty;
6353
6354 },{"../../Observable":28,"../../observable/empty":95}],40:[function(require,module,exports){
6355 "use strict";
6356 var Observable_1 = require('../../Observable');
6357 var from_1 = require('../../observable/from');
6358 Observable_1.Observable.from = from_1.from;
6359
6360 },{"../../Observable":28,"../../observable/from":96}],41:[function(require,module,exports){
6361 "use strict";
6362 var Observable_1 = require('../../Observable');
6363 var fromEvent_1 = require('../../observable/fromEvent');
6364 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6365
6366 },{"../../Observable":28,"../../observable/fromEvent":97}],42:[function(require,module,exports){
6367 "use strict";
6368 var Observable_1 = require('../../Observable');
6369 var fromPromise_1 = require('../../observable/fromPromise');
6370 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6371
6372 },{"../../Observable":28,"../../observable/fromPromise":98}],43:[function(require,module,exports){
6373 "use strict";
6374 var Observable_1 = require('../../Observable');
6375 var merge_1 = require('../../observable/merge');
6376 Observable_1.Observable.merge = merge_1.merge;
6377
6378 },{"../../Observable":28,"../../observable/merge":99}],44:[function(require,module,exports){
6379 "use strict";
6380 var Observable_1 = require('../../Observable');
6381 var of_1 = require('../../observable/of');
6382 Observable_1.Observable.of = of_1.of;
6383
6384 },{"../../Observable":28,"../../observable/of":100}],45:[function(require,module,exports){
6385 "use strict";
6386 var Observable_1 = require('../../Observable');
6387 var throw_1 = require('../../observable/throw');
6388 Observable_1.Observable.throw = throw_1._throw;
6389
6390 },{"../../Observable":28,"../../observable/throw":101}],46:[function(require,module,exports){
6391 "use strict";
6392 var Observable_1 = require('../../Observable');
6393 var zip_1 = require('../../observable/zip');
6394 Observable_1.Observable.zip = zip_1.zip;
6395
6396 },{"../../Observable":28,"../../observable/zip":102}],47:[function(require,module,exports){
6397 "use strict";
6398 var Observable_1 = require('../../Observable');
6399 var buffer_1 = require('../../operator/buffer');
6400 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6401
6402 },{"../../Observable":28,"../../operator/buffer":103}],48:[function(require,module,exports){
6403 "use strict";
6404 var Observable_1 = require('../../Observable');
6405 var bufferCount_1 = require('../../operator/bufferCount');
6406 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6407
6408 },{"../../Observable":28,"../../operator/bufferCount":104}],49:[function(require,module,exports){
6409 "use strict";
6410 var Observable_1 = require('../../Observable');
6411 var catch_1 = require('../../operator/catch');
6412 Observable_1.Observable.prototype.catch = catch_1._catch;
6413 Observable_1.Observable.prototype._catch = catch_1._catch;
6414
6415 },{"../../Observable":28,"../../operator/catch":105}],50:[function(require,module,exports){
6416 "use strict";
6417 var Observable_1 = require('../../Observable');
6418 var combineLatest_1 = require('../../operator/combineLatest');
6419 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6420
6421 },{"../../Observable":28,"../../operator/combineLatest":106}],51:[function(require,module,exports){
6422 "use strict";
6423 var Observable_1 = require('../../Observable');
6424 var concat_1 = require('../../operator/concat');
6425 Observable_1.Observable.prototype.concat = concat_1.concat;
6426
6427 },{"../../Observable":28,"../../operator/concat":107}],52:[function(require,module,exports){
6428 "use strict";
6429 var Observable_1 = require('../../Observable');
6430 var debounceTime_1 = require('../../operator/debounceTime');
6431 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6432
6433 },{"../../Observable":28,"../../operator/debounceTime":108}],53:[function(require,module,exports){
6434 "use strict";
6435 var Observable_1 = require('../../Observable');
6436 var delay_1 = require('../../operator/delay');
6437 Observable_1.Observable.prototype.delay = delay_1.delay;
6438
6439 },{"../../Observable":28,"../../operator/delay":109}],54:[function(require,module,exports){
6440 "use strict";
6441 var Observable_1 = require('../../Observable');
6442 var distinct_1 = require('../../operator/distinct');
6443 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6444
6445 },{"../../Observable":28,"../../operator/distinct":110}],55:[function(require,module,exports){
6446 "use strict";
6447 var Observable_1 = require('../../Observable');
6448 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6449 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6450
6451 },{"../../Observable":28,"../../operator/distinctUntilChanged":111}],56:[function(require,module,exports){
6452 "use strict";
6453 var Observable_1 = require('../../Observable');
6454 var do_1 = require('../../operator/do');
6455 Observable_1.Observable.prototype.do = do_1._do;
6456 Observable_1.Observable.prototype._do = do_1._do;
6457
6458 },{"../../Observable":28,"../../operator/do":112}],57:[function(require,module,exports){
6459 "use strict";
6460 var Observable_1 = require('../../Observable');
6461 var expand_1 = require('../../operator/expand');
6462 Observable_1.Observable.prototype.expand = expand_1.expand;
6463
6464 },{"../../Observable":28,"../../operator/expand":113}],58:[function(require,module,exports){
6465 "use strict";
6466 var Observable_1 = require('../../Observable');
6467 var filter_1 = require('../../operator/filter');
6468 Observable_1.Observable.prototype.filter = filter_1.filter;
6469
6470 },{"../../Observable":28,"../../operator/filter":114}],59:[function(require,module,exports){
6471 "use strict";
6472 var Observable_1 = require('../../Observable');
6473 var finally_1 = require('../../operator/finally');
6474 Observable_1.Observable.prototype.finally = finally_1._finally;
6475 Observable_1.Observable.prototype._finally = finally_1._finally;
6476
6477 },{"../../Observable":28,"../../operator/finally":115}],60:[function(require,module,exports){
6478 "use strict";
6479 var Observable_1 = require('../../Observable');
6480 var first_1 = require('../../operator/first');
6481 Observable_1.Observable.prototype.first = first_1.first;
6482
6483 },{"../../Observable":28,"../../operator/first":116}],61:[function(require,module,exports){
6484 "use strict";
6485 var Observable_1 = require('../../Observable');
6486 var last_1 = require('../../operator/last');
6487 Observable_1.Observable.prototype.last = last_1.last;
6488
6489 },{"../../Observable":28,"../../operator/last":117}],62:[function(require,module,exports){
6490 "use strict";
6491 var Observable_1 = require('../../Observable');
6492 var map_1 = require('../../operator/map');
6493 Observable_1.Observable.prototype.map = map_1.map;
6494
6495 },{"../../Observable":28,"../../operator/map":118}],63:[function(require,module,exports){
6496 "use strict";
6497 var Observable_1 = require('../../Observable');
6498 var merge_1 = require('../../operator/merge');
6499 Observable_1.Observable.prototype.merge = merge_1.merge;
6500
6501 },{"../../Observable":28,"../../operator/merge":119}],64:[function(require,module,exports){
6502 "use strict";
6503 var Observable_1 = require('../../Observable');
6504 var mergeAll_1 = require('../../operator/mergeAll');
6505 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6506
6507 },{"../../Observable":28,"../../operator/mergeAll":120}],65:[function(require,module,exports){
6508 "use strict";
6509 var Observable_1 = require('../../Observable');
6510 var mergeMap_1 = require('../../operator/mergeMap');
6511 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6512 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6513
6514 },{"../../Observable":28,"../../operator/mergeMap":121}],66:[function(require,module,exports){
6515 "use strict";
6516 var Observable_1 = require('../../Observable');
6517 var pairwise_1 = require('../../operator/pairwise');
6518 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6519
6520 },{"../../Observable":28,"../../operator/pairwise":124}],67:[function(require,module,exports){
6521 "use strict";
6522 var Observable_1 = require('../../Observable');
6523 var pluck_1 = require('../../operator/pluck');
6524 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6525
6526 },{"../../Observable":28,"../../operator/pluck":125}],68:[function(require,module,exports){
6527 "use strict";
6528 var Observable_1 = require('../../Observable');
6529 var publish_1 = require('../../operator/publish');
6530 Observable_1.Observable.prototype.publish = publish_1.publish;
6531
6532 },{"../../Observable":28,"../../operator/publish":126}],69:[function(require,module,exports){
6533 "use strict";
6534 var Observable_1 = require('../../Observable');
6535 var publishReplay_1 = require('../../operator/publishReplay');
6536 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6537
6538 },{"../../Observable":28,"../../operator/publishReplay":127}],70:[function(require,module,exports){
6539 "use strict";
6540 var Observable_1 = require('../../Observable');
6541 var scan_1 = require('../../operator/scan');
6542 Observable_1.Observable.prototype.scan = scan_1.scan;
6543
6544 },{"../../Observable":28,"../../operator/scan":128}],71:[function(require,module,exports){
6545 "use strict";
6546 var Observable_1 = require('../../Observable');
6547 var share_1 = require('../../operator/share');
6548 Observable_1.Observable.prototype.share = share_1.share;
6549
6550 },{"../../Observable":28,"../../operator/share":129}],72:[function(require,module,exports){
6551 "use strict";
6552 var Observable_1 = require('../../Observable');
6553 var skip_1 = require('../../operator/skip');
6554 Observable_1.Observable.prototype.skip = skip_1.skip;
6555
6556 },{"../../Observable":28,"../../operator/skip":130}],73:[function(require,module,exports){
6557 "use strict";
6558 var Observable_1 = require('../../Observable');
6559 var skipUntil_1 = require('../../operator/skipUntil');
6560 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6561
6562 },{"../../Observable":28,"../../operator/skipUntil":131}],74:[function(require,module,exports){
6563 "use strict";
6564 var Observable_1 = require('../../Observable');
6565 var skipWhile_1 = require('../../operator/skipWhile');
6566 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
6567
6568 },{"../../Observable":28,"../../operator/skipWhile":132}],75:[function(require,module,exports){
6569 "use strict";
6570 var Observable_1 = require('../../Observable');
6571 var startWith_1 = require('../../operator/startWith');
6572 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
6573
6574 },{"../../Observable":28,"../../operator/startWith":133}],76:[function(require,module,exports){
6575 "use strict";
6576 var Observable_1 = require('../../Observable');
6577 var switchMap_1 = require('../../operator/switchMap');
6578 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
6579
6580 },{"../../Observable":28,"../../operator/switchMap":134}],77:[function(require,module,exports){
6581 "use strict";
6582 var Observable_1 = require('../../Observable');
6583 var take_1 = require('../../operator/take');
6584 Observable_1.Observable.prototype.take = take_1.take;
6585
6586 },{"../../Observable":28,"../../operator/take":135}],78:[function(require,module,exports){
6587 "use strict";
6588 var Observable_1 = require('../../Observable');
6589 var takeUntil_1 = require('../../operator/takeUntil');
6590 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
6591
6592 },{"../../Observable":28,"../../operator/takeUntil":136}],79:[function(require,module,exports){
6593 "use strict";
6594 var Observable_1 = require('../../Observable');
6595 var throttleTime_1 = require('../../operator/throttleTime');
6596 Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime;
6597
6598 },{"../../Observable":28,"../../operator/throttleTime":137}],80:[function(require,module,exports){
6599 "use strict";
6600 var Observable_1 = require('../../Observable');
6601 var withLatestFrom_1 = require('../../operator/withLatestFrom');
6602 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
6603
6604 },{"../../Observable":28,"../../operator/withLatestFrom":138}],81:[function(require,module,exports){
6605 "use strict";
6606 var Observable_1 = require('../../Observable');
6607 var zip_1 = require('../../operator/zip');
6608 Observable_1.Observable.prototype.zip = zip_1.zipProto;
6609
6610 },{"../../Observable":28,"../../operator/zip":139}],82:[function(require,module,exports){
6611 "use strict";
6612 var __extends = (this && this.__extends) || function (d, b) {
6613     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6614     function __() { this.constructor = d; }
6615     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6616 };
6617 var Observable_1 = require('../Observable');
6618 var ScalarObservable_1 = require('./ScalarObservable');
6619 var EmptyObservable_1 = require('./EmptyObservable');
6620 /**
6621  * We need this JSDoc comment for affecting ESDoc.
6622  * @extends {Ignored}
6623  * @hide true
6624  */
6625 var ArrayLikeObservable = (function (_super) {
6626     __extends(ArrayLikeObservable, _super);
6627     function ArrayLikeObservable(arrayLike, scheduler) {
6628         _super.call(this);
6629         this.arrayLike = arrayLike;
6630         this.scheduler = scheduler;
6631         if (!scheduler && arrayLike.length === 1) {
6632             this._isScalar = true;
6633             this.value = arrayLike[0];
6634         }
6635     }
6636     ArrayLikeObservable.create = function (arrayLike, scheduler) {
6637         var length = arrayLike.length;
6638         if (length === 0) {
6639             return new EmptyObservable_1.EmptyObservable();
6640         }
6641         else if (length === 1) {
6642             return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
6643         }
6644         else {
6645             return new ArrayLikeObservable(arrayLike, scheduler);
6646         }
6647     };
6648     ArrayLikeObservable.dispatch = function (state) {
6649         var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
6650         if (subscriber.closed) {
6651             return;
6652         }
6653         if (index >= length) {
6654             subscriber.complete();
6655             return;
6656         }
6657         subscriber.next(arrayLike[index]);
6658         state.index = index + 1;
6659         this.schedule(state);
6660     };
6661     ArrayLikeObservable.prototype._subscribe = function (subscriber) {
6662         var index = 0;
6663         var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
6664         var length = arrayLike.length;
6665         if (scheduler) {
6666             return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
6667                 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
6668             });
6669         }
6670         else {
6671             for (var i = 0; i < length && !subscriber.closed; i++) {
6672                 subscriber.next(arrayLike[i]);
6673             }
6674             subscriber.complete();
6675         }
6676     };
6677     return ArrayLikeObservable;
6678 }(Observable_1.Observable));
6679 exports.ArrayLikeObservable = ArrayLikeObservable;
6680
6681 },{"../Observable":28,"./EmptyObservable":86,"./ScalarObservable":92}],83:[function(require,module,exports){
6682 "use strict";
6683 var __extends = (this && this.__extends) || function (d, b) {
6684     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6685     function __() { this.constructor = d; }
6686     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6687 };
6688 var Observable_1 = require('../Observable');
6689 var ScalarObservable_1 = require('./ScalarObservable');
6690 var EmptyObservable_1 = require('./EmptyObservable');
6691 var isScheduler_1 = require('../util/isScheduler');
6692 /**
6693  * We need this JSDoc comment for affecting ESDoc.
6694  * @extends {Ignored}
6695  * @hide true
6696  */
6697 var ArrayObservable = (function (_super) {
6698     __extends(ArrayObservable, _super);
6699     function ArrayObservable(array, scheduler) {
6700         _super.call(this);
6701         this.array = array;
6702         this.scheduler = scheduler;
6703         if (!scheduler && array.length === 1) {
6704             this._isScalar = true;
6705             this.value = array[0];
6706         }
6707     }
6708     ArrayObservable.create = function (array, scheduler) {
6709         return new ArrayObservable(array, scheduler);
6710     };
6711     /**
6712      * Creates an Observable that emits some values you specify as arguments,
6713      * immediately one after the other, and then emits a complete notification.
6714      *
6715      * <span class="informal">Emits the arguments you provide, then completes.
6716      * </span>
6717      *
6718      * <img src="./img/of.png" width="100%">
6719      *
6720      * This static operator is useful for creating a simple Observable that only
6721      * emits the arguments given, and the complete notification thereafter. It can
6722      * be used for composing with other Observables, such as with {@link concat}.
6723      * By default, it uses a `null` IScheduler, which means the `next`
6724      * notifications are sent synchronously, although with a different IScheduler
6725      * it is possible to determine when those notifications will be delivered.
6726      *
6727      * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
6728      * var numbers = Rx.Observable.of(10, 20, 30);
6729      * var letters = Rx.Observable.of('a', 'b', 'c');
6730      * var interval = Rx.Observable.interval(1000);
6731      * var result = numbers.concat(letters).concat(interval);
6732      * result.subscribe(x => console.log(x));
6733      *
6734      * @see {@link create}
6735      * @see {@link empty}
6736      * @see {@link never}
6737      * @see {@link throw}
6738      *
6739      * @param {...T} values Arguments that represent `next` values to be emitted.
6740      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
6741      * the emissions of the `next` notifications.
6742      * @return {Observable<T>} An Observable that emits each given input value.
6743      * @static true
6744      * @name of
6745      * @owner Observable
6746      */
6747     ArrayObservable.of = function () {
6748         var array = [];
6749         for (var _i = 0; _i < arguments.length; _i++) {
6750             array[_i - 0] = arguments[_i];
6751         }
6752         var scheduler = array[array.length - 1];
6753         if (isScheduler_1.isScheduler(scheduler)) {
6754             array.pop();
6755         }
6756         else {
6757             scheduler = null;
6758         }
6759         var len = array.length;
6760         if (len > 1) {
6761             return new ArrayObservable(array, scheduler);
6762         }
6763         else if (len === 1) {
6764             return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
6765         }
6766         else {
6767             return new EmptyObservable_1.EmptyObservable(scheduler);
6768         }
6769     };
6770     ArrayObservable.dispatch = function (state) {
6771         var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
6772         if (index >= count) {
6773             subscriber.complete();
6774             return;
6775         }
6776         subscriber.next(array[index]);
6777         if (subscriber.closed) {
6778             return;
6779         }
6780         state.index = index + 1;
6781         this.schedule(state);
6782     };
6783     ArrayObservable.prototype._subscribe = function (subscriber) {
6784         var index = 0;
6785         var array = this.array;
6786         var count = array.length;
6787         var scheduler = this.scheduler;
6788         if (scheduler) {
6789             return scheduler.schedule(ArrayObservable.dispatch, 0, {
6790                 array: array, index: index, count: count, subscriber: subscriber
6791             });
6792         }
6793         else {
6794             for (var i = 0; i < count && !subscriber.closed; i++) {
6795                 subscriber.next(array[i]);
6796             }
6797             subscriber.complete();
6798         }
6799     };
6800     return ArrayObservable;
6801 }(Observable_1.Observable));
6802 exports.ArrayObservable = ArrayObservable;
6803
6804 },{"../Observable":28,"../util/isScheduler":162,"./EmptyObservable":86,"./ScalarObservable":92}],84:[function(require,module,exports){
6805 "use strict";
6806 var __extends = (this && this.__extends) || function (d, b) {
6807     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6808     function __() { this.constructor = d; }
6809     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6810 };
6811 var Subject_1 = require('../Subject');
6812 var Observable_1 = require('../Observable');
6813 var Subscriber_1 = require('../Subscriber');
6814 var Subscription_1 = require('../Subscription');
6815 /**
6816  * @class ConnectableObservable<T>
6817  */
6818 var ConnectableObservable = (function (_super) {
6819     __extends(ConnectableObservable, _super);
6820     function ConnectableObservable(source, subjectFactory) {
6821         _super.call(this);
6822         this.source = source;
6823         this.subjectFactory = subjectFactory;
6824         this._refCount = 0;
6825     }
6826     ConnectableObservable.prototype._subscribe = function (subscriber) {
6827         return this.getSubject().subscribe(subscriber);
6828     };
6829     ConnectableObservable.prototype.getSubject = function () {
6830         var subject = this._subject;
6831         if (!subject || subject.isStopped) {
6832             this._subject = this.subjectFactory();
6833         }
6834         return this._subject;
6835     };
6836     ConnectableObservable.prototype.connect = function () {
6837         var connection = this._connection;
6838         if (!connection) {
6839             connection = this._connection = new Subscription_1.Subscription();
6840             connection.add(this.source
6841                 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
6842             if (connection.closed) {
6843                 this._connection = null;
6844                 connection = Subscription_1.Subscription.EMPTY;
6845             }
6846             else {
6847                 this._connection = connection;
6848             }
6849         }
6850         return connection;
6851     };
6852     ConnectableObservable.prototype.refCount = function () {
6853         return this.lift(new RefCountOperator(this));
6854     };
6855     return ConnectableObservable;
6856 }(Observable_1.Observable));
6857 exports.ConnectableObservable = ConnectableObservable;
6858 exports.connectableObservableDescriptor = {
6859     operator: { value: null },
6860     _refCount: { value: 0, writable: true },
6861     _subscribe: { value: ConnectableObservable.prototype._subscribe },
6862     getSubject: { value: ConnectableObservable.prototype.getSubject },
6863     connect: { value: ConnectableObservable.prototype.connect },
6864     refCount: { value: ConnectableObservable.prototype.refCount }
6865 };
6866 var ConnectableSubscriber = (function (_super) {
6867     __extends(ConnectableSubscriber, _super);
6868     function ConnectableSubscriber(destination, connectable) {
6869         _super.call(this, destination);
6870         this.connectable = connectable;
6871     }
6872     ConnectableSubscriber.prototype._error = function (err) {
6873         this._unsubscribe();
6874         _super.prototype._error.call(this, err);
6875     };
6876     ConnectableSubscriber.prototype._complete = function () {
6877         this._unsubscribe();
6878         _super.prototype._complete.call(this);
6879     };
6880     ConnectableSubscriber.prototype._unsubscribe = function () {
6881         var connectable = this.connectable;
6882         if (connectable) {
6883             this.connectable = null;
6884             var connection = connectable._connection;
6885             connectable._refCount = 0;
6886             connectable._subject = null;
6887             connectable._connection = null;
6888             if (connection) {
6889                 connection.unsubscribe();
6890             }
6891         }
6892     };
6893     return ConnectableSubscriber;
6894 }(Subject_1.SubjectSubscriber));
6895 var RefCountOperator = (function () {
6896     function RefCountOperator(connectable) {
6897         this.connectable = connectable;
6898     }
6899     RefCountOperator.prototype.call = function (subscriber, source) {
6900         var connectable = this.connectable;
6901         connectable._refCount++;
6902         var refCounter = new RefCountSubscriber(subscriber, connectable);
6903         var subscription = source.subscribe(refCounter);
6904         if (!refCounter.closed) {
6905             refCounter.connection = connectable.connect();
6906         }
6907         return subscription;
6908     };
6909     return RefCountOperator;
6910 }());
6911 var RefCountSubscriber = (function (_super) {
6912     __extends(RefCountSubscriber, _super);
6913     function RefCountSubscriber(destination, connectable) {
6914         _super.call(this, destination);
6915         this.connectable = connectable;
6916     }
6917     RefCountSubscriber.prototype._unsubscribe = function () {
6918         var connectable = this.connectable;
6919         if (!connectable) {
6920             this.connection = null;
6921             return;
6922         }
6923         this.connectable = null;
6924         var refCount = connectable._refCount;
6925         if (refCount <= 0) {
6926             this.connection = null;
6927             return;
6928         }
6929         connectable._refCount = refCount - 1;
6930         if (refCount > 1) {
6931             this.connection = null;
6932             return;
6933         }
6934         ///
6935         // Compare the local RefCountSubscriber's connection Subscription to the
6936         // connection Subscription on the shared ConnectableObservable. In cases
6937         // where the ConnectableObservable source synchronously emits values, and
6938         // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
6939         // execution continues to here before the RefCountOperator has a chance to
6940         // supply the RefCountSubscriber with the shared connection Subscription.
6941         // For example:
6942         // ```
6943         // Observable.range(0, 10)
6944         //   .publish()
6945         //   .refCount()
6946         //   .take(5)
6947         //   .subscribe();
6948         // ```
6949         // In order to account for this case, RefCountSubscriber should only dispose
6950         // the ConnectableObservable's shared connection Subscription if the
6951         // connection Subscription exists, *and* either:
6952         //   a. RefCountSubscriber doesn't have a reference to the shared connection
6953         //      Subscription yet, or,
6954         //   b. RefCountSubscriber's connection Subscription reference is identical
6955         //      to the shared connection Subscription
6956         ///
6957         var connection = this.connection;
6958         var sharedConnection = connectable._connection;
6959         this.connection = null;
6960         if (sharedConnection && (!connection || sharedConnection === connection)) {
6961             sharedConnection.unsubscribe();
6962         }
6963     };
6964     return RefCountSubscriber;
6965 }(Subscriber_1.Subscriber));
6966
6967 },{"../Observable":28,"../Subject":33,"../Subscriber":35,"../Subscription":36}],85:[function(require,module,exports){
6968 "use strict";
6969 var __extends = (this && this.__extends) || function (d, b) {
6970     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6971     function __() { this.constructor = d; }
6972     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6973 };
6974 var Observable_1 = require('../Observable');
6975 var subscribeToResult_1 = require('../util/subscribeToResult');
6976 var OuterSubscriber_1 = require('../OuterSubscriber');
6977 /**
6978  * We need this JSDoc comment for affecting ESDoc.
6979  * @extends {Ignored}
6980  * @hide true
6981  */
6982 var DeferObservable = (function (_super) {
6983     __extends(DeferObservable, _super);
6984     function DeferObservable(observableFactory) {
6985         _super.call(this);
6986         this.observableFactory = observableFactory;
6987     }
6988     /**
6989      * Creates an Observable that, on subscribe, calls an Observable factory to
6990      * make an Observable for each new Observer.
6991      *
6992      * <span class="informal">Creates the Observable lazily, that is, only when it
6993      * is subscribed.
6994      * </span>
6995      *
6996      * <img src="./img/defer.png" width="100%">
6997      *
6998      * `defer` allows you to create the Observable only when the Observer
6999      * subscribes, and create a fresh Observable for each Observer. It waits until
7000      * an Observer subscribes to it, and then it generates an Observable,
7001      * typically with an Observable factory function. It does this afresh for each
7002      * subscriber, so although each subscriber may think it is subscribing to the
7003      * same Observable, in fact each subscriber gets its own individual
7004      * Observable.
7005      *
7006      * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7007      * var clicksOrInterval = Rx.Observable.defer(function () {
7008      *   if (Math.random() > 0.5) {
7009      *     return Rx.Observable.fromEvent(document, 'click');
7010      *   } else {
7011      *     return Rx.Observable.interval(1000);
7012      *   }
7013      * });
7014      * clicksOrInterval.subscribe(x => console.log(x));
7015      *
7016      * // Results in the following behavior:
7017      * // If the result of Math.random() is greater than 0.5 it will listen
7018      * // for clicks anywhere on the "document"; when document is clicked it
7019      * // will log a MouseEvent object to the console. If the result is less
7020      * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7021      *
7022      * @see {@link create}
7023      *
7024      * @param {function(): Observable|Promise} observableFactory The Observable
7025      * factory function to invoke for each Observer that subscribes to the output
7026      * Observable. May also return a Promise, which will be converted on the fly
7027      * to an Observable.
7028      * @return {Observable} An Observable whose Observers' subscriptions trigger
7029      * an invocation of the given Observable factory function.
7030      * @static true
7031      * @name defer
7032      * @owner Observable
7033      */
7034     DeferObservable.create = function (observableFactory) {
7035         return new DeferObservable(observableFactory);
7036     };
7037     DeferObservable.prototype._subscribe = function (subscriber) {
7038         return new DeferSubscriber(subscriber, this.observableFactory);
7039     };
7040     return DeferObservable;
7041 }(Observable_1.Observable));
7042 exports.DeferObservable = DeferObservable;
7043 var DeferSubscriber = (function (_super) {
7044     __extends(DeferSubscriber, _super);
7045     function DeferSubscriber(destination, factory) {
7046         _super.call(this, destination);
7047         this.factory = factory;
7048         this.tryDefer();
7049     }
7050     DeferSubscriber.prototype.tryDefer = function () {
7051         try {
7052             this._callFactory();
7053         }
7054         catch (err) {
7055             this._error(err);
7056         }
7057     };
7058     DeferSubscriber.prototype._callFactory = function () {
7059         var result = this.factory();
7060         if (result) {
7061             this.add(subscribeToResult_1.subscribeToResult(this, result));
7062         }
7063     };
7064     return DeferSubscriber;
7065 }(OuterSubscriber_1.OuterSubscriber));
7066
7067 },{"../Observable":28,"../OuterSubscriber":30,"../util/subscribeToResult":164}],86:[function(require,module,exports){
7068 "use strict";
7069 var __extends = (this && this.__extends) || function (d, b) {
7070     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7071     function __() { this.constructor = d; }
7072     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7073 };
7074 var Observable_1 = require('../Observable');
7075 /**
7076  * We need this JSDoc comment for affecting ESDoc.
7077  * @extends {Ignored}
7078  * @hide true
7079  */
7080 var EmptyObservable = (function (_super) {
7081     __extends(EmptyObservable, _super);
7082     function EmptyObservable(scheduler) {
7083         _super.call(this);
7084         this.scheduler = scheduler;
7085     }
7086     /**
7087      * Creates an Observable that emits no items to the Observer and immediately
7088      * emits a complete notification.
7089      *
7090      * <span class="informal">Just emits 'complete', and nothing else.
7091      * </span>
7092      *
7093      * <img src="./img/empty.png" width="100%">
7094      *
7095      * This static operator is useful for creating a simple Observable that only
7096      * emits the complete notification. It can be used for composing with other
7097      * Observables, such as in a {@link mergeMap}.
7098      *
7099      * @example <caption>Emit the number 7, then complete.</caption>
7100      * var result = Rx.Observable.empty().startWith(7);
7101      * result.subscribe(x => console.log(x));
7102      *
7103      * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7104      * var interval = Rx.Observable.interval(1000);
7105      * var result = interval.mergeMap(x =>
7106      *   x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7107      * );
7108      * result.subscribe(x => console.log(x));
7109      *
7110      * // Results in the following to the console:
7111      * // x is equal to the count on the interval eg(0,1,2,3,...)
7112      * // x will occur every 1000ms
7113      * // if x % 2 is equal to 1 print abc
7114      * // if x % 2 is not equal to 1 nothing will be output
7115      *
7116      * @see {@link create}
7117      * @see {@link never}
7118      * @see {@link of}
7119      * @see {@link throw}
7120      *
7121      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7122      * the emission of the complete notification.
7123      * @return {Observable} An "empty" Observable: emits only the complete
7124      * notification.
7125      * @static true
7126      * @name empty
7127      * @owner Observable
7128      */
7129     EmptyObservable.create = function (scheduler) {
7130         return new EmptyObservable(scheduler);
7131     };
7132     EmptyObservable.dispatch = function (arg) {
7133         var subscriber = arg.subscriber;
7134         subscriber.complete();
7135     };
7136     EmptyObservable.prototype._subscribe = function (subscriber) {
7137         var scheduler = this.scheduler;
7138         if (scheduler) {
7139             return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7140         }
7141         else {
7142             subscriber.complete();
7143         }
7144     };
7145     return EmptyObservable;
7146 }(Observable_1.Observable));
7147 exports.EmptyObservable = EmptyObservable;
7148
7149 },{"../Observable":28}],87:[function(require,module,exports){
7150 "use strict";
7151 var __extends = (this && this.__extends) || function (d, b) {
7152     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7153     function __() { this.constructor = d; }
7154     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7155 };
7156 var Observable_1 = require('../Observable');
7157 /**
7158  * We need this JSDoc comment for affecting ESDoc.
7159  * @extends {Ignored}
7160  * @hide true
7161  */
7162 var ErrorObservable = (function (_super) {
7163     __extends(ErrorObservable, _super);
7164     function ErrorObservable(error, scheduler) {
7165         _super.call(this);
7166         this.error = error;
7167         this.scheduler = scheduler;
7168     }
7169     /**
7170      * Creates an Observable that emits no items to the Observer and immediately
7171      * emits an error notification.
7172      *
7173      * <span class="informal">Just emits 'error', and nothing else.
7174      * </span>
7175      *
7176      * <img src="./img/throw.png" width="100%">
7177      *
7178      * This static operator is useful for creating a simple Observable that only
7179      * emits the error notification. It can be used for composing with other
7180      * Observables, such as in a {@link mergeMap}.
7181      *
7182      * @example <caption>Emit the number 7, then emit an error.</caption>
7183      * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7184      * result.subscribe(x => console.log(x), e => console.error(e));
7185      *
7186      * @example <caption>Map and flattens numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7187      * var interval = Rx.Observable.interval(1000);
7188      * var result = interval.mergeMap(x =>
7189      *   x === 13 ?
7190      *     Rx.Observable.throw('Thirteens are bad') :
7191      *     Rx.Observable.of('a', 'b', 'c')
7192      * );
7193      * result.subscribe(x => console.log(x), e => console.error(e));
7194      *
7195      * @see {@link create}
7196      * @see {@link empty}
7197      * @see {@link never}
7198      * @see {@link of}
7199      *
7200      * @param {any} error The particular Error to pass to the error notification.
7201      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7202      * the emission of the error notification.
7203      * @return {Observable} An error Observable: emits only the error notification
7204      * using the given error argument.
7205      * @static true
7206      * @name throw
7207      * @owner Observable
7208      */
7209     ErrorObservable.create = function (error, scheduler) {
7210         return new ErrorObservable(error, scheduler);
7211     };
7212     ErrorObservable.dispatch = function (arg) {
7213         var error = arg.error, subscriber = arg.subscriber;
7214         subscriber.error(error);
7215     };
7216     ErrorObservable.prototype._subscribe = function (subscriber) {
7217         var error = this.error;
7218         var scheduler = this.scheduler;
7219         if (scheduler) {
7220             return scheduler.schedule(ErrorObservable.dispatch, 0, {
7221                 error: error, subscriber: subscriber
7222             });
7223         }
7224         else {
7225             subscriber.error(error);
7226         }
7227     };
7228     return ErrorObservable;
7229 }(Observable_1.Observable));
7230 exports.ErrorObservable = ErrorObservable;
7231
7232 },{"../Observable":28}],88:[function(require,module,exports){
7233 "use strict";
7234 var __extends = (this && this.__extends) || function (d, b) {
7235     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7236     function __() { this.constructor = d; }
7237     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7238 };
7239 var Observable_1 = require('../Observable');
7240 var tryCatch_1 = require('../util/tryCatch');
7241 var isFunction_1 = require('../util/isFunction');
7242 var errorObject_1 = require('../util/errorObject');
7243 var Subscription_1 = require('../Subscription');
7244 var toString = Object.prototype.toString;
7245 function isNodeStyleEventEmmitter(sourceObj) {
7246     return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7247 }
7248 function isJQueryStyleEventEmitter(sourceObj) {
7249     return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7250 }
7251 function isNodeList(sourceObj) {
7252     return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7253 }
7254 function isHTMLCollection(sourceObj) {
7255     return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7256 }
7257 function isEventTarget(sourceObj) {
7258     return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7259 }
7260 /**
7261  * We need this JSDoc comment for affecting ESDoc.
7262  * @extends {Ignored}
7263  * @hide true
7264  */
7265 var FromEventObservable = (function (_super) {
7266     __extends(FromEventObservable, _super);
7267     function FromEventObservable(sourceObj, eventName, selector, options) {
7268         _super.call(this);
7269         this.sourceObj = sourceObj;
7270         this.eventName = eventName;
7271         this.selector = selector;
7272         this.options = options;
7273     }
7274     /* tslint:enable:max-line-length */
7275     /**
7276      * Creates an Observable that emits events of a specific type coming from the
7277      * given event target.
7278      *
7279      * <span class="informal">Creates an Observable from DOM events, or Node
7280      * EventEmitter events or others.</span>
7281      *
7282      * <img src="./img/fromEvent.png" width="100%">
7283      *
7284      * Creates an Observable by attaching an event listener to an "event target",
7285      * which may be an object with `addEventListener` and `removeEventListener`,
7286      * a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the
7287      * DOM, or an HTMLCollection from the DOM. The event handler is attached when
7288      * the output Observable is subscribed, and removed when the Subscription is
7289      * unsubscribed.
7290      *
7291      * @example <caption>Emits clicks happening on the DOM document</caption>
7292      * var clicks = Rx.Observable.fromEvent(document, 'click');
7293      * clicks.subscribe(x => console.log(x));
7294      *
7295      * // Results in:
7296      * // MouseEvent object logged to console everytime a click
7297      * // occurs on the document.
7298      *
7299      * @see {@link from}
7300      * @see {@link fromEventPattern}
7301      *
7302      * @param {EventTargetLike} target The DOMElement, event target, Node.js
7303      * EventEmitter, NodeList or HTMLCollection to attach the event handler to.
7304      * @param {string} eventName The event name of interest, being emitted by the
7305      * `target`.
7306      * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7307      * @param {SelectorMethodSignature<T>} [selector] An optional function to
7308      * post-process results. It takes the arguments from the event handler and
7309      * should return a single value.
7310      * @return {Observable<T>}
7311      * @static true
7312      * @name fromEvent
7313      * @owner Observable
7314      */
7315     FromEventObservable.create = function (target, eventName, options, selector) {
7316         if (isFunction_1.isFunction(options)) {
7317             selector = options;
7318             options = undefined;
7319         }
7320         return new FromEventObservable(target, eventName, selector, options);
7321     };
7322     FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7323         var unsubscribe;
7324         if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7325             for (var i = 0, len = sourceObj.length; i < len; i++) {
7326                 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7327             }
7328         }
7329         else if (isEventTarget(sourceObj)) {
7330             var source_1 = sourceObj;
7331             sourceObj.addEventListener(eventName, handler, options);
7332             unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7333         }
7334         else if (isJQueryStyleEventEmitter(sourceObj)) {
7335             var source_2 = sourceObj;
7336             sourceObj.on(eventName, handler);
7337             unsubscribe = function () { return source_2.off(eventName, handler); };
7338         }
7339         else if (isNodeStyleEventEmmitter(sourceObj)) {
7340             var source_3 = sourceObj;
7341             sourceObj.addListener(eventName, handler);
7342             unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7343         }
7344         else {
7345             throw new TypeError('Invalid event target');
7346         }
7347         subscriber.add(new Subscription_1.Subscription(unsubscribe));
7348     };
7349     FromEventObservable.prototype._subscribe = function (subscriber) {
7350         var sourceObj = this.sourceObj;
7351         var eventName = this.eventName;
7352         var options = this.options;
7353         var selector = this.selector;
7354         var handler = selector ? function () {
7355             var args = [];
7356             for (var _i = 0; _i < arguments.length; _i++) {
7357                 args[_i - 0] = arguments[_i];
7358             }
7359             var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7360             if (result === errorObject_1.errorObject) {
7361                 subscriber.error(errorObject_1.errorObject.e);
7362             }
7363             else {
7364                 subscriber.next(result);
7365             }
7366         } : function (e) { return subscriber.next(e); };
7367         FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7368     };
7369     return FromEventObservable;
7370 }(Observable_1.Observable));
7371 exports.FromEventObservable = FromEventObservable;
7372
7373 },{"../Observable":28,"../Subscription":36,"../util/errorObject":156,"../util/isFunction":159,"../util/tryCatch":166}],89:[function(require,module,exports){
7374 "use strict";
7375 var __extends = (this && this.__extends) || function (d, b) {
7376     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7377     function __() { this.constructor = d; }
7378     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7379 };
7380 var isArray_1 = require('../util/isArray');
7381 var isPromise_1 = require('../util/isPromise');
7382 var PromiseObservable_1 = require('./PromiseObservable');
7383 var IteratorObservable_1 = require('./IteratorObservable');
7384 var ArrayObservable_1 = require('./ArrayObservable');
7385 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7386 var iterator_1 = require('../symbol/iterator');
7387 var Observable_1 = require('../Observable');
7388 var observeOn_1 = require('../operator/observeOn');
7389 var observable_1 = require('../symbol/observable');
7390 var isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
7391 /**
7392  * We need this JSDoc comment for affecting ESDoc.
7393  * @extends {Ignored}
7394  * @hide true
7395  */
7396 var FromObservable = (function (_super) {
7397     __extends(FromObservable, _super);
7398     function FromObservable(ish, scheduler) {
7399         _super.call(this, null);
7400         this.ish = ish;
7401         this.scheduler = scheduler;
7402     }
7403     /**
7404      * Creates an Observable from an Array, an array-like object, a Promise, an
7405      * iterable object, or an Observable-like object.
7406      *
7407      * <span class="informal">Converts almost anything to an Observable.</span>
7408      *
7409      * <img src="./img/from.png" width="100%">
7410      *
7411      * Convert various other objects and data types into Observables. `from`
7412      * converts a Promise or an array-like or an
7413      * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7414      * object into an Observable that emits the items in that promise or array or
7415      * iterable. A String, in this context, is treated as an array of characters.
7416      * Observable-like objects (contains a function named with the ES2015 Symbol
7417      * for Observable) can also be converted through this operator.
7418      *
7419      * @example <caption>Converts an array to an Observable</caption>
7420      * var array = [10, 20, 30];
7421      * var result = Rx.Observable.from(array);
7422      * result.subscribe(x => console.log(x));
7423      *
7424      * // Results in the following:
7425      * // 10 20 30
7426      *
7427      * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7428      * function* generateDoubles(seed) {
7429      *   var i = seed;
7430      *   while (true) {
7431      *     yield i;
7432      *     i = 2 * i; // double it
7433      *   }
7434      * }
7435      *
7436      * var iterator = generateDoubles(3);
7437      * var result = Rx.Observable.from(iterator).take(10);
7438      * result.subscribe(x => console.log(x));
7439      *
7440      * // Results in the following:
7441      * // 3 6 12 24 48 96 192 384 768 1536
7442      *
7443      * @see {@link create}
7444      * @see {@link fromEvent}
7445      * @see {@link fromEventPattern}
7446      * @see {@link fromPromise}
7447      *
7448      * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7449      * Observable-like, an Array, an iterable or an array-like object to be
7450      * converted.
7451      * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7452      * emissions of values.
7453      * @return {Observable<T>} The Observable whose values are originally from the
7454      * input object that was converted.
7455      * @static true
7456      * @name from
7457      * @owner Observable
7458      */
7459     FromObservable.create = function (ish, scheduler) {
7460         if (ish != null) {
7461             if (typeof ish[observable_1.$$observable] === 'function') {
7462                 if (ish instanceof Observable_1.Observable && !scheduler) {
7463                     return ish;
7464                 }
7465                 return new FromObservable(ish, scheduler);
7466             }
7467             else if (isArray_1.isArray(ish)) {
7468                 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
7469             }
7470             else if (isPromise_1.isPromise(ish)) {
7471                 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
7472             }
7473             else if (typeof ish[iterator_1.$$iterator] === 'function' || typeof ish === 'string') {
7474                 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
7475             }
7476             else if (isArrayLike(ish)) {
7477                 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
7478             }
7479         }
7480         throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
7481     };
7482     FromObservable.prototype._subscribe = function (subscriber) {
7483         var ish = this.ish;
7484         var scheduler = this.scheduler;
7485         if (scheduler == null) {
7486             return ish[observable_1.$$observable]().subscribe(subscriber);
7487         }
7488         else {
7489             return ish[observable_1.$$observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
7490         }
7491     };
7492     return FromObservable;
7493 }(Observable_1.Observable));
7494 exports.FromObservable = FromObservable;
7495
7496 },{"../Observable":28,"../operator/observeOn":123,"../symbol/iterator":147,"../symbol/observable":148,"../util/isArray":157,"../util/isPromise":161,"./ArrayLikeObservable":82,"./ArrayObservable":83,"./IteratorObservable":90,"./PromiseObservable":91}],90:[function(require,module,exports){
7497 "use strict";
7498 var __extends = (this && this.__extends) || function (d, b) {
7499     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7500     function __() { this.constructor = d; }
7501     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7502 };
7503 var root_1 = require('../util/root');
7504 var Observable_1 = require('../Observable');
7505 var iterator_1 = require('../symbol/iterator');
7506 /**
7507  * We need this JSDoc comment for affecting ESDoc.
7508  * @extends {Ignored}
7509  * @hide true
7510  */
7511 var IteratorObservable = (function (_super) {
7512     __extends(IteratorObservable, _super);
7513     function IteratorObservable(iterator, scheduler) {
7514         _super.call(this);
7515         this.scheduler = scheduler;
7516         if (iterator == null) {
7517             throw new Error('iterator cannot be null.');
7518         }
7519         this.iterator = getIterator(iterator);
7520     }
7521     IteratorObservable.create = function (iterator, scheduler) {
7522         return new IteratorObservable(iterator, scheduler);
7523     };
7524     IteratorObservable.dispatch = function (state) {
7525         var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
7526         if (hasError) {
7527             subscriber.error(state.error);
7528             return;
7529         }
7530         var result = iterator.next();
7531         if (result.done) {
7532             subscriber.complete();
7533             return;
7534         }
7535         subscriber.next(result.value);
7536         state.index = index + 1;
7537         if (subscriber.closed) {
7538             if (typeof iterator.return === 'function') {
7539                 iterator.return();
7540             }
7541             return;
7542         }
7543         this.schedule(state);
7544     };
7545     IteratorObservable.prototype._subscribe = function (subscriber) {
7546         var index = 0;
7547         var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
7548         if (scheduler) {
7549             return scheduler.schedule(IteratorObservable.dispatch, 0, {
7550                 index: index, iterator: iterator, subscriber: subscriber
7551             });
7552         }
7553         else {
7554             do {
7555                 var result = iterator.next();
7556                 if (result.done) {
7557                     subscriber.complete();
7558                     break;
7559                 }
7560                 else {
7561                     subscriber.next(result.value);
7562                 }
7563                 if (subscriber.closed) {
7564                     if (typeof iterator.return === 'function') {
7565                         iterator.return();
7566                     }
7567                     break;
7568                 }
7569             } while (true);
7570         }
7571     };
7572     return IteratorObservable;
7573 }(Observable_1.Observable));
7574 exports.IteratorObservable = IteratorObservable;
7575 var StringIterator = (function () {
7576     function StringIterator(str, idx, len) {
7577         if (idx === void 0) { idx = 0; }
7578         if (len === void 0) { len = str.length; }
7579         this.str = str;
7580         this.idx = idx;
7581         this.len = len;
7582     }
7583     StringIterator.prototype[iterator_1.$$iterator] = function () { return (this); };
7584     StringIterator.prototype.next = function () {
7585         return this.idx < this.len ? {
7586             done: false,
7587             value: this.str.charAt(this.idx++)
7588         } : {
7589             done: true,
7590             value: undefined
7591         };
7592     };
7593     return StringIterator;
7594 }());
7595 var ArrayIterator = (function () {
7596     function ArrayIterator(arr, idx, len) {
7597         if (idx === void 0) { idx = 0; }
7598         if (len === void 0) { len = toLength(arr); }
7599         this.arr = arr;
7600         this.idx = idx;
7601         this.len = len;
7602     }
7603     ArrayIterator.prototype[iterator_1.$$iterator] = function () { return this; };
7604     ArrayIterator.prototype.next = function () {
7605         return this.idx < this.len ? {
7606             done: false,
7607             value: this.arr[this.idx++]
7608         } : {
7609             done: true,
7610             value: undefined
7611         };
7612     };
7613     return ArrayIterator;
7614 }());
7615 function getIterator(obj) {
7616     var i = obj[iterator_1.$$iterator];
7617     if (!i && typeof obj === 'string') {
7618         return new StringIterator(obj);
7619     }
7620     if (!i && obj.length !== undefined) {
7621         return new ArrayIterator(obj);
7622     }
7623     if (!i) {
7624         throw new TypeError('object is not iterable');
7625     }
7626     return obj[iterator_1.$$iterator]();
7627 }
7628 var maxSafeInteger = Math.pow(2, 53) - 1;
7629 function toLength(o) {
7630     var len = +o.length;
7631     if (isNaN(len)) {
7632         return 0;
7633     }
7634     if (len === 0 || !numberIsFinite(len)) {
7635         return len;
7636     }
7637     len = sign(len) * Math.floor(Math.abs(len));
7638     if (len <= 0) {
7639         return 0;
7640     }
7641     if (len > maxSafeInteger) {
7642         return maxSafeInteger;
7643     }
7644     return len;
7645 }
7646 function numberIsFinite(value) {
7647     return typeof value === 'number' && root_1.root.isFinite(value);
7648 }
7649 function sign(value) {
7650     var valueAsNumber = +value;
7651     if (valueAsNumber === 0) {
7652         return valueAsNumber;
7653     }
7654     if (isNaN(valueAsNumber)) {
7655         return valueAsNumber;
7656     }
7657     return valueAsNumber < 0 ? -1 : 1;
7658 }
7659
7660 },{"../Observable":28,"../symbol/iterator":147,"../util/root":163}],91:[function(require,module,exports){
7661 "use strict";
7662 var __extends = (this && this.__extends) || function (d, b) {
7663     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7664     function __() { this.constructor = d; }
7665     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7666 };
7667 var root_1 = require('../util/root');
7668 var Observable_1 = require('../Observable');
7669 /**
7670  * We need this JSDoc comment for affecting ESDoc.
7671  * @extends {Ignored}
7672  * @hide true
7673  */
7674 var PromiseObservable = (function (_super) {
7675     __extends(PromiseObservable, _super);
7676     function PromiseObservable(promise, scheduler) {
7677         _super.call(this);
7678         this.promise = promise;
7679         this.scheduler = scheduler;
7680     }
7681     /**
7682      * Converts a Promise to an Observable.
7683      *
7684      * <span class="informal">Returns an Observable that just emits the Promise's
7685      * resolved value, then completes.</span>
7686      *
7687      * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
7688      * Observable. If the Promise resolves with a value, the output Observable
7689      * emits that resolved value as a `next`, and then completes. If the Promise
7690      * is rejected, then the output Observable emits the corresponding Error.
7691      *
7692      * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
7693      * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
7694      * result.subscribe(x => console.log(x), e => console.error(e));
7695      *
7696      * @see {@link bindCallback}
7697      * @see {@link from}
7698      *
7699      * @param {Promise<T>} promise The promise to be converted.
7700      * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
7701      * the delivery of the resolved value (or the rejection).
7702      * @return {Observable<T>} An Observable which wraps the Promise.
7703      * @static true
7704      * @name fromPromise
7705      * @owner Observable
7706      */
7707     PromiseObservable.create = function (promise, scheduler) {
7708         return new PromiseObservable(promise, scheduler);
7709     };
7710     PromiseObservable.prototype._subscribe = function (subscriber) {
7711         var _this = this;
7712         var promise = this.promise;
7713         var scheduler = this.scheduler;
7714         if (scheduler == null) {
7715             if (this._isScalar) {
7716                 if (!subscriber.closed) {
7717                     subscriber.next(this.value);
7718                     subscriber.complete();
7719                 }
7720             }
7721             else {
7722                 promise.then(function (value) {
7723                     _this.value = value;
7724                     _this._isScalar = true;
7725                     if (!subscriber.closed) {
7726                         subscriber.next(value);
7727                         subscriber.complete();
7728                     }
7729                 }, function (err) {
7730                     if (!subscriber.closed) {
7731                         subscriber.error(err);
7732                     }
7733                 })
7734                     .then(null, function (err) {
7735                     // escape the promise trap, throw unhandled errors
7736                     root_1.root.setTimeout(function () { throw err; });
7737                 });
7738             }
7739         }
7740         else {
7741             if (this._isScalar) {
7742                 if (!subscriber.closed) {
7743                     return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
7744                 }
7745             }
7746             else {
7747                 promise.then(function (value) {
7748                     _this.value = value;
7749                     _this._isScalar = true;
7750                     if (!subscriber.closed) {
7751                         subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
7752                     }
7753                 }, function (err) {
7754                     if (!subscriber.closed) {
7755                         subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
7756                     }
7757                 })
7758                     .then(null, function (err) {
7759                     // escape the promise trap, throw unhandled errors
7760                     root_1.root.setTimeout(function () { throw err; });
7761                 });
7762             }
7763         }
7764     };
7765     return PromiseObservable;
7766 }(Observable_1.Observable));
7767 exports.PromiseObservable = PromiseObservable;
7768 function dispatchNext(arg) {
7769     var value = arg.value, subscriber = arg.subscriber;
7770     if (!subscriber.closed) {
7771         subscriber.next(value);
7772         subscriber.complete();
7773     }
7774 }
7775 function dispatchError(arg) {
7776     var err = arg.err, subscriber = arg.subscriber;
7777     if (!subscriber.closed) {
7778         subscriber.error(err);
7779     }
7780 }
7781
7782 },{"../Observable":28,"../util/root":163}],92:[function(require,module,exports){
7783 "use strict";
7784 var __extends = (this && this.__extends) || function (d, b) {
7785     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7786     function __() { this.constructor = d; }
7787     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7788 };
7789 var Observable_1 = require('../Observable');
7790 /**
7791  * We need this JSDoc comment for affecting ESDoc.
7792  * @extends {Ignored}
7793  * @hide true
7794  */
7795 var ScalarObservable = (function (_super) {
7796     __extends(ScalarObservable, _super);
7797     function ScalarObservable(value, scheduler) {
7798         _super.call(this);
7799         this.value = value;
7800         this.scheduler = scheduler;
7801         this._isScalar = true;
7802         if (scheduler) {
7803             this._isScalar = false;
7804         }
7805     }
7806     ScalarObservable.create = function (value, scheduler) {
7807         return new ScalarObservable(value, scheduler);
7808     };
7809     ScalarObservable.dispatch = function (state) {
7810         var done = state.done, value = state.value, subscriber = state.subscriber;
7811         if (done) {
7812             subscriber.complete();
7813             return;
7814         }
7815         subscriber.next(value);
7816         if (subscriber.closed) {
7817             return;
7818         }
7819         state.done = true;
7820         this.schedule(state);
7821     };
7822     ScalarObservable.prototype._subscribe = function (subscriber) {
7823         var value = this.value;
7824         var scheduler = this.scheduler;
7825         if (scheduler) {
7826             return scheduler.schedule(ScalarObservable.dispatch, 0, {
7827                 done: false, value: value, subscriber: subscriber
7828             });
7829         }
7830         else {
7831             subscriber.next(value);
7832             if (!subscriber.closed) {
7833                 subscriber.complete();
7834             }
7835         }
7836     };
7837     return ScalarObservable;
7838 }(Observable_1.Observable));
7839 exports.ScalarObservable = ScalarObservable;
7840
7841 },{"../Observable":28}],93:[function(require,module,exports){
7842 "use strict";
7843 var isScheduler_1 = require('../util/isScheduler');
7844 var isArray_1 = require('../util/isArray');
7845 var ArrayObservable_1 = require('./ArrayObservable');
7846 var combineLatest_1 = require('../operator/combineLatest');
7847 /* tslint:enable:max-line-length */
7848 /**
7849  * Combines multiple Observables to create an Observable whose values are
7850  * calculated from the latest values of each of its input Observables.
7851  *
7852  * <span class="informal">Whenever any input Observable emits a value, it
7853  * computes a formula using the latest values from all the inputs, then emits
7854  * the output of that formula.</span>
7855  *
7856  * <img src="./img/combineLatest.png" width="100%">
7857  *
7858  * `combineLatest` combines the values from all the Observables passed as
7859  * arguments. This is done by subscribing to each Observable, in order, and
7860  * collecting an array of each of the most recent values any time any of the
7861  * input Observables emits, then either taking that array and passing it as
7862  * arguments to an optional `project` function and emitting the return value of
7863  * that, or just emitting the array of recent values directly if there is no
7864  * `project` function.
7865  *
7866  * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
7867  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
7868  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
7869  * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
7870  * bmi.subscribe(x => console.log('BMI is ' + x));
7871  *
7872  * // With output to console:
7873  * // BMI is 24.212293388429753
7874  * // BMI is 23.93948099205209
7875  * // BMI is 23.671253629592222
7876  *
7877  * @see {@link combineAll}
7878  * @see {@link merge}
7879  * @see {@link withLatestFrom}
7880  *
7881  * @param {Observable} observable1 An input Observable to combine with the
7882  * source Observable.
7883  * @param {Observable} observable2 An input Observable to combine with the
7884  * source Observable. More than one input Observables may be given as argument.
7885  * @param {function} [project] An optional function to project the values from
7886  * the combined latest values into a new value on the output Observable.
7887  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
7888  * each input Observable.
7889  * @return {Observable} An Observable of projected values from the most recent
7890  * values from each input Observable, or an array of the most recent values from
7891  * each input Observable.
7892  * @static true
7893  * @name combineLatest
7894  * @owner Observable
7895  */
7896 function combineLatest() {
7897     var observables = [];
7898     for (var _i = 0; _i < arguments.length; _i++) {
7899         observables[_i - 0] = arguments[_i];
7900     }
7901     var project = null;
7902     var scheduler = null;
7903     if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
7904         scheduler = observables.pop();
7905     }
7906     if (typeof observables[observables.length - 1] === 'function') {
7907         project = observables.pop();
7908     }
7909     // if the first and only other argument besides the resultSelector is an array
7910     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
7911     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
7912         observables = observables[0];
7913     }
7914     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
7915 }
7916 exports.combineLatest = combineLatest;
7917
7918 },{"../operator/combineLatest":106,"../util/isArray":157,"../util/isScheduler":162,"./ArrayObservable":83}],94:[function(require,module,exports){
7919 "use strict";
7920 var DeferObservable_1 = require('./DeferObservable');
7921 exports.defer = DeferObservable_1.DeferObservable.create;
7922
7923 },{"./DeferObservable":85}],95:[function(require,module,exports){
7924 "use strict";
7925 var EmptyObservable_1 = require('./EmptyObservable');
7926 exports.empty = EmptyObservable_1.EmptyObservable.create;
7927
7928 },{"./EmptyObservable":86}],96:[function(require,module,exports){
7929 "use strict";
7930 var FromObservable_1 = require('./FromObservable');
7931 exports.from = FromObservable_1.FromObservable.create;
7932
7933 },{"./FromObservable":89}],97:[function(require,module,exports){
7934 "use strict";
7935 var FromEventObservable_1 = require('./FromEventObservable');
7936 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
7937
7938 },{"./FromEventObservable":88}],98:[function(require,module,exports){
7939 "use strict";
7940 var PromiseObservable_1 = require('./PromiseObservable');
7941 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
7942
7943 },{"./PromiseObservable":91}],99:[function(require,module,exports){
7944 "use strict";
7945 var merge_1 = require('../operator/merge');
7946 exports.merge = merge_1.mergeStatic;
7947
7948 },{"../operator/merge":119}],100:[function(require,module,exports){
7949 "use strict";
7950 var ArrayObservable_1 = require('./ArrayObservable');
7951 exports.of = ArrayObservable_1.ArrayObservable.of;
7952
7953 },{"./ArrayObservable":83}],101:[function(require,module,exports){
7954 "use strict";
7955 var ErrorObservable_1 = require('./ErrorObservable');
7956 exports._throw = ErrorObservable_1.ErrorObservable.create;
7957
7958 },{"./ErrorObservable":87}],102:[function(require,module,exports){
7959 "use strict";
7960 var zip_1 = require('../operator/zip');
7961 exports.zip = zip_1.zipStatic;
7962
7963 },{"../operator/zip":139}],103:[function(require,module,exports){
7964 "use strict";
7965 var __extends = (this && this.__extends) || function (d, b) {
7966     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7967     function __() { this.constructor = d; }
7968     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7969 };
7970 var OuterSubscriber_1 = require('../OuterSubscriber');
7971 var subscribeToResult_1 = require('../util/subscribeToResult');
7972 /**
7973  * Buffers the source Observable values until `closingNotifier` emits.
7974  *
7975  * <span class="informal">Collects values from the past as an array, and emits
7976  * that array only when another Observable emits.</span>
7977  *
7978  * <img src="./img/buffer.png" width="100%">
7979  *
7980  * Buffers the incoming Observable values until the given `closingNotifier`
7981  * Observable emits a value, at which point it emits the buffer on the output
7982  * Observable and starts a new buffer internally, awaiting the next time
7983  * `closingNotifier` emits.
7984  *
7985  * @example <caption>On every click, emit array of most recent interval events</caption>
7986  * var clicks = Rx.Observable.fromEvent(document, 'click');
7987  * var interval = Rx.Observable.interval(1000);
7988  * var buffered = interval.buffer(clicks);
7989  * buffered.subscribe(x => console.log(x));
7990  *
7991  * @see {@link bufferCount}
7992  * @see {@link bufferTime}
7993  * @see {@link bufferToggle}
7994  * @see {@link bufferWhen}
7995  * @see {@link window}
7996  *
7997  * @param {Observable<any>} closingNotifier An Observable that signals the
7998  * buffer to be emitted on the output Observable.
7999  * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8000  * values.
8001  * @method buffer
8002  * @owner Observable
8003  */
8004 function buffer(closingNotifier) {
8005     return this.lift(new BufferOperator(closingNotifier));
8006 }
8007 exports.buffer = buffer;
8008 var BufferOperator = (function () {
8009     function BufferOperator(closingNotifier) {
8010         this.closingNotifier = closingNotifier;
8011     }
8012     BufferOperator.prototype.call = function (subscriber, source) {
8013         return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
8014     };
8015     return BufferOperator;
8016 }());
8017 /**
8018  * We need this JSDoc comment for affecting ESDoc.
8019  * @ignore
8020  * @extends {Ignored}
8021  */
8022 var BufferSubscriber = (function (_super) {
8023     __extends(BufferSubscriber, _super);
8024     function BufferSubscriber(destination, closingNotifier) {
8025         _super.call(this, destination);
8026         this.buffer = [];
8027         this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8028     }
8029     BufferSubscriber.prototype._next = function (value) {
8030         this.buffer.push(value);
8031     };
8032     BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8033         var buffer = this.buffer;
8034         this.buffer = [];
8035         this.destination.next(buffer);
8036     };
8037     return BufferSubscriber;
8038 }(OuterSubscriber_1.OuterSubscriber));
8039
8040 },{"../OuterSubscriber":30,"../util/subscribeToResult":164}],104:[function(require,module,exports){
8041 "use strict";
8042 var __extends = (this && this.__extends) || function (d, b) {
8043     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8044     function __() { this.constructor = d; }
8045     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8046 };
8047 var Subscriber_1 = require('../Subscriber');
8048 /**
8049  * Buffers the source Observable values until the size hits the maximum
8050  * `bufferSize` given.
8051  *
8052  * <span class="informal">Collects values from the past as an array, and emits
8053  * that array only when its size reaches `bufferSize`.</span>
8054  *
8055  * <img src="./img/bufferCount.png" width="100%">
8056  *
8057  * Buffers a number of values from the source Observable by `bufferSize` then
8058  * emits the buffer and clears it, and starts a new buffer each
8059  * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8060  * `null`, then new buffers are started immediately at the start of the source
8061  * and when each buffer closes and is emitted.
8062  *
8063  * @example <caption>Emit the last two click events as an array</caption>
8064  * var clicks = Rx.Observable.fromEvent(document, 'click');
8065  * var buffered = clicks.bufferCount(2);
8066  * buffered.subscribe(x => console.log(x));
8067  *
8068  * @example <caption>On every click, emit the last two click events as an array</caption>
8069  * var clicks = Rx.Observable.fromEvent(document, 'click');
8070  * var buffered = clicks.bufferCount(2, 1);
8071  * buffered.subscribe(x => console.log(x));
8072  *
8073  * @see {@link buffer}
8074  * @see {@link bufferTime}
8075  * @see {@link bufferToggle}
8076  * @see {@link bufferWhen}
8077  * @see {@link pairwise}
8078  * @see {@link windowCount}
8079  *
8080  * @param {number} bufferSize The maximum size of the buffer emitted.
8081  * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8082  * For example if `startBufferEvery` is `2`, then a new buffer will be started
8083  * on every other value from the source. A new buffer is started at the
8084  * beginning of the source by default.
8085  * @return {Observable<T[]>} An Observable of arrays of buffered values.
8086  * @method bufferCount
8087  * @owner Observable
8088  */
8089 function bufferCount(bufferSize, startBufferEvery) {
8090     if (startBufferEvery === void 0) { startBufferEvery = null; }
8091     return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
8092 }
8093 exports.bufferCount = bufferCount;
8094 var BufferCountOperator = (function () {
8095     function BufferCountOperator(bufferSize, startBufferEvery) {
8096         this.bufferSize = bufferSize;
8097         this.startBufferEvery = startBufferEvery;
8098     }
8099     BufferCountOperator.prototype.call = function (subscriber, source) {
8100         return source.subscribe(new BufferCountSubscriber(subscriber, this.bufferSize, this.startBufferEvery));
8101     };
8102     return BufferCountOperator;
8103 }());
8104 /**
8105  * We need this JSDoc comment for affecting ESDoc.
8106  * @ignore
8107  * @extends {Ignored}
8108  */
8109 var BufferCountSubscriber = (function (_super) {
8110     __extends(BufferCountSubscriber, _super);
8111     function BufferCountSubscriber(destination, bufferSize, startBufferEvery) {
8112         _super.call(this, destination);
8113         this.bufferSize = bufferSize;
8114         this.startBufferEvery = startBufferEvery;
8115         this.buffers = [];
8116         this.count = 0;
8117     }
8118     BufferCountSubscriber.prototype._next = function (value) {
8119         var count = this.count++;
8120         var _a = this, destination = _a.destination, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers;
8121         var startOn = (startBufferEvery == null) ? bufferSize : startBufferEvery;
8122         if (count % startOn === 0) {
8123             buffers.push([]);
8124         }
8125         for (var i = buffers.length; i--;) {
8126             var buffer = buffers[i];
8127             buffer.push(value);
8128             if (buffer.length === bufferSize) {
8129                 buffers.splice(i, 1);
8130                 destination.next(buffer);
8131             }
8132         }
8133     };
8134     BufferCountSubscriber.prototype._complete = function () {
8135         var destination = this.destination;
8136         var buffers = this.buffers;
8137         while (buffers.length > 0) {
8138             var buffer = buffers.shift();
8139             if (buffer.length > 0) {
8140                 destination.next(buffer);
8141             }
8142         }
8143         _super.prototype._complete.call(this);
8144     };
8145     return BufferCountSubscriber;
8146 }(Subscriber_1.Subscriber));
8147
8148 },{"../Subscriber":35}],105:[function(require,module,exports){
8149 "use strict";
8150 var __extends = (this && this.__extends) || function (d, b) {
8151     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8152     function __() { this.constructor = d; }
8153     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8154 };
8155 var OuterSubscriber_1 = require('../OuterSubscriber');
8156 var subscribeToResult_1 = require('../util/subscribeToResult');
8157 /**
8158  * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8159  * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
8160  *  is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
8161  *  is returned by the `selector` will be used to continue the observable chain.
8162  * @return {Observable} an observable that originates from either the source or the observable returned by the
8163  *  catch `selector` function.
8164  * @method catch
8165  * @name catch
8166  * @owner Observable
8167  */
8168 function _catch(selector) {
8169     var operator = new CatchOperator(selector);
8170     var caught = this.lift(operator);
8171     return (operator.caught = caught);
8172 }
8173 exports._catch = _catch;
8174 var CatchOperator = (function () {
8175     function CatchOperator(selector) {
8176         this.selector = selector;
8177     }
8178     CatchOperator.prototype.call = function (subscriber, source) {
8179         return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
8180     };
8181     return CatchOperator;
8182 }());
8183 /**
8184  * We need this JSDoc comment for affecting ESDoc.
8185  * @ignore
8186  * @extends {Ignored}
8187  */
8188 var CatchSubscriber = (function (_super) {
8189     __extends(CatchSubscriber, _super);
8190     function CatchSubscriber(destination, selector, caught) {
8191         _super.call(this, destination);
8192         this.selector = selector;
8193         this.caught = caught;
8194     }
8195     // NOTE: overriding `error` instead of `_error` because we don't want
8196     // to have this flag this subscriber as `isStopped`.
8197     CatchSubscriber.prototype.error = function (err) {
8198         if (!this.isStopped) {
8199             var result = void 0;
8200             try {
8201                 result = this.selector(err, this.caught);
8202             }
8203             catch (err) {
8204                 this.destination.error(err);
8205                 return;
8206             }
8207             this.unsubscribe();
8208             this.destination.remove(this);
8209             subscribeToResult_1.subscribeToResult(this, result);
8210         }
8211     };
8212     return CatchSubscriber;
8213 }(OuterSubscriber_1.OuterSubscriber));
8214
8215 },{"../OuterSubscriber":30,"../util/subscribeToResult":164}],106:[function(require,module,exports){
8216 "use strict";
8217 var __extends = (this && this.__extends) || function (d, b) {
8218     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8219     function __() { this.constructor = d; }
8220     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8221 };
8222 var ArrayObservable_1 = require('../observable/ArrayObservable');
8223 var isArray_1 = require('../util/isArray');
8224 var OuterSubscriber_1 = require('../OuterSubscriber');
8225 var subscribeToResult_1 = require('../util/subscribeToResult');
8226 var none = {};
8227 /* tslint:disable:max-line-length */
8228 /**
8229  * Combines multiple Observables to create an Observable whose values are
8230  * calculated from the latest values of each of its input Observables.
8231  *
8232  * <span class="informal">Whenever any input Observable emits a value, it
8233  * computes a formula using the latest values from all the inputs, then emits
8234  * the output of that formula.</span>
8235  *
8236  * <img src="./img/combineLatest.png" width="100%">
8237  *
8238  * `combineLatest` combines the values from this Observable with values from
8239  * Observables passed as arguments. This is done by subscribing to each
8240  * Observable, in order, and collecting an array of each of the most recent
8241  * values any time any of the input Observables emits, then either taking that
8242  * array and passing it as arguments to an optional `project` function and
8243  * emitting the return value of that, or just emitting the array of recent
8244  * values directly if there is no `project` function.
8245  *
8246  * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
8247  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8248  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8249  * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
8250  * bmi.subscribe(x => console.log('BMI is ' + x));
8251  *
8252  * // With output to console:
8253  * // BMI is 24.212293388429753
8254  * // BMI is 23.93948099205209
8255  * // BMI is 23.671253629592222
8256  *
8257  * @see {@link combineAll}
8258  * @see {@link merge}
8259  * @see {@link withLatestFrom}
8260  *
8261  * @param {Observable} other An input Observable to combine with the source
8262  * Observable. More than one input Observables may be given as argument.
8263  * @param {function} [project] An optional function to project the values from
8264  * the combined latest values into a new value on the output Observable.
8265  * @return {Observable} An Observable of projected values from the most recent
8266  * values from each input Observable, or an array of the most recent values from
8267  * each input Observable.
8268  * @method combineLatest
8269  * @owner Observable
8270  */
8271 function combineLatest() {
8272     var observables = [];
8273     for (var _i = 0; _i < arguments.length; _i++) {
8274         observables[_i - 0] = arguments[_i];
8275     }
8276     var project = null;
8277     if (typeof observables[observables.length - 1] === 'function') {
8278         project = observables.pop();
8279     }
8280     // if the first and only other argument besides the resultSelector is an array
8281     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8282     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8283         observables = observables[0];
8284     }
8285     observables.unshift(this);
8286     return this.lift.call(new ArrayObservable_1.ArrayObservable(observables), new CombineLatestOperator(project));
8287 }
8288 exports.combineLatest = combineLatest;
8289 var CombineLatestOperator = (function () {
8290     function CombineLatestOperator(project) {
8291         this.project = project;
8292     }
8293     CombineLatestOperator.prototype.call = function (subscriber, source) {
8294         return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
8295     };
8296     return CombineLatestOperator;
8297 }());
8298 exports.CombineLatestOperator = CombineLatestOperator;
8299 /**
8300  * We need this JSDoc comment for affecting ESDoc.
8301  * @ignore
8302  * @extends {Ignored}
8303  */
8304 var CombineLatestSubscriber = (function (_super) {
8305     __extends(CombineLatestSubscriber, _super);
8306     function CombineLatestSubscriber(destination, project) {
8307         _super.call(this, destination);
8308         this.project = project;
8309         this.active = 0;
8310         this.values = [];
8311         this.observables = [];
8312     }
8313     CombineLatestSubscriber.prototype._next = function (observable) {
8314         this.values.push(none);
8315         this.observables.push(observable);
8316     };
8317     CombineLatestSubscriber.prototype._complete = function () {
8318         var observables = this.observables;
8319         var len = observables.length;
8320         if (len === 0) {
8321             this.destination.complete();
8322         }
8323         else {
8324             this.active = len;
8325             this.toRespond = len;
8326             for (var i = 0; i < len; i++) {
8327                 var observable = observables[i];
8328                 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
8329             }
8330         }
8331     };
8332     CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
8333         if ((this.active -= 1) === 0) {
8334             this.destination.complete();
8335         }
8336     };
8337     CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8338         var values = this.values;
8339         var oldVal = values[outerIndex];
8340         var toRespond = !this.toRespond
8341             ? 0
8342             : oldVal === none ? --this.toRespond : this.toRespond;
8343         values[outerIndex] = innerValue;
8344         if (toRespond === 0) {
8345             if (this.project) {
8346                 this._tryProject(values);
8347             }
8348             else {
8349                 this.destination.next(values.slice());
8350             }
8351         }
8352     };
8353     CombineLatestSubscriber.prototype._tryProject = function (values) {
8354         var result;
8355         try {
8356             result = this.project.apply(this, values);
8357         }
8358         catch (err) {
8359             this.destination.error(err);
8360             return;
8361         }
8362         this.destination.next(result);
8363     };
8364     return CombineLatestSubscriber;
8365 }(OuterSubscriber_1.OuterSubscriber));
8366 exports.CombineLatestSubscriber = CombineLatestSubscriber;
8367
8368 },{"../OuterSubscriber":30,"../observable/ArrayObservable":83,"../util/isArray":157,"../util/subscribeToResult":164}],107:[function(require,module,exports){
8369 "use strict";
8370 var isScheduler_1 = require('../util/isScheduler');
8371 var ArrayObservable_1 = require('../observable/ArrayObservable');
8372 var mergeAll_1 = require('./mergeAll');
8373 /* tslint:disable:max-line-length */
8374 /**
8375  * Creates an output Observable which sequentially emits all values from every
8376  * given input Observable after the current Observable.
8377  *
8378  * <span class="informal">Concatenates multiple Observables together by
8379  * sequentially emitting their values, one Observable after the other.</span>
8380  *
8381  * <img src="./img/concat.png" width="100%">
8382  *
8383  * Joins this Observable with multiple other Observables by subscribing to them
8384  * one at a time, starting with the source, and merging their results into the
8385  * output Observable. Will wait for each Observable to complete before moving
8386  * on to the next.
8387  *
8388  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8389  * var timer = Rx.Observable.interval(1000).take(4);
8390  * var sequence = Rx.Observable.range(1, 10);
8391  * var result = timer.concat(sequence);
8392  * result.subscribe(x => console.log(x));
8393  *
8394  * // results in:
8395  * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8396  *
8397  * @example <caption>Concatenate 3 Observables</caption>
8398  * var timer1 = Rx.Observable.interval(1000).take(10);
8399  * var timer2 = Rx.Observable.interval(2000).take(6);
8400  * var timer3 = Rx.Observable.interval(500).take(10);
8401  * var result = timer1.concat(timer2, timer3);
8402  * result.subscribe(x => console.log(x));
8403  *
8404  * // results in the following:
8405  * // (Prints to console sequentially)
8406  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8407  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8408  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8409  *
8410  * @see {@link concatAll}
8411  * @see {@link concatMap}
8412  * @see {@link concatMapTo}
8413  *
8414  * @param {Observable} other An input Observable to concatenate after the source
8415  * Observable. More than one input Observables may be given as argument.
8416  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8417  * Observable subscription on.
8418  * @return {Observable} All values of each passed Observable merged into a
8419  * single Observable, in order, in serial fashion.
8420  * @method concat
8421  * @owner Observable
8422  */
8423 function concat() {
8424     var observables = [];
8425     for (var _i = 0; _i < arguments.length; _i++) {
8426         observables[_i - 0] = arguments[_i];
8427     }
8428     return this.lift.call(concatStatic.apply(void 0, [this].concat(observables)));
8429 }
8430 exports.concat = concat;
8431 /* tslint:enable:max-line-length */
8432 /**
8433  * Creates an output Observable which sequentially emits all values from every
8434  * given input Observable after the current Observable.
8435  *
8436  * <span class="informal">Concatenates multiple Observables together by
8437  * sequentially emitting their values, one Observable after the other.</span>
8438  *
8439  * <img src="./img/concat.png" width="100%">
8440  *
8441  * Joins multiple Observables together by subscribing to them one at a time and
8442  * merging their results into the output Observable. Will wait for each
8443  * Observable to complete before moving on to the next.
8444  *
8445  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8446  * var timer = Rx.Observable.interval(1000).take(4);
8447  * var sequence = Rx.Observable.range(1, 10);
8448  * var result = Rx.Observable.concat(timer, sequence);
8449  * result.subscribe(x => console.log(x));
8450  *
8451  * // results in:
8452  * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8453  *
8454  * @example <caption>Concatenate 3 Observables</caption>
8455  * var timer1 = Rx.Observable.interval(1000).take(10);
8456  * var timer2 = Rx.Observable.interval(2000).take(6);
8457  * var timer3 = Rx.Observable.interval(500).take(10);
8458  * var result = Rx.Observable.concat(timer1, timer2, timer3);
8459  * result.subscribe(x => console.log(x));
8460  *
8461  * // results in the following:
8462  * // (Prints to console sequentially)
8463  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8464  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8465  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8466  *
8467  * @see {@link concatAll}
8468  * @see {@link concatMap}
8469  * @see {@link concatMapTo}
8470  *
8471  * @param {Observable} input1 An input Observable to concatenate with others.
8472  * @param {Observable} input2 An input Observable to concatenate with others.
8473  * More than one input Observables may be given as argument.
8474  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8475  * Observable subscription on.
8476  * @return {Observable} All values of each passed Observable merged into a
8477  * single Observable, in order, in serial fashion.
8478  * @static true
8479  * @name concat
8480  * @owner Observable
8481  */
8482 function concatStatic() {
8483     var observables = [];
8484     for (var _i = 0; _i < arguments.length; _i++) {
8485         observables[_i - 0] = arguments[_i];
8486     }
8487     var scheduler = null;
8488     var args = observables;
8489     if (isScheduler_1.isScheduler(args[observables.length - 1])) {
8490         scheduler = args.pop();
8491     }
8492     if (scheduler === null && observables.length === 1) {
8493         return observables[0];
8494     }
8495     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1));
8496 }
8497 exports.concatStatic = concatStatic;
8498
8499 },{"../observable/ArrayObservable":83,"../util/isScheduler":162,"./mergeAll":120}],108:[function(require,module,exports){
8500 "use strict";
8501 var __extends = (this && this.__extends) || function (d, b) {
8502     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8503     function __() { this.constructor = d; }
8504     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8505 };
8506 var Subscriber_1 = require('../Subscriber');
8507 var async_1 = require('../scheduler/async');
8508 /**
8509  * Emits a value from the source Observable only after a particular time span
8510  * has passed without another source emission.
8511  *
8512  * <span class="informal">It's like {@link delay}, but passes only the most
8513  * recent value from each burst of emissions.</span>
8514  *
8515  * <img src="./img/debounceTime.png" width="100%">
8516  *
8517  * `debounceTime` delays values emitted by the source Observable, but drops
8518  * previous pending delayed emissions if a new value arrives on the source
8519  * Observable. This operator keeps track of the most recent value from the
8520  * source Observable, and emits that only when `dueTime` enough time has passed
8521  * without any other value appearing on the source Observable. If a new value
8522  * appears before `dueTime` silence occurs, the previous value will be dropped
8523  * and will not be emitted on the output Observable.
8524  *
8525  * This is a rate-limiting operator, because it is impossible for more than one
8526  * value to be emitted in any time window of duration `dueTime`, but it is also
8527  * a delay-like operator since output emissions do not occur at the same time as
8528  * they did on the source Observable. Optionally takes a {@link IScheduler} for
8529  * managing timers.
8530  *
8531  * @example <caption>Emit the most recent click after a burst of clicks</caption>
8532  * var clicks = Rx.Observable.fromEvent(document, 'click');
8533  * var result = clicks.debounceTime(1000);
8534  * result.subscribe(x => console.log(x));
8535  *
8536  * @see {@link auditTime}
8537  * @see {@link debounce}
8538  * @see {@link delay}
8539  * @see {@link sampleTime}
8540  * @see {@link throttleTime}
8541  *
8542  * @param {number} dueTime The timeout duration in milliseconds (or the time
8543  * unit determined internally by the optional `scheduler`) for the window of
8544  * time required to wait for emission silence before emitting the most recent
8545  * source value.
8546  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
8547  * managing the timers that handle the timeout for each value.
8548  * @return {Observable} An Observable that delays the emissions of the source
8549  * Observable by the specified `dueTime`, and may drop some values if they occur
8550  * too frequently.
8551  * @method debounceTime
8552  * @owner Observable
8553  */
8554 function debounceTime(dueTime, scheduler) {
8555     if (scheduler === void 0) { scheduler = async_1.async; }
8556     return this.lift(new DebounceTimeOperator(dueTime, scheduler));
8557 }
8558 exports.debounceTime = debounceTime;
8559 var DebounceTimeOperator = (function () {
8560     function DebounceTimeOperator(dueTime, scheduler) {
8561         this.dueTime = dueTime;
8562         this.scheduler = scheduler;
8563     }
8564     DebounceTimeOperator.prototype.call = function (subscriber, source) {
8565         return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
8566     };
8567     return DebounceTimeOperator;
8568 }());
8569 /**
8570  * We need this JSDoc comment for affecting ESDoc.
8571  * @ignore
8572  * @extends {Ignored}
8573  */
8574 var DebounceTimeSubscriber = (function (_super) {
8575     __extends(DebounceTimeSubscriber, _super);
8576     function DebounceTimeSubscriber(destination, dueTime, scheduler) {
8577         _super.call(this, destination);
8578         this.dueTime = dueTime;
8579         this.scheduler = scheduler;
8580         this.debouncedSubscription = null;
8581         this.lastValue = null;
8582         this.hasValue = false;
8583     }
8584     DebounceTimeSubscriber.prototype._next = function (value) {
8585         this.clearDebounce();
8586         this.lastValue = value;
8587         this.hasValue = true;
8588         this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
8589     };
8590     DebounceTimeSubscriber.prototype._complete = function () {
8591         this.debouncedNext();
8592         this.destination.complete();
8593     };
8594     DebounceTimeSubscriber.prototype.debouncedNext = function () {
8595         this.clearDebounce();
8596         if (this.hasValue) {
8597             this.destination.next(this.lastValue);
8598             this.lastValue = null;
8599             this.hasValue = false;
8600         }
8601     };
8602     DebounceTimeSubscriber.prototype.clearDebounce = function () {
8603         var debouncedSubscription = this.debouncedSubscription;
8604         if (debouncedSubscription !== null) {
8605             this.remove(debouncedSubscription);
8606             debouncedSubscription.unsubscribe();
8607             this.debouncedSubscription = null;
8608         }
8609     };
8610     return DebounceTimeSubscriber;
8611 }(Subscriber_1.Subscriber));
8612 function dispatchNext(subscriber) {
8613     subscriber.debouncedNext();
8614 }
8615
8616 },{"../Subscriber":35,"../scheduler/async":145}],109:[function(require,module,exports){
8617 "use strict";
8618 var __extends = (this && this.__extends) || function (d, b) {
8619     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8620     function __() { this.constructor = d; }
8621     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8622 };
8623 var async_1 = require('../scheduler/async');
8624 var isDate_1 = require('../util/isDate');
8625 var Subscriber_1 = require('../Subscriber');
8626 var Notification_1 = require('../Notification');
8627 /**
8628  * Delays the emission of items from the source Observable by a given timeout or
8629  * until a given Date.
8630  *
8631  * <span class="informal">Time shifts each item by some specified amount of
8632  * milliseconds.</span>
8633  *
8634  * <img src="./img/delay.png" width="100%">
8635  *
8636  * If the delay argument is a Number, this operator time shifts the source
8637  * Observable by that amount of time expressed in milliseconds. The relative
8638  * time intervals between the values are preserved.
8639  *
8640  * If the delay argument is a Date, this operator time shifts the start of the
8641  * Observable execution until the given date occurs.
8642  *
8643  * @example <caption>Delay each click by one second</caption>
8644  * var clicks = Rx.Observable.fromEvent(document, 'click');
8645  * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
8646  * delayedClicks.subscribe(x => console.log(x));
8647  *
8648  * @example <caption>Delay all clicks until a future date happens</caption>
8649  * var clicks = Rx.Observable.fromEvent(document, 'click');
8650  * var date = new Date('March 15, 2050 12:00:00'); // in the future
8651  * var delayedClicks = clicks.delay(date); // click emitted only after that date
8652  * delayedClicks.subscribe(x => console.log(x));
8653  *
8654  * @see {@link debounceTime}
8655  * @see {@link delayWhen}
8656  *
8657  * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
8658  * a `Date` until which the emission of the source items is delayed.
8659  * @param {Scheduler} [scheduler=async] The IScheduler to use for
8660  * managing the timers that handle the time-shift for each item.
8661  * @return {Observable} An Observable that delays the emissions of the source
8662  * Observable by the specified timeout or Date.
8663  * @method delay
8664  * @owner Observable
8665  */
8666 function delay(delay, scheduler) {
8667     if (scheduler === void 0) { scheduler = async_1.async; }
8668     var absoluteDelay = isDate_1.isDate(delay);
8669     var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
8670     return this.lift(new DelayOperator(delayFor, scheduler));
8671 }
8672 exports.delay = delay;
8673 var DelayOperator = (function () {
8674     function DelayOperator(delay, scheduler) {
8675         this.delay = delay;
8676         this.scheduler = scheduler;
8677     }
8678     DelayOperator.prototype.call = function (subscriber, source) {
8679         return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
8680     };
8681     return DelayOperator;
8682 }());
8683 /**
8684  * We need this JSDoc comment for affecting ESDoc.
8685  * @ignore
8686  * @extends {Ignored}
8687  */
8688 var DelaySubscriber = (function (_super) {
8689     __extends(DelaySubscriber, _super);
8690     function DelaySubscriber(destination, delay, scheduler) {
8691         _super.call(this, destination);
8692         this.delay = delay;
8693         this.scheduler = scheduler;
8694         this.queue = [];
8695         this.active = false;
8696         this.errored = false;
8697     }
8698     DelaySubscriber.dispatch = function (state) {
8699         var source = state.source;
8700         var queue = source.queue;
8701         var scheduler = state.scheduler;
8702         var destination = state.destination;
8703         while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
8704             queue.shift().notification.observe(destination);
8705         }
8706         if (queue.length > 0) {
8707             var delay_1 = Math.max(0, queue[0].time - scheduler.now());
8708             this.schedule(state, delay_1);
8709         }
8710         else {
8711             source.active = false;
8712         }
8713     };
8714     DelaySubscriber.prototype._schedule = function (scheduler) {
8715         this.active = true;
8716         this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
8717             source: this, destination: this.destination, scheduler: scheduler
8718         }));
8719     };
8720     DelaySubscriber.prototype.scheduleNotification = function (notification) {
8721         if (this.errored === true) {
8722             return;
8723         }
8724         var scheduler = this.scheduler;
8725         var message = new DelayMessage(scheduler.now() + this.delay, notification);
8726         this.queue.push(message);
8727         if (this.active === false) {
8728             this._schedule(scheduler);
8729         }
8730     };
8731     DelaySubscriber.prototype._next = function (value) {
8732         this.scheduleNotification(Notification_1.Notification.createNext(value));
8733     };
8734     DelaySubscriber.prototype._error = function (err) {
8735         this.errored = true;
8736         this.queue = [];
8737         this.destination.error(err);
8738     };
8739     DelaySubscriber.prototype._complete = function () {
8740         this.scheduleNotification(Notification_1.Notification.createComplete());
8741     };
8742     return DelaySubscriber;
8743 }(Subscriber_1.Subscriber));
8744 var DelayMessage = (function () {
8745     function DelayMessage(time, notification) {
8746         this.time = time;
8747         this.notification = notification;
8748     }
8749     return DelayMessage;
8750 }());
8751
8752 },{"../Notification":27,"../Subscriber":35,"../scheduler/async":145,"../util/isDate":158}],110:[function(require,module,exports){
8753 "use strict";
8754 var __extends = (this && this.__extends) || function (d, b) {
8755     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8756     function __() { this.constructor = d; }
8757     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8758 };
8759 var OuterSubscriber_1 = require('../OuterSubscriber');
8760 var subscribeToResult_1 = require('../util/subscribeToResult');
8761 var Set_1 = require('../util/Set');
8762 /**
8763  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
8764  *
8765  * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
8766  * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
8767  * source observable directly with an equality check against previous values.
8768  *
8769  * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
8770  *
8771  * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
8772  * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
8773  * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
8774  * that the internal `Set` can be "flushed", basically clearing it of values.
8775  *
8776  * @example <caption>A simple example with numbers</caption>
8777  * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
8778  *   .distinct()
8779  *   .subscribe(x => console.log(x)); // 1, 2, 3, 4
8780  *
8781  * @example <caption>An example using a keySelector function</caption>
8782  * interface Person {
8783  *    age: number,
8784  *    name: string
8785  * }
8786  *
8787  * Observable.of<Person>(
8788  *     { age: 4, name: 'Foo'},
8789  *     { age: 7, name: 'Bar'},
8790  *     { age: 5, name: 'Foo'})
8791  *     .distinct((p: Person) => p.name)
8792  *     .subscribe(x => console.log(x));
8793  *
8794  * // displays:
8795  * // { age: 4, name: 'Foo' }
8796  * // { age: 7, name: 'Bar' }
8797  *
8798  * @see {@link distinctUntilChanged}
8799  * @see {@link distinctUntilKeyChanged}
8800  *
8801  * @param {function} [keySelector] optional function to select which value you want to check as distinct.
8802  * @param {Observable} [flushes] optional Observable for flushing the internal HashSet of the operator.
8803  * @return {Observable} an Observable that emits items from the source Observable with distinct values.
8804  * @method distinct
8805  * @owner Observable
8806  */
8807 function distinct(keySelector, flushes) {
8808     return this.lift(new DistinctOperator(keySelector, flushes));
8809 }
8810 exports.distinct = distinct;
8811 var DistinctOperator = (function () {
8812     function DistinctOperator(keySelector, flushes) {
8813         this.keySelector = keySelector;
8814         this.flushes = flushes;
8815     }
8816     DistinctOperator.prototype.call = function (subscriber, source) {
8817         return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
8818     };
8819     return DistinctOperator;
8820 }());
8821 /**
8822  * We need this JSDoc comment for affecting ESDoc.
8823  * @ignore
8824  * @extends {Ignored}
8825  */
8826 var DistinctSubscriber = (function (_super) {
8827     __extends(DistinctSubscriber, _super);
8828     function DistinctSubscriber(destination, keySelector, flushes) {
8829         _super.call(this, destination);
8830         this.keySelector = keySelector;
8831         this.values = new Set_1.Set();
8832         if (flushes) {
8833             this.add(subscribeToResult_1.subscribeToResult(this, flushes));
8834         }
8835     }
8836     DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8837         this.values.clear();
8838     };
8839     DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
8840         this._error(error);
8841     };
8842     DistinctSubscriber.prototype._next = function (value) {
8843         if (this.keySelector) {
8844             this._useKeySelector(value);
8845         }
8846         else {
8847             this._finalizeNext(value, value);
8848         }
8849     };
8850     DistinctSubscriber.prototype._useKeySelector = function (value) {
8851         var key;
8852         var destination = this.destination;
8853         try {
8854             key = this.keySelector(value);
8855         }
8856         catch (err) {
8857             destination.error(err);
8858             return;
8859         }
8860         this._finalizeNext(key, value);
8861     };
8862     DistinctSubscriber.prototype._finalizeNext = function (key, value) {
8863         var values = this.values;
8864         if (!values.has(key)) {
8865             values.add(key);
8866             this.destination.next(value);
8867         }
8868     };
8869     return DistinctSubscriber;
8870 }(OuterSubscriber_1.OuterSubscriber));
8871 exports.DistinctSubscriber = DistinctSubscriber;
8872
8873 },{"../OuterSubscriber":30,"../util/Set":154,"../util/subscribeToResult":164}],111:[function(require,module,exports){
8874 "use strict";
8875 var __extends = (this && this.__extends) || function (d, b) {
8876     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8877     function __() { this.constructor = d; }
8878     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8879 };
8880 var Subscriber_1 = require('../Subscriber');
8881 var tryCatch_1 = require('../util/tryCatch');
8882 var errorObject_1 = require('../util/errorObject');
8883 /* tslint:disable:max-line-length */
8884 /**
8885  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
8886  *
8887  * 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.
8888  *
8889  * If a comparator function is not provided, an equality check is used by default.
8890  *
8891  * @example <caption>A simple example with numbers</caption>
8892  * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
8893  *   .distinctUntilChanged()
8894  *   .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
8895  *
8896  * @example <caption>An example using a compare function</caption>
8897  * interface Person {
8898  *    age: number,
8899  *    name: string
8900  * }
8901  *
8902  * Observable.of<Person>(
8903  *     { age: 4, name: 'Foo'},
8904  *     { age: 7, name: 'Bar'},
8905  *     { age: 5, name: 'Foo'})
8906  *     { age: 6, name: 'Foo'})
8907  *     .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
8908  *     .subscribe(x => console.log(x));
8909  *
8910  * // displays:
8911  * // { age: 4, name: 'Foo' }
8912  * // { age: 7, name: 'Bar' }
8913  * // { age: 5, name: 'Foo' }
8914  *
8915  * @see {@link distinct}
8916  * @see {@link distinctUntilKeyChanged}
8917  *
8918  * @param {function} [compare] optional comparison function called to test if an item is distinct from the previous item in the source.
8919  * @return {Observable} an Observable that emits items from the source Observable with distinct values.
8920  * @method distinctUntilChanged
8921  * @owner Observable
8922  */
8923 function distinctUntilChanged(compare, keySelector) {
8924     return this.lift(new DistinctUntilChangedOperator(compare, keySelector));
8925 }
8926 exports.distinctUntilChanged = distinctUntilChanged;
8927 var DistinctUntilChangedOperator = (function () {
8928     function DistinctUntilChangedOperator(compare, keySelector) {
8929         this.compare = compare;
8930         this.keySelector = keySelector;
8931     }
8932     DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
8933         return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
8934     };
8935     return DistinctUntilChangedOperator;
8936 }());
8937 /**
8938  * We need this JSDoc comment for affecting ESDoc.
8939  * @ignore
8940  * @extends {Ignored}
8941  */
8942 var DistinctUntilChangedSubscriber = (function (_super) {
8943     __extends(DistinctUntilChangedSubscriber, _super);
8944     function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
8945         _super.call(this, destination);
8946         this.keySelector = keySelector;
8947         this.hasKey = false;
8948         if (typeof compare === 'function') {
8949             this.compare = compare;
8950         }
8951     }
8952     DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
8953         return x === y;
8954     };
8955     DistinctUntilChangedSubscriber.prototype._next = function (value) {
8956         var keySelector = this.keySelector;
8957         var key = value;
8958         if (keySelector) {
8959             key = tryCatch_1.tryCatch(this.keySelector)(value);
8960             if (key === errorObject_1.errorObject) {
8961                 return this.destination.error(errorObject_1.errorObject.e);
8962             }
8963         }
8964         var result = false;
8965         if (this.hasKey) {
8966             result = tryCatch_1.tryCatch(this.compare)(this.key, key);
8967             if (result === errorObject_1.errorObject) {
8968                 return this.destination.error(errorObject_1.errorObject.e);
8969             }
8970         }
8971         else {
8972             this.hasKey = true;
8973         }
8974         if (Boolean(result) === false) {
8975             this.key = key;
8976             this.destination.next(value);
8977         }
8978     };
8979     return DistinctUntilChangedSubscriber;
8980 }(Subscriber_1.Subscriber));
8981
8982 },{"../Subscriber":35,"../util/errorObject":156,"../util/tryCatch":166}],112:[function(require,module,exports){
8983 "use strict";
8984 var __extends = (this && this.__extends) || function (d, b) {
8985     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8986     function __() { this.constructor = d; }
8987     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8988 };
8989 var Subscriber_1 = require('../Subscriber');
8990 /* tslint:disable:max-line-length */
8991 /**
8992  * Perform a side effect for every emission on the source Observable, but return
8993  * an Observable that is identical to the source.
8994  *
8995  * <span class="informal">Intercepts each emission on the source and runs a
8996  * function, but returns an output which is identical to the source.</span>
8997  *
8998  * <img src="./img/do.png" width="100%">
8999  *
9000  * Returns a mirrored Observable of the source Observable, but modified so that
9001  * the provided Observer is called to perform a side effect for every value,
9002  * error, and completion emitted by the source. Any errors that are thrown in
9003  * the aforementioned Observer or handlers are safely sent down the error path
9004  * of the output Observable.
9005  *
9006  * This operator is useful for debugging your Observables for the correct values
9007  * or performing other side effects.
9008  *
9009  * Note: this is different to a `subscribe` on the Observable. If the Observable
9010  * returned by `do` is not subscribed, the side effects specified by the
9011  * Observer will never happen. `do` therefore simply spies on existing
9012  * execution, it does not trigger an execution to happen like `subscribe` does.
9013  *
9014  * @example <caption>Map every every click to the clientX position of that click, while also logging the click event</caption>
9015  * var clicks = Rx.Observable.fromEvent(document, 'click');
9016  * var positions = clicks
9017  *   .do(ev => console.log(ev))
9018  *   .map(ev => ev.clientX);
9019  * positions.subscribe(x => console.log(x));
9020  *
9021  * @see {@link map}
9022  * @see {@link subscribe}
9023  *
9024  * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9025  * callback for `next`.
9026  * @param {function} [error] Callback for errors in the source.
9027  * @param {function} [complete] Callback for the completion of the source.
9028  * @return {Observable} An Observable identical to the source, but runs the
9029  * specified Observer or callback(s) for each item.
9030  * @method do
9031  * @name do
9032  * @owner Observable
9033  */
9034 function _do(nextOrObserver, error, complete) {
9035     return this.lift(new DoOperator(nextOrObserver, error, complete));
9036 }
9037 exports._do = _do;
9038 var DoOperator = (function () {
9039     function DoOperator(nextOrObserver, error, complete) {
9040         this.nextOrObserver = nextOrObserver;
9041         this.error = error;
9042         this.complete = complete;
9043     }
9044     DoOperator.prototype.call = function (subscriber, source) {
9045         return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
9046     };
9047     return DoOperator;
9048 }());
9049 /**
9050  * We need this JSDoc comment for affecting ESDoc.
9051  * @ignore
9052  * @extends {Ignored}
9053  */
9054 var DoSubscriber = (function (_super) {
9055     __extends(DoSubscriber, _super);
9056     function DoSubscriber(destination, nextOrObserver, error, complete) {
9057         _super.call(this, destination);
9058         var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
9059         safeSubscriber.syncErrorThrowable = true;
9060         this.add(safeSubscriber);
9061         this.safeSubscriber = safeSubscriber;
9062     }
9063     DoSubscriber.prototype._next = function (value) {
9064         var safeSubscriber = this.safeSubscriber;
9065         safeSubscriber.next(value);
9066         if (safeSubscriber.syncErrorThrown) {
9067             this.destination.error(safeSubscriber.syncErrorValue);
9068         }
9069         else {
9070             this.destination.next(value);
9071         }
9072     };
9073     DoSubscriber.prototype._error = function (err) {
9074         var safeSubscriber = this.safeSubscriber;
9075         safeSubscriber.error(err);
9076         if (safeSubscriber.syncErrorThrown) {
9077             this.destination.error(safeSubscriber.syncErrorValue);
9078         }
9079         else {
9080             this.destination.error(err);
9081         }
9082     };
9083     DoSubscriber.prototype._complete = function () {
9084         var safeSubscriber = this.safeSubscriber;
9085         safeSubscriber.complete();
9086         if (safeSubscriber.syncErrorThrown) {
9087             this.destination.error(safeSubscriber.syncErrorValue);
9088         }
9089         else {
9090             this.destination.complete();
9091         }
9092     };
9093     return DoSubscriber;
9094 }(Subscriber_1.Subscriber));
9095
9096 },{"../Subscriber":35}],113:[function(require,module,exports){
9097 "use strict";
9098 var __extends = (this && this.__extends) || function (d, b) {
9099     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9100     function __() { this.constructor = d; }
9101     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9102 };
9103 var tryCatch_1 = require('../util/tryCatch');
9104 var errorObject_1 = require('../util/errorObject');
9105 var OuterSubscriber_1 = require('../OuterSubscriber');
9106 var subscribeToResult_1 = require('../util/subscribeToResult');
9107 /* tslint:disable:max-line-length */
9108 /**
9109  * Recursively projects each source value to an Observable which is merged in
9110  * the output Observable.
9111  *
9112  * <span class="informal">It's similar to {@link mergeMap}, but applies the
9113  * projection function to every source value as well as every output value.
9114  * It's recursive.</span>
9115  *
9116  * <img src="./img/expand.png" width="100%">
9117  *
9118  * Returns an Observable that emits items based on applying a function that you
9119  * supply to each item emitted by the source Observable, where that function
9120  * returns an Observable, and then merging those resulting Observables and
9121  * emitting the results of this merger. *Expand* will re-emit on the output
9122  * Observable every source value. Then, each output value is given to the
9123  * `project` function which returns an inner Observable to be merged on the
9124  * output Observable. Those output values resulting from the projection are also
9125  * given to the `project` function to produce new output values. This is how
9126  * *expand* behaves recursively.
9127  *
9128  * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9129  * var clicks = Rx.Observable.fromEvent(document, 'click');
9130  * var powersOfTwo = clicks
9131  *   .mapTo(1)
9132  *   .expand(x => Rx.Observable.of(2 * x).delay(1000))
9133  *   .take(10);
9134  * powersOfTwo.subscribe(x => console.log(x));
9135  *
9136  * @see {@link mergeMap}
9137  * @see {@link mergeScan}
9138  *
9139  * @param {function(value: T, index: number) => Observable} project A function
9140  * that, when applied to an item emitted by the source or the output Observable,
9141  * returns an Observable.
9142  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9143  * Observables being subscribed to concurrently.
9144  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9145  * each projected inner Observable.
9146  * @return {Observable} An Observable that emits the source values and also
9147  * result of applying the projection function to each value emitted on the
9148  * output Observable and and merging the results of the Observables obtained
9149  * from this transformation.
9150  * @method expand
9151  * @owner Observable
9152  */
9153 function expand(project, concurrent, scheduler) {
9154     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9155     if (scheduler === void 0) { scheduler = undefined; }
9156     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9157     return this.lift(new ExpandOperator(project, concurrent, scheduler));
9158 }
9159 exports.expand = expand;
9160 var ExpandOperator = (function () {
9161     function ExpandOperator(project, concurrent, scheduler) {
9162         this.project = project;
9163         this.concurrent = concurrent;
9164         this.scheduler = scheduler;
9165     }
9166     ExpandOperator.prototype.call = function (subscriber, source) {
9167         return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
9168     };
9169     return ExpandOperator;
9170 }());
9171 exports.ExpandOperator = ExpandOperator;
9172 /**
9173  * We need this JSDoc comment for affecting ESDoc.
9174  * @ignore
9175  * @extends {Ignored}
9176  */
9177 var ExpandSubscriber = (function (_super) {
9178     __extends(ExpandSubscriber, _super);
9179     function ExpandSubscriber(destination, project, concurrent, scheduler) {
9180         _super.call(this, destination);
9181         this.project = project;
9182         this.concurrent = concurrent;
9183         this.scheduler = scheduler;
9184         this.index = 0;
9185         this.active = 0;
9186         this.hasCompleted = false;
9187         if (concurrent < Number.POSITIVE_INFINITY) {
9188             this.buffer = [];
9189         }
9190     }
9191     ExpandSubscriber.dispatch = function (arg) {
9192         var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
9193         subscriber.subscribeToProjection(result, value, index);
9194     };
9195     ExpandSubscriber.prototype._next = function (value) {
9196         var destination = this.destination;
9197         if (destination.closed) {
9198             this._complete();
9199             return;
9200         }
9201         var index = this.index++;
9202         if (this.active < this.concurrent) {
9203             destination.next(value);
9204             var result = tryCatch_1.tryCatch(this.project)(value, index);
9205             if (result === errorObject_1.errorObject) {
9206                 destination.error(errorObject_1.errorObject.e);
9207             }
9208             else if (!this.scheduler) {
9209                 this.subscribeToProjection(result, value, index);
9210             }
9211             else {
9212                 var state = { subscriber: this, result: result, value: value, index: index };
9213                 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
9214             }
9215         }
9216         else {
9217             this.buffer.push(value);
9218         }
9219     };
9220     ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
9221         this.active++;
9222         this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
9223     };
9224     ExpandSubscriber.prototype._complete = function () {
9225         this.hasCompleted = true;
9226         if (this.hasCompleted && this.active === 0) {
9227             this.destination.complete();
9228         }
9229     };
9230     ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9231         this._next(innerValue);
9232     };
9233     ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
9234         var buffer = this.buffer;
9235         this.remove(innerSub);
9236         this.active--;
9237         if (buffer && buffer.length > 0) {
9238             this._next(buffer.shift());
9239         }
9240         if (this.hasCompleted && this.active === 0) {
9241             this.destination.complete();
9242         }
9243     };
9244     return ExpandSubscriber;
9245 }(OuterSubscriber_1.OuterSubscriber));
9246 exports.ExpandSubscriber = ExpandSubscriber;
9247
9248 },{"../OuterSubscriber":30,"../util/errorObject":156,"../util/subscribeToResult":164,"../util/tryCatch":166}],114:[function(require,module,exports){
9249 "use strict";
9250 var __extends = (this && this.__extends) || function (d, b) {
9251     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9252     function __() { this.constructor = d; }
9253     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9254 };
9255 var Subscriber_1 = require('../Subscriber');
9256 /* tslint:disable:max-line-length */
9257 /**
9258  * Filter items emitted by the source Observable by only emitting those that
9259  * satisfy a specified predicate.
9260  *
9261  * <span class="informal">Like
9262  * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
9263  * it only emits a value from the source if it passes a criterion function.</span>
9264  *
9265  * <img src="./img/filter.png" width="100%">
9266  *
9267  * Similar to the well-known `Array.prototype.filter` method, this operator
9268  * takes values from the source Observable, passes them through a `predicate`
9269  * function and only emits those values that yielded `true`.
9270  *
9271  * @example <caption>Emit only click events whose target was a DIV element</caption>
9272  * var clicks = Rx.Observable.fromEvent(document, 'click');
9273  * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
9274  * clicksOnDivs.subscribe(x => console.log(x));
9275  *
9276  * @see {@link distinct}
9277  * @see {@link distinctUntilChanged}
9278  * @see {@link distinctUntilKeyChanged}
9279  * @see {@link ignoreElements}
9280  * @see {@link partition}
9281  * @see {@link skip}
9282  *
9283  * @param {function(value: T, index: number): boolean} predicate A function that
9284  * evaluates each value emitted by the source Observable. If it returns `true`,
9285  * the value is emitted, if `false` the value is not passed to the output
9286  * Observable. The `index` parameter is the number `i` for the i-th source
9287  * emission that has happened since the subscription, starting from the number
9288  * `0`.
9289  * @param {any} [thisArg] An optional argument to determine the value of `this`
9290  * in the `predicate` function.
9291  * @return {Observable} An Observable of values from the source that were
9292  * allowed by the `predicate` function.
9293  * @method filter
9294  * @owner Observable
9295  */
9296 function filter(predicate, thisArg) {
9297     return this.lift(new FilterOperator(predicate, thisArg));
9298 }
9299 exports.filter = filter;
9300 var FilterOperator = (function () {
9301     function FilterOperator(predicate, thisArg) {
9302         this.predicate = predicate;
9303         this.thisArg = thisArg;
9304     }
9305     FilterOperator.prototype.call = function (subscriber, source) {
9306         return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
9307     };
9308     return FilterOperator;
9309 }());
9310 /**
9311  * We need this JSDoc comment for affecting ESDoc.
9312  * @ignore
9313  * @extends {Ignored}
9314  */
9315 var FilterSubscriber = (function (_super) {
9316     __extends(FilterSubscriber, _super);
9317     function FilterSubscriber(destination, predicate, thisArg) {
9318         _super.call(this, destination);
9319         this.predicate = predicate;
9320         this.thisArg = thisArg;
9321         this.count = 0;
9322         this.predicate = predicate;
9323     }
9324     // the try catch block below is left specifically for
9325     // optimization and perf reasons. a tryCatcher is not necessary here.
9326     FilterSubscriber.prototype._next = function (value) {
9327         var result;
9328         try {
9329             result = this.predicate.call(this.thisArg, value, this.count++);
9330         }
9331         catch (err) {
9332             this.destination.error(err);
9333             return;
9334         }
9335         if (result) {
9336             this.destination.next(value);
9337         }
9338     };
9339     return FilterSubscriber;
9340 }(Subscriber_1.Subscriber));
9341
9342 },{"../Subscriber":35}],115:[function(require,module,exports){
9343 "use strict";
9344 var __extends = (this && this.__extends) || function (d, b) {
9345     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9346     function __() { this.constructor = d; }
9347     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9348 };
9349 var Subscriber_1 = require('../Subscriber');
9350 var Subscription_1 = require('../Subscription');
9351 /**
9352  * Returns an Observable that mirrors the source Observable, but will call a specified function when
9353  * the source terminates on complete or error.
9354  * @param {function} callback function to be called when source terminates.
9355  * @return {Observable} an Observable that mirrors the source, but will call the specified function on termination.
9356  * @method finally
9357  * @owner Observable
9358  */
9359 function _finally(callback) {
9360     return this.lift(new FinallyOperator(callback));
9361 }
9362 exports._finally = _finally;
9363 var FinallyOperator = (function () {
9364     function FinallyOperator(callback) {
9365         this.callback = callback;
9366     }
9367     FinallyOperator.prototype.call = function (subscriber, source) {
9368         return source.subscribe(new FinallySubscriber(subscriber, this.callback));
9369     };
9370     return FinallyOperator;
9371 }());
9372 /**
9373  * We need this JSDoc comment for affecting ESDoc.
9374  * @ignore
9375  * @extends {Ignored}
9376  */
9377 var FinallySubscriber = (function (_super) {
9378     __extends(FinallySubscriber, _super);
9379     function FinallySubscriber(destination, callback) {
9380         _super.call(this, destination);
9381         this.add(new Subscription_1.Subscription(callback));
9382     }
9383     return FinallySubscriber;
9384 }(Subscriber_1.Subscriber));
9385
9386 },{"../Subscriber":35,"../Subscription":36}],116:[function(require,module,exports){
9387 "use strict";
9388 var __extends = (this && this.__extends) || function (d, b) {
9389     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9390     function __() { this.constructor = d; }
9391     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9392 };
9393 var Subscriber_1 = require('../Subscriber');
9394 var EmptyError_1 = require('../util/EmptyError');
9395 /**
9396  * Emits only the first value (or the first value that meets some condition)
9397  * emitted by the source Observable.
9398  *
9399  * <span class="informal">Emits only the first value. Or emits only the first
9400  * value that passes some test.</span>
9401  *
9402  * <img src="./img/first.png" width="100%">
9403  *
9404  * If called with no arguments, `first` emits the first value of the source
9405  * Observable, then completes. If called with a `predicate` function, `first`
9406  * emits the first value of the source that matches the specified condition. It
9407  * may also take a `resultSelector` function to produce the output value from
9408  * the input value, and a `defaultValue` to emit in case the source completes
9409  * before it is able to emit a valid value. Throws an error if `defaultValue`
9410  * was not provided and a matching element is not found.
9411  *
9412  * @example <caption>Emit only the first click that happens on the DOM</caption>
9413  * var clicks = Rx.Observable.fromEvent(document, 'click');
9414  * var result = clicks.first();
9415  * result.subscribe(x => console.log(x));
9416  *
9417  * @example <caption>Emits the first click that happens on a DIV</caption>
9418  * var clicks = Rx.Observable.fromEvent(document, 'click');
9419  * var result = clicks.first(ev => ev.target.tagName === 'DIV');
9420  * result.subscribe(x => console.log(x));
9421  *
9422  * @see {@link filter}
9423  * @see {@link find}
9424  * @see {@link take}
9425  *
9426  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9427  * callback if the Observable completes before any `next` notification was sent.
9428  *
9429  * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
9430  * An optional function called with each item to test for condition matching.
9431  * @param {function(value: T, index: number): R} [resultSelector] A function to
9432  * produce the value on the output Observable based on the values
9433  * and the indices of the source Observable. The arguments passed to this
9434  * function are:
9435  * - `value`: the value that was emitted on the source.
9436  * - `index`: the "index" of the value from the source.
9437  * @param {R} [defaultValue] The default value emitted in case no valid value
9438  * was found on the source.
9439  * @return {Observable<T|R>} an Observable of the first item that matches the
9440  * condition.
9441  * @method first
9442  * @owner Observable
9443  */
9444 function first(predicate, resultSelector, defaultValue) {
9445     return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this));
9446 }
9447 exports.first = first;
9448 var FirstOperator = (function () {
9449     function FirstOperator(predicate, resultSelector, defaultValue, source) {
9450         this.predicate = predicate;
9451         this.resultSelector = resultSelector;
9452         this.defaultValue = defaultValue;
9453         this.source = source;
9454     }
9455     FirstOperator.prototype.call = function (observer, source) {
9456         return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
9457     };
9458     return FirstOperator;
9459 }());
9460 /**
9461  * We need this JSDoc comment for affecting ESDoc.
9462  * @ignore
9463  * @extends {Ignored}
9464  */
9465 var FirstSubscriber = (function (_super) {
9466     __extends(FirstSubscriber, _super);
9467     function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
9468         _super.call(this, destination);
9469         this.predicate = predicate;
9470         this.resultSelector = resultSelector;
9471         this.defaultValue = defaultValue;
9472         this.source = source;
9473         this.index = 0;
9474         this.hasCompleted = false;
9475         this._emitted = false;
9476     }
9477     FirstSubscriber.prototype._next = function (value) {
9478         var index = this.index++;
9479         if (this.predicate) {
9480             this._tryPredicate(value, index);
9481         }
9482         else {
9483             this._emit(value, index);
9484         }
9485     };
9486     FirstSubscriber.prototype._tryPredicate = function (value, index) {
9487         var result;
9488         try {
9489             result = this.predicate(value, index, this.source);
9490         }
9491         catch (err) {
9492             this.destination.error(err);
9493             return;
9494         }
9495         if (result) {
9496             this._emit(value, index);
9497         }
9498     };
9499     FirstSubscriber.prototype._emit = function (value, index) {
9500         if (this.resultSelector) {
9501             this._tryResultSelector(value, index);
9502             return;
9503         }
9504         this._emitFinal(value);
9505     };
9506     FirstSubscriber.prototype._tryResultSelector = function (value, index) {
9507         var result;
9508         try {
9509             result = this.resultSelector(value, index);
9510         }
9511         catch (err) {
9512             this.destination.error(err);
9513             return;
9514         }
9515         this._emitFinal(result);
9516     };
9517     FirstSubscriber.prototype._emitFinal = function (value) {
9518         var destination = this.destination;
9519         if (!this._emitted) {
9520             this._emitted = true;
9521             destination.next(value);
9522             destination.complete();
9523             this.hasCompleted = true;
9524         }
9525     };
9526     FirstSubscriber.prototype._complete = function () {
9527         var destination = this.destination;
9528         if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
9529             destination.next(this.defaultValue);
9530             destination.complete();
9531         }
9532         else if (!this.hasCompleted) {
9533             destination.error(new EmptyError_1.EmptyError);
9534         }
9535     };
9536     return FirstSubscriber;
9537 }(Subscriber_1.Subscriber));
9538
9539 },{"../Subscriber":35,"../util/EmptyError":152}],117:[function(require,module,exports){
9540 "use strict";
9541 var __extends = (this && this.__extends) || function (d, b) {
9542     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9543     function __() { this.constructor = d; }
9544     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9545 };
9546 var Subscriber_1 = require('../Subscriber');
9547 var EmptyError_1 = require('../util/EmptyError');
9548 /* tslint:disable:max-line-length */
9549 /**
9550  * Returns an Observable that emits only the last item emitted by the source Observable.
9551  * It optionally takes a predicate function as a parameter, in which case, rather than emitting
9552  * the last item from the source Observable, the resulting Observable will emit the last item
9553  * from the source Observable that satisfies the predicate.
9554  *
9555  * <img src="./img/last.png" width="100%">
9556  *
9557  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9558  * callback if the Observable completes before any `next` notification was sent.
9559  * @param {function} predicate - the condition any source emitted item has to satisfy.
9560  * @return {Observable} an Observable that emits only the last item satisfying the given condition
9561  * from the source, or an NoSuchElementException if no such items are emitted.
9562  * @throws - Throws if no items that match the predicate are emitted by the source Observable.
9563  * @method last
9564  * @owner Observable
9565  */
9566 function last(predicate, resultSelector, defaultValue) {
9567     return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this));
9568 }
9569 exports.last = last;
9570 var LastOperator = (function () {
9571     function LastOperator(predicate, resultSelector, defaultValue, source) {
9572         this.predicate = predicate;
9573         this.resultSelector = resultSelector;
9574         this.defaultValue = defaultValue;
9575         this.source = source;
9576     }
9577     LastOperator.prototype.call = function (observer, source) {
9578         return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
9579     };
9580     return LastOperator;
9581 }());
9582 /**
9583  * We need this JSDoc comment for affecting ESDoc.
9584  * @ignore
9585  * @extends {Ignored}
9586  */
9587 var LastSubscriber = (function (_super) {
9588     __extends(LastSubscriber, _super);
9589     function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
9590         _super.call(this, destination);
9591         this.predicate = predicate;
9592         this.resultSelector = resultSelector;
9593         this.defaultValue = defaultValue;
9594         this.source = source;
9595         this.hasValue = false;
9596         this.index = 0;
9597         if (typeof defaultValue !== 'undefined') {
9598             this.lastValue = defaultValue;
9599             this.hasValue = true;
9600         }
9601     }
9602     LastSubscriber.prototype._next = function (value) {
9603         var index = this.index++;
9604         if (this.predicate) {
9605             this._tryPredicate(value, index);
9606         }
9607         else {
9608             if (this.resultSelector) {
9609                 this._tryResultSelector(value, index);
9610                 return;
9611             }
9612             this.lastValue = value;
9613             this.hasValue = true;
9614         }
9615     };
9616     LastSubscriber.prototype._tryPredicate = function (value, index) {
9617         var result;
9618         try {
9619             result = this.predicate(value, index, this.source);
9620         }
9621         catch (err) {
9622             this.destination.error(err);
9623             return;
9624         }
9625         if (result) {
9626             if (this.resultSelector) {
9627                 this._tryResultSelector(value, index);
9628                 return;
9629             }
9630             this.lastValue = value;
9631             this.hasValue = true;
9632         }
9633     };
9634     LastSubscriber.prototype._tryResultSelector = function (value, index) {
9635         var result;
9636         try {
9637             result = this.resultSelector(value, index);
9638         }
9639         catch (err) {
9640             this.destination.error(err);
9641             return;
9642         }
9643         this.lastValue = result;
9644         this.hasValue = true;
9645     };
9646     LastSubscriber.prototype._complete = function () {
9647         var destination = this.destination;
9648         if (this.hasValue) {
9649             destination.next(this.lastValue);
9650             destination.complete();
9651         }
9652         else {
9653             destination.error(new EmptyError_1.EmptyError);
9654         }
9655     };
9656     return LastSubscriber;
9657 }(Subscriber_1.Subscriber));
9658
9659 },{"../Subscriber":35,"../util/EmptyError":152}],118:[function(require,module,exports){
9660 "use strict";
9661 var __extends = (this && this.__extends) || function (d, b) {
9662     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9663     function __() { this.constructor = d; }
9664     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9665 };
9666 var Subscriber_1 = require('../Subscriber');
9667 /**
9668  * Applies a given `project` function to each value emitted by the source
9669  * Observable, and emits the resulting values as an Observable.
9670  *
9671  * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
9672  * it passes each source value through a transformation function to get
9673  * corresponding output values.</span>
9674  *
9675  * <img src="./img/map.png" width="100%">
9676  *
9677  * Similar to the well known `Array.prototype.map` function, this operator
9678  * applies a projection to each value and emits that projection in the output
9679  * Observable.
9680  *
9681  * @example <caption>Map every every click to the clientX position of that click</caption>
9682  * var clicks = Rx.Observable.fromEvent(document, 'click');
9683  * var positions = clicks.map(ev => ev.clientX);
9684  * positions.subscribe(x => console.log(x));
9685  *
9686  * @see {@link mapTo}
9687  * @see {@link pluck}
9688  *
9689  * @param {function(value: T, index: number): R} project The function to apply
9690  * to each `value` emitted by the source Observable. The `index` parameter is
9691  * the number `i` for the i-th emission that has happened since the
9692  * subscription, starting from the number `0`.
9693  * @param {any} [thisArg] An optional argument to define what `this` is in the
9694  * `project` function.
9695  * @return {Observable<R>} An Observable that emits the values from the source
9696  * Observable transformed by the given `project` function.
9697  * @method map
9698  * @owner Observable
9699  */
9700 function map(project, thisArg) {
9701     if (typeof project !== 'function') {
9702         throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
9703     }
9704     return this.lift(new MapOperator(project, thisArg));
9705 }
9706 exports.map = map;
9707 var MapOperator = (function () {
9708     function MapOperator(project, thisArg) {
9709         this.project = project;
9710         this.thisArg = thisArg;
9711     }
9712     MapOperator.prototype.call = function (subscriber, source) {
9713         return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
9714     };
9715     return MapOperator;
9716 }());
9717 exports.MapOperator = MapOperator;
9718 /**
9719  * We need this JSDoc comment for affecting ESDoc.
9720  * @ignore
9721  * @extends {Ignored}
9722  */
9723 var MapSubscriber = (function (_super) {
9724     __extends(MapSubscriber, _super);
9725     function MapSubscriber(destination, project, thisArg) {
9726         _super.call(this, destination);
9727         this.project = project;
9728         this.count = 0;
9729         this.thisArg = thisArg || this;
9730     }
9731     // NOTE: This looks unoptimized, but it's actually purposefully NOT
9732     // using try/catch optimizations.
9733     MapSubscriber.prototype._next = function (value) {
9734         var result;
9735         try {
9736             result = this.project.call(this.thisArg, value, this.count++);
9737         }
9738         catch (err) {
9739             this.destination.error(err);
9740             return;
9741         }
9742         this.destination.next(result);
9743     };
9744     return MapSubscriber;
9745 }(Subscriber_1.Subscriber));
9746
9747 },{"../Subscriber":35}],119:[function(require,module,exports){
9748 "use strict";
9749 var ArrayObservable_1 = require('../observable/ArrayObservable');
9750 var mergeAll_1 = require('./mergeAll');
9751 var isScheduler_1 = require('../util/isScheduler');
9752 /* tslint:disable:max-line-length */
9753 /**
9754  * Creates an output Observable which concurrently emits all values from every
9755  * given input Observable.
9756  *
9757  * <span class="informal">Flattens multiple Observables together by blending
9758  * their values into one Observable.</span>
9759  *
9760  * <img src="./img/merge.png" width="100%">
9761  *
9762  * `merge` subscribes to each given input Observable (either the source or an
9763  * Observable given as argument), and simply forwards (without doing any
9764  * transformation) all the values from all the input Observables to the output
9765  * Observable. The output Observable only completes once all input Observables
9766  * have completed. Any error delivered by an input Observable will be immediately
9767  * emitted on the output Observable.
9768  *
9769  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
9770  * var clicks = Rx.Observable.fromEvent(document, 'click');
9771  * var timer = Rx.Observable.interval(1000);
9772  * var clicksOrTimer = clicks.merge(timer);
9773  * clicksOrTimer.subscribe(x => console.log(x));
9774  *
9775  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
9776  * var timer1 = Rx.Observable.interval(1000).take(10);
9777  * var timer2 = Rx.Observable.interval(2000).take(6);
9778  * var timer3 = Rx.Observable.interval(500).take(10);
9779  * var concurrent = 2; // the argument
9780  * var merged = timer1.merge(timer2, timer3, concurrent);
9781  * merged.subscribe(x => console.log(x));
9782  *
9783  * @see {@link mergeAll}
9784  * @see {@link mergeMap}
9785  * @see {@link mergeMapTo}
9786  * @see {@link mergeScan}
9787  *
9788  * @param {Observable} other An input Observable to merge with the source
9789  * Observable. More than one input Observables may be given as argument.
9790  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9791  * Observables being subscribed to concurrently.
9792  * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
9793  * concurrency of input Observables.
9794  * @return {Observable} an Observable that emits items that are the result of
9795  * every input Observable.
9796  * @method merge
9797  * @owner Observable
9798  */
9799 function merge() {
9800     var observables = [];
9801     for (var _i = 0; _i < arguments.length; _i++) {
9802         observables[_i - 0] = arguments[_i];
9803     }
9804     return this.lift.call(mergeStatic.apply(void 0, [this].concat(observables)));
9805 }
9806 exports.merge = merge;
9807 /* tslint:enable:max-line-length */
9808 /**
9809  * Creates an output Observable which concurrently emits all values from every
9810  * given input Observable.
9811  *
9812  * <span class="informal">Flattens multiple Observables together by blending
9813  * their values into one Observable.</span>
9814  *
9815  * <img src="./img/merge.png" width="100%">
9816  *
9817  * `merge` subscribes to each given input Observable (as arguments), and simply
9818  * forwards (without doing any transformation) all the values from all the input
9819  * Observables to the output Observable. The output Observable only completes
9820  * once all input Observables have completed. Any error delivered by an input
9821  * Observable will be immediately emitted on the output Observable.
9822  *
9823  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
9824  * var clicks = Rx.Observable.fromEvent(document, 'click');
9825  * var timer = Rx.Observable.interval(1000);
9826  * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
9827  * clicksOrTimer.subscribe(x => console.log(x));
9828  *
9829  * // Results in the following:
9830  * // timer will emit ascending values, one every second(1000ms) to console
9831  * // clicks logs MouseEvents to console everytime the "document" is clicked
9832  * // Since the two streams are merged you see these happening
9833  * // as they occur.
9834  *
9835  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
9836  * var timer1 = Rx.Observable.interval(1000).take(10);
9837  * var timer2 = Rx.Observable.interval(2000).take(6);
9838  * var timer3 = Rx.Observable.interval(500).take(10);
9839  * var concurrent = 2; // the argument
9840  * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
9841  * merged.subscribe(x => console.log(x));
9842  *
9843  * // Results in the following:
9844  * // - First timer1 and timer2 will run concurrently
9845  * // - timer1 will emit a value every 1000ms for 10 iterations
9846  * // - timer2 will emit a value every 2000ms for 6 iterations
9847  * // - after timer1 hits it's max iteration, timer2 will
9848  * //   continue, and timer3 will start to run concurrently with timer2
9849  * // - when timer2 hits it's max iteration it terminates, and
9850  * //   timer3 will continue to emit a value every 500ms until it is complete
9851  *
9852  * @see {@link mergeAll}
9853  * @see {@link mergeMap}
9854  * @see {@link mergeMapTo}
9855  * @see {@link mergeScan}
9856  *
9857  * @param {...Observable} observables Input Observables to merge together.
9858  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9859  * Observables being subscribed to concurrently.
9860  * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
9861  * concurrency of input Observables.
9862  * @return {Observable} an Observable that emits items that are the result of
9863  * every input Observable.
9864  * @static true
9865  * @name merge
9866  * @owner Observable
9867  */
9868 function mergeStatic() {
9869     var observables = [];
9870     for (var _i = 0; _i < arguments.length; _i++) {
9871         observables[_i - 0] = arguments[_i];
9872     }
9873     var concurrent = Number.POSITIVE_INFINITY;
9874     var scheduler = null;
9875     var last = observables[observables.length - 1];
9876     if (isScheduler_1.isScheduler(last)) {
9877         scheduler = observables.pop();
9878         if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
9879             concurrent = observables.pop();
9880         }
9881     }
9882     else if (typeof last === 'number') {
9883         concurrent = observables.pop();
9884     }
9885     if (scheduler === null && observables.length === 1) {
9886         return observables[0];
9887     }
9888     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent));
9889 }
9890 exports.mergeStatic = mergeStatic;
9891
9892 },{"../observable/ArrayObservable":83,"../util/isScheduler":162,"./mergeAll":120}],120:[function(require,module,exports){
9893 "use strict";
9894 var __extends = (this && this.__extends) || function (d, b) {
9895     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9896     function __() { this.constructor = d; }
9897     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9898 };
9899 var OuterSubscriber_1 = require('../OuterSubscriber');
9900 var subscribeToResult_1 = require('../util/subscribeToResult');
9901 /**
9902  * Converts a higher-order Observable into a first-order Observable which
9903  * concurrently delivers all values that are emitted on the inner Observables.
9904  *
9905  * <span class="informal">Flattens an Observable-of-Observables.</span>
9906  *
9907  * <img src="./img/mergeAll.png" width="100%">
9908  *
9909  * `mergeAll` subscribes to an Observable that emits Observables, also known as
9910  * a higher-order Observable. Each time it observes one of these emitted inner
9911  * Observables, it subscribes to that and delivers all the values from the
9912  * inner Observable on the output Observable. The output Observable only
9913  * completes once all inner Observables have completed. Any error delivered by
9914  * a inner Observable will be immediately emitted on the output Observable.
9915  *
9916  * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
9917  * var clicks = Rx.Observable.fromEvent(document, 'click');
9918  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
9919  * var firstOrder = higherOrder.mergeAll();
9920  * firstOrder.subscribe(x => console.log(x));
9921  *
9922  * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
9923  * var clicks = Rx.Observable.fromEvent(document, 'click');
9924  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
9925  * var firstOrder = higherOrder.mergeAll(2);
9926  * firstOrder.subscribe(x => console.log(x));
9927  *
9928  * @see {@link combineAll}
9929  * @see {@link concatAll}
9930  * @see {@link exhaust}
9931  * @see {@link merge}
9932  * @see {@link mergeMap}
9933  * @see {@link mergeMapTo}
9934  * @see {@link mergeScan}
9935  * @see {@link switch}
9936  * @see {@link zipAll}
9937  *
9938  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
9939  * Observables being subscribed to concurrently.
9940  * @return {Observable} An Observable that emits values coming from all the
9941  * inner Observables emitted by the source Observable.
9942  * @method mergeAll
9943  * @owner Observable
9944  */
9945 function mergeAll(concurrent) {
9946     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9947     return this.lift(new MergeAllOperator(concurrent));
9948 }
9949 exports.mergeAll = mergeAll;
9950 var MergeAllOperator = (function () {
9951     function MergeAllOperator(concurrent) {
9952         this.concurrent = concurrent;
9953     }
9954     MergeAllOperator.prototype.call = function (observer, source) {
9955         return source.subscribe(new MergeAllSubscriber(observer, this.concurrent));
9956     };
9957     return MergeAllOperator;
9958 }());
9959 exports.MergeAllOperator = MergeAllOperator;
9960 /**
9961  * We need this JSDoc comment for affecting ESDoc.
9962  * @ignore
9963  * @extends {Ignored}
9964  */
9965 var MergeAllSubscriber = (function (_super) {
9966     __extends(MergeAllSubscriber, _super);
9967     function MergeAllSubscriber(destination, concurrent) {
9968         _super.call(this, destination);
9969         this.concurrent = concurrent;
9970         this.hasCompleted = false;
9971         this.buffer = [];
9972         this.active = 0;
9973     }
9974     MergeAllSubscriber.prototype._next = function (observable) {
9975         if (this.active < this.concurrent) {
9976             this.active++;
9977             this.add(subscribeToResult_1.subscribeToResult(this, observable));
9978         }
9979         else {
9980             this.buffer.push(observable);
9981         }
9982     };
9983     MergeAllSubscriber.prototype._complete = function () {
9984         this.hasCompleted = true;
9985         if (this.active === 0 && this.buffer.length === 0) {
9986             this.destination.complete();
9987         }
9988     };
9989     MergeAllSubscriber.prototype.notifyComplete = function (innerSub) {
9990         var buffer = this.buffer;
9991         this.remove(innerSub);
9992         this.active--;
9993         if (buffer.length > 0) {
9994             this._next(buffer.shift());
9995         }
9996         else if (this.active === 0 && this.hasCompleted) {
9997             this.destination.complete();
9998         }
9999     };
10000     return MergeAllSubscriber;
10001 }(OuterSubscriber_1.OuterSubscriber));
10002 exports.MergeAllSubscriber = MergeAllSubscriber;
10003
10004 },{"../OuterSubscriber":30,"../util/subscribeToResult":164}],121:[function(require,module,exports){
10005 "use strict";
10006 var __extends = (this && this.__extends) || function (d, b) {
10007     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10008     function __() { this.constructor = d; }
10009     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10010 };
10011 var subscribeToResult_1 = require('../util/subscribeToResult');
10012 var OuterSubscriber_1 = require('../OuterSubscriber');
10013 /* tslint:disable:max-line-length */
10014 /**
10015  * Projects each source value to an Observable which is merged in the output
10016  * Observable.
10017  *
10018  * <span class="informal">Maps each value to an Observable, then flattens all of
10019  * these inner Observables using {@link mergeAll}.</span>
10020  *
10021  * <img src="./img/mergeMap.png" width="100%">
10022  *
10023  * Returns an Observable that emits items based on applying a function that you
10024  * supply to each item emitted by the source Observable, where that function
10025  * returns an Observable, and then merging those resulting Observables and
10026  * emitting the results of this merger.
10027  *
10028  * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
10029  * var letters = Rx.Observable.of('a', 'b', 'c');
10030  * var result = letters.mergeMap(x =>
10031  *   Rx.Observable.interval(1000).map(i => x+i)
10032  * );
10033  * result.subscribe(x => console.log(x));
10034  *
10035  * // Results in the following:
10036  * // a0
10037  * // b0
10038  * // c0
10039  * // a1
10040  * // b1
10041  * // c1
10042  * // continues to list a,b,c with respective ascending integers
10043  *
10044  * @see {@link concatMap}
10045  * @see {@link exhaustMap}
10046  * @see {@link merge}
10047  * @see {@link mergeAll}
10048  * @see {@link mergeMapTo}
10049  * @see {@link mergeScan}
10050  * @see {@link switchMap}
10051  *
10052  * @param {function(value: T, ?index: number): Observable} project A function
10053  * that, when applied to an item emitted by the source Observable, returns an
10054  * Observable.
10055  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10056  * A function to produce the value on the output Observable based on the values
10057  * and the indices of the source (outer) emission and the inner Observable
10058  * emission. The arguments passed to this function are:
10059  * - `outerValue`: the value that came from the source
10060  * - `innerValue`: the value that came from the projected Observable
10061  * - `outerIndex`: the "index" of the value that came from the source
10062  * - `innerIndex`: the "index" of the value from the projected Observable
10063  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10064  * Observables being subscribed to concurrently.
10065  * @return {Observable} An Observable that emits the result of applying the
10066  * projection function (and the optional `resultSelector`) to each item emitted
10067  * by the source Observable and merging the results of the Observables obtained
10068  * from this transformation.
10069  * @method mergeMap
10070  * @owner Observable
10071  */
10072 function mergeMap(project, resultSelector, concurrent) {
10073     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10074     if (typeof resultSelector === 'number') {
10075         concurrent = resultSelector;
10076         resultSelector = null;
10077     }
10078     return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
10079 }
10080 exports.mergeMap = mergeMap;
10081 var MergeMapOperator = (function () {
10082     function MergeMapOperator(project, resultSelector, concurrent) {
10083         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10084         this.project = project;
10085         this.resultSelector = resultSelector;
10086         this.concurrent = concurrent;
10087     }
10088     MergeMapOperator.prototype.call = function (observer, source) {
10089         return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
10090     };
10091     return MergeMapOperator;
10092 }());
10093 exports.MergeMapOperator = MergeMapOperator;
10094 /**
10095  * We need this JSDoc comment for affecting ESDoc.
10096  * @ignore
10097  * @extends {Ignored}
10098  */
10099 var MergeMapSubscriber = (function (_super) {
10100     __extends(MergeMapSubscriber, _super);
10101     function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
10102         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10103         _super.call(this, destination);
10104         this.project = project;
10105         this.resultSelector = resultSelector;
10106         this.concurrent = concurrent;
10107         this.hasCompleted = false;
10108         this.buffer = [];
10109         this.active = 0;
10110         this.index = 0;
10111     }
10112     MergeMapSubscriber.prototype._next = function (value) {
10113         if (this.active < this.concurrent) {
10114             this._tryNext(value);
10115         }
10116         else {
10117             this.buffer.push(value);
10118         }
10119     };
10120     MergeMapSubscriber.prototype._tryNext = function (value) {
10121         var result;
10122         var index = this.index++;
10123         try {
10124             result = this.project(value, index);
10125         }
10126         catch (err) {
10127             this.destination.error(err);
10128             return;
10129         }
10130         this.active++;
10131         this._innerSub(result, value, index);
10132     };
10133     MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
10134         this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
10135     };
10136     MergeMapSubscriber.prototype._complete = function () {
10137         this.hasCompleted = true;
10138         if (this.active === 0 && this.buffer.length === 0) {
10139             this.destination.complete();
10140         }
10141     };
10142     MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10143         if (this.resultSelector) {
10144             this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
10145         }
10146         else {
10147             this.destination.next(innerValue);
10148         }
10149     };
10150     MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
10151         var result;
10152         try {
10153             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
10154         }
10155         catch (err) {
10156             this.destination.error(err);
10157             return;
10158         }
10159         this.destination.next(result);
10160     };
10161     MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
10162         var buffer = this.buffer;
10163         this.remove(innerSub);
10164         this.active--;
10165         if (buffer.length > 0) {
10166             this._next(buffer.shift());
10167         }
10168         else if (this.active === 0 && this.hasCompleted) {
10169             this.destination.complete();
10170         }
10171     };
10172     return MergeMapSubscriber;
10173 }(OuterSubscriber_1.OuterSubscriber));
10174 exports.MergeMapSubscriber = MergeMapSubscriber;
10175
10176 },{"../OuterSubscriber":30,"../util/subscribeToResult":164}],122:[function(require,module,exports){
10177 "use strict";
10178 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
10179 /* tslint:disable:max-line-length */
10180 /**
10181  * Returns an Observable that emits the results of invoking a specified selector on items
10182  * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
10183  *
10184  * <img src="./img/multicast.png" width="100%">
10185  *
10186  * @param {Function|Subject} Factory function to create an intermediate subject through
10187  * which the source sequence's elements will be multicast to the selector function
10188  * or Subject to push source elements into.
10189  * @param {Function} Optional selector function that can use the multicasted source stream
10190  * as many times as needed, without causing multiple subscriptions to the source stream.
10191  * Subscribers to the given source will receive all notifications of the source from the
10192  * time of the subscription forward.
10193  * @return {Observable} an Observable that emits the results of invoking the selector
10194  * on the items emitted by a `ConnectableObservable` that shares a single subscription to
10195  * the underlying stream.
10196  * @method multicast
10197  * @owner Observable
10198  */
10199 function multicast(subjectOrSubjectFactory, selector) {
10200     var subjectFactory;
10201     if (typeof subjectOrSubjectFactory === 'function') {
10202         subjectFactory = subjectOrSubjectFactory;
10203     }
10204     else {
10205         subjectFactory = function subjectFactory() {
10206             return subjectOrSubjectFactory;
10207         };
10208     }
10209     if (typeof selector === 'function') {
10210         return this.lift(new MulticastOperator(subjectFactory, selector));
10211     }
10212     var connectable = Object.create(this, ConnectableObservable_1.connectableObservableDescriptor);
10213     connectable.source = this;
10214     connectable.subjectFactory = subjectFactory;
10215     return connectable;
10216 }
10217 exports.multicast = multicast;
10218 var MulticastOperator = (function () {
10219     function MulticastOperator(subjectFactory, selector) {
10220         this.subjectFactory = subjectFactory;
10221         this.selector = selector;
10222     }
10223     MulticastOperator.prototype.call = function (subscriber, source) {
10224         var selector = this.selector;
10225         var subject = this.subjectFactory();
10226         var subscription = selector(subject).subscribe(subscriber);
10227         subscription.add(source.subscribe(subject));
10228         return subscription;
10229     };
10230     return MulticastOperator;
10231 }());
10232 exports.MulticastOperator = MulticastOperator;
10233
10234 },{"../observable/ConnectableObservable":84}],123:[function(require,module,exports){
10235 "use strict";
10236 var __extends = (this && this.__extends) || function (d, b) {
10237     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10238     function __() { this.constructor = d; }
10239     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10240 };
10241 var Subscriber_1 = require('../Subscriber');
10242 var Notification_1 = require('../Notification');
10243 /**
10244  * @see {@link Notification}
10245  *
10246  * @param scheduler
10247  * @param delay
10248  * @return {Observable<R>|WebSocketSubject<T>|Observable<T>}
10249  * @method observeOn
10250  * @owner Observable
10251  */
10252 function observeOn(scheduler, delay) {
10253     if (delay === void 0) { delay = 0; }
10254     return this.lift(new ObserveOnOperator(scheduler, delay));
10255 }
10256 exports.observeOn = observeOn;
10257 var ObserveOnOperator = (function () {
10258     function ObserveOnOperator(scheduler, delay) {
10259         if (delay === void 0) { delay = 0; }
10260         this.scheduler = scheduler;
10261         this.delay = delay;
10262     }
10263     ObserveOnOperator.prototype.call = function (subscriber, source) {
10264         return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
10265     };
10266     return ObserveOnOperator;
10267 }());
10268 exports.ObserveOnOperator = ObserveOnOperator;
10269 /**
10270  * We need this JSDoc comment for affecting ESDoc.
10271  * @ignore
10272  * @extends {Ignored}
10273  */
10274 var ObserveOnSubscriber = (function (_super) {
10275     __extends(ObserveOnSubscriber, _super);
10276     function ObserveOnSubscriber(destination, scheduler, delay) {
10277         if (delay === void 0) { delay = 0; }
10278         _super.call(this, destination);
10279         this.scheduler = scheduler;
10280         this.delay = delay;
10281     }
10282     ObserveOnSubscriber.dispatch = function (arg) {
10283         var notification = arg.notification, destination = arg.destination, subscription = arg.subscription;
10284         notification.observe(destination);
10285         if (subscription) {
10286             subscription.unsubscribe();
10287         }
10288     };
10289     ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
10290         var message = new ObserveOnMessage(notification, this.destination);
10291         message.subscription = this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, message));
10292     };
10293     ObserveOnSubscriber.prototype._next = function (value) {
10294         this.scheduleMessage(Notification_1.Notification.createNext(value));
10295     };
10296     ObserveOnSubscriber.prototype._error = function (err) {
10297         this.scheduleMessage(Notification_1.Notification.createError(err));
10298     };
10299     ObserveOnSubscriber.prototype._complete = function () {
10300         this.scheduleMessage(Notification_1.Notification.createComplete());
10301     };
10302     return ObserveOnSubscriber;
10303 }(Subscriber_1.Subscriber));
10304 exports.ObserveOnSubscriber = ObserveOnSubscriber;
10305 var ObserveOnMessage = (function () {
10306     function ObserveOnMessage(notification, destination) {
10307         this.notification = notification;
10308         this.destination = destination;
10309     }
10310     return ObserveOnMessage;
10311 }());
10312 exports.ObserveOnMessage = ObserveOnMessage;
10313
10314 },{"../Notification":27,"../Subscriber":35}],124:[function(require,module,exports){
10315 "use strict";
10316 var __extends = (this && this.__extends) || function (d, b) {
10317     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10318     function __() { this.constructor = d; }
10319     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10320 };
10321 var Subscriber_1 = require('../Subscriber');
10322 /**
10323  * Groups pairs of consecutive emissions together and emits them as an array of
10324  * two values.
10325  *
10326  * <span class="informal">Puts the current value and previous value together as
10327  * an array, and emits that.</span>
10328  *
10329  * <img src="./img/pairwise.png" width="100%">
10330  *
10331  * The Nth emission from the source Observable will cause the output Observable
10332  * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
10333  * pair. For this reason, `pairwise` emits on the second and subsequent
10334  * emissions from the source Observable, but not on the first emission, because
10335  * there is no previous value in that case.
10336  *
10337  * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
10338  * var clicks = Rx.Observable.fromEvent(document, 'click');
10339  * var pairs = clicks.pairwise();
10340  * var distance = pairs.map(pair => {
10341  *   var x0 = pair[0].clientX;
10342  *   var y0 = pair[0].clientY;
10343  *   var x1 = pair[1].clientX;
10344  *   var y1 = pair[1].clientY;
10345  *   return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
10346  * });
10347  * distance.subscribe(x => console.log(x));
10348  *
10349  * @see {@link buffer}
10350  * @see {@link bufferCount}
10351  *
10352  * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
10353  * consecutive values from the source Observable.
10354  * @method pairwise
10355  * @owner Observable
10356  */
10357 function pairwise() {
10358     return this.lift(new PairwiseOperator());
10359 }
10360 exports.pairwise = pairwise;
10361 var PairwiseOperator = (function () {
10362     function PairwiseOperator() {
10363     }
10364     PairwiseOperator.prototype.call = function (subscriber, source) {
10365         return source.subscribe(new PairwiseSubscriber(subscriber));
10366     };
10367     return PairwiseOperator;
10368 }());
10369 /**
10370  * We need this JSDoc comment for affecting ESDoc.
10371  * @ignore
10372  * @extends {Ignored}
10373  */
10374 var PairwiseSubscriber = (function (_super) {
10375     __extends(PairwiseSubscriber, _super);
10376     function PairwiseSubscriber(destination) {
10377         _super.call(this, destination);
10378         this.hasPrev = false;
10379     }
10380     PairwiseSubscriber.prototype._next = function (value) {
10381         if (this.hasPrev) {
10382             this.destination.next([this.prev, value]);
10383         }
10384         else {
10385             this.hasPrev = true;
10386         }
10387         this.prev = value;
10388     };
10389     return PairwiseSubscriber;
10390 }(Subscriber_1.Subscriber));
10391
10392 },{"../Subscriber":35}],125:[function(require,module,exports){
10393 "use strict";
10394 var map_1 = require('./map');
10395 /**
10396  * Maps each source value (an object) to its specified nested property.
10397  *
10398  * <span class="informal">Like {@link map}, but meant only for picking one of
10399  * the nested properties of every emitted object.</span>
10400  *
10401  * <img src="./img/pluck.png" width="100%">
10402  *
10403  * Given a list of strings describing a path to an object property, retrieves
10404  * the value of a specified nested property from all values in the source
10405  * Observable. If a property can't be resolved, it will return `undefined` for
10406  * that value.
10407  *
10408  * @example <caption>Map every every click to the tagName of the clicked target element</caption>
10409  * var clicks = Rx.Observable.fromEvent(document, 'click');
10410  * var tagNames = clicks.pluck('target', 'tagName');
10411  * tagNames.subscribe(x => console.log(x));
10412  *
10413  * @see {@link map}
10414  *
10415  * @param {...string} properties The nested properties to pluck from each source
10416  * value (an object).
10417  * @return {Observable} Returns a new Observable of property values from the
10418  * source values.
10419  * @method pluck
10420  * @owner Observable
10421  */
10422 function pluck() {
10423     var properties = [];
10424     for (var _i = 0; _i < arguments.length; _i++) {
10425         properties[_i - 0] = arguments[_i];
10426     }
10427     var length = properties.length;
10428     if (length === 0) {
10429         throw new Error('list of properties cannot be empty.');
10430     }
10431     return map_1.map.call(this, plucker(properties, length));
10432 }
10433 exports.pluck = pluck;
10434 function plucker(props, length) {
10435     var mapper = function (x) {
10436         var currentProp = x;
10437         for (var i = 0; i < length; i++) {
10438             var p = currentProp[props[i]];
10439             if (typeof p !== 'undefined') {
10440                 currentProp = p;
10441             }
10442             else {
10443                 return undefined;
10444             }
10445         }
10446         return currentProp;
10447     };
10448     return mapper;
10449 }
10450
10451 },{"./map":118}],126:[function(require,module,exports){
10452 "use strict";
10453 var Subject_1 = require('../Subject');
10454 var multicast_1 = require('./multicast');
10455 /* tslint:disable:max-line-length */
10456 /**
10457  * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
10458  * before it begins emitting items to those Observers that have subscribed to it.
10459  *
10460  * <img src="./img/publish.png" width="100%">
10461  *
10462  * @param {Function} Optional selector function which can use the multicasted source sequence as many times as needed,
10463  * without causing multiple subscriptions to the source sequence.
10464  * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
10465  * @return a ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
10466  * @method publish
10467  * @owner Observable
10468  */
10469 function publish(selector) {
10470     return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
10471         multicast_1.multicast.call(this, new Subject_1.Subject());
10472 }
10473 exports.publish = publish;
10474
10475 },{"../Subject":33,"./multicast":122}],127:[function(require,module,exports){
10476 "use strict";
10477 var ReplaySubject_1 = require('../ReplaySubject');
10478 var multicast_1 = require('./multicast');
10479 /**
10480  * @param bufferSize
10481  * @param windowTime
10482  * @param scheduler
10483  * @return {ConnectableObservable<T>}
10484  * @method publishReplay
10485  * @owner Observable
10486  */
10487 function publishReplay(bufferSize, windowTime, scheduler) {
10488     if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
10489     if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
10490     return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler));
10491 }
10492 exports.publishReplay = publishReplay;
10493
10494 },{"../ReplaySubject":31,"./multicast":122}],128:[function(require,module,exports){
10495 "use strict";
10496 var __extends = (this && this.__extends) || function (d, b) {
10497     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10498     function __() { this.constructor = d; }
10499     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10500 };
10501 var Subscriber_1 = require('../Subscriber');
10502 /* tslint:disable:max-line-length */
10503 /**
10504  * Applies an accumulator function over the source Observable, and returns each
10505  * intermediate result, with an optional seed value.
10506  *
10507  * <span class="informal">It's like {@link reduce}, but emits the current
10508  * accumulation whenever the source emits a value.</span>
10509  *
10510  * <img src="./img/scan.png" width="100%">
10511  *
10512  * Combines together all values emitted on the source, using an accumulator
10513  * function that knows how to join a new source value into the accumulation from
10514  * the past. Is similar to {@link reduce}, but emits the intermediate
10515  * accumulations.
10516  *
10517  * Returns an Observable that applies a specified `accumulator` function to each
10518  * item emitted by the source Observable. If a `seed` value is specified, then
10519  * that value will be used as the initial value for the accumulator. If no seed
10520  * value is specified, the first item of the source is used as the seed.
10521  *
10522  * @example <caption>Count the number of click events</caption>
10523  * var clicks = Rx.Observable.fromEvent(document, 'click');
10524  * var ones = clicks.mapTo(1);
10525  * var seed = 0;
10526  * var count = ones.scan((acc, one) => acc + one, seed);
10527  * count.subscribe(x => console.log(x));
10528  *
10529  * @see {@link expand}
10530  * @see {@link mergeScan}
10531  * @see {@link reduce}
10532  *
10533  * @param {function(acc: R, value: T, index: number): R} accumulator
10534  * The accumulator function called on each source value.
10535  * @param {T|R} [seed] The initial accumulation value.
10536  * @return {Observable<R>} An observable of the accumulated values.
10537  * @method scan
10538  * @owner Observable
10539  */
10540 function scan(accumulator, seed) {
10541     var hasSeed = false;
10542     // providing a seed of `undefined` *should* be valid and trigger
10543     // hasSeed! so don't use `seed !== undefined` checks!
10544     // For this reason, we have to check it here at the original call site
10545     // otherwise inside Operator/Subscriber we won't know if `undefined`
10546     // means they didn't provide anything or if they literally provided `undefined`
10547     if (arguments.length >= 2) {
10548         hasSeed = true;
10549     }
10550     return this.lift(new ScanOperator(accumulator, seed, hasSeed));
10551 }
10552 exports.scan = scan;
10553 var ScanOperator = (function () {
10554     function ScanOperator(accumulator, seed, hasSeed) {
10555         if (hasSeed === void 0) { hasSeed = false; }
10556         this.accumulator = accumulator;
10557         this.seed = seed;
10558         this.hasSeed = hasSeed;
10559     }
10560     ScanOperator.prototype.call = function (subscriber, source) {
10561         return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
10562     };
10563     return ScanOperator;
10564 }());
10565 /**
10566  * We need this JSDoc comment for affecting ESDoc.
10567  * @ignore
10568  * @extends {Ignored}
10569  */
10570 var ScanSubscriber = (function (_super) {
10571     __extends(ScanSubscriber, _super);
10572     function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
10573         _super.call(this, destination);
10574         this.accumulator = accumulator;
10575         this._seed = _seed;
10576         this.hasSeed = hasSeed;
10577         this.index = 0;
10578     }
10579     Object.defineProperty(ScanSubscriber.prototype, "seed", {
10580         get: function () {
10581             return this._seed;
10582         },
10583         set: function (value) {
10584             this.hasSeed = true;
10585             this._seed = value;
10586         },
10587         enumerable: true,
10588         configurable: true
10589     });
10590     ScanSubscriber.prototype._next = function (value) {
10591         if (!this.hasSeed) {
10592             this.seed = value;
10593             this.destination.next(value);
10594         }
10595         else {
10596             return this._tryNext(value);
10597         }
10598     };
10599     ScanSubscriber.prototype._tryNext = function (value) {
10600         var index = this.index++;
10601         var result;
10602         try {
10603             result = this.accumulator(this.seed, value, index);
10604         }
10605         catch (err) {
10606             this.destination.error(err);
10607         }
10608         this.seed = result;
10609         this.destination.next(result);
10610     };
10611     return ScanSubscriber;
10612 }(Subscriber_1.Subscriber));
10613
10614 },{"../Subscriber":35}],129:[function(require,module,exports){
10615 "use strict";
10616 var multicast_1 = require('./multicast');
10617 var Subject_1 = require('../Subject');
10618 function shareSubjectFactory() {
10619     return new Subject_1.Subject();
10620 }
10621 /**
10622  * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
10623  * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
10624  * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
10625  * This is an alias for .publish().refCount().
10626  *
10627  * <img src="./img/share.png" width="100%">
10628  *
10629  * @return {Observable<T>} an Observable that upon connection causes the source Observable to emit items to its Observers
10630  * @method share
10631  * @owner Observable
10632  */
10633 function share() {
10634     return multicast_1.multicast.call(this, shareSubjectFactory).refCount();
10635 }
10636 exports.share = share;
10637 ;
10638
10639 },{"../Subject":33,"./multicast":122}],130:[function(require,module,exports){
10640 "use strict";
10641 var __extends = (this && this.__extends) || function (d, b) {
10642     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10643     function __() { this.constructor = d; }
10644     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10645 };
10646 var Subscriber_1 = require('../Subscriber');
10647 /**
10648  * Returns an Observable that skips `n` items emitted by an Observable.
10649  *
10650  * <img src="./img/skip.png" width="100%">
10651  *
10652  * @param {Number} the `n` of times, items emitted by source Observable should be skipped.
10653  * @return {Observable} an Observable that skips values emitted by the source Observable.
10654  *
10655  * @method skip
10656  * @owner Observable
10657  */
10658 function skip(total) {
10659     return this.lift(new SkipOperator(total));
10660 }
10661 exports.skip = skip;
10662 var SkipOperator = (function () {
10663     function SkipOperator(total) {
10664         this.total = total;
10665     }
10666     SkipOperator.prototype.call = function (subscriber, source) {
10667         return source.subscribe(new SkipSubscriber(subscriber, this.total));
10668     };
10669     return SkipOperator;
10670 }());
10671 /**
10672  * We need this JSDoc comment for affecting ESDoc.
10673  * @ignore
10674  * @extends {Ignored}
10675  */
10676 var SkipSubscriber = (function (_super) {
10677     __extends(SkipSubscriber, _super);
10678     function SkipSubscriber(destination, total) {
10679         _super.call(this, destination);
10680         this.total = total;
10681         this.count = 0;
10682     }
10683     SkipSubscriber.prototype._next = function (x) {
10684         if (++this.count > this.total) {
10685             this.destination.next(x);
10686         }
10687     };
10688     return SkipSubscriber;
10689 }(Subscriber_1.Subscriber));
10690
10691 },{"../Subscriber":35}],131:[function(require,module,exports){
10692 "use strict";
10693 var __extends = (this && this.__extends) || function (d, b) {
10694     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10695     function __() { this.constructor = d; }
10696     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10697 };
10698 var OuterSubscriber_1 = require('../OuterSubscriber');
10699 var subscribeToResult_1 = require('../util/subscribeToResult');
10700 /**
10701  * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
10702  *
10703  * <img src="./img/skipUntil.png" width="100%">
10704  *
10705  * @param {Observable} the second Observable that has to emit an item before the source Observable's elements begin to
10706  * be mirrored by the resulting Observable.
10707  * @return {Observable<T>} an Observable that skips items from the source Observable until the second Observable emits
10708  * an item, then emits the remaining items.
10709  * @method skipUntil
10710  * @owner Observable
10711  */
10712 function skipUntil(notifier) {
10713     return this.lift(new SkipUntilOperator(notifier));
10714 }
10715 exports.skipUntil = skipUntil;
10716 var SkipUntilOperator = (function () {
10717     function SkipUntilOperator(notifier) {
10718         this.notifier = notifier;
10719     }
10720     SkipUntilOperator.prototype.call = function (subscriber, source) {
10721         return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
10722     };
10723     return SkipUntilOperator;
10724 }());
10725 /**
10726  * We need this JSDoc comment for affecting ESDoc.
10727  * @ignore
10728  * @extends {Ignored}
10729  */
10730 var SkipUntilSubscriber = (function (_super) {
10731     __extends(SkipUntilSubscriber, _super);
10732     function SkipUntilSubscriber(destination, notifier) {
10733         _super.call(this, destination);
10734         this.hasValue = false;
10735         this.isInnerStopped = false;
10736         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
10737     }
10738     SkipUntilSubscriber.prototype._next = function (value) {
10739         if (this.hasValue) {
10740             _super.prototype._next.call(this, value);
10741         }
10742     };
10743     SkipUntilSubscriber.prototype._complete = function () {
10744         if (this.isInnerStopped) {
10745             _super.prototype._complete.call(this);
10746         }
10747         else {
10748             this.unsubscribe();
10749         }
10750     };
10751     SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10752         this.hasValue = true;
10753     };
10754     SkipUntilSubscriber.prototype.notifyComplete = function () {
10755         this.isInnerStopped = true;
10756         if (this.isStopped) {
10757             _super.prototype._complete.call(this);
10758         }
10759     };
10760     return SkipUntilSubscriber;
10761 }(OuterSubscriber_1.OuterSubscriber));
10762
10763 },{"../OuterSubscriber":30,"../util/subscribeToResult":164}],132:[function(require,module,exports){
10764 "use strict";
10765 var __extends = (this && this.__extends) || function (d, b) {
10766     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10767     function __() { this.constructor = d; }
10768     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10769 };
10770 var Subscriber_1 = require('../Subscriber');
10771 /**
10772  * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
10773  * true, but emits all further source items as soon as the condition becomes false.
10774  *
10775  * <img src="./img/skipWhile.png" width="100%">
10776  *
10777  * @param {Function} predicate - a function to test each item emitted from the source Observable.
10778  * @return {Observable<T>} an Observable that begins emitting items emitted by the source Observable when the
10779  * specified predicate becomes false.
10780  * @method skipWhile
10781  * @owner Observable
10782  */
10783 function skipWhile(predicate) {
10784     return this.lift(new SkipWhileOperator(predicate));
10785 }
10786 exports.skipWhile = skipWhile;
10787 var SkipWhileOperator = (function () {
10788     function SkipWhileOperator(predicate) {
10789         this.predicate = predicate;
10790     }
10791     SkipWhileOperator.prototype.call = function (subscriber, source) {
10792         return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
10793     };
10794     return SkipWhileOperator;
10795 }());
10796 /**
10797  * We need this JSDoc comment for affecting ESDoc.
10798  * @ignore
10799  * @extends {Ignored}
10800  */
10801 var SkipWhileSubscriber = (function (_super) {
10802     __extends(SkipWhileSubscriber, _super);
10803     function SkipWhileSubscriber(destination, predicate) {
10804         _super.call(this, destination);
10805         this.predicate = predicate;
10806         this.skipping = true;
10807         this.index = 0;
10808     }
10809     SkipWhileSubscriber.prototype._next = function (value) {
10810         var destination = this.destination;
10811         if (this.skipping) {
10812             this.tryCallPredicate(value);
10813         }
10814         if (!this.skipping) {
10815             destination.next(value);
10816         }
10817     };
10818     SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
10819         try {
10820             var result = this.predicate(value, this.index++);
10821             this.skipping = Boolean(result);
10822         }
10823         catch (err) {
10824             this.destination.error(err);
10825         }
10826     };
10827     return SkipWhileSubscriber;
10828 }(Subscriber_1.Subscriber));
10829
10830 },{"../Subscriber":35}],133:[function(require,module,exports){
10831 "use strict";
10832 var ArrayObservable_1 = require('../observable/ArrayObservable');
10833 var ScalarObservable_1 = require('../observable/ScalarObservable');
10834 var EmptyObservable_1 = require('../observable/EmptyObservable');
10835 var concat_1 = require('./concat');
10836 var isScheduler_1 = require('../util/isScheduler');
10837 /* tslint:disable:max-line-length */
10838 /**
10839  * Returns an Observable that emits the items in a specified Iterable before it begins to emit items emitted by the
10840  * source Observable.
10841  *
10842  * <img src="./img/startWith.png" width="100%">
10843  *
10844  * @param {Values} an Iterable that contains the items you want the modified Observable to emit first.
10845  * @return {Observable} an Observable that emits the items in the specified Iterable and then emits the items
10846  * emitted by the source Observable.
10847  * @method startWith
10848  * @owner Observable
10849  */
10850 function startWith() {
10851     var array = [];
10852     for (var _i = 0; _i < arguments.length; _i++) {
10853         array[_i - 0] = arguments[_i];
10854     }
10855     var scheduler = array[array.length - 1];
10856     if (isScheduler_1.isScheduler(scheduler)) {
10857         array.pop();
10858     }
10859     else {
10860         scheduler = null;
10861     }
10862     var len = array.length;
10863     if (len === 1) {
10864         return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this);
10865     }
10866     else if (len > 1) {
10867         return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this);
10868     }
10869     else {
10870         return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this);
10871     }
10872 }
10873 exports.startWith = startWith;
10874
10875 },{"../observable/ArrayObservable":83,"../observable/EmptyObservable":86,"../observable/ScalarObservable":92,"../util/isScheduler":162,"./concat":107}],134:[function(require,module,exports){
10876 "use strict";
10877 var __extends = (this && this.__extends) || function (d, b) {
10878     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10879     function __() { this.constructor = d; }
10880     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10881 };
10882 var OuterSubscriber_1 = require('../OuterSubscriber');
10883 var subscribeToResult_1 = require('../util/subscribeToResult');
10884 /* tslint:disable:max-line-length */
10885 /**
10886  * Projects each source value to an Observable which is merged in the output
10887  * Observable, emitting values only from the most recently projected Observable.
10888  *
10889  * <span class="informal">Maps each value to an Observable, then flattens all of
10890  * these inner Observables using {@link switch}.</span>
10891  *
10892  * <img src="./img/switchMap.png" width="100%">
10893  *
10894  * Returns an Observable that emits items based on applying a function that you
10895  * supply to each item emitted by the source Observable, where that function
10896  * returns an (so-called "inner") Observable. Each time it observes one of these
10897  * inner Observables, the output Observable begins emitting the items emitted by
10898  * that inner Observable. When a new inner Observable is emitted, `switchMap`
10899  * stops emitting items from the earlier-emitted inner Observable and begins
10900  * emitting items from the new one. It continues to behave like this for
10901  * subsequent inner Observables.
10902  *
10903  * @example <caption>Rerun an interval Observable on every click event</caption>
10904  * var clicks = Rx.Observable.fromEvent(document, 'click');
10905  * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
10906  * result.subscribe(x => console.log(x));
10907  *
10908  * @see {@link concatMap}
10909  * @see {@link exhaustMap}
10910  * @see {@link mergeMap}
10911  * @see {@link switch}
10912  * @see {@link switchMapTo}
10913  *
10914  * @param {function(value: T, ?index: number): Observable} project A function
10915  * that, when applied to an item emitted by the source Observable, returns an
10916  * Observable.
10917  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10918  * A function to produce the value on the output Observable based on the values
10919  * and the indices of the source (outer) emission and the inner Observable
10920  * emission. The arguments passed to this function are:
10921  * - `outerValue`: the value that came from the source
10922  * - `innerValue`: the value that came from the projected Observable
10923  * - `outerIndex`: the "index" of the value that came from the source
10924  * - `innerIndex`: the "index" of the value from the projected Observable
10925  * @return {Observable} An Observable that emits the result of applying the
10926  * projection function (and the optional `resultSelector`) to each item emitted
10927  * by the source Observable and taking only the values from the most recently
10928  * projected inner Observable.
10929  * @method switchMap
10930  * @owner Observable
10931  */
10932 function switchMap(project, resultSelector) {
10933     return this.lift(new SwitchMapOperator(project, resultSelector));
10934 }
10935 exports.switchMap = switchMap;
10936 var SwitchMapOperator = (function () {
10937     function SwitchMapOperator(project, resultSelector) {
10938         this.project = project;
10939         this.resultSelector = resultSelector;
10940     }
10941     SwitchMapOperator.prototype.call = function (subscriber, source) {
10942         return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
10943     };
10944     return SwitchMapOperator;
10945 }());
10946 /**
10947  * We need this JSDoc comment for affecting ESDoc.
10948  * @ignore
10949  * @extends {Ignored}
10950  */
10951 var SwitchMapSubscriber = (function (_super) {
10952     __extends(SwitchMapSubscriber, _super);
10953     function SwitchMapSubscriber(destination, project, resultSelector) {
10954         _super.call(this, destination);
10955         this.project = project;
10956         this.resultSelector = resultSelector;
10957         this.index = 0;
10958     }
10959     SwitchMapSubscriber.prototype._next = function (value) {
10960         var result;
10961         var index = this.index++;
10962         try {
10963             result = this.project(value, index);
10964         }
10965         catch (error) {
10966             this.destination.error(error);
10967             return;
10968         }
10969         this._innerSub(result, value, index);
10970     };
10971     SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
10972         var innerSubscription = this.innerSubscription;
10973         if (innerSubscription) {
10974             innerSubscription.unsubscribe();
10975         }
10976         this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
10977     };
10978     SwitchMapSubscriber.prototype._complete = function () {
10979         var innerSubscription = this.innerSubscription;
10980         if (!innerSubscription || innerSubscription.closed) {
10981             _super.prototype._complete.call(this);
10982         }
10983     };
10984     SwitchMapSubscriber.prototype._unsubscribe = function () {
10985         this.innerSubscription = null;
10986     };
10987     SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
10988         this.remove(innerSub);
10989         this.innerSubscription = null;
10990         if (this.isStopped) {
10991             _super.prototype._complete.call(this);
10992         }
10993     };
10994     SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10995         if (this.resultSelector) {
10996             this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
10997         }
10998         else {
10999             this.destination.next(innerValue);
11000         }
11001     };
11002     SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
11003         var result;
11004         try {
11005             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
11006         }
11007         catch (err) {
11008             this.destination.error(err);
11009             return;
11010         }
11011         this.destination.next(result);
11012     };
11013     return SwitchMapSubscriber;
11014 }(OuterSubscriber_1.OuterSubscriber));
11015
11016 },{"../OuterSubscriber":30,"../util/subscribeToResult":164}],135:[function(require,module,exports){
11017 "use strict";
11018 var __extends = (this && this.__extends) || function (d, b) {
11019     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11020     function __() { this.constructor = d; }
11021     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11022 };
11023 var Subscriber_1 = require('../Subscriber');
11024 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
11025 var EmptyObservable_1 = require('../observable/EmptyObservable');
11026 /**
11027  * Emits only the first `count` values emitted by the source Observable.
11028  *
11029  * <span class="informal">Takes the first `count` values from the source, then
11030  * completes.</span>
11031  *
11032  * <img src="./img/take.png" width="100%">
11033  *
11034  * `take` returns an Observable that emits only the first `count` values emitted
11035  * by the source Observable. If the source emits fewer than `count` values then
11036  * all of its values are emitted. After that, it completes, regardless if the
11037  * source completes.
11038  *
11039  * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
11040  * var interval = Rx.Observable.interval(1000);
11041  * var five = interval.take(5);
11042  * five.subscribe(x => console.log(x));
11043  *
11044  * @see {@link takeLast}
11045  * @see {@link takeUntil}
11046  * @see {@link takeWhile}
11047  * @see {@link skip}
11048  *
11049  * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
11050  * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
11051  *
11052  * @param {number} count The maximum number of `next` values to emit.
11053  * @return {Observable<T>} An Observable that emits only the first `count`
11054  * values emitted by the source Observable, or all of the values from the source
11055  * if the source emits fewer than `count` values.
11056  * @method take
11057  * @owner Observable
11058  */
11059 function take(count) {
11060     if (count === 0) {
11061         return new EmptyObservable_1.EmptyObservable();
11062     }
11063     else {
11064         return this.lift(new TakeOperator(count));
11065     }
11066 }
11067 exports.take = take;
11068 var TakeOperator = (function () {
11069     function TakeOperator(total) {
11070         this.total = total;
11071         if (this.total < 0) {
11072             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
11073         }
11074     }
11075     TakeOperator.prototype.call = function (subscriber, source) {
11076         return source.subscribe(new TakeSubscriber(subscriber, this.total));
11077     };
11078     return TakeOperator;
11079 }());
11080 /**
11081  * We need this JSDoc comment for affecting ESDoc.
11082  * @ignore
11083  * @extends {Ignored}
11084  */
11085 var TakeSubscriber = (function (_super) {
11086     __extends(TakeSubscriber, _super);
11087     function TakeSubscriber(destination, total) {
11088         _super.call(this, destination);
11089         this.total = total;
11090         this.count = 0;
11091     }
11092     TakeSubscriber.prototype._next = function (value) {
11093         var total = this.total;
11094         var count = ++this.count;
11095         if (count <= total) {
11096             this.destination.next(value);
11097             if (count === total) {
11098                 this.destination.complete();
11099                 this.unsubscribe();
11100             }
11101         }
11102     };
11103     return TakeSubscriber;
11104 }(Subscriber_1.Subscriber));
11105
11106 },{"../Subscriber":35,"../observable/EmptyObservable":86,"../util/ArgumentOutOfRangeError":151}],136:[function(require,module,exports){
11107 "use strict";
11108 var __extends = (this && this.__extends) || function (d, b) {
11109     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11110     function __() { this.constructor = d; }
11111     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11112 };
11113 var OuterSubscriber_1 = require('../OuterSubscriber');
11114 var subscribeToResult_1 = require('../util/subscribeToResult');
11115 /**
11116  * Emits the values emitted by the source Observable until a `notifier`
11117  * Observable emits a value.
11118  *
11119  * <span class="informal">Lets values pass until a second Observable,
11120  * `notifier`, emits something. Then, it completes.</span>
11121  *
11122  * <img src="./img/takeUntil.png" width="100%">
11123  *
11124  * `takeUntil` subscribes and begins mirroring the source Observable. It also
11125  * monitors a second Observable, `notifier` that you provide. If the `notifier`
11126  * emits a value or a complete notification, the output Observable stops
11127  * mirroring the source Observable and completes.
11128  *
11129  * @example <caption>Tick every second until the first click happens</caption>
11130  * var interval = Rx.Observable.interval(1000);
11131  * var clicks = Rx.Observable.fromEvent(document, 'click');
11132  * var result = interval.takeUntil(clicks);
11133  * result.subscribe(x => console.log(x));
11134  *
11135  * @see {@link take}
11136  * @see {@link takeLast}
11137  * @see {@link takeWhile}
11138  * @see {@link skip}
11139  *
11140  * @param {Observable} notifier The Observable whose first emitted value will
11141  * cause the output Observable of `takeUntil` to stop emitting values from the
11142  * source Observable.
11143  * @return {Observable<T>} An Observable that emits the values from the source
11144  * Observable until such time as `notifier` emits its first value.
11145  * @method takeUntil
11146  * @owner Observable
11147  */
11148 function takeUntil(notifier) {
11149     return this.lift(new TakeUntilOperator(notifier));
11150 }
11151 exports.takeUntil = takeUntil;
11152 var TakeUntilOperator = (function () {
11153     function TakeUntilOperator(notifier) {
11154         this.notifier = notifier;
11155     }
11156     TakeUntilOperator.prototype.call = function (subscriber, source) {
11157         return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
11158     };
11159     return TakeUntilOperator;
11160 }());
11161 /**
11162  * We need this JSDoc comment for affecting ESDoc.
11163  * @ignore
11164  * @extends {Ignored}
11165  */
11166 var TakeUntilSubscriber = (function (_super) {
11167     __extends(TakeUntilSubscriber, _super);
11168     function TakeUntilSubscriber(destination, notifier) {
11169         _super.call(this, destination);
11170         this.notifier = notifier;
11171         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11172     }
11173     TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11174         this.complete();
11175     };
11176     TakeUntilSubscriber.prototype.notifyComplete = function () {
11177         // noop
11178     };
11179     return TakeUntilSubscriber;
11180 }(OuterSubscriber_1.OuterSubscriber));
11181
11182 },{"../OuterSubscriber":30,"../util/subscribeToResult":164}],137:[function(require,module,exports){
11183 "use strict";
11184 var __extends = (this && this.__extends) || function (d, b) {
11185     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11186     function __() { this.constructor = d; }
11187     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11188 };
11189 var Subscriber_1 = require('../Subscriber');
11190 var async_1 = require('../scheduler/async');
11191 /**
11192  * Emits a value from the source Observable, then ignores subsequent source
11193  * values for `duration` milliseconds, then repeats this process.
11194  *
11195  * <span class="informal">Lets a value pass, then ignores source values for the
11196  * next `duration` milliseconds.</span>
11197  *
11198  * <img src="./img/throttleTime.png" width="100%">
11199  *
11200  * `throttleTime` emits the source Observable values on the output Observable
11201  * when its internal timer is disabled, and ignores source values when the timer
11202  * is enabled. Initially, the timer is disabled. As soon as the first source
11203  * value arrives, it is forwarded to the output Observable, and then the timer
11204  * is enabled. After `duration` milliseconds (or the time unit determined
11205  * internally by the optional `scheduler`) has passed, the timer is disabled,
11206  * and this process repeats for the next source value. Optionally takes a
11207  * {@link IScheduler} for managing timers.
11208  *
11209  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
11210  * var clicks = Rx.Observable.fromEvent(document, 'click');
11211  * var result = clicks.throttleTime(1000);
11212  * result.subscribe(x => console.log(x));
11213  *
11214  * @see {@link auditTime}
11215  * @see {@link debounceTime}
11216  * @see {@link delay}
11217  * @see {@link sampleTime}
11218  * @see {@link throttle}
11219  *
11220  * @param {number} duration Time to wait before emitting another value after
11221  * emitting the last value, measured in milliseconds or the time unit determined
11222  * internally by the optional `scheduler`.
11223  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
11224  * managing the timers that handle the sampling.
11225  * @return {Observable<T>} An Observable that performs the throttle operation to
11226  * limit the rate of emissions from the source.
11227  * @method throttleTime
11228  * @owner Observable
11229  */
11230 function throttleTime(duration, scheduler) {
11231     if (scheduler === void 0) { scheduler = async_1.async; }
11232     return this.lift(new ThrottleTimeOperator(duration, scheduler));
11233 }
11234 exports.throttleTime = throttleTime;
11235 var ThrottleTimeOperator = (function () {
11236     function ThrottleTimeOperator(duration, scheduler) {
11237         this.duration = duration;
11238         this.scheduler = scheduler;
11239     }
11240     ThrottleTimeOperator.prototype.call = function (subscriber, source) {
11241         return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler));
11242     };
11243     return ThrottleTimeOperator;
11244 }());
11245 /**
11246  * We need this JSDoc comment for affecting ESDoc.
11247  * @ignore
11248  * @extends {Ignored}
11249  */
11250 var ThrottleTimeSubscriber = (function (_super) {
11251     __extends(ThrottleTimeSubscriber, _super);
11252     function ThrottleTimeSubscriber(destination, duration, scheduler) {
11253         _super.call(this, destination);
11254         this.duration = duration;
11255         this.scheduler = scheduler;
11256     }
11257     ThrottleTimeSubscriber.prototype._next = function (value) {
11258         if (!this.throttled) {
11259             this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
11260             this.destination.next(value);
11261         }
11262     };
11263     ThrottleTimeSubscriber.prototype.clearThrottle = function () {
11264         var throttled = this.throttled;
11265         if (throttled) {
11266             throttled.unsubscribe();
11267             this.remove(throttled);
11268             this.throttled = null;
11269         }
11270     };
11271     return ThrottleTimeSubscriber;
11272 }(Subscriber_1.Subscriber));
11273 function dispatchNext(arg) {
11274     var subscriber = arg.subscriber;
11275     subscriber.clearThrottle();
11276 }
11277
11278 },{"../Subscriber":35,"../scheduler/async":145}],138:[function(require,module,exports){
11279 "use strict";
11280 var __extends = (this && this.__extends) || function (d, b) {
11281     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11282     function __() { this.constructor = d; }
11283     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11284 };
11285 var OuterSubscriber_1 = require('../OuterSubscriber');
11286 var subscribeToResult_1 = require('../util/subscribeToResult');
11287 /* tslint:disable:max-line-length */
11288 /**
11289  * Combines the source Observable with other Observables to create an Observable
11290  * whose values are calculated from the latest values of each, only when the
11291  * source emits.
11292  *
11293  * <span class="informal">Whenever the source Observable emits a value, it
11294  * computes a formula using that value plus the latest values from other input
11295  * Observables, then emits the output of that formula.</span>
11296  *
11297  * <img src="./img/withLatestFrom.png" width="100%">
11298  *
11299  * `withLatestFrom` combines each value from the source Observable (the
11300  * instance) with the latest values from the other input Observables only when
11301  * the source emits a value, optionally using a `project` function to determine
11302  * the value to be emitted on the output Observable. All input Observables must
11303  * emit at least one value before the output Observable will emit a value.
11304  *
11305  * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
11306  * var clicks = Rx.Observable.fromEvent(document, 'click');
11307  * var timer = Rx.Observable.interval(1000);
11308  * var result = clicks.withLatestFrom(timer);
11309  * result.subscribe(x => console.log(x));
11310  *
11311  * @see {@link combineLatest}
11312  *
11313  * @param {Observable} other An input Observable to combine with the source
11314  * Observable. More than one input Observables may be given as argument.
11315  * @param {Function} [project] Projection function for combining values
11316  * together. Receives all values in order of the Observables passed, where the
11317  * first parameter is a value from the source Observable. (e.g.
11318  * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
11319  * passed, arrays will be emitted on the output Observable.
11320  * @return {Observable} An Observable of projected values from the most recent
11321  * values from each input Observable, or an array of the most recent values from
11322  * each input Observable.
11323  * @method withLatestFrom
11324  * @owner Observable
11325  */
11326 function withLatestFrom() {
11327     var args = [];
11328     for (var _i = 0; _i < arguments.length; _i++) {
11329         args[_i - 0] = arguments[_i];
11330     }
11331     var project;
11332     if (typeof args[args.length - 1] === 'function') {
11333         project = args.pop();
11334     }
11335     var observables = args;
11336     return this.lift(new WithLatestFromOperator(observables, project));
11337 }
11338 exports.withLatestFrom = withLatestFrom;
11339 var WithLatestFromOperator = (function () {
11340     function WithLatestFromOperator(observables, project) {
11341         this.observables = observables;
11342         this.project = project;
11343     }
11344     WithLatestFromOperator.prototype.call = function (subscriber, source) {
11345         return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
11346     };
11347     return WithLatestFromOperator;
11348 }());
11349 /**
11350  * We need this JSDoc comment for affecting ESDoc.
11351  * @ignore
11352  * @extends {Ignored}
11353  */
11354 var WithLatestFromSubscriber = (function (_super) {
11355     __extends(WithLatestFromSubscriber, _super);
11356     function WithLatestFromSubscriber(destination, observables, project) {
11357         _super.call(this, destination);
11358         this.observables = observables;
11359         this.project = project;
11360         this.toRespond = [];
11361         var len = observables.length;
11362         this.values = new Array(len);
11363         for (var i = 0; i < len; i++) {
11364             this.toRespond.push(i);
11365         }
11366         for (var i = 0; i < len; i++) {
11367             var observable = observables[i];
11368             this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
11369         }
11370     }
11371     WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11372         this.values[outerIndex] = innerValue;
11373         var toRespond = this.toRespond;
11374         if (toRespond.length > 0) {
11375             var found = toRespond.indexOf(outerIndex);
11376             if (found !== -1) {
11377                 toRespond.splice(found, 1);
11378             }
11379         }
11380     };
11381     WithLatestFromSubscriber.prototype.notifyComplete = function () {
11382         // noop
11383     };
11384     WithLatestFromSubscriber.prototype._next = function (value) {
11385         if (this.toRespond.length === 0) {
11386             var args = [value].concat(this.values);
11387             if (this.project) {
11388                 this._tryProject(args);
11389             }
11390             else {
11391                 this.destination.next(args);
11392             }
11393         }
11394     };
11395     WithLatestFromSubscriber.prototype._tryProject = function (args) {
11396         var result;
11397         try {
11398             result = this.project.apply(this, args);
11399         }
11400         catch (err) {
11401             this.destination.error(err);
11402             return;
11403         }
11404         this.destination.next(result);
11405     };
11406     return WithLatestFromSubscriber;
11407 }(OuterSubscriber_1.OuterSubscriber));
11408
11409 },{"../OuterSubscriber":30,"../util/subscribeToResult":164}],139:[function(require,module,exports){
11410 "use strict";
11411 var __extends = (this && this.__extends) || function (d, b) {
11412     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11413     function __() { this.constructor = d; }
11414     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11415 };
11416 var ArrayObservable_1 = require('../observable/ArrayObservable');
11417 var isArray_1 = require('../util/isArray');
11418 var Subscriber_1 = require('../Subscriber');
11419 var OuterSubscriber_1 = require('../OuterSubscriber');
11420 var subscribeToResult_1 = require('../util/subscribeToResult');
11421 var iterator_1 = require('../symbol/iterator');
11422 /* tslint:disable:max-line-length */
11423 /**
11424  * @param observables
11425  * @return {Observable<R>}
11426  * @method zip
11427  * @owner Observable
11428  */
11429 function zipProto() {
11430     var observables = [];
11431     for (var _i = 0; _i < arguments.length; _i++) {
11432         observables[_i - 0] = arguments[_i];
11433     }
11434     return this.lift.call(zipStatic.apply(void 0, [this].concat(observables)));
11435 }
11436 exports.zipProto = zipProto;
11437 /* tslint:enable:max-line-length */
11438 /**
11439  * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
11440  * of its input Observables.
11441  *
11442  * If the latest parameter is a function, this function is used to compute the created value from the input values.
11443  * Otherwise, an array of the input values is returned.
11444  *
11445  * @example <caption>Combine age and name from different sources</caption>
11446  *
11447  * let age$ = Observable.of<number>(27, 25, 29);
11448  * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
11449  * let isDev$ = Observable.of<boolean>(true, true, false);
11450  *
11451  * Observable
11452  *     .zip(age$,
11453  *          name$,
11454  *          isDev$,
11455  *          (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
11456  *     .subscribe(x => console.log(x));
11457  *
11458  * // outputs
11459  * // { age: 7, name: 'Foo', isDev: true }
11460  * // { age: 5, name: 'Bar', isDev: true }
11461  * // { age: 9, name: 'Beer', isDev: false }
11462  *
11463  * @param observables
11464  * @return {Observable<R>}
11465  * @static true
11466  * @name zip
11467  * @owner Observable
11468  */
11469 function zipStatic() {
11470     var observables = [];
11471     for (var _i = 0; _i < arguments.length; _i++) {
11472         observables[_i - 0] = arguments[_i];
11473     }
11474     var project = observables[observables.length - 1];
11475     if (typeof project === 'function') {
11476         observables.pop();
11477     }
11478     return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
11479 }
11480 exports.zipStatic = zipStatic;
11481 var ZipOperator = (function () {
11482     function ZipOperator(project) {
11483         this.project = project;
11484     }
11485     ZipOperator.prototype.call = function (subscriber, source) {
11486         return source.subscribe(new ZipSubscriber(subscriber, this.project));
11487     };
11488     return ZipOperator;
11489 }());
11490 exports.ZipOperator = ZipOperator;
11491 /**
11492  * We need this JSDoc comment for affecting ESDoc.
11493  * @ignore
11494  * @extends {Ignored}
11495  */
11496 var ZipSubscriber = (function (_super) {
11497     __extends(ZipSubscriber, _super);
11498     function ZipSubscriber(destination, project, values) {
11499         if (values === void 0) { values = Object.create(null); }
11500         _super.call(this, destination);
11501         this.iterators = [];
11502         this.active = 0;
11503         this.project = (typeof project === 'function') ? project : null;
11504         this.values = values;
11505     }
11506     ZipSubscriber.prototype._next = function (value) {
11507         var iterators = this.iterators;
11508         if (isArray_1.isArray(value)) {
11509             iterators.push(new StaticArrayIterator(value));
11510         }
11511         else if (typeof value[iterator_1.$$iterator] === 'function') {
11512             iterators.push(new StaticIterator(value[iterator_1.$$iterator]()));
11513         }
11514         else {
11515             iterators.push(new ZipBufferIterator(this.destination, this, value));
11516         }
11517     };
11518     ZipSubscriber.prototype._complete = function () {
11519         var iterators = this.iterators;
11520         var len = iterators.length;
11521         this.active = len;
11522         for (var i = 0; i < len; i++) {
11523             var iterator = iterators[i];
11524             if (iterator.stillUnsubscribed) {
11525                 this.add(iterator.subscribe(iterator, i));
11526             }
11527             else {
11528                 this.active--; // not an observable
11529             }
11530         }
11531     };
11532     ZipSubscriber.prototype.notifyInactive = function () {
11533         this.active--;
11534         if (this.active === 0) {
11535             this.destination.complete();
11536         }
11537     };
11538     ZipSubscriber.prototype.checkIterators = function () {
11539         var iterators = this.iterators;
11540         var len = iterators.length;
11541         var destination = this.destination;
11542         // abort if not all of them have values
11543         for (var i = 0; i < len; i++) {
11544             var iterator = iterators[i];
11545             if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
11546                 return;
11547             }
11548         }
11549         var shouldComplete = false;
11550         var args = [];
11551         for (var i = 0; i < len; i++) {
11552             var iterator = iterators[i];
11553             var result = iterator.next();
11554             // check to see if it's completed now that you've gotten
11555             // the next value.
11556             if (iterator.hasCompleted()) {
11557                 shouldComplete = true;
11558             }
11559             if (result.done) {
11560                 destination.complete();
11561                 return;
11562             }
11563             args.push(result.value);
11564         }
11565         if (this.project) {
11566             this._tryProject(args);
11567         }
11568         else {
11569             destination.next(args);
11570         }
11571         if (shouldComplete) {
11572             destination.complete();
11573         }
11574     };
11575     ZipSubscriber.prototype._tryProject = function (args) {
11576         var result;
11577         try {
11578             result = this.project.apply(this, args);
11579         }
11580         catch (err) {
11581             this.destination.error(err);
11582             return;
11583         }
11584         this.destination.next(result);
11585     };
11586     return ZipSubscriber;
11587 }(Subscriber_1.Subscriber));
11588 exports.ZipSubscriber = ZipSubscriber;
11589 var StaticIterator = (function () {
11590     function StaticIterator(iterator) {
11591         this.iterator = iterator;
11592         this.nextResult = iterator.next();
11593     }
11594     StaticIterator.prototype.hasValue = function () {
11595         return true;
11596     };
11597     StaticIterator.prototype.next = function () {
11598         var result = this.nextResult;
11599         this.nextResult = this.iterator.next();
11600         return result;
11601     };
11602     StaticIterator.prototype.hasCompleted = function () {
11603         var nextResult = this.nextResult;
11604         return nextResult && nextResult.done;
11605     };
11606     return StaticIterator;
11607 }());
11608 var StaticArrayIterator = (function () {
11609     function StaticArrayIterator(array) {
11610         this.array = array;
11611         this.index = 0;
11612         this.length = 0;
11613         this.length = array.length;
11614     }
11615     StaticArrayIterator.prototype[iterator_1.$$iterator] = function () {
11616         return this;
11617     };
11618     StaticArrayIterator.prototype.next = function (value) {
11619         var i = this.index++;
11620         var array = this.array;
11621         return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
11622     };
11623     StaticArrayIterator.prototype.hasValue = function () {
11624         return this.array.length > this.index;
11625     };
11626     StaticArrayIterator.prototype.hasCompleted = function () {
11627         return this.array.length === this.index;
11628     };
11629     return StaticArrayIterator;
11630 }());
11631 /**
11632  * We need this JSDoc comment for affecting ESDoc.
11633  * @ignore
11634  * @extends {Ignored}
11635  */
11636 var ZipBufferIterator = (function (_super) {
11637     __extends(ZipBufferIterator, _super);
11638     function ZipBufferIterator(destination, parent, observable) {
11639         _super.call(this, destination);
11640         this.parent = parent;
11641         this.observable = observable;
11642         this.stillUnsubscribed = true;
11643         this.buffer = [];
11644         this.isComplete = false;
11645     }
11646     ZipBufferIterator.prototype[iterator_1.$$iterator] = function () {
11647         return this;
11648     };
11649     // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
11650     //    this is legit because `next()` will never be called by a subscription in this case.
11651     ZipBufferIterator.prototype.next = function () {
11652         var buffer = this.buffer;
11653         if (buffer.length === 0 && this.isComplete) {
11654             return { value: null, done: true };
11655         }
11656         else {
11657             return { value: buffer.shift(), done: false };
11658         }
11659     };
11660     ZipBufferIterator.prototype.hasValue = function () {
11661         return this.buffer.length > 0;
11662     };
11663     ZipBufferIterator.prototype.hasCompleted = function () {
11664         return this.buffer.length === 0 && this.isComplete;
11665     };
11666     ZipBufferIterator.prototype.notifyComplete = function () {
11667         if (this.buffer.length > 0) {
11668             this.isComplete = true;
11669             this.parent.notifyInactive();
11670         }
11671         else {
11672             this.destination.complete();
11673         }
11674     };
11675     ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11676         this.buffer.push(innerValue);
11677         this.parent.checkIterators();
11678     };
11679     ZipBufferIterator.prototype.subscribe = function (value, index) {
11680         return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
11681     };
11682     return ZipBufferIterator;
11683 }(OuterSubscriber_1.OuterSubscriber));
11684
11685 },{"../OuterSubscriber":30,"../Subscriber":35,"../observable/ArrayObservable":83,"../symbol/iterator":147,"../util/isArray":157,"../util/subscribeToResult":164}],140:[function(require,module,exports){
11686 "use strict";
11687 var __extends = (this && this.__extends) || function (d, b) {
11688     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11689     function __() { this.constructor = d; }
11690     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11691 };
11692 var Subscription_1 = require('../Subscription');
11693 /**
11694  * A unit of work to be executed in a {@link Scheduler}. An action is typically
11695  * created from within a Scheduler and an RxJS user does not need to concern
11696  * themselves about creating and manipulating an Action.
11697  *
11698  * ```ts
11699  * class Action<T> extends Subscription {
11700  *   new (scheduler: Scheduler, work: (state?: T) => void);
11701  *   schedule(state?: T, delay: number = 0): Subscription;
11702  * }
11703  * ```
11704  *
11705  * @class Action<T>
11706  */
11707 var Action = (function (_super) {
11708     __extends(Action, _super);
11709     function Action(scheduler, work) {
11710         _super.call(this);
11711     }
11712     /**
11713      * Schedules this action on its parent Scheduler for execution. May be passed
11714      * some context object, `state`. May happen at some point in the future,
11715      * according to the `delay` parameter, if specified.
11716      * @param {T} [state] Some contextual data that the `work` function uses when
11717      * called by the Scheduler.
11718      * @param {number} [delay] Time to wait before executing the work, where the
11719      * time unit is implicit and defined by the Scheduler.
11720      * @return {void}
11721      */
11722     Action.prototype.schedule = function (state, delay) {
11723         if (delay === void 0) { delay = 0; }
11724         return this;
11725     };
11726     return Action;
11727 }(Subscription_1.Subscription));
11728 exports.Action = Action;
11729
11730 },{"../Subscription":36}],141:[function(require,module,exports){
11731 "use strict";
11732 var __extends = (this && this.__extends) || function (d, b) {
11733     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11734     function __() { this.constructor = d; }
11735     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11736 };
11737 var root_1 = require('../util/root');
11738 var Action_1 = require('./Action');
11739 /**
11740  * We need this JSDoc comment for affecting ESDoc.
11741  * @ignore
11742  * @extends {Ignored}
11743  */
11744 var AsyncAction = (function (_super) {
11745     __extends(AsyncAction, _super);
11746     function AsyncAction(scheduler, work) {
11747         _super.call(this, scheduler, work);
11748         this.scheduler = scheduler;
11749         this.work = work;
11750         this.pending = false;
11751     }
11752     AsyncAction.prototype.schedule = function (state, delay) {
11753         if (delay === void 0) { delay = 0; }
11754         if (this.closed) {
11755             return this;
11756         }
11757         // Always replace the current state with the new state.
11758         this.state = state;
11759         // Set the pending flag indicating that this action has been scheduled, or
11760         // has recursively rescheduled itself.
11761         this.pending = true;
11762         var id = this.id;
11763         var scheduler = this.scheduler;
11764         //
11765         // Important implementation note:
11766         //
11767         // Actions only execute once by default, unless rescheduled from within the
11768         // scheduled callback. This allows us to implement single and repeat
11769         // actions via the same code path, without adding API surface area, as well
11770         // as mimic traditional recursion but across asynchronous boundaries.
11771         //
11772         // However, JS runtimes and timers distinguish between intervals achieved by
11773         // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
11774         // serial `setTimeout` calls can be individually delayed, which delays
11775         // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
11776         // guarantee the interval callback will be invoked more precisely to the
11777         // interval period, regardless of load.
11778         //
11779         // Therefore, we use `setInterval` to schedule single and repeat actions.
11780         // If the action reschedules itself with the same delay, the interval is not
11781         // canceled. If the action doesn't reschedule, or reschedules with a
11782         // different delay, the interval will be canceled after scheduled callback
11783         // execution.
11784         //
11785         if (id != null) {
11786             this.id = this.recycleAsyncId(scheduler, id, delay);
11787         }
11788         this.delay = delay;
11789         // If this action has already an async Id, don't request a new one.
11790         this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
11791         return this;
11792     };
11793     AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
11794         if (delay === void 0) { delay = 0; }
11795         return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
11796     };
11797     AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
11798         if (delay === void 0) { delay = 0; }
11799         // If this action is rescheduled with the same delay time, don't clear the interval id.
11800         if (delay !== null && this.delay === delay) {
11801             return id;
11802         }
11803         // Otherwise, if the action's delay time is different from the current delay,
11804         // clear the interval id
11805         return root_1.root.clearInterval(id) && undefined || undefined;
11806     };
11807     /**
11808      * Immediately executes this action and the `work` it contains.
11809      * @return {any}
11810      */
11811     AsyncAction.prototype.execute = function (state, delay) {
11812         if (this.closed) {
11813             return new Error('executing a cancelled action');
11814         }
11815         this.pending = false;
11816         var error = this._execute(state, delay);
11817         if (error) {
11818             return error;
11819         }
11820         else if (this.pending === false && this.id != null) {
11821             // Dequeue if the action didn't reschedule itself. Don't call
11822             // unsubscribe(), because the action could reschedule later.
11823             // For example:
11824             // ```
11825             // scheduler.schedule(function doWork(counter) {
11826             //   /* ... I'm a busy worker bee ... */
11827             //   var originalAction = this;
11828             //   /* wait 100ms before rescheduling the action */
11829             //   setTimeout(function () {
11830             //     originalAction.schedule(counter + 1);
11831             //   }, 100);
11832             // }, 1000);
11833             // ```
11834             this.id = this.recycleAsyncId(this.scheduler, this.id, null);
11835         }
11836     };
11837     AsyncAction.prototype._execute = function (state, delay) {
11838         var errored = false;
11839         var errorValue = undefined;
11840         try {
11841             this.work(state);
11842         }
11843         catch (e) {
11844             errored = true;
11845             errorValue = !!e && e || new Error(e);
11846         }
11847         if (errored) {
11848             this.unsubscribe();
11849             return errorValue;
11850         }
11851     };
11852     AsyncAction.prototype._unsubscribe = function () {
11853         var id = this.id;
11854         var scheduler = this.scheduler;
11855         var actions = scheduler.actions;
11856         var index = actions.indexOf(this);
11857         this.work = null;
11858         this.delay = null;
11859         this.state = null;
11860         this.pending = false;
11861         this.scheduler = null;
11862         if (index !== -1) {
11863             actions.splice(index, 1);
11864         }
11865         if (id != null) {
11866             this.id = this.recycleAsyncId(scheduler, id, null);
11867         }
11868     };
11869     return AsyncAction;
11870 }(Action_1.Action));
11871 exports.AsyncAction = AsyncAction;
11872
11873 },{"../util/root":163,"./Action":140}],142:[function(require,module,exports){
11874 "use strict";
11875 var __extends = (this && this.__extends) || function (d, b) {
11876     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11877     function __() { this.constructor = d; }
11878     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11879 };
11880 var Scheduler_1 = require('../Scheduler');
11881 var AsyncScheduler = (function (_super) {
11882     __extends(AsyncScheduler, _super);
11883     function AsyncScheduler() {
11884         _super.apply(this, arguments);
11885         this.actions = [];
11886         /**
11887          * A flag to indicate whether the Scheduler is currently executing a batch of
11888          * queued actions.
11889          * @type {boolean}
11890          */
11891         this.active = false;
11892         /**
11893          * An internal ID used to track the latest asynchronous task such as those
11894          * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
11895          * others.
11896          * @type {any}
11897          */
11898         this.scheduled = undefined;
11899     }
11900     AsyncScheduler.prototype.flush = function (action) {
11901         var actions = this.actions;
11902         if (this.active) {
11903             actions.push(action);
11904             return;
11905         }
11906         var error;
11907         this.active = true;
11908         do {
11909             if (error = action.execute(action.state, action.delay)) {
11910                 break;
11911             }
11912         } while (action = actions.shift()); // exhaust the scheduler queue
11913         this.active = false;
11914         if (error) {
11915             while (action = actions.shift()) {
11916                 action.unsubscribe();
11917             }
11918             throw error;
11919         }
11920     };
11921     return AsyncScheduler;
11922 }(Scheduler_1.Scheduler));
11923 exports.AsyncScheduler = AsyncScheduler;
11924
11925 },{"../Scheduler":32}],143:[function(require,module,exports){
11926 "use strict";
11927 var __extends = (this && this.__extends) || function (d, b) {
11928     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11929     function __() { this.constructor = d; }
11930     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11931 };
11932 var AsyncAction_1 = require('./AsyncAction');
11933 /**
11934  * We need this JSDoc comment for affecting ESDoc.
11935  * @ignore
11936  * @extends {Ignored}
11937  */
11938 var QueueAction = (function (_super) {
11939     __extends(QueueAction, _super);
11940     function QueueAction(scheduler, work) {
11941         _super.call(this, scheduler, work);
11942         this.scheduler = scheduler;
11943         this.work = work;
11944     }
11945     QueueAction.prototype.schedule = function (state, delay) {
11946         if (delay === void 0) { delay = 0; }
11947         if (delay > 0) {
11948             return _super.prototype.schedule.call(this, state, delay);
11949         }
11950         this.delay = delay;
11951         this.state = state;
11952         this.scheduler.flush(this);
11953         return this;
11954     };
11955     QueueAction.prototype.execute = function (state, delay) {
11956         return (delay > 0 || this.closed) ?
11957             _super.prototype.execute.call(this, state, delay) :
11958             this._execute(state, delay);
11959     };
11960     QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
11961         if (delay === void 0) { delay = 0; }
11962         // If delay exists and is greater than 0, or if the delay is null (the
11963         // action wasn't rescheduled) but was originally scheduled as an async
11964         // action, then recycle as an async action.
11965         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
11966             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
11967         }
11968         // Otherwise flush the scheduler starting with this action.
11969         return scheduler.flush(this);
11970     };
11971     return QueueAction;
11972 }(AsyncAction_1.AsyncAction));
11973 exports.QueueAction = QueueAction;
11974
11975 },{"./AsyncAction":141}],144:[function(require,module,exports){
11976 "use strict";
11977 var __extends = (this && this.__extends) || function (d, b) {
11978     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11979     function __() { this.constructor = d; }
11980     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11981 };
11982 var AsyncScheduler_1 = require('./AsyncScheduler');
11983 var QueueScheduler = (function (_super) {
11984     __extends(QueueScheduler, _super);
11985     function QueueScheduler() {
11986         _super.apply(this, arguments);
11987     }
11988     return QueueScheduler;
11989 }(AsyncScheduler_1.AsyncScheduler));
11990 exports.QueueScheduler = QueueScheduler;
11991
11992 },{"./AsyncScheduler":142}],145:[function(require,module,exports){
11993 "use strict";
11994 var AsyncAction_1 = require('./AsyncAction');
11995 var AsyncScheduler_1 = require('./AsyncScheduler');
11996 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
11997
11998 },{"./AsyncAction":141,"./AsyncScheduler":142}],146:[function(require,module,exports){
11999 "use strict";
12000 var QueueAction_1 = require('./QueueAction');
12001 var QueueScheduler_1 = require('./QueueScheduler');
12002 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
12003
12004 },{"./QueueAction":143,"./QueueScheduler":144}],147:[function(require,module,exports){
12005 "use strict";
12006 var root_1 = require('../util/root');
12007 function symbolIteratorPonyfill(root) {
12008     var Symbol = root.Symbol;
12009     if (typeof Symbol === 'function') {
12010         if (!Symbol.iterator) {
12011             Symbol.iterator = Symbol('iterator polyfill');
12012         }
12013         return Symbol.iterator;
12014     }
12015     else {
12016         // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
12017         var Set_1 = root.Set;
12018         if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
12019             return '@@iterator';
12020         }
12021         var Map_1 = root.Map;
12022         // required for compatability with es6-shim
12023         if (Map_1) {
12024             var keys = Object.getOwnPropertyNames(Map_1.prototype);
12025             for (var i = 0; i < keys.length; ++i) {
12026                 var key = keys[i];
12027                 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
12028                 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
12029                     return key;
12030                 }
12031             }
12032         }
12033         return '@@iterator';
12034     }
12035 }
12036 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
12037 exports.$$iterator = symbolIteratorPonyfill(root_1.root);
12038
12039 },{"../util/root":163}],148:[function(require,module,exports){
12040 "use strict";
12041 var root_1 = require('../util/root');
12042 function getSymbolObservable(context) {
12043     var $$observable;
12044     var Symbol = context.Symbol;
12045     if (typeof Symbol === 'function') {
12046         if (Symbol.observable) {
12047             $$observable = Symbol.observable;
12048         }
12049         else {
12050             $$observable = Symbol('observable');
12051             Symbol.observable = $$observable;
12052         }
12053     }
12054     else {
12055         $$observable = '@@observable';
12056     }
12057     return $$observable;
12058 }
12059 exports.getSymbolObservable = getSymbolObservable;
12060 exports.$$observable = getSymbolObservable(root_1.root);
12061
12062 },{"../util/root":163}],149:[function(require,module,exports){
12063 "use strict";
12064 var root_1 = require('../util/root');
12065 var Symbol = root_1.root.Symbol;
12066 exports.$$rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
12067     Symbol.for('rxSubscriber') : '@@rxSubscriber';
12068
12069 },{"../util/root":163}],150:[function(require,module,exports){
12070 "use strict";
12071 var root_1 = require('./root');
12072 var RequestAnimationFrameDefinition = (function () {
12073     function RequestAnimationFrameDefinition(root) {
12074         if (root.requestAnimationFrame) {
12075             this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
12076             this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
12077         }
12078         else if (root.mozRequestAnimationFrame) {
12079             this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
12080             this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
12081         }
12082         else if (root.webkitRequestAnimationFrame) {
12083             this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
12084             this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
12085         }
12086         else if (root.msRequestAnimationFrame) {
12087             this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
12088             this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
12089         }
12090         else if (root.oRequestAnimationFrame) {
12091             this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
12092             this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
12093         }
12094         else {
12095             this.cancelAnimationFrame = root.clearTimeout.bind(root);
12096             this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
12097         }
12098     }
12099     return RequestAnimationFrameDefinition;
12100 }());
12101 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
12102 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
12103
12104 },{"./root":163}],151:[function(require,module,exports){
12105 "use strict";
12106 var __extends = (this && this.__extends) || function (d, b) {
12107     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12108     function __() { this.constructor = d; }
12109     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12110 };
12111 /**
12112  * An error thrown when an element was queried at a certain index of an
12113  * Observable, but no such index or position exists in that sequence.
12114  *
12115  * @see {@link elementAt}
12116  * @see {@link take}
12117  * @see {@link takeLast}
12118  *
12119  * @class ArgumentOutOfRangeError
12120  */
12121 var ArgumentOutOfRangeError = (function (_super) {
12122     __extends(ArgumentOutOfRangeError, _super);
12123     function ArgumentOutOfRangeError() {
12124         var err = _super.call(this, 'argument out of range');
12125         this.name = err.name = 'ArgumentOutOfRangeError';
12126         this.stack = err.stack;
12127         this.message = err.message;
12128     }
12129     return ArgumentOutOfRangeError;
12130 }(Error));
12131 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
12132
12133 },{}],152:[function(require,module,exports){
12134 "use strict";
12135 var __extends = (this && this.__extends) || function (d, b) {
12136     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12137     function __() { this.constructor = d; }
12138     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12139 };
12140 /**
12141  * An error thrown when an Observable or a sequence was queried but has no
12142  * elements.
12143  *
12144  * @see {@link first}
12145  * @see {@link last}
12146  * @see {@link single}
12147  *
12148  * @class EmptyError
12149  */
12150 var EmptyError = (function (_super) {
12151     __extends(EmptyError, _super);
12152     function EmptyError() {
12153         var err = _super.call(this, 'no elements in sequence');
12154         this.name = err.name = 'EmptyError';
12155         this.stack = err.stack;
12156         this.message = err.message;
12157     }
12158     return EmptyError;
12159 }(Error));
12160 exports.EmptyError = EmptyError;
12161
12162 },{}],153:[function(require,module,exports){
12163 "use strict";
12164 var __extends = (this && this.__extends) || function (d, b) {
12165     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12166     function __() { this.constructor = d; }
12167     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12168 };
12169 /**
12170  * An error thrown when an action is invalid because the object has been
12171  * unsubscribed.
12172  *
12173  * @see {@link Subject}
12174  * @see {@link BehaviorSubject}
12175  *
12176  * @class ObjectUnsubscribedError
12177  */
12178 var ObjectUnsubscribedError = (function (_super) {
12179     __extends(ObjectUnsubscribedError, _super);
12180     function ObjectUnsubscribedError() {
12181         var err = _super.call(this, 'object unsubscribed');
12182         this.name = err.name = 'ObjectUnsubscribedError';
12183         this.stack = err.stack;
12184         this.message = err.message;
12185     }
12186     return ObjectUnsubscribedError;
12187 }(Error));
12188 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
12189
12190 },{}],154:[function(require,module,exports){
12191 "use strict";
12192 var root_1 = require('./root');
12193 function minimalSetImpl() {
12194     // THIS IS NOT a full impl of Set, this is just the minimum
12195     // bits of functionality we need for this library.
12196     return (function () {
12197         function MinimalSet() {
12198             this._values = [];
12199         }
12200         MinimalSet.prototype.add = function (value) {
12201             if (!this.has(value)) {
12202                 this._values.push(value);
12203             }
12204         };
12205         MinimalSet.prototype.has = function (value) {
12206             return this._values.indexOf(value) !== -1;
12207         };
12208         Object.defineProperty(MinimalSet.prototype, "size", {
12209             get: function () {
12210                 return this._values.length;
12211             },
12212             enumerable: true,
12213             configurable: true
12214         });
12215         MinimalSet.prototype.clear = function () {
12216             this._values.length = 0;
12217         };
12218         return MinimalSet;
12219     }());
12220 }
12221 exports.minimalSetImpl = minimalSetImpl;
12222 exports.Set = root_1.root.Set || minimalSetImpl();
12223
12224 },{"./root":163}],155:[function(require,module,exports){
12225 "use strict";
12226 var __extends = (this && this.__extends) || function (d, b) {
12227     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12228     function __() { this.constructor = d; }
12229     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12230 };
12231 /**
12232  * An error thrown when one or more errors have occurred during the
12233  * `unsubscribe` of a {@link Subscription}.
12234  */
12235 var UnsubscriptionError = (function (_super) {
12236     __extends(UnsubscriptionError, _super);
12237     function UnsubscriptionError(errors) {
12238         _super.call(this);
12239         this.errors = errors;
12240         var err = Error.call(this, errors ?
12241             errors.length + " errors occurred during unsubscription:\n  " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n  ') : '');
12242         this.name = err.name = 'UnsubscriptionError';
12243         this.stack = err.stack;
12244         this.message = err.message;
12245     }
12246     return UnsubscriptionError;
12247 }(Error));
12248 exports.UnsubscriptionError = UnsubscriptionError;
12249
12250 },{}],156:[function(require,module,exports){
12251 "use strict";
12252 // typeof any so that it we don't have to cast when comparing a result to the error object
12253 exports.errorObject = { e: {} };
12254
12255 },{}],157:[function(require,module,exports){
12256 "use strict";
12257 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
12258
12259 },{}],158:[function(require,module,exports){
12260 "use strict";
12261 function isDate(value) {
12262     return value instanceof Date && !isNaN(+value);
12263 }
12264 exports.isDate = isDate;
12265
12266 },{}],159:[function(require,module,exports){
12267 "use strict";
12268 function isFunction(x) {
12269     return typeof x === 'function';
12270 }
12271 exports.isFunction = isFunction;
12272
12273 },{}],160:[function(require,module,exports){
12274 "use strict";
12275 function isObject(x) {
12276     return x != null && typeof x === 'object';
12277 }
12278 exports.isObject = isObject;
12279
12280 },{}],161:[function(require,module,exports){
12281 "use strict";
12282 function isPromise(value) {
12283     return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
12284 }
12285 exports.isPromise = isPromise;
12286
12287 },{}],162:[function(require,module,exports){
12288 "use strict";
12289 function isScheduler(value) {
12290     return value && typeof value.schedule === 'function';
12291 }
12292 exports.isScheduler = isScheduler;
12293
12294 },{}],163:[function(require,module,exports){
12295 (function (global){
12296 "use strict";
12297 /**
12298  * window: browser in DOM main thread
12299  * self: browser in WebWorker
12300  * global: Node.js/other
12301  */
12302 exports.root = (typeof window == 'object' && window.window === window && window
12303     || typeof self == 'object' && self.self === self && self
12304     || typeof global == 'object' && global.global === global && global);
12305 if (!exports.root) {
12306     throw new Error('RxJS could not find any global context (window, self, global)');
12307 }
12308
12309 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12310
12311 },{}],164:[function(require,module,exports){
12312 "use strict";
12313 var root_1 = require('./root');
12314 var isArray_1 = require('./isArray');
12315 var isPromise_1 = require('./isPromise');
12316 var isObject_1 = require('./isObject');
12317 var Observable_1 = require('../Observable');
12318 var iterator_1 = require('../symbol/iterator');
12319 var InnerSubscriber_1 = require('../InnerSubscriber');
12320 var observable_1 = require('../symbol/observable');
12321 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
12322     var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
12323     if (destination.closed) {
12324         return null;
12325     }
12326     if (result instanceof Observable_1.Observable) {
12327         if (result._isScalar) {
12328             destination.next(result.value);
12329             destination.complete();
12330             return null;
12331         }
12332         else {
12333             return result.subscribe(destination);
12334         }
12335     }
12336     else if (isArray_1.isArray(result)) {
12337         for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
12338             destination.next(result[i]);
12339         }
12340         if (!destination.closed) {
12341             destination.complete();
12342         }
12343     }
12344     else if (isPromise_1.isPromise(result)) {
12345         result.then(function (value) {
12346             if (!destination.closed) {
12347                 destination.next(value);
12348                 destination.complete();
12349             }
12350         }, function (err) { return destination.error(err); })
12351             .then(null, function (err) {
12352             // Escaping the Promise trap: globally throw unhandled errors
12353             root_1.root.setTimeout(function () { throw err; });
12354         });
12355         return destination;
12356     }
12357     else if (result && typeof result[iterator_1.$$iterator] === 'function') {
12358         var iterator = result[iterator_1.$$iterator]();
12359         do {
12360             var item = iterator.next();
12361             if (item.done) {
12362                 destination.complete();
12363                 break;
12364             }
12365             destination.next(item.value);
12366             if (destination.closed) {
12367                 break;
12368             }
12369         } while (true);
12370     }
12371     else if (result && typeof result[observable_1.$$observable] === 'function') {
12372         var obs = result[observable_1.$$observable]();
12373         if (typeof obs.subscribe !== 'function') {
12374             destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
12375         }
12376         else {
12377             return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
12378         }
12379     }
12380     else {
12381         var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
12382         var msg = ("You provided " + value + " where a stream was expected.")
12383             + ' You can provide an Observable, Promise, Array, or Iterable.';
12384         destination.error(new TypeError(msg));
12385     }
12386     return null;
12387 }
12388 exports.subscribeToResult = subscribeToResult;
12389
12390 },{"../InnerSubscriber":26,"../Observable":28,"../symbol/iterator":147,"../symbol/observable":148,"./isArray":157,"./isObject":160,"./isPromise":161,"./root":163}],165:[function(require,module,exports){
12391 "use strict";
12392 var Subscriber_1 = require('../Subscriber');
12393 var rxSubscriber_1 = require('../symbol/rxSubscriber');
12394 var Observer_1 = require('../Observer');
12395 function toSubscriber(nextOrObserver, error, complete) {
12396     if (nextOrObserver) {
12397         if (nextOrObserver instanceof Subscriber_1.Subscriber) {
12398             return nextOrObserver;
12399         }
12400         if (nextOrObserver[rxSubscriber_1.$$rxSubscriber]) {
12401             return nextOrObserver[rxSubscriber_1.$$rxSubscriber]();
12402         }
12403     }
12404     if (!nextOrObserver && !error && !complete) {
12405         return new Subscriber_1.Subscriber(Observer_1.empty);
12406     }
12407     return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
12408 }
12409 exports.toSubscriber = toSubscriber;
12410
12411 },{"../Observer":29,"../Subscriber":35,"../symbol/rxSubscriber":149}],166:[function(require,module,exports){
12412 "use strict";
12413 var errorObject_1 = require('./errorObject');
12414 var tryCatchTarget;
12415 function tryCatcher() {
12416     try {
12417         return tryCatchTarget.apply(this, arguments);
12418     }
12419     catch (e) {
12420         errorObject_1.errorObject.e = e;
12421         return errorObject_1.errorObject;
12422     }
12423 }
12424 function tryCatch(fn) {
12425     tryCatchTarget = fn;
12426     return tryCatcher;
12427 }
12428 exports.tryCatch = tryCatch;
12429 ;
12430
12431 },{"./errorObject":156}],167:[function(require,module,exports){
12432 // threejs.org/license
12433 (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=
12434 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=
12435 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=
12436 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>=
12437 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,
12438 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();
12439 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}}
12440 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,
12441 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;
12442 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,
12443 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=
12444 !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=
12445 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);
12446 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}",
12447 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),
12448 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,
12449 "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],
12450 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,
12451 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<
12452 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,
12453 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,
12454 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"));
12455 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"));
12456 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=
12457 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();
12458 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,
12459 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),
12460 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,
12461 "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=
12462 !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=
12463 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=
12464 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.")}
12465 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:
12466 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=
12467 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,
12468 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=
12469 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,
12470 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);
12471 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,
12472 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!==
12473 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,
12474 {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(){}}
12475 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=
12476 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;
12477 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,
12478 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",
12479 {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",
12480 {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,
12481 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,
12482 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",
12483 "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);
12484 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);
12485 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=
12486 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===
12487 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");
12488 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=
12489 {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=
12490 {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),
12491 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,
12492 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":
12493 "",(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,
12494 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<
12495 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";
12496 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;",
12497 "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?
12498 "#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":
12499 "",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;",
12500 "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;",
12501 "\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":
12502 "",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?
12503 "#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":
12504 "",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?
12505 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,
12506 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()",
12507 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);
12508 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&&
12509 (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"},
12510 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(" ");
12511 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&&
12512 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,
12513 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,
12514 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,
12515 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=
12516 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);
12517 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)),
12518 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:
12519 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."):
12520 (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;
12521 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);
12522 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 ("+
12523 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;
12524 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,
12525 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,
12526 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,
12527 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."),
12528 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=
12529 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,
12530 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,
12531 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"))||
12532 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,
12533 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,
12534 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);
12535 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,
12536 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+
12537 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=
12538 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),
12539 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&&
12540 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");
12541 }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?
12542 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+
12543 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)):
12544 (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)),
12545 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),
12546 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!==
12547 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=
12548 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),
12549 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,
12550 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=
12551 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)},
12552 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):
12553 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===
12554 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&&
12555 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),
12556 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,
12557 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")||
12558 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");
12559 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+
12560 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;
12561 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;
12562 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-
12563 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!==
12564 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)||
12565 (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,
12566 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);
12567 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,
12568 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!==
12569 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<=
12570 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=
12571 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,
12572 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||
12573 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=
12574 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);
12575 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!==
12576 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):
12577 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,
12578 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,
12579 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,
12580 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);
12581 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;
12582 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;
12583 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;
12584 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;
12585 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"),
12586 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?
12587 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=
12588 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,
12589 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,
12590 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,
12591 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=
12592 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))};
12593 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,
12594 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);
12595 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,
12596 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,
12597 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();
12598 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&&
12599 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.");
12600 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*
12601 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,
12602 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);
12603 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=
12604 "";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++]=
12605 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);
12606 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);
12607 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),
12608 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;
12609 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]=
12610 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?
12611 (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)):
12612 (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&&
12613 (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."),
12614 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=
12615 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;
12616 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)===
12617 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,
12618 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)}
12619 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*
12620 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,
12621 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]?
12622 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=
12623 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"}
12624 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!==
12625 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=
12626 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=
12627 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+
12628 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",
12629 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=
12630 {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||
12631 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+
12632 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=
12633 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";
12634 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";
12635 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,
12636 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,
12637 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};
12638 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",
12639 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);
12640 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,
12641 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-
12642 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.");
12643 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=
12644 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",
12645 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."),
12646 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)||
12647 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<
12648 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,
12649 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)/
12650 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);
12651 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||
12652 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=
12653 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);
12654 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,
12655 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);
12656 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;
12657 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===
12658 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=
12659 {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*
12660 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++,
12661 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()}
12662 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,
12663 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));
12664 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,
12665 {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:""};
12666 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=
12667 .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;
12668 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=
12669 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=
12670 !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=
12671 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!==
12672 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=
12673 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",
12674 {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,
12675 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=
12676 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,
12677 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=
12678 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=
12679 [];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=
12680 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=
12681 !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);
12682 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);
12683 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=
12684 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=
12685 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},
12686 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=
12687 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);
12688 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=
12689 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=
12690 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);
12691 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=
12692 !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,
12693 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=
12694 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,
12695 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",
12696 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)*
12697 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",
12698 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)}
12699 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",
12700 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]),
12701 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,
12702 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,
12703 -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,
12704 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!==
12705 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},
12706 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":
12707 (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)+
12708 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,
12709 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;
12710 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,
12711 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;
12712 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,
12713 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);
12714 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))},
12715 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+
12716 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,
12717 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;
12718 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=
12719 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"})},
12720 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,
12721 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: "+
12722 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,
12723 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-=
12724 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=
12725 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>
12726 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)/
12727 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));
12728 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);
12729 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*
12730 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,
12731 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);
12732 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=
12733 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=
12734 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/
12735 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+
12736 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=
12737 .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,
12738 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+
12739 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,
12740 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);
12741 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];
12742 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<=
12743 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=
12744 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."),
12745 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;
12746 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,
12747 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;
12748 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]*
12749 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);
12750 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,
12751 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,
12752 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):
12753 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/
12754 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=
12755 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()*
12756 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=
12757 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=
12758 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}};
12759 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]=
12760 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;
12761 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-
12762 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-
12763 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-
12764 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!==
12765 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],
12766 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]=
12767 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+=
12768 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*
12769 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],
12770 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]=
12771 (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-
12772 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);
12773 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},
12774 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=
12775 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]=
12776 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},
12777 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,
12778 "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];
12779 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||
12780 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",
12781 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",
12782 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",
12783 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",
12784 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",
12785 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",
12786 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",
12787 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",
12788 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",
12789 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",
12790 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",
12791 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",
12792 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",
12793 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",
12794 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",
12795 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",
12796 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",
12797 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",
12798 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",
12799 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",
12800 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",
12801 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",
12802 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",
12803 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",
12804 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",
12805 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",
12806 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",
12807 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",
12808 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",
12809 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",
12810 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",
12811 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",
12812 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",
12813 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",
12814 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",
12815 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",
12816 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",
12817 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",
12818 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",
12819 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",
12820 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",
12821 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",
12822 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",
12823 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",
12824 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",
12825 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",
12826 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",
12827 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",
12828 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",
12829 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",
12830 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",
12831 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",
12832 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",
12833 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",
12834 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",
12835 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,
12836 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,
12837 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=
12838 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])/
12839 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!==
12840 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=
12841 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):
12842 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+=
12843 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=
12844 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,
12845 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,
12846 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,
12847 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,
12848 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,
12849 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,
12850 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}},
12851 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:{},
12852 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:{},
12853 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,
12854 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}}]),
12855 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,
12856 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,
12857 {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)},
12858 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);
12859 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-
12860 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);
12861 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."):
12862 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);
12863 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=
12864 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=
12865 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);
12866 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;
12867 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;
12868 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=
12869 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;
12870 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=
12871 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=
12872 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=
12873 {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),
12874 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();
12875 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=
12876 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);
12877 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)/
12878 (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*
12879 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()}}(),
12880 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);
12881 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);
12882 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);
12883 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},
12884 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)&&
12885 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],
12886 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;
12887 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===
12888 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()},
12889 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);
12890 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);
12891 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||
12892 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)},
12893 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===
12894 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];
12895 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)}}(),
12896 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?
12897 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);
12898 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)},
12899 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);
12900 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,
12901 -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)<=
12902 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;
12903 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=
12904 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);
12905 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},
12906 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||
12907 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>
12908 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();
12909 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];
12910 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^=
12911 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)},
12912 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;
12913 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=
12914 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"}),
12915 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]===
12916 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);
12917 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);
12918 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,
12919 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=
12920 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=
12921 [];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);
12922 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=
12923 {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)},
12924 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);
12925 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=
12926 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)},
12927 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,
12928 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=
12929 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]=
12930 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;
12931 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/
12932 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<
12933 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;
12934 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},
12935 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*
12936 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);
12937 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;
12938 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,
12939 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,
12940 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);
12941 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);
12942 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===
12943 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=
12944 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=
12945 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!==
12946 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,
12947 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===
12948 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<
12949 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]=
12950 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]=
12951 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();
12952 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===
12953 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,
12954 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);
12955 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<
12956 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=
12957 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()+
12958 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!==
12959 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,
12960 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=
12961 [];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},
12962 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."),
12963 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;
12964 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===
12965 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();
12966 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());
12967 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;
12968 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),
12969 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)},
12970 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)));
12971 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*
12972 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):
12973 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);
12974 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;
12975 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,
12976 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.",
12977 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."),
12978 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]&&
12979 (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(),
12980 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=
12981 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);
12982 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=
12983 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,
12984 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=
12985 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]),
12986 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);
12987 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,
12988 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*
12989 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*
12990 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!==
12991 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,
12992 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),
12993 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=
12994 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);
12995 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!==
12996 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);
12997 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=
12998 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)}});
12999 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-
13000 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;
13001 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<
13002 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]),
13003 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);
13004 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(),
13005 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)}});
13006 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&&
13007 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||
13008 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],
13009 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=
13010 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),
13011 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,
13012 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);
13013 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);
13014 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=
13015 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*
13016 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=
13017 !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])&&
13018 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];
13019 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]}
13020 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=
13021 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*
13022 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=
13023 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],
13024 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&&
13025 (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]]);
13026 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:
13027 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);
13028 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],
13029 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=
13030 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=
13031 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=
13032 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);
13033 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=
13034 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,
13035 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,
13036 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=
13037 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=
13038 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;
13039 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,
13040 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=
13041 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=
13042 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);
13043 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=
13044 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=
13045 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=
13046 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,
13047 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)?,(.*)$/);
13048 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&&
13049 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&&
13050 (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,
13051 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,
13052 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");
13053 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===
13054 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);
13055 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);
13056 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},
13057 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&&
13058 (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);
13059 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),
13060 {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();
13061 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();
13062 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=
13063 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],
13064 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&&
13065 (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||
13066 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},
13067 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,
13068 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;
13069 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,
13070 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);
13071 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=
13072 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",
13073 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,
13074 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"});
13075 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});
13076 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});
13077 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=
13078 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;
13079 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,
13080 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),
13081 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,
13082 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]]=
13083 -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=
13084 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);
13085 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!==
13086 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&&
13087 (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=
13088 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=
13089 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<
13090 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),
13091 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=
13092 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=
13093 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:",
13094 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,
13095 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;
13096 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);
13097 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);
13098 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;
13099 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"===
13100 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);
13101 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,
13102 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+
13103 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++],
13104 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*
13105 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],
13106 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=
13107 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);
13108 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}}});
13109 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=
13110 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,
13111 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,
13112 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=
13113 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=
13114 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=
13115 [],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,
13116 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));
13117 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",
13118 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=
13119 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,
13120 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));
13121 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&&
13122 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);
13123 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/
13124 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),
13125 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=
13126 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-
13127 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);
13128 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),
13129 {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=
13130 !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=
13131 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];
13132 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),
13133 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)*
13134 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,
13135 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=
13136 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(),
13137 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,
13138 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);
13139 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,
13140 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<=
13141 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=
13142 !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("");
13143 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=
13144 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;
13145 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,
13146 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;
13147 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);
13148 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);
13149 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),
13150 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,
13151 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.");
13152 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.");
13153 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-
13154 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.");
13155 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=
13156 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=
13157 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);
13158 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&&
13159 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=
13160 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",
13161 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===
13162 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"===
13163 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?
13164 (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(){},
13165 _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,
13166 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,
13167 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,
13168 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_,
13169 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]};
13170 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};
13171 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=
13172 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]=
13173 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(),
13174 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=
13175 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&&
13176 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,
13177 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},
13178 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=
13179 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,
13180 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===
13181 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,
13182 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,
13183 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,
13184 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=
13185 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},
13186 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=
13187 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=
13188 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,
13189 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=
13190 {};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;
13191 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=
13192 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=
13193 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;
13194 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),
13195 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;
13196 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},
13197 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*
13198 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+
13199 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*=
13200 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;
13201 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()):
13202 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);
13203 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,
13204 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,
13205 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,
13206 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,
13207 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)/
13208 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["+
13209 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+=
13210 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);
13211 $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<
13212 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,
13213 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));
13214 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<
13215 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)};
13216 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);
13217 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=
13218 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());
13219 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=
13220 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()};
13221 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);
13222 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",
13223 -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]=
13224 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(),
13225 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,
13226 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=
13227 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:
13228 .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),
13229 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=
13230 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);
13231 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().");
13232 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().");
13233 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().");
13234 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)},
13235 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().");
13236 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().");
13237 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.");
13238 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.")},
13239 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().");
13240 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().");
13241 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,
13242 {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().");
13243 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.")},
13244 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.")},
13245 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,
13246 {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.");
13247 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.")}},
13248 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,
13249 {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,
13250 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.");
13251 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+
13252 ": .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.");
13253 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' ).");
13254 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' ).");
13255 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.");
13256 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.")},
13257 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.");
13258 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,
13259 {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.");
13260 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.");
13261 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},
13262 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.");
13263 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};
13264 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=
13265 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=
13266 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=
13267 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=
13268 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]];
13269 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),
13270 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=
13271 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=
13272 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,
13273 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=
13274 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=
13275 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=
13276 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;
13277 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=
13278 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=
13279 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;
13280 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=
13281 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=
13282 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,
13283 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)};
13284 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.");
13285 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=
13286 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.");
13287 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!==
13288 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.");
13289 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},
13290 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.")}};
13291 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");
13292 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})});
13293
13294 },{}],168:[function(require,module,exports){
13295 //     Underscore.js 1.8.3
13296 //     http://underscorejs.org
13297 //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
13298 //     Underscore may be freely distributed under the MIT license.
13299
13300 (function() {
13301
13302   // Baseline setup
13303   // --------------
13304
13305   // Establish the root object, `window` in the browser, or `exports` on the server.
13306   var root = this;
13307
13308   // Save the previous value of the `_` variable.
13309   var previousUnderscore = root._;
13310
13311   // Save bytes in the minified (but not gzipped) version:
13312   var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
13313
13314   // Create quick reference variables for speed access to core prototypes.
13315   var
13316     push             = ArrayProto.push,
13317     slice            = ArrayProto.slice,
13318     toString         = ObjProto.toString,
13319     hasOwnProperty   = ObjProto.hasOwnProperty;
13320
13321   // All **ECMAScript 5** native function implementations that we hope to use
13322   // are declared here.
13323   var
13324     nativeIsArray      = Array.isArray,
13325     nativeKeys         = Object.keys,
13326     nativeBind         = FuncProto.bind,
13327     nativeCreate       = Object.create;
13328
13329   // Naked function reference for surrogate-prototype-swapping.
13330   var Ctor = function(){};
13331
13332   // Create a safe reference to the Underscore object for use below.
13333   var _ = function(obj) {
13334     if (obj instanceof _) return obj;
13335     if (!(this instanceof _)) return new _(obj);
13336     this._wrapped = obj;
13337   };
13338
13339   // Export the Underscore object for **Node.js**, with
13340   // backwards-compatibility for the old `require()` API. If we're in
13341   // the browser, add `_` as a global object.
13342   if (typeof exports !== 'undefined') {
13343     if (typeof module !== 'undefined' && module.exports) {
13344       exports = module.exports = _;
13345     }
13346     exports._ = _;
13347   } else {
13348     root._ = _;
13349   }
13350
13351   // Current version.
13352   _.VERSION = '1.8.3';
13353
13354   // Internal function that returns an efficient (for current engines) version
13355   // of the passed-in callback, to be repeatedly applied in other Underscore
13356   // functions.
13357   var optimizeCb = function(func, context, argCount) {
13358     if (context === void 0) return func;
13359     switch (argCount == null ? 3 : argCount) {
13360       case 1: return function(value) {
13361         return func.call(context, value);
13362       };
13363       case 2: return function(value, other) {
13364         return func.call(context, value, other);
13365       };
13366       case 3: return function(value, index, collection) {
13367         return func.call(context, value, index, collection);
13368       };
13369       case 4: return function(accumulator, value, index, collection) {
13370         return func.call(context, accumulator, value, index, collection);
13371       };
13372     }
13373     return function() {
13374       return func.apply(context, arguments);
13375     };
13376   };
13377
13378   // A mostly-internal function to generate callbacks that can be applied
13379   // to each element in a collection, returning the desired result — either
13380   // identity, an arbitrary callback, a property matcher, or a property accessor.
13381   var cb = function(value, context, argCount) {
13382     if (value == null) return _.identity;
13383     if (_.isFunction(value)) return optimizeCb(value, context, argCount);
13384     if (_.isObject(value)) return _.matcher(value);
13385     return _.property(value);
13386   };
13387   _.iteratee = function(value, context) {
13388     return cb(value, context, Infinity);
13389   };
13390
13391   // An internal function for creating assigner functions.
13392   var createAssigner = function(keysFunc, undefinedOnly) {
13393     return function(obj) {
13394       var length = arguments.length;
13395       if (length < 2 || obj == null) return obj;
13396       for (var index = 1; index < length; index++) {
13397         var source = arguments[index],
13398             keys = keysFunc(source),
13399             l = keys.length;
13400         for (var i = 0; i < l; i++) {
13401           var key = keys[i];
13402           if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
13403         }
13404       }
13405       return obj;
13406     };
13407   };
13408
13409   // An internal function for creating a new object that inherits from another.
13410   var baseCreate = function(prototype) {
13411     if (!_.isObject(prototype)) return {};
13412     if (nativeCreate) return nativeCreate(prototype);
13413     Ctor.prototype = prototype;
13414     var result = new Ctor;
13415     Ctor.prototype = null;
13416     return result;
13417   };
13418
13419   var property = function(key) {
13420     return function(obj) {
13421       return obj == null ? void 0 : obj[key];
13422     };
13423   };
13424
13425   // Helper for collection methods to determine whether a collection
13426   // should be iterated as an array or as an object
13427   // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
13428   // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
13429   var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
13430   var getLength = property('length');
13431   var isArrayLike = function(collection) {
13432     var length = getLength(collection);
13433     return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
13434   };
13435
13436   // Collection Functions
13437   // --------------------
13438
13439   // The cornerstone, an `each` implementation, aka `forEach`.
13440   // Handles raw objects in addition to array-likes. Treats all
13441   // sparse array-likes as if they were dense.
13442   _.each = _.forEach = function(obj, iteratee, context) {
13443     iteratee = optimizeCb(iteratee, context);
13444     var i, length;
13445     if (isArrayLike(obj)) {
13446       for (i = 0, length = obj.length; i < length; i++) {
13447         iteratee(obj[i], i, obj);
13448       }
13449     } else {
13450       var keys = _.keys(obj);
13451       for (i = 0, length = keys.length; i < length; i++) {
13452         iteratee(obj[keys[i]], keys[i], obj);
13453       }
13454     }
13455     return obj;
13456   };
13457
13458   // Return the results of applying the iteratee to each element.
13459   _.map = _.collect = function(obj, iteratee, context) {
13460     iteratee = cb(iteratee, context);
13461     var keys = !isArrayLike(obj) && _.keys(obj),
13462         length = (keys || obj).length,
13463         results = Array(length);
13464     for (var index = 0; index < length; index++) {
13465       var currentKey = keys ? keys[index] : index;
13466       results[index] = iteratee(obj[currentKey], currentKey, obj);
13467     }
13468     return results;
13469   };
13470
13471   // Create a reducing function iterating left or right.
13472   function createReduce(dir) {
13473     // Optimized iterator function as using arguments.length
13474     // in the main function will deoptimize the, see #1991.
13475     function iterator(obj, iteratee, memo, keys, index, length) {
13476       for (; index >= 0 && index < length; index += dir) {
13477         var currentKey = keys ? keys[index] : index;
13478         memo = iteratee(memo, obj[currentKey], currentKey, obj);
13479       }
13480       return memo;
13481     }
13482
13483     return function(obj, iteratee, memo, context) {
13484       iteratee = optimizeCb(iteratee, context, 4);
13485       var keys = !isArrayLike(obj) && _.keys(obj),
13486           length = (keys || obj).length,
13487           index = dir > 0 ? 0 : length - 1;
13488       // Determine the initial value if none is provided.
13489       if (arguments.length < 3) {
13490         memo = obj[keys ? keys[index] : index];
13491         index += dir;
13492       }
13493       return iterator(obj, iteratee, memo, keys, index, length);
13494     };
13495   }
13496
13497   // **Reduce** builds up a single result from a list of values, aka `inject`,
13498   // or `foldl`.
13499   _.reduce = _.foldl = _.inject = createReduce(1);
13500
13501   // The right-associative version of reduce, also known as `foldr`.
13502   _.reduceRight = _.foldr = createReduce(-1);
13503
13504   // Return the first value which passes a truth test. Aliased as `detect`.
13505   _.find = _.detect = function(obj, predicate, context) {
13506     var key;
13507     if (isArrayLike(obj)) {
13508       key = _.findIndex(obj, predicate, context);
13509     } else {
13510       key = _.findKey(obj, predicate, context);
13511     }
13512     if (key !== void 0 && key !== -1) return obj[key];
13513   };
13514
13515   // Return all the elements that pass a truth test.
13516   // Aliased as `select`.
13517   _.filter = _.select = function(obj, predicate, context) {
13518     var results = [];
13519     predicate = cb(predicate, context);
13520     _.each(obj, function(value, index, list) {
13521       if (predicate(value, index, list)) results.push(value);
13522     });
13523     return results;
13524   };
13525
13526   // Return all the elements for which a truth test fails.
13527   _.reject = function(obj, predicate, context) {
13528     return _.filter(obj, _.negate(cb(predicate)), context);
13529   };
13530
13531   // Determine whether all of the elements match a truth test.
13532   // Aliased as `all`.
13533   _.every = _.all = function(obj, predicate, context) {
13534     predicate = cb(predicate, context);
13535     var keys = !isArrayLike(obj) && _.keys(obj),
13536         length = (keys || obj).length;
13537     for (var index = 0; index < length; index++) {
13538       var currentKey = keys ? keys[index] : index;
13539       if (!predicate(obj[currentKey], currentKey, obj)) return false;
13540     }
13541     return true;
13542   };
13543
13544   // Determine if at least one element in the object matches a truth test.
13545   // Aliased as `any`.
13546   _.some = _.any = function(obj, predicate, context) {
13547     predicate = cb(predicate, context);
13548     var keys = !isArrayLike(obj) && _.keys(obj),
13549         length = (keys || obj).length;
13550     for (var index = 0; index < length; index++) {
13551       var currentKey = keys ? keys[index] : index;
13552       if (predicate(obj[currentKey], currentKey, obj)) return true;
13553     }
13554     return false;
13555   };
13556
13557   // Determine if the array or object contains a given item (using `===`).
13558   // Aliased as `includes` and `include`.
13559   _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
13560     if (!isArrayLike(obj)) obj = _.values(obj);
13561     if (typeof fromIndex != 'number' || guard) fromIndex = 0;
13562     return _.indexOf(obj, item, fromIndex) >= 0;
13563   };
13564
13565   // Invoke a method (with arguments) on every item in a collection.
13566   _.invoke = function(obj, method) {
13567     var args = slice.call(arguments, 2);
13568     var isFunc = _.isFunction(method);
13569     return _.map(obj, function(value) {
13570       var func = isFunc ? method : value[method];
13571       return func == null ? func : func.apply(value, args);
13572     });
13573   };
13574
13575   // Convenience version of a common use case of `map`: fetching a property.
13576   _.pluck = function(obj, key) {
13577     return _.map(obj, _.property(key));
13578   };
13579
13580   // Convenience version of a common use case of `filter`: selecting only objects
13581   // containing specific `key:value` pairs.
13582   _.where = function(obj, attrs) {
13583     return _.filter(obj, _.matcher(attrs));
13584   };
13585
13586   // Convenience version of a common use case of `find`: getting the first object
13587   // containing specific `key:value` pairs.
13588   _.findWhere = function(obj, attrs) {
13589     return _.find(obj, _.matcher(attrs));
13590   };
13591
13592   // Return the maximum element (or element-based computation).
13593   _.max = function(obj, iteratee, context) {
13594     var result = -Infinity, lastComputed = -Infinity,
13595         value, computed;
13596     if (iteratee == null && obj != null) {
13597       obj = isArrayLike(obj) ? obj : _.values(obj);
13598       for (var i = 0, length = obj.length; i < length; i++) {
13599         value = obj[i];
13600         if (value > result) {
13601           result = value;
13602         }
13603       }
13604     } else {
13605       iteratee = cb(iteratee, context);
13606       _.each(obj, function(value, index, list) {
13607         computed = iteratee(value, index, list);
13608         if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
13609           result = value;
13610           lastComputed = computed;
13611         }
13612       });
13613     }
13614     return result;
13615   };
13616
13617   // Return the minimum element (or element-based computation).
13618   _.min = function(obj, iteratee, context) {
13619     var result = Infinity, lastComputed = Infinity,
13620         value, computed;
13621     if (iteratee == null && obj != null) {
13622       obj = isArrayLike(obj) ? obj : _.values(obj);
13623       for (var i = 0, length = obj.length; i < length; i++) {
13624         value = obj[i];
13625         if (value < result) {
13626           result = value;
13627         }
13628       }
13629     } else {
13630       iteratee = cb(iteratee, context);
13631       _.each(obj, function(value, index, list) {
13632         computed = iteratee(value, index, list);
13633         if (computed < lastComputed || computed === Infinity && result === Infinity) {
13634           result = value;
13635           lastComputed = computed;
13636         }
13637       });
13638     }
13639     return result;
13640   };
13641
13642   // Shuffle a collection, using the modern version of the
13643   // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
13644   _.shuffle = function(obj) {
13645     var set = isArrayLike(obj) ? obj : _.values(obj);
13646     var length = set.length;
13647     var shuffled = Array(length);
13648     for (var index = 0, rand; index < length; index++) {
13649       rand = _.random(0, index);
13650       if (rand !== index) shuffled[index] = shuffled[rand];
13651       shuffled[rand] = set[index];
13652     }
13653     return shuffled;
13654   };
13655
13656   // Sample **n** random values from a collection.
13657   // If **n** is not specified, returns a single random element.
13658   // The internal `guard` argument allows it to work with `map`.
13659   _.sample = function(obj, n, guard) {
13660     if (n == null || guard) {
13661       if (!isArrayLike(obj)) obj = _.values(obj);
13662       return obj[_.random(obj.length - 1)];
13663     }
13664     return _.shuffle(obj).slice(0, Math.max(0, n));
13665   };
13666
13667   // Sort the object's values by a criterion produced by an iteratee.
13668   _.sortBy = function(obj, iteratee, context) {
13669     iteratee = cb(iteratee, context);
13670     return _.pluck(_.map(obj, function(value, index, list) {
13671       return {
13672         value: value,
13673         index: index,
13674         criteria: iteratee(value, index, list)
13675       };
13676     }).sort(function(left, right) {
13677       var a = left.criteria;
13678       var b = right.criteria;
13679       if (a !== b) {
13680         if (a > b || a === void 0) return 1;
13681         if (a < b || b === void 0) return -1;
13682       }
13683       return left.index - right.index;
13684     }), 'value');
13685   };
13686
13687   // An internal function used for aggregate "group by" operations.
13688   var group = function(behavior) {
13689     return function(obj, iteratee, context) {
13690       var result = {};
13691       iteratee = cb(iteratee, context);
13692       _.each(obj, function(value, index) {
13693         var key = iteratee(value, index, obj);
13694         behavior(result, value, key);
13695       });
13696       return result;
13697     };
13698   };
13699
13700   // Groups the object's values by a criterion. Pass either a string attribute
13701   // to group by, or a function that returns the criterion.
13702   _.groupBy = group(function(result, value, key) {
13703     if (_.has(result, key)) result[key].push(value); else result[key] = [value];
13704   });
13705
13706   // Indexes the object's values by a criterion, similar to `groupBy`, but for
13707   // when you know that your index values will be unique.
13708   _.indexBy = group(function(result, value, key) {
13709     result[key] = value;
13710   });
13711
13712   // Counts instances of an object that group by a certain criterion. Pass
13713   // either a string attribute to count by, or a function that returns the
13714   // criterion.
13715   _.countBy = group(function(result, value, key) {
13716     if (_.has(result, key)) result[key]++; else result[key] = 1;
13717   });
13718
13719   // Safely create a real, live array from anything iterable.
13720   _.toArray = function(obj) {
13721     if (!obj) return [];
13722     if (_.isArray(obj)) return slice.call(obj);
13723     if (isArrayLike(obj)) return _.map(obj, _.identity);
13724     return _.values(obj);
13725   };
13726
13727   // Return the number of elements in an object.
13728   _.size = function(obj) {
13729     if (obj == null) return 0;
13730     return isArrayLike(obj) ? obj.length : _.keys(obj).length;
13731   };
13732
13733   // Split a collection into two arrays: one whose elements all satisfy the given
13734   // predicate, and one whose elements all do not satisfy the predicate.
13735   _.partition = function(obj, predicate, context) {
13736     predicate = cb(predicate, context);
13737     var pass = [], fail = [];
13738     _.each(obj, function(value, key, obj) {
13739       (predicate(value, key, obj) ? pass : fail).push(value);
13740     });
13741     return [pass, fail];
13742   };
13743
13744   // Array Functions
13745   // ---------------
13746
13747   // Get the first element of an array. Passing **n** will return the first N
13748   // values in the array. Aliased as `head` and `take`. The **guard** check
13749   // allows it to work with `_.map`.
13750   _.first = _.head = _.take = function(array, n, guard) {
13751     if (array == null) return void 0;
13752     if (n == null || guard) return array[0];
13753     return _.initial(array, array.length - n);
13754   };
13755
13756   // Returns everything but the last entry of the array. Especially useful on
13757   // the arguments object. Passing **n** will return all the values in
13758   // the array, excluding the last N.
13759   _.initial = function(array, n, guard) {
13760     return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
13761   };
13762
13763   // Get the last element of an array. Passing **n** will return the last N
13764   // values in the array.
13765   _.last = function(array, n, guard) {
13766     if (array == null) return void 0;
13767     if (n == null || guard) return array[array.length - 1];
13768     return _.rest(array, Math.max(0, array.length - n));
13769   };
13770
13771   // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
13772   // Especially useful on the arguments object. Passing an **n** will return
13773   // the rest N values in the array.
13774   _.rest = _.tail = _.drop = function(array, n, guard) {
13775     return slice.call(array, n == null || guard ? 1 : n);
13776   };
13777
13778   // Trim out all falsy values from an array.
13779   _.compact = function(array) {
13780     return _.filter(array, _.identity);
13781   };
13782
13783   // Internal implementation of a recursive `flatten` function.
13784   var flatten = function(input, shallow, strict, startIndex) {
13785     var output = [], idx = 0;
13786     for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
13787       var value = input[i];
13788       if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
13789         //flatten current level of array or arguments object
13790         if (!shallow) value = flatten(value, shallow, strict);
13791         var j = 0, len = value.length;
13792         output.length += len;
13793         while (j < len) {
13794           output[idx++] = value[j++];
13795         }
13796       } else if (!strict) {
13797         output[idx++] = value;
13798       }
13799     }
13800     return output;
13801   };
13802
13803   // Flatten out an array, either recursively (by default), or just one level.
13804   _.flatten = function(array, shallow) {
13805     return flatten(array, shallow, false);
13806   };
13807
13808   // Return a version of the array that does not contain the specified value(s).
13809   _.without = function(array) {
13810     return _.difference(array, slice.call(arguments, 1));
13811   };
13812
13813   // Produce a duplicate-free version of the array. If the array has already
13814   // been sorted, you have the option of using a faster algorithm.
13815   // Aliased as `unique`.
13816   _.uniq = _.unique = function(array, isSorted, iteratee, context) {
13817     if (!_.isBoolean(isSorted)) {
13818       context = iteratee;
13819       iteratee = isSorted;
13820       isSorted = false;
13821     }
13822     if (iteratee != null) iteratee = cb(iteratee, context);
13823     var result = [];
13824     var seen = [];
13825     for (var i = 0, length = getLength(array); i < length; i++) {
13826       var value = array[i],
13827           computed = iteratee ? iteratee(value, i, array) : value;
13828       if (isSorted) {
13829         if (!i || seen !== computed) result.push(value);
13830         seen = computed;
13831       } else if (iteratee) {
13832         if (!_.contains(seen, computed)) {
13833           seen.push(computed);
13834           result.push(value);
13835         }
13836       } else if (!_.contains(result, value)) {
13837         result.push(value);
13838       }
13839     }
13840     return result;
13841   };
13842
13843   // Produce an array that contains the union: each distinct element from all of
13844   // the passed-in arrays.
13845   _.union = function() {
13846     return _.uniq(flatten(arguments, true, true));
13847   };
13848
13849   // Produce an array that contains every item shared between all the
13850   // passed-in arrays.
13851   _.intersection = function(array) {
13852     var result = [];
13853     var argsLength = arguments.length;
13854     for (var i = 0, length = getLength(array); i < length; i++) {
13855       var item = array[i];
13856       if (_.contains(result, item)) continue;
13857       for (var j = 1; j < argsLength; j++) {
13858         if (!_.contains(arguments[j], item)) break;
13859       }
13860       if (j === argsLength) result.push(item);
13861     }
13862     return result;
13863   };
13864
13865   // Take the difference between one array and a number of other arrays.
13866   // Only the elements present in just the first array will remain.
13867   _.difference = function(array) {
13868     var rest = flatten(arguments, true, true, 1);
13869     return _.filter(array, function(value){
13870       return !_.contains(rest, value);
13871     });
13872   };
13873
13874   // Zip together multiple lists into a single array -- elements that share
13875   // an index go together.
13876   _.zip = function() {
13877     return _.unzip(arguments);
13878   };
13879
13880   // Complement of _.zip. Unzip accepts an array of arrays and groups
13881   // each array's elements on shared indices
13882   _.unzip = function(array) {
13883     var length = array && _.max(array, getLength).length || 0;
13884     var result = Array(length);
13885
13886     for (var index = 0; index < length; index++) {
13887       result[index] = _.pluck(array, index);
13888     }
13889     return result;
13890   };
13891
13892   // Converts lists into objects. Pass either a single array of `[key, value]`
13893   // pairs, or two parallel arrays of the same length -- one of keys, and one of
13894   // the corresponding values.
13895   _.object = function(list, values) {
13896     var result = {};
13897     for (var i = 0, length = getLength(list); i < length; i++) {
13898       if (values) {
13899         result[list[i]] = values[i];
13900       } else {
13901         result[list[i][0]] = list[i][1];
13902       }
13903     }
13904     return result;
13905   };
13906
13907   // Generator function to create the findIndex and findLastIndex functions
13908   function createPredicateIndexFinder(dir) {
13909     return function(array, predicate, context) {
13910       predicate = cb(predicate, context);
13911       var length = getLength(array);
13912       var index = dir > 0 ? 0 : length - 1;
13913       for (; index >= 0 && index < length; index += dir) {
13914         if (predicate(array[index], index, array)) return index;
13915       }
13916       return -1;
13917     };
13918   }
13919
13920   // Returns the first index on an array-like that passes a predicate test
13921   _.findIndex = createPredicateIndexFinder(1);
13922   _.findLastIndex = createPredicateIndexFinder(-1);
13923
13924   // Use a comparator function to figure out the smallest index at which
13925   // an object should be inserted so as to maintain order. Uses binary search.
13926   _.sortedIndex = function(array, obj, iteratee, context) {
13927     iteratee = cb(iteratee, context, 1);
13928     var value = iteratee(obj);
13929     var low = 0, high = getLength(array);
13930     while (low < high) {
13931       var mid = Math.floor((low + high) / 2);
13932       if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
13933     }
13934     return low;
13935   };
13936
13937   // Generator function to create the indexOf and lastIndexOf functions
13938   function createIndexFinder(dir, predicateFind, sortedIndex) {
13939     return function(array, item, idx) {
13940       var i = 0, length = getLength(array);
13941       if (typeof idx == 'number') {
13942         if (dir > 0) {
13943             i = idx >= 0 ? idx : Math.max(idx + length, i);
13944         } else {
13945             length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
13946         }
13947       } else if (sortedIndex && idx && length) {
13948         idx = sortedIndex(array, item);
13949         return array[idx] === item ? idx : -1;
13950       }
13951       if (item !== item) {
13952         idx = predicateFind(slice.call(array, i, length), _.isNaN);
13953         return idx >= 0 ? idx + i : -1;
13954       }
13955       for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
13956         if (array[idx] === item) return idx;
13957       }
13958       return -1;
13959     };
13960   }
13961
13962   // Return the position of the first occurrence of an item in an array,
13963   // or -1 if the item is not included in the array.
13964   // If the array is large and already in sort order, pass `true`
13965   // for **isSorted** to use binary search.
13966   _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
13967   _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
13968
13969   // Generate an integer Array containing an arithmetic progression. A port of
13970   // the native Python `range()` function. See
13971   // [the Python documentation](http://docs.python.org/library/functions.html#range).
13972   _.range = function(start, stop, step) {
13973     if (stop == null) {
13974       stop = start || 0;
13975       start = 0;
13976     }
13977     step = step || 1;
13978
13979     var length = Math.max(Math.ceil((stop - start) / step), 0);
13980     var range = Array(length);
13981
13982     for (var idx = 0; idx < length; idx++, start += step) {
13983       range[idx] = start;
13984     }
13985
13986     return range;
13987   };
13988
13989   // Function (ahem) Functions
13990   // ------------------
13991
13992   // Determines whether to execute a function as a constructor
13993   // or a normal function with the provided arguments
13994   var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
13995     if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
13996     var self = baseCreate(sourceFunc.prototype);
13997     var result = sourceFunc.apply(self, args);
13998     if (_.isObject(result)) return result;
13999     return self;
14000   };
14001
14002   // Create a function bound to a given object (assigning `this`, and arguments,
14003   // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
14004   // available.
14005   _.bind = function(func, context) {
14006     if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
14007     if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
14008     var args = slice.call(arguments, 2);
14009     var bound = function() {
14010       return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
14011     };
14012     return bound;
14013   };
14014
14015   // Partially apply a function by creating a version that has had some of its
14016   // arguments pre-filled, without changing its dynamic `this` context. _ acts
14017   // as a placeholder, allowing any combination of arguments to be pre-filled.
14018   _.partial = function(func) {
14019     var boundArgs = slice.call(arguments, 1);
14020     var bound = function() {
14021       var position = 0, length = boundArgs.length;
14022       var args = Array(length);
14023       for (var i = 0; i < length; i++) {
14024         args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
14025       }
14026       while (position < arguments.length) args.push(arguments[position++]);
14027       return executeBound(func, bound, this, this, args);
14028     };
14029     return bound;
14030   };
14031
14032   // Bind a number of an object's methods to that object. Remaining arguments
14033   // are the method names to be bound. Useful for ensuring that all callbacks
14034   // defined on an object belong to it.
14035   _.bindAll = function(obj) {
14036     var i, length = arguments.length, key;
14037     if (length <= 1) throw new Error('bindAll must be passed function names');
14038     for (i = 1; i < length; i++) {
14039       key = arguments[i];
14040       obj[key] = _.bind(obj[key], obj);
14041     }
14042     return obj;
14043   };
14044
14045   // Memoize an expensive function by storing its results.
14046   _.memoize = function(func, hasher) {
14047     var memoize = function(key) {
14048       var cache = memoize.cache;
14049       var address = '' + (hasher ? hasher.apply(this, arguments) : key);
14050       if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
14051       return cache[address];
14052     };
14053     memoize.cache = {};
14054     return memoize;
14055   };
14056
14057   // Delays a function for the given number of milliseconds, and then calls
14058   // it with the arguments supplied.
14059   _.delay = function(func, wait) {
14060     var args = slice.call(arguments, 2);
14061     return setTimeout(function(){
14062       return func.apply(null, args);
14063     }, wait);
14064   };
14065
14066   // Defers a function, scheduling it to run after the current call stack has
14067   // cleared.
14068   _.defer = _.partial(_.delay, _, 1);
14069
14070   // Returns a function, that, when invoked, will only be triggered at most once
14071   // during a given window of time. Normally, the throttled function will run
14072   // as much as it can, without ever going more than once per `wait` duration;
14073   // but if you'd like to disable the execution on the leading edge, pass
14074   // `{leading: false}`. To disable execution on the trailing edge, ditto.
14075   _.throttle = function(func, wait, options) {
14076     var context, args, result;
14077     var timeout = null;
14078     var previous = 0;
14079     if (!options) options = {};
14080     var later = function() {
14081       previous = options.leading === false ? 0 : _.now();
14082       timeout = null;
14083       result = func.apply(context, args);
14084       if (!timeout) context = args = null;
14085     };
14086     return function() {
14087       var now = _.now();
14088       if (!previous && options.leading === false) previous = now;
14089       var remaining = wait - (now - previous);
14090       context = this;
14091       args = arguments;
14092       if (remaining <= 0 || remaining > wait) {
14093         if (timeout) {
14094           clearTimeout(timeout);
14095           timeout = null;
14096         }
14097         previous = now;
14098         result = func.apply(context, args);
14099         if (!timeout) context = args = null;
14100       } else if (!timeout && options.trailing !== false) {
14101         timeout = setTimeout(later, remaining);
14102       }
14103       return result;
14104     };
14105   };
14106
14107   // Returns a function, that, as long as it continues to be invoked, will not
14108   // be triggered. The function will be called after it stops being called for
14109   // N milliseconds. If `immediate` is passed, trigger the function on the
14110   // leading edge, instead of the trailing.
14111   _.debounce = function(func, wait, immediate) {
14112     var timeout, args, context, timestamp, result;
14113
14114     var later = function() {
14115       var last = _.now() - timestamp;
14116
14117       if (last < wait && last >= 0) {
14118         timeout = setTimeout(later, wait - last);
14119       } else {
14120         timeout = null;
14121         if (!immediate) {
14122           result = func.apply(context, args);
14123           if (!timeout) context = args = null;
14124         }
14125       }
14126     };
14127
14128     return function() {
14129       context = this;
14130       args = arguments;
14131       timestamp = _.now();
14132       var callNow = immediate && !timeout;
14133       if (!timeout) timeout = setTimeout(later, wait);
14134       if (callNow) {
14135         result = func.apply(context, args);
14136         context = args = null;
14137       }
14138
14139       return result;
14140     };
14141   };
14142
14143   // Returns the first function passed as an argument to the second,
14144   // allowing you to adjust arguments, run code before and after, and
14145   // conditionally execute the original function.
14146   _.wrap = function(func, wrapper) {
14147     return _.partial(wrapper, func);
14148   };
14149
14150   // Returns a negated version of the passed-in predicate.
14151   _.negate = function(predicate) {
14152     return function() {
14153       return !predicate.apply(this, arguments);
14154     };
14155   };
14156
14157   // Returns a function that is the composition of a list of functions, each
14158   // consuming the return value of the function that follows.
14159   _.compose = function() {
14160     var args = arguments;
14161     var start = args.length - 1;
14162     return function() {
14163       var i = start;
14164       var result = args[start].apply(this, arguments);
14165       while (i--) result = args[i].call(this, result);
14166       return result;
14167     };
14168   };
14169
14170   // Returns a function that will only be executed on and after the Nth call.
14171   _.after = function(times, func) {
14172     return function() {
14173       if (--times < 1) {
14174         return func.apply(this, arguments);
14175       }
14176     };
14177   };
14178
14179   // Returns a function that will only be executed up to (but not including) the Nth call.
14180   _.before = function(times, func) {
14181     var memo;
14182     return function() {
14183       if (--times > 0) {
14184         memo = func.apply(this, arguments);
14185       }
14186       if (times <= 1) func = null;
14187       return memo;
14188     };
14189   };
14190
14191   // Returns a function that will be executed at most one time, no matter how
14192   // often you call it. Useful for lazy initialization.
14193   _.once = _.partial(_.before, 2);
14194
14195   // Object Functions
14196   // ----------------
14197
14198   // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
14199   var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
14200   var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
14201                       'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
14202
14203   function collectNonEnumProps(obj, keys) {
14204     var nonEnumIdx = nonEnumerableProps.length;
14205     var constructor = obj.constructor;
14206     var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
14207
14208     // Constructor is a special case.
14209     var prop = 'constructor';
14210     if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
14211
14212     while (nonEnumIdx--) {
14213       prop = nonEnumerableProps[nonEnumIdx];
14214       if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
14215         keys.push(prop);
14216       }
14217     }
14218   }
14219
14220   // Retrieve the names of an object's own properties.
14221   // Delegates to **ECMAScript 5**'s native `Object.keys`
14222   _.keys = function(obj) {
14223     if (!_.isObject(obj)) return [];
14224     if (nativeKeys) return nativeKeys(obj);
14225     var keys = [];
14226     for (var key in obj) if (_.has(obj, key)) keys.push(key);
14227     // Ahem, IE < 9.
14228     if (hasEnumBug) collectNonEnumProps(obj, keys);
14229     return keys;
14230   };
14231
14232   // Retrieve all the property names of an object.
14233   _.allKeys = function(obj) {
14234     if (!_.isObject(obj)) return [];
14235     var keys = [];
14236     for (var key in obj) keys.push(key);
14237     // Ahem, IE < 9.
14238     if (hasEnumBug) collectNonEnumProps(obj, keys);
14239     return keys;
14240   };
14241
14242   // Retrieve the values of an object's properties.
14243   _.values = function(obj) {
14244     var keys = _.keys(obj);
14245     var length = keys.length;
14246     var values = Array(length);
14247     for (var i = 0; i < length; i++) {
14248       values[i] = obj[keys[i]];
14249     }
14250     return values;
14251   };
14252
14253   // Returns the results of applying the iteratee to each element of the object
14254   // In contrast to _.map it returns an object
14255   _.mapObject = function(obj, iteratee, context) {
14256     iteratee = cb(iteratee, context);
14257     var keys =  _.keys(obj),
14258           length = keys.length,
14259           results = {},
14260           currentKey;
14261       for (var index = 0; index < length; index++) {
14262         currentKey = keys[index];
14263         results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
14264       }
14265       return results;
14266   };
14267
14268   // Convert an object into a list of `[key, value]` pairs.
14269   _.pairs = function(obj) {
14270     var keys = _.keys(obj);
14271     var length = keys.length;
14272     var pairs = Array(length);
14273     for (var i = 0; i < length; i++) {
14274       pairs[i] = [keys[i], obj[keys[i]]];
14275     }
14276     return pairs;
14277   };
14278
14279   // Invert the keys and values of an object. The values must be serializable.
14280   _.invert = function(obj) {
14281     var result = {};
14282     var keys = _.keys(obj);
14283     for (var i = 0, length = keys.length; i < length; i++) {
14284       result[obj[keys[i]]] = keys[i];
14285     }
14286     return result;
14287   };
14288
14289   // Return a sorted list of the function names available on the object.
14290   // Aliased as `methods`
14291   _.functions = _.methods = function(obj) {
14292     var names = [];
14293     for (var key in obj) {
14294       if (_.isFunction(obj[key])) names.push(key);
14295     }
14296     return names.sort();
14297   };
14298
14299   // Extend a given object with all the properties in passed-in object(s).
14300   _.extend = createAssigner(_.allKeys);
14301
14302   // Assigns a given object with all the own properties in the passed-in object(s)
14303   // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
14304   _.extendOwn = _.assign = createAssigner(_.keys);
14305
14306   // Returns the first key on an object that passes a predicate test
14307   _.findKey = function(obj, predicate, context) {
14308     predicate = cb(predicate, context);
14309     var keys = _.keys(obj), key;
14310     for (var i = 0, length = keys.length; i < length; i++) {
14311       key = keys[i];
14312       if (predicate(obj[key], key, obj)) return key;
14313     }
14314   };
14315
14316   // Return a copy of the object only containing the whitelisted properties.
14317   _.pick = function(object, oiteratee, context) {
14318     var result = {}, obj = object, iteratee, keys;
14319     if (obj == null) return result;
14320     if (_.isFunction(oiteratee)) {
14321       keys = _.allKeys(obj);
14322       iteratee = optimizeCb(oiteratee, context);
14323     } else {
14324       keys = flatten(arguments, false, false, 1);
14325       iteratee = function(value, key, obj) { return key in obj; };
14326       obj = Object(obj);
14327     }
14328     for (var i = 0, length = keys.length; i < length; i++) {
14329       var key = keys[i];
14330       var value = obj[key];
14331       if (iteratee(value, key, obj)) result[key] = value;
14332     }
14333     return result;
14334   };
14335
14336    // Return a copy of the object without the blacklisted properties.
14337   _.omit = function(obj, iteratee, context) {
14338     if (_.isFunction(iteratee)) {
14339       iteratee = _.negate(iteratee);
14340     } else {
14341       var keys = _.map(flatten(arguments, false, false, 1), String);
14342       iteratee = function(value, key) {
14343         return !_.contains(keys, key);
14344       };
14345     }
14346     return _.pick(obj, iteratee, context);
14347   };
14348
14349   // Fill in a given object with default properties.
14350   _.defaults = createAssigner(_.allKeys, true);
14351
14352   // Creates an object that inherits from the given prototype object.
14353   // If additional properties are provided then they will be added to the
14354   // created object.
14355   _.create = function(prototype, props) {
14356     var result = baseCreate(prototype);
14357     if (props) _.extendOwn(result, props);
14358     return result;
14359   };
14360
14361   // Create a (shallow-cloned) duplicate of an object.
14362   _.clone = function(obj) {
14363     if (!_.isObject(obj)) return obj;
14364     return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
14365   };
14366
14367   // Invokes interceptor with the obj, and then returns obj.
14368   // The primary purpose of this method is to "tap into" a method chain, in
14369   // order to perform operations on intermediate results within the chain.
14370   _.tap = function(obj, interceptor) {
14371     interceptor(obj);
14372     return obj;
14373   };
14374
14375   // Returns whether an object has a given set of `key:value` pairs.
14376   _.isMatch = function(object, attrs) {
14377     var keys = _.keys(attrs), length = keys.length;
14378     if (object == null) return !length;
14379     var obj = Object(object);
14380     for (var i = 0; i < length; i++) {
14381       var key = keys[i];
14382       if (attrs[key] !== obj[key] || !(key in obj)) return false;
14383     }
14384     return true;
14385   };
14386
14387
14388   // Internal recursive comparison function for `isEqual`.
14389   var eq = function(a, b, aStack, bStack) {
14390     // Identical objects are equal. `0 === -0`, but they aren't identical.
14391     // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
14392     if (a === b) return a !== 0 || 1 / a === 1 / b;
14393     // A strict comparison is necessary because `null == undefined`.
14394     if (a == null || b == null) return a === b;
14395     // Unwrap any wrapped objects.
14396     if (a instanceof _) a = a._wrapped;
14397     if (b instanceof _) b = b._wrapped;
14398     // Compare `[[Class]]` names.
14399     var className = toString.call(a);
14400     if (className !== toString.call(b)) return false;
14401     switch (className) {
14402       // Strings, numbers, regular expressions, dates, and booleans are compared by value.
14403       case '[object RegExp]':
14404       // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
14405       case '[object String]':
14406         // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
14407         // equivalent to `new String("5")`.
14408         return '' + a === '' + b;
14409       case '[object Number]':
14410         // `NaN`s are equivalent, but non-reflexive.
14411         // Object(NaN) is equivalent to NaN
14412         if (+a !== +a) return +b !== +b;
14413         // An `egal` comparison is performed for other numeric values.
14414         return +a === 0 ? 1 / +a === 1 / b : +a === +b;
14415       case '[object Date]':
14416       case '[object Boolean]':
14417         // Coerce dates and booleans to numeric primitive values. Dates are compared by their
14418         // millisecond representations. Note that invalid dates with millisecond representations
14419         // of `NaN` are not equivalent.
14420         return +a === +b;
14421     }
14422
14423     var areArrays = className === '[object Array]';
14424     if (!areArrays) {
14425       if (typeof a != 'object' || typeof b != 'object') return false;
14426
14427       // Objects with different constructors are not equivalent, but `Object`s or `Array`s
14428       // from different frames are.
14429       var aCtor = a.constructor, bCtor = b.constructor;
14430       if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
14431                                _.isFunction(bCtor) && bCtor instanceof bCtor)
14432                           && ('constructor' in a && 'constructor' in b)) {
14433         return false;
14434       }
14435     }
14436     // Assume equality for cyclic structures. The algorithm for detecting cyclic
14437     // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
14438
14439     // Initializing stack of traversed objects.
14440     // It's done here since we only need them for objects and arrays comparison.
14441     aStack = aStack || [];
14442     bStack = bStack || [];
14443     var length = aStack.length;
14444     while (length--) {
14445       // Linear search. Performance is inversely proportional to the number of
14446       // unique nested structures.
14447       if (aStack[length] === a) return bStack[length] === b;
14448     }
14449
14450     // Add the first object to the stack of traversed objects.
14451     aStack.push(a);
14452     bStack.push(b);
14453
14454     // Recursively compare objects and arrays.
14455     if (areArrays) {
14456       // Compare array lengths to determine if a deep comparison is necessary.
14457       length = a.length;
14458       if (length !== b.length) return false;
14459       // Deep compare the contents, ignoring non-numeric properties.
14460       while (length--) {
14461         if (!eq(a[length], b[length], aStack, bStack)) return false;
14462       }
14463     } else {
14464       // Deep compare objects.
14465       var keys = _.keys(a), key;
14466       length = keys.length;
14467       // Ensure that both objects contain the same number of properties before comparing deep equality.
14468       if (_.keys(b).length !== length) return false;
14469       while (length--) {
14470         // Deep compare each member
14471         key = keys[length];
14472         if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
14473       }
14474     }
14475     // Remove the first object from the stack of traversed objects.
14476     aStack.pop();
14477     bStack.pop();
14478     return true;
14479   };
14480
14481   // Perform a deep comparison to check if two objects are equal.
14482   _.isEqual = function(a, b) {
14483     return eq(a, b);
14484   };
14485
14486   // Is a given array, string, or object empty?
14487   // An "empty" object has no enumerable own-properties.
14488   _.isEmpty = function(obj) {
14489     if (obj == null) return true;
14490     if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
14491     return _.keys(obj).length === 0;
14492   };
14493
14494   // Is a given value a DOM element?
14495   _.isElement = function(obj) {
14496     return !!(obj && obj.nodeType === 1);
14497   };
14498
14499   // Is a given value an array?
14500   // Delegates to ECMA5's native Array.isArray
14501   _.isArray = nativeIsArray || function(obj) {
14502     return toString.call(obj) === '[object Array]';
14503   };
14504
14505   // Is a given variable an object?
14506   _.isObject = function(obj) {
14507     var type = typeof obj;
14508     return type === 'function' || type === 'object' && !!obj;
14509   };
14510
14511   // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
14512   _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
14513     _['is' + name] = function(obj) {
14514       return toString.call(obj) === '[object ' + name + ']';
14515     };
14516   });
14517
14518   // Define a fallback version of the method in browsers (ahem, IE < 9), where
14519   // there isn't any inspectable "Arguments" type.
14520   if (!_.isArguments(arguments)) {
14521     _.isArguments = function(obj) {
14522       return _.has(obj, 'callee');
14523     };
14524   }
14525
14526   // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
14527   // IE 11 (#1621), and in Safari 8 (#1929).
14528   if (typeof /./ != 'function' && typeof Int8Array != 'object') {
14529     _.isFunction = function(obj) {
14530       return typeof obj == 'function' || false;
14531     };
14532   }
14533
14534   // Is a given object a finite number?
14535   _.isFinite = function(obj) {
14536     return isFinite(obj) && !isNaN(parseFloat(obj));
14537   };
14538
14539   // Is the given value `NaN`? (NaN is the only number which does not equal itself).
14540   _.isNaN = function(obj) {
14541     return _.isNumber(obj) && obj !== +obj;
14542   };
14543
14544   // Is a given value a boolean?
14545   _.isBoolean = function(obj) {
14546     return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
14547   };
14548
14549   // Is a given value equal to null?
14550   _.isNull = function(obj) {
14551     return obj === null;
14552   };
14553
14554   // Is a given variable undefined?
14555   _.isUndefined = function(obj) {
14556     return obj === void 0;
14557   };
14558
14559   // Shortcut function for checking if an object has a given property directly
14560   // on itself (in other words, not on a prototype).
14561   _.has = function(obj, key) {
14562     return obj != null && hasOwnProperty.call(obj, key);
14563   };
14564
14565   // Utility Functions
14566   // -----------------
14567
14568   // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
14569   // previous owner. Returns a reference to the Underscore object.
14570   _.noConflict = function() {
14571     root._ = previousUnderscore;
14572     return this;
14573   };
14574
14575   // Keep the identity function around for default iteratees.
14576   _.identity = function(value) {
14577     return value;
14578   };
14579
14580   // Predicate-generating functions. Often useful outside of Underscore.
14581   _.constant = function(value) {
14582     return function() {
14583       return value;
14584     };
14585   };
14586
14587   _.noop = function(){};
14588
14589   _.property = property;
14590
14591   // Generates a function for a given object that returns a given property.
14592   _.propertyOf = function(obj) {
14593     return obj == null ? function(){} : function(key) {
14594       return obj[key];
14595     };
14596   };
14597
14598   // Returns a predicate for checking whether an object has a given set of
14599   // `key:value` pairs.
14600   _.matcher = _.matches = function(attrs) {
14601     attrs = _.extendOwn({}, attrs);
14602     return function(obj) {
14603       return _.isMatch(obj, attrs);
14604     };
14605   };
14606
14607   // Run a function **n** times.
14608   _.times = function(n, iteratee, context) {
14609     var accum = Array(Math.max(0, n));
14610     iteratee = optimizeCb(iteratee, context, 1);
14611     for (var i = 0; i < n; i++) accum[i] = iteratee(i);
14612     return accum;
14613   };
14614
14615   // Return a random integer between min and max (inclusive).
14616   _.random = function(min, max) {
14617     if (max == null) {
14618       max = min;
14619       min = 0;
14620     }
14621     return min + Math.floor(Math.random() * (max - min + 1));
14622   };
14623
14624   // A (possibly faster) way to get the current timestamp as an integer.
14625   _.now = Date.now || function() {
14626     return new Date().getTime();
14627   };
14628
14629    // List of HTML entities for escaping.
14630   var escapeMap = {
14631     '&': '&amp;',
14632     '<': '&lt;',
14633     '>': '&gt;',
14634     '"': '&quot;',
14635     "'": '&#x27;',
14636     '`': '&#x60;'
14637   };
14638   var unescapeMap = _.invert(escapeMap);
14639
14640   // Functions for escaping and unescaping strings to/from HTML interpolation.
14641   var createEscaper = function(map) {
14642     var escaper = function(match) {
14643       return map[match];
14644     };
14645     // Regexes for identifying a key that needs to be escaped
14646     var source = '(?:' + _.keys(map).join('|') + ')';
14647     var testRegexp = RegExp(source);
14648     var replaceRegexp = RegExp(source, 'g');
14649     return function(string) {
14650       string = string == null ? '' : '' + string;
14651       return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
14652     };
14653   };
14654   _.escape = createEscaper(escapeMap);
14655   _.unescape = createEscaper(unescapeMap);
14656
14657   // If the value of the named `property` is a function then invoke it with the
14658   // `object` as context; otherwise, return it.
14659   _.result = function(object, property, fallback) {
14660     var value = object == null ? void 0 : object[property];
14661     if (value === void 0) {
14662       value = fallback;
14663     }
14664     return _.isFunction(value) ? value.call(object) : value;
14665   };
14666
14667   // Generate a unique integer id (unique within the entire client session).
14668   // Useful for temporary DOM ids.
14669   var idCounter = 0;
14670   _.uniqueId = function(prefix) {
14671     var id = ++idCounter + '';
14672     return prefix ? prefix + id : id;
14673   };
14674
14675   // By default, Underscore uses ERB-style template delimiters, change the
14676   // following template settings to use alternative delimiters.
14677   _.templateSettings = {
14678     evaluate    : /<%([\s\S]+?)%>/g,
14679     interpolate : /<%=([\s\S]+?)%>/g,
14680     escape      : /<%-([\s\S]+?)%>/g
14681   };
14682
14683   // When customizing `templateSettings`, if you don't want to define an
14684   // interpolation, evaluation or escaping regex, we need one that is
14685   // guaranteed not to match.
14686   var noMatch = /(.)^/;
14687
14688   // Certain characters need to be escaped so that they can be put into a
14689   // string literal.
14690   var escapes = {
14691     "'":      "'",
14692     '\\':     '\\',
14693     '\r':     'r',
14694     '\n':     'n',
14695     '\u2028': 'u2028',
14696     '\u2029': 'u2029'
14697   };
14698
14699   var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
14700
14701   var escapeChar = function(match) {
14702     return '\\' + escapes[match];
14703   };
14704
14705   // JavaScript micro-templating, similar to John Resig's implementation.
14706   // Underscore templating handles arbitrary delimiters, preserves whitespace,
14707   // and correctly escapes quotes within interpolated code.
14708   // NB: `oldSettings` only exists for backwards compatibility.
14709   _.template = function(text, settings, oldSettings) {
14710     if (!settings && oldSettings) settings = oldSettings;
14711     settings = _.defaults({}, settings, _.templateSettings);
14712
14713     // Combine delimiters into one regular expression via alternation.
14714     var matcher = RegExp([
14715       (settings.escape || noMatch).source,
14716       (settings.interpolate || noMatch).source,
14717       (settings.evaluate || noMatch).source
14718     ].join('|') + '|$', 'g');
14719
14720     // Compile the template source, escaping string literals appropriately.
14721     var index = 0;
14722     var source = "__p+='";
14723     text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
14724       source += text.slice(index, offset).replace(escaper, escapeChar);
14725       index = offset + match.length;
14726
14727       if (escape) {
14728         source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
14729       } else if (interpolate) {
14730         source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
14731       } else if (evaluate) {
14732         source += "';\n" + evaluate + "\n__p+='";
14733       }
14734
14735       // Adobe VMs need the match returned to produce the correct offest.
14736       return match;
14737     });
14738     source += "';\n";
14739
14740     // If a variable is not specified, place data values in local scope.
14741     if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
14742
14743     source = "var __t,__p='',__j=Array.prototype.join," +
14744       "print=function(){__p+=__j.call(arguments,'');};\n" +
14745       source + 'return __p;\n';
14746
14747     try {
14748       var render = new Function(settings.variable || 'obj', '_', source);
14749     } catch (e) {
14750       e.source = source;
14751       throw e;
14752     }
14753
14754     var template = function(data) {
14755       return render.call(this, data, _);
14756     };
14757
14758     // Provide the compiled source as a convenience for precompilation.
14759     var argument = settings.variable || 'obj';
14760     template.source = 'function(' + argument + '){\n' + source + '}';
14761
14762     return template;
14763   };
14764
14765   // Add a "chain" function. Start chaining a wrapped Underscore object.
14766   _.chain = function(obj) {
14767     var instance = _(obj);
14768     instance._chain = true;
14769     return instance;
14770   };
14771
14772   // OOP
14773   // ---------------
14774   // If Underscore is called as a function, it returns a wrapped object that
14775   // can be used OO-style. This wrapper holds altered versions of all the
14776   // underscore functions. Wrapped objects may be chained.
14777
14778   // Helper function to continue chaining intermediate results.
14779   var result = function(instance, obj) {
14780     return instance._chain ? _(obj).chain() : obj;
14781   };
14782
14783   // Add your own custom functions to the Underscore object.
14784   _.mixin = function(obj) {
14785     _.each(_.functions(obj), function(name) {
14786       var func = _[name] = obj[name];
14787       _.prototype[name] = function() {
14788         var args = [this._wrapped];
14789         push.apply(args, arguments);
14790         return result(this, func.apply(_, args));
14791       };
14792     });
14793   };
14794
14795   // Add all of the Underscore functions to the wrapper object.
14796   _.mixin(_);
14797
14798   // Add all mutator Array functions to the wrapper.
14799   _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
14800     var method = ArrayProto[name];
14801     _.prototype[name] = function() {
14802       var obj = this._wrapped;
14803       method.apply(obj, arguments);
14804       if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
14805       return result(this, obj);
14806     };
14807   });
14808
14809   // Add all accessor Array functions to the wrapper.
14810   _.each(['concat', 'join', 'slice'], function(name) {
14811     var method = ArrayProto[name];
14812     _.prototype[name] = function() {
14813       return result(this, method.apply(this._wrapped, arguments));
14814     };
14815   });
14816
14817   // Extracts the result from a wrapped and chained object.
14818   _.prototype.value = function() {
14819     return this._wrapped;
14820   };
14821
14822   // Provide unwrapping proxy for some methods used in engine operations
14823   // such as arithmetic and JSON stringification.
14824   _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
14825
14826   _.prototype.toString = function() {
14827     return '' + this._wrapped;
14828   };
14829
14830   // AMD registration happens at the end for compatibility with AMD loaders
14831   // that may not enforce next-turn semantics on modules. Even though general
14832   // practice for AMD registration is to be anonymous, underscore registers
14833   // as a named module because, like jQuery, it is a base library that is
14834   // popular enough to be bundled in a third party lib, but not be part of
14835   // an AMD load request. Those cases could generate an error when an
14836   // anonymous define() is called outside of a loader request.
14837   if (typeof define === 'function' && define.amd) {
14838     define('underscore', [], function() {
14839       return _;
14840     });
14841   }
14842 }.call(this));
14843
14844 },{}],169:[function(require,module,exports){
14845 /*
14846  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
14847  *
14848  * Redistribution and use in source and binary forms, with or without
14849  * modification, are permitted provided that the following conditions
14850  * are met:
14851  * 1. Redistributions of source code must retain the above copyright
14852  *    notice, this list of conditions and the following disclaimer.
14853  * 2. Redistributions in binary form must reproduce the above copyright
14854  *    notice, this list of conditions and the following disclaimer in the
14855  *    documentation and/or other materials provided with the distribution.
14856  *
14857  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14858  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14859  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
14860  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
14861  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
14862  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
14863  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
14864  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
14865  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14866  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14867  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14868  *
14869  * Ported from Webkit
14870  * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
14871  */
14872
14873 module.exports = UnitBezier;
14874
14875 function UnitBezier(p1x, p1y, p2x, p2y) {
14876     // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
14877     this.cx = 3.0 * p1x;
14878     this.bx = 3.0 * (p2x - p1x) - this.cx;
14879     this.ax = 1.0 - this.cx - this.bx;
14880
14881     this.cy = 3.0 * p1y;
14882     this.by = 3.0 * (p2y - p1y) - this.cy;
14883     this.ay = 1.0 - this.cy - this.by;
14884
14885     this.p1x = p1x;
14886     this.p1y = p2y;
14887     this.p2x = p2x;
14888     this.p2y = p2y;
14889 }
14890
14891 UnitBezier.prototype.sampleCurveX = function(t) {
14892     // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
14893     return ((this.ax * t + this.bx) * t + this.cx) * t;
14894 };
14895
14896 UnitBezier.prototype.sampleCurveY = function(t) {
14897     return ((this.ay * t + this.by) * t + this.cy) * t;
14898 };
14899
14900 UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
14901     return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
14902 };
14903
14904 UnitBezier.prototype.solveCurveX = function(x, epsilon) {
14905     if (typeof epsilon === 'undefined') epsilon = 1e-6;
14906
14907     var t0, t1, t2, x2, i;
14908
14909     // First try a few iterations of Newton's method -- normally very fast.
14910     for (t2 = x, i = 0; i < 8; i++) {
14911
14912         x2 = this.sampleCurveX(t2) - x;
14913         if (Math.abs(x2) < epsilon) return t2;
14914
14915         var d2 = this.sampleCurveDerivativeX(t2);
14916         if (Math.abs(d2) < 1e-6) break;
14917
14918         t2 = t2 - x2 / d2;
14919     }
14920
14921     // Fall back to the bisection method for reliability.
14922     t0 = 0.0;
14923     t1 = 1.0;
14924     t2 = x;
14925
14926     if (t2 < t0) return t0;
14927     if (t2 > t1) return t1;
14928
14929     while (t0 < t1) {
14930
14931         x2 = this.sampleCurveX(t2);
14932         if (Math.abs(x2 - x) < epsilon) return t2;
14933
14934         if (x > x2) {
14935             t0 = t2;
14936         } else {
14937             t1 = t2;
14938         }
14939
14940         t2 = (t1 - t0) * 0.5 + t0;
14941     }
14942
14943     // Failure.
14944     return t2;
14945 };
14946
14947 UnitBezier.prototype.solve = function(x, epsilon) {
14948     return this.sampleCurveY(this.solveCurveX(x, epsilon));
14949 };
14950
14951 },{}],170:[function(require,module,exports){
14952 var createElement = require("./vdom/create-element.js")
14953
14954 module.exports = createElement
14955
14956 },{"./vdom/create-element.js":176}],171:[function(require,module,exports){
14957 var diff = require("./vtree/diff.js")
14958
14959 module.exports = diff
14960
14961 },{"./vtree/diff.js":196}],172:[function(require,module,exports){
14962 var h = require("./virtual-hyperscript/index.js")
14963
14964 module.exports = h
14965
14966 },{"./virtual-hyperscript/index.js":183}],173:[function(require,module,exports){
14967 var diff = require("./diff.js")
14968 var patch = require("./patch.js")
14969 var h = require("./h.js")
14970 var create = require("./create-element.js")
14971 var VNode = require('./vnode/vnode.js')
14972 var VText = require('./vnode/vtext.js')
14973
14974 module.exports = {
14975     diff: diff,
14976     patch: patch,
14977     h: h,
14978     create: create,
14979     VNode: VNode,
14980     VText: VText
14981 }
14982
14983 },{"./create-element.js":170,"./diff.js":171,"./h.js":172,"./patch.js":174,"./vnode/vnode.js":192,"./vnode/vtext.js":194}],174:[function(require,module,exports){
14984 var patch = require("./vdom/patch.js")
14985
14986 module.exports = patch
14987
14988 },{"./vdom/patch.js":179}],175:[function(require,module,exports){
14989 var isObject = require("is-object")
14990 var isHook = require("../vnode/is-vhook.js")
14991
14992 module.exports = applyProperties
14993
14994 function applyProperties(node, props, previous) {
14995     for (var propName in props) {
14996         var propValue = props[propName]
14997
14998         if (propValue === undefined) {
14999             removeProperty(node, propName, propValue, previous);
15000         } else if (isHook(propValue)) {
15001             removeProperty(node, propName, propValue, previous)
15002             if (propValue.hook) {
15003                 propValue.hook(node,
15004                     propName,
15005                     previous ? previous[propName] : undefined)
15006             }
15007         } else {
15008             if (isObject(propValue)) {
15009                 patchObject(node, props, previous, propName, propValue);
15010             } else {
15011                 node[propName] = propValue
15012             }
15013         }
15014     }
15015 }
15016
15017 function removeProperty(node, propName, propValue, previous) {
15018     if (previous) {
15019         var previousValue = previous[propName]
15020
15021         if (!isHook(previousValue)) {
15022             if (propName === "attributes") {
15023                 for (var attrName in previousValue) {
15024                     node.removeAttribute(attrName)
15025                 }
15026             } else if (propName === "style") {
15027                 for (var i in previousValue) {
15028                     node.style[i] = ""
15029                 }
15030             } else if (typeof previousValue === "string") {
15031                 node[propName] = ""
15032             } else {
15033                 node[propName] = null
15034             }
15035         } else if (previousValue.unhook) {
15036             previousValue.unhook(node, propName, propValue)
15037         }
15038     }
15039 }
15040
15041 function patchObject(node, props, previous, propName, propValue) {
15042     var previousValue = previous ? previous[propName] : undefined
15043
15044     // Set attributes
15045     if (propName === "attributes") {
15046         for (var attrName in propValue) {
15047             var attrValue = propValue[attrName]
15048
15049             if (attrValue === undefined) {
15050                 node.removeAttribute(attrName)
15051             } else {
15052                 node.setAttribute(attrName, attrValue)
15053             }
15054         }
15055
15056         return
15057     }
15058
15059     if(previousValue && isObject(previousValue) &&
15060         getPrototype(previousValue) !== getPrototype(propValue)) {
15061         node[propName] = propValue
15062         return
15063     }
15064
15065     if (!isObject(node[propName])) {
15066         node[propName] = {}
15067     }
15068
15069     var replacer = propName === "style" ? "" : undefined
15070
15071     for (var k in propValue) {
15072         var value = propValue[k]
15073         node[propName][k] = (value === undefined) ? replacer : value
15074     }
15075 }
15076
15077 function getPrototype(value) {
15078     if (Object.getPrototypeOf) {
15079         return Object.getPrototypeOf(value)
15080     } else if (value.__proto__) {
15081         return value.__proto__
15082     } else if (value.constructor) {
15083         return value.constructor.prototype
15084     }
15085 }
15086
15087 },{"../vnode/is-vhook.js":187,"is-object":18}],176:[function(require,module,exports){
15088 var document = require("global/document")
15089
15090 var applyProperties = require("./apply-properties")
15091
15092 var isVNode = require("../vnode/is-vnode.js")
15093 var isVText = require("../vnode/is-vtext.js")
15094 var isWidget = require("../vnode/is-widget.js")
15095 var handleThunk = require("../vnode/handle-thunk.js")
15096
15097 module.exports = createElement
15098
15099 function createElement(vnode, opts) {
15100     var doc = opts ? opts.document || document : document
15101     var warn = opts ? opts.warn : null
15102
15103     vnode = handleThunk(vnode).a
15104
15105     if (isWidget(vnode)) {
15106         return vnode.init()
15107     } else if (isVText(vnode)) {
15108         return doc.createTextNode(vnode.text)
15109     } else if (!isVNode(vnode)) {
15110         if (warn) {
15111             warn("Item is not a valid virtual dom node", vnode)
15112         }
15113         return null
15114     }
15115
15116     var node = (vnode.namespace === null) ?
15117         doc.createElement(vnode.tagName) :
15118         doc.createElementNS(vnode.namespace, vnode.tagName)
15119
15120     var props = vnode.properties
15121     applyProperties(node, props)
15122
15123     var children = vnode.children
15124
15125     for (var i = 0; i < children.length; i++) {
15126         var childNode = createElement(children[i], opts)
15127         if (childNode) {
15128             node.appendChild(childNode)
15129         }
15130     }
15131
15132     return node
15133 }
15134
15135 },{"../vnode/handle-thunk.js":185,"../vnode/is-vnode.js":188,"../vnode/is-vtext.js":189,"../vnode/is-widget.js":190,"./apply-properties":175,"global/document":14}],177:[function(require,module,exports){
15136 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
15137 // We don't want to read all of the DOM nodes in the tree so we use
15138 // the in-order tree indexing to eliminate recursion down certain branches.
15139 // We only recurse into a DOM node if we know that it contains a child of
15140 // interest.
15141
15142 var noChild = {}
15143
15144 module.exports = domIndex
15145
15146 function domIndex(rootNode, tree, indices, nodes) {
15147     if (!indices || indices.length === 0) {
15148         return {}
15149     } else {
15150         indices.sort(ascending)
15151         return recurse(rootNode, tree, indices, nodes, 0)
15152     }
15153 }
15154
15155 function recurse(rootNode, tree, indices, nodes, rootIndex) {
15156     nodes = nodes || {}
15157
15158
15159     if (rootNode) {
15160         if (indexInRange(indices, rootIndex, rootIndex)) {
15161             nodes[rootIndex] = rootNode
15162         }
15163
15164         var vChildren = tree.children
15165
15166         if (vChildren) {
15167
15168             var childNodes = rootNode.childNodes
15169
15170             for (var i = 0; i < tree.children.length; i++) {
15171                 rootIndex += 1
15172
15173                 var vChild = vChildren[i] || noChild
15174                 var nextIndex = rootIndex + (vChild.count || 0)
15175
15176                 // skip recursion down the tree if there are no nodes down here
15177                 if (indexInRange(indices, rootIndex, nextIndex)) {
15178                     recurse(childNodes[i], vChild, indices, nodes, rootIndex)
15179                 }
15180
15181                 rootIndex = nextIndex
15182             }
15183         }
15184     }
15185
15186     return nodes
15187 }
15188
15189 // Binary search for an index in the interval [left, right]
15190 function indexInRange(indices, left, right) {
15191     if (indices.length === 0) {
15192         return false
15193     }
15194
15195     var minIndex = 0
15196     var maxIndex = indices.length - 1
15197     var currentIndex
15198     var currentItem
15199
15200     while (minIndex <= maxIndex) {
15201         currentIndex = ((maxIndex + minIndex) / 2) >> 0
15202         currentItem = indices[currentIndex]
15203
15204         if (minIndex === maxIndex) {
15205             return currentItem >= left && currentItem <= right
15206         } else if (currentItem < left) {
15207             minIndex = currentIndex + 1
15208         } else  if (currentItem > right) {
15209             maxIndex = currentIndex - 1
15210         } else {
15211             return true
15212         }
15213     }
15214
15215     return false;
15216 }
15217
15218 function ascending(a, b) {
15219     return a > b ? 1 : -1
15220 }
15221
15222 },{}],178:[function(require,module,exports){
15223 var applyProperties = require("./apply-properties")
15224
15225 var isWidget = require("../vnode/is-widget.js")
15226 var VPatch = require("../vnode/vpatch.js")
15227
15228 var updateWidget = require("./update-widget")
15229
15230 module.exports = applyPatch
15231
15232 function applyPatch(vpatch, domNode, renderOptions) {
15233     var type = vpatch.type
15234     var vNode = vpatch.vNode
15235     var patch = vpatch.patch
15236
15237     switch (type) {
15238         case VPatch.REMOVE:
15239             return removeNode(domNode, vNode)
15240         case VPatch.INSERT:
15241             return insertNode(domNode, patch, renderOptions)
15242         case VPatch.VTEXT:
15243             return stringPatch(domNode, vNode, patch, renderOptions)
15244         case VPatch.WIDGET:
15245             return widgetPatch(domNode, vNode, patch, renderOptions)
15246         case VPatch.VNODE:
15247             return vNodePatch(domNode, vNode, patch, renderOptions)
15248         case VPatch.ORDER:
15249             reorderChildren(domNode, patch)
15250             return domNode
15251         case VPatch.PROPS:
15252             applyProperties(domNode, patch, vNode.properties)
15253             return domNode
15254         case VPatch.THUNK:
15255             return replaceRoot(domNode,
15256                 renderOptions.patch(domNode, patch, renderOptions))
15257         default:
15258             return domNode
15259     }
15260 }
15261
15262 function removeNode(domNode, vNode) {
15263     var parentNode = domNode.parentNode
15264
15265     if (parentNode) {
15266         parentNode.removeChild(domNode)
15267     }
15268
15269     destroyWidget(domNode, vNode);
15270
15271     return null
15272 }
15273
15274 function insertNode(parentNode, vNode, renderOptions) {
15275     var newNode = renderOptions.render(vNode, renderOptions)
15276
15277     if (parentNode) {
15278         parentNode.appendChild(newNode)
15279     }
15280
15281     return parentNode
15282 }
15283
15284 function stringPatch(domNode, leftVNode, vText, renderOptions) {
15285     var newNode
15286
15287     if (domNode.nodeType === 3) {
15288         domNode.replaceData(0, domNode.length, vText.text)
15289         newNode = domNode
15290     } else {
15291         var parentNode = domNode.parentNode
15292         newNode = renderOptions.render(vText, renderOptions)
15293
15294         if (parentNode && newNode !== domNode) {
15295             parentNode.replaceChild(newNode, domNode)
15296         }
15297     }
15298
15299     return newNode
15300 }
15301
15302 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
15303     var updating = updateWidget(leftVNode, widget)
15304     var newNode
15305
15306     if (updating) {
15307         newNode = widget.update(leftVNode, domNode) || domNode
15308     } else {
15309         newNode = renderOptions.render(widget, renderOptions)
15310     }
15311
15312     var parentNode = domNode.parentNode
15313
15314     if (parentNode && newNode !== domNode) {
15315         parentNode.replaceChild(newNode, domNode)
15316     }
15317
15318     if (!updating) {
15319         destroyWidget(domNode, leftVNode)
15320     }
15321
15322     return newNode
15323 }
15324
15325 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
15326     var parentNode = domNode.parentNode
15327     var newNode = renderOptions.render(vNode, renderOptions)
15328
15329     if (parentNode && newNode !== domNode) {
15330         parentNode.replaceChild(newNode, domNode)
15331     }
15332
15333     return newNode
15334 }
15335
15336 function destroyWidget(domNode, w) {
15337     if (typeof w.destroy === "function" && isWidget(w)) {
15338         w.destroy(domNode)
15339     }
15340 }
15341
15342 function reorderChildren(domNode, moves) {
15343     var childNodes = domNode.childNodes
15344     var keyMap = {}
15345     var node
15346     var remove
15347     var insert
15348
15349     for (var i = 0; i < moves.removes.length; i++) {
15350         remove = moves.removes[i]
15351         node = childNodes[remove.from]
15352         if (remove.key) {
15353             keyMap[remove.key] = node
15354         }
15355         domNode.removeChild(node)
15356     }
15357
15358     var length = childNodes.length
15359     for (var j = 0; j < moves.inserts.length; j++) {
15360         insert = moves.inserts[j]
15361         node = keyMap[insert.key]
15362         // this is the weirdest bug i've ever seen in webkit
15363         domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
15364     }
15365 }
15366
15367 function replaceRoot(oldRoot, newRoot) {
15368     if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
15369         oldRoot.parentNode.replaceChild(newRoot, oldRoot)
15370     }
15371
15372     return newRoot;
15373 }
15374
15375 },{"../vnode/is-widget.js":190,"../vnode/vpatch.js":193,"./apply-properties":175,"./update-widget":180}],179:[function(require,module,exports){
15376 var document = require("global/document")
15377 var isArray = require("x-is-array")
15378
15379 var render = require("./create-element")
15380 var domIndex = require("./dom-index")
15381 var patchOp = require("./patch-op")
15382 module.exports = patch
15383
15384 function patch(rootNode, patches, renderOptions) {
15385     renderOptions = renderOptions || {}
15386     renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
15387         ? renderOptions.patch
15388         : patchRecursive
15389     renderOptions.render = renderOptions.render || render
15390
15391     return renderOptions.patch(rootNode, patches, renderOptions)
15392 }
15393
15394 function patchRecursive(rootNode, patches, renderOptions) {
15395     var indices = patchIndices(patches)
15396
15397     if (indices.length === 0) {
15398         return rootNode
15399     }
15400
15401     var index = domIndex(rootNode, patches.a, indices)
15402     var ownerDocument = rootNode.ownerDocument
15403
15404     if (!renderOptions.document && ownerDocument !== document) {
15405         renderOptions.document = ownerDocument
15406     }
15407
15408     for (var i = 0; i < indices.length; i++) {
15409         var nodeIndex = indices[i]
15410         rootNode = applyPatch(rootNode,
15411             index[nodeIndex],
15412             patches[nodeIndex],
15413             renderOptions)
15414     }
15415
15416     return rootNode
15417 }
15418
15419 function applyPatch(rootNode, domNode, patchList, renderOptions) {
15420     if (!domNode) {
15421         return rootNode
15422     }
15423
15424     var newNode
15425
15426     if (isArray(patchList)) {
15427         for (var i = 0; i < patchList.length; i++) {
15428             newNode = patchOp(patchList[i], domNode, renderOptions)
15429
15430             if (domNode === rootNode) {
15431                 rootNode = newNode
15432             }
15433         }
15434     } else {
15435         newNode = patchOp(patchList, domNode, renderOptions)
15436
15437         if (domNode === rootNode) {
15438             rootNode = newNode
15439         }
15440     }
15441
15442     return rootNode
15443 }
15444
15445 function patchIndices(patches) {
15446     var indices = []
15447
15448     for (var key in patches) {
15449         if (key !== "a") {
15450             indices.push(Number(key))
15451         }
15452     }
15453
15454     return indices
15455 }
15456
15457 },{"./create-element":176,"./dom-index":177,"./patch-op":178,"global/document":14,"x-is-array":215}],180:[function(require,module,exports){
15458 var isWidget = require("../vnode/is-widget.js")
15459
15460 module.exports = updateWidget
15461
15462 function updateWidget(a, b) {
15463     if (isWidget(a) && isWidget(b)) {
15464         if ("name" in a && "name" in b) {
15465             return a.id === b.id
15466         } else {
15467             return a.init === b.init
15468         }
15469     }
15470
15471     return false
15472 }
15473
15474 },{"../vnode/is-widget.js":190}],181:[function(require,module,exports){
15475 'use strict';
15476
15477 var EvStore = require('ev-store');
15478
15479 module.exports = EvHook;
15480
15481 function EvHook(value) {
15482     if (!(this instanceof EvHook)) {
15483         return new EvHook(value);
15484     }
15485
15486     this.value = value;
15487 }
15488
15489 EvHook.prototype.hook = function (node, propertyName) {
15490     var es = EvStore(node);
15491     var propName = propertyName.substr(3);
15492
15493     es[propName] = this.value;
15494 };
15495
15496 EvHook.prototype.unhook = function(node, propertyName) {
15497     var es = EvStore(node);
15498     var propName = propertyName.substr(3);
15499
15500     es[propName] = undefined;
15501 };
15502
15503 },{"ev-store":7}],182:[function(require,module,exports){
15504 'use strict';
15505
15506 module.exports = SoftSetHook;
15507
15508 function SoftSetHook(value) {
15509     if (!(this instanceof SoftSetHook)) {
15510         return new SoftSetHook(value);
15511     }
15512
15513     this.value = value;
15514 }
15515
15516 SoftSetHook.prototype.hook = function (node, propertyName) {
15517     if (node[propertyName] !== this.value) {
15518         node[propertyName] = this.value;
15519     }
15520 };
15521
15522 },{}],183:[function(require,module,exports){
15523 'use strict';
15524
15525 var isArray = require('x-is-array');
15526
15527 var VNode = require('../vnode/vnode.js');
15528 var VText = require('../vnode/vtext.js');
15529 var isVNode = require('../vnode/is-vnode');
15530 var isVText = require('../vnode/is-vtext');
15531 var isWidget = require('../vnode/is-widget');
15532 var isHook = require('../vnode/is-vhook');
15533 var isVThunk = require('../vnode/is-thunk');
15534
15535 var parseTag = require('./parse-tag.js');
15536 var softSetHook = require('./hooks/soft-set-hook.js');
15537 var evHook = require('./hooks/ev-hook.js');
15538
15539 module.exports = h;
15540
15541 function h(tagName, properties, children) {
15542     var childNodes = [];
15543     var tag, props, key, namespace;
15544
15545     if (!children && isChildren(properties)) {
15546         children = properties;
15547         props = {};
15548     }
15549
15550     props = props || properties || {};
15551     tag = parseTag(tagName, props);
15552
15553     // support keys
15554     if (props.hasOwnProperty('key')) {
15555         key = props.key;
15556         props.key = undefined;
15557     }
15558
15559     // support namespace
15560     if (props.hasOwnProperty('namespace')) {
15561         namespace = props.namespace;
15562         props.namespace = undefined;
15563     }
15564
15565     // fix cursor bug
15566     if (tag === 'INPUT' &&
15567         !namespace &&
15568         props.hasOwnProperty('value') &&
15569         props.value !== undefined &&
15570         !isHook(props.value)
15571     ) {
15572         props.value = softSetHook(props.value);
15573     }
15574
15575     transformProperties(props);
15576
15577     if (children !== undefined && children !== null) {
15578         addChild(children, childNodes, tag, props);
15579     }
15580
15581
15582     return new VNode(tag, props, childNodes, key, namespace);
15583 }
15584
15585 function addChild(c, childNodes, tag, props) {
15586     if (typeof c === 'string') {
15587         childNodes.push(new VText(c));
15588     } else if (typeof c === 'number') {
15589         childNodes.push(new VText(String(c)));
15590     } else if (isChild(c)) {
15591         childNodes.push(c);
15592     } else if (isArray(c)) {
15593         for (var i = 0; i < c.length; i++) {
15594             addChild(c[i], childNodes, tag, props);
15595         }
15596     } else if (c === null || c === undefined) {
15597         return;
15598     } else {
15599         throw UnexpectedVirtualElement({
15600             foreignObject: c,
15601             parentVnode: {
15602                 tagName: tag,
15603                 properties: props
15604             }
15605         });
15606     }
15607 }
15608
15609 function transformProperties(props) {
15610     for (var propName in props) {
15611         if (props.hasOwnProperty(propName)) {
15612             var value = props[propName];
15613
15614             if (isHook(value)) {
15615                 continue;
15616             }
15617
15618             if (propName.substr(0, 3) === 'ev-') {
15619                 // add ev-foo support
15620                 props[propName] = evHook(value);
15621             }
15622         }
15623     }
15624 }
15625
15626 function isChild(x) {
15627     return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
15628 }
15629
15630 function isChildren(x) {
15631     return typeof x === 'string' || isArray(x) || isChild(x);
15632 }
15633
15634 function UnexpectedVirtualElement(data) {
15635     var err = new Error();
15636
15637     err.type = 'virtual-hyperscript.unexpected.virtual-element';
15638     err.message = 'Unexpected virtual child passed to h().\n' +
15639         'Expected a VNode / Vthunk / VWidget / string but:\n' +
15640         'got:\n' +
15641         errorString(data.foreignObject) +
15642         '.\n' +
15643         'The parent vnode is:\n' +
15644         errorString(data.parentVnode)
15645         '\n' +
15646         'Suggested fix: change your `h(..., [ ... ])` callsite.';
15647     err.foreignObject = data.foreignObject;
15648     err.parentVnode = data.parentVnode;
15649
15650     return err;
15651 }
15652
15653 function errorString(obj) {
15654     try {
15655         return JSON.stringify(obj, null, '    ');
15656     } catch (e) {
15657         return String(obj);
15658     }
15659 }
15660
15661 },{"../vnode/is-thunk":186,"../vnode/is-vhook":187,"../vnode/is-vnode":188,"../vnode/is-vtext":189,"../vnode/is-widget":190,"../vnode/vnode.js":192,"../vnode/vtext.js":194,"./hooks/ev-hook.js":181,"./hooks/soft-set-hook.js":182,"./parse-tag.js":184,"x-is-array":215}],184:[function(require,module,exports){
15662 'use strict';
15663
15664 var split = require('browser-split');
15665
15666 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
15667 var notClassId = /^\.|#/;
15668
15669 module.exports = parseTag;
15670
15671 function parseTag(tag, props) {
15672     if (!tag) {
15673         return 'DIV';
15674     }
15675
15676     var noId = !(props.hasOwnProperty('id'));
15677
15678     var tagParts = split(tag, classIdSplit);
15679     var tagName = null;
15680
15681     if (notClassId.test(tagParts[1])) {
15682         tagName = 'DIV';
15683     }
15684
15685     var classes, part, type, i;
15686
15687     for (i = 0; i < tagParts.length; i++) {
15688         part = tagParts[i];
15689
15690         if (!part) {
15691             continue;
15692         }
15693
15694         type = part.charAt(0);
15695
15696         if (!tagName) {
15697             tagName = part;
15698         } else if (type === '.') {
15699             classes = classes || [];
15700             classes.push(part.substring(1, part.length));
15701         } else if (type === '#' && noId) {
15702             props.id = part.substring(1, part.length);
15703         }
15704     }
15705
15706     if (classes) {
15707         if (props.className) {
15708             classes.push(props.className);
15709         }
15710
15711         props.className = classes.join(' ');
15712     }
15713
15714     return props.namespace ? tagName : tagName.toUpperCase();
15715 }
15716
15717 },{"browser-split":3}],185:[function(require,module,exports){
15718 var isVNode = require("./is-vnode")
15719 var isVText = require("./is-vtext")
15720 var isWidget = require("./is-widget")
15721 var isThunk = require("./is-thunk")
15722
15723 module.exports = handleThunk
15724
15725 function handleThunk(a, b) {
15726     var renderedA = a
15727     var renderedB = b
15728
15729     if (isThunk(b)) {
15730         renderedB = renderThunk(b, a)
15731     }
15732
15733     if (isThunk(a)) {
15734         renderedA = renderThunk(a, null)
15735     }
15736
15737     return {
15738         a: renderedA,
15739         b: renderedB
15740     }
15741 }
15742
15743 function renderThunk(thunk, previous) {
15744     var renderedThunk = thunk.vnode
15745
15746     if (!renderedThunk) {
15747         renderedThunk = thunk.vnode = thunk.render(previous)
15748     }
15749
15750     if (!(isVNode(renderedThunk) ||
15751             isVText(renderedThunk) ||
15752             isWidget(renderedThunk))) {
15753         throw new Error("thunk did not return a valid node");
15754     }
15755
15756     return renderedThunk
15757 }
15758
15759 },{"./is-thunk":186,"./is-vnode":188,"./is-vtext":189,"./is-widget":190}],186:[function(require,module,exports){
15760 module.exports = isThunk
15761
15762 function isThunk(t) {
15763     return t && t.type === "Thunk"
15764 }
15765
15766 },{}],187:[function(require,module,exports){
15767 module.exports = isHook
15768
15769 function isHook(hook) {
15770     return hook &&
15771       (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
15772        typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
15773 }
15774
15775 },{}],188:[function(require,module,exports){
15776 var version = require("./version")
15777
15778 module.exports = isVirtualNode
15779
15780 function isVirtualNode(x) {
15781     return x && x.type === "VirtualNode" && x.version === version
15782 }
15783
15784 },{"./version":191}],189:[function(require,module,exports){
15785 var version = require("./version")
15786
15787 module.exports = isVirtualText
15788
15789 function isVirtualText(x) {
15790     return x && x.type === "VirtualText" && x.version === version
15791 }
15792
15793 },{"./version":191}],190:[function(require,module,exports){
15794 module.exports = isWidget
15795
15796 function isWidget(w) {
15797     return w && w.type === "Widget"
15798 }
15799
15800 },{}],191:[function(require,module,exports){
15801 module.exports = "2"
15802
15803 },{}],192:[function(require,module,exports){
15804 var version = require("./version")
15805 var isVNode = require("./is-vnode")
15806 var isWidget = require("./is-widget")
15807 var isThunk = require("./is-thunk")
15808 var isVHook = require("./is-vhook")
15809
15810 module.exports = VirtualNode
15811
15812 var noProperties = {}
15813 var noChildren = []
15814
15815 function VirtualNode(tagName, properties, children, key, namespace) {
15816     this.tagName = tagName
15817     this.properties = properties || noProperties
15818     this.children = children || noChildren
15819     this.key = key != null ? String(key) : undefined
15820     this.namespace = (typeof namespace === "string") ? namespace : null
15821
15822     var count = (children && children.length) || 0
15823     var descendants = 0
15824     var hasWidgets = false
15825     var hasThunks = false
15826     var descendantHooks = false
15827     var hooks
15828
15829     for (var propName in properties) {
15830         if (properties.hasOwnProperty(propName)) {
15831             var property = properties[propName]
15832             if (isVHook(property) && property.unhook) {
15833                 if (!hooks) {
15834                     hooks = {}
15835                 }
15836
15837                 hooks[propName] = property
15838             }
15839         }
15840     }
15841
15842     for (var i = 0; i < count; i++) {
15843         var child = children[i]
15844         if (isVNode(child)) {
15845             descendants += child.count || 0
15846
15847             if (!hasWidgets && child.hasWidgets) {
15848                 hasWidgets = true
15849             }
15850
15851             if (!hasThunks && child.hasThunks) {
15852                 hasThunks = true
15853             }
15854
15855             if (!descendantHooks && (child.hooks || child.descendantHooks)) {
15856                 descendantHooks = true
15857             }
15858         } else if (!hasWidgets && isWidget(child)) {
15859             if (typeof child.destroy === "function") {
15860                 hasWidgets = true
15861             }
15862         } else if (!hasThunks && isThunk(child)) {
15863             hasThunks = true;
15864         }
15865     }
15866
15867     this.count = count + descendants
15868     this.hasWidgets = hasWidgets
15869     this.hasThunks = hasThunks
15870     this.hooks = hooks
15871     this.descendantHooks = descendantHooks
15872 }
15873
15874 VirtualNode.prototype.version = version
15875 VirtualNode.prototype.type = "VirtualNode"
15876
15877 },{"./is-thunk":186,"./is-vhook":187,"./is-vnode":188,"./is-widget":190,"./version":191}],193:[function(require,module,exports){
15878 var version = require("./version")
15879
15880 VirtualPatch.NONE = 0
15881 VirtualPatch.VTEXT = 1
15882 VirtualPatch.VNODE = 2
15883 VirtualPatch.WIDGET = 3
15884 VirtualPatch.PROPS = 4
15885 VirtualPatch.ORDER = 5
15886 VirtualPatch.INSERT = 6
15887 VirtualPatch.REMOVE = 7
15888 VirtualPatch.THUNK = 8
15889
15890 module.exports = VirtualPatch
15891
15892 function VirtualPatch(type, vNode, patch) {
15893     this.type = Number(type)
15894     this.vNode = vNode
15895     this.patch = patch
15896 }
15897
15898 VirtualPatch.prototype.version = version
15899 VirtualPatch.prototype.type = "VirtualPatch"
15900
15901 },{"./version":191}],194:[function(require,module,exports){
15902 var version = require("./version")
15903
15904 module.exports = VirtualText
15905
15906 function VirtualText(text) {
15907     this.text = String(text)
15908 }
15909
15910 VirtualText.prototype.version = version
15911 VirtualText.prototype.type = "VirtualText"
15912
15913 },{"./version":191}],195:[function(require,module,exports){
15914 var isObject = require("is-object")
15915 var isHook = require("../vnode/is-vhook")
15916
15917 module.exports = diffProps
15918
15919 function diffProps(a, b) {
15920     var diff
15921
15922     for (var aKey in a) {
15923         if (!(aKey in b)) {
15924             diff = diff || {}
15925             diff[aKey] = undefined
15926         }
15927
15928         var aValue = a[aKey]
15929         var bValue = b[aKey]
15930
15931         if (aValue === bValue) {
15932             continue
15933         } else if (isObject(aValue) && isObject(bValue)) {
15934             if (getPrototype(bValue) !== getPrototype(aValue)) {
15935                 diff = diff || {}
15936                 diff[aKey] = bValue
15937             } else if (isHook(bValue)) {
15938                  diff = diff || {}
15939                  diff[aKey] = bValue
15940             } else {
15941                 var objectDiff = diffProps(aValue, bValue)
15942                 if (objectDiff) {
15943                     diff = diff || {}
15944                     diff[aKey] = objectDiff
15945                 }
15946             }
15947         } else {
15948             diff = diff || {}
15949             diff[aKey] = bValue
15950         }
15951     }
15952
15953     for (var bKey in b) {
15954         if (!(bKey in a)) {
15955             diff = diff || {}
15956             diff[bKey] = b[bKey]
15957         }
15958     }
15959
15960     return diff
15961 }
15962
15963 function getPrototype(value) {
15964   if (Object.getPrototypeOf) {
15965     return Object.getPrototypeOf(value)
15966   } else if (value.__proto__) {
15967     return value.__proto__
15968   } else if (value.constructor) {
15969     return value.constructor.prototype
15970   }
15971 }
15972
15973 },{"../vnode/is-vhook":187,"is-object":18}],196:[function(require,module,exports){
15974 var isArray = require("x-is-array")
15975
15976 var VPatch = require("../vnode/vpatch")
15977 var isVNode = require("../vnode/is-vnode")
15978 var isVText = require("../vnode/is-vtext")
15979 var isWidget = require("../vnode/is-widget")
15980 var isThunk = require("../vnode/is-thunk")
15981 var handleThunk = require("../vnode/handle-thunk")
15982
15983 var diffProps = require("./diff-props")
15984
15985 module.exports = diff
15986
15987 function diff(a, b) {
15988     var patch = { a: a }
15989     walk(a, b, patch, 0)
15990     return patch
15991 }
15992
15993 function walk(a, b, patch, index) {
15994     if (a === b) {
15995         return
15996     }
15997
15998     var apply = patch[index]
15999     var applyClear = false
16000
16001     if (isThunk(a) || isThunk(b)) {
16002         thunks(a, b, patch, index)
16003     } else if (b == null) {
16004
16005         // If a is a widget we will add a remove patch for it
16006         // Otherwise any child widgets/hooks must be destroyed.
16007         // This prevents adding two remove patches for a widget.
16008         if (!isWidget(a)) {
16009             clearState(a, patch, index)
16010             apply = patch[index]
16011         }
16012
16013         apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
16014     } else if (isVNode(b)) {
16015         if (isVNode(a)) {
16016             if (a.tagName === b.tagName &&
16017                 a.namespace === b.namespace &&
16018                 a.key === b.key) {
16019                 var propsPatch = diffProps(a.properties, b.properties)
16020                 if (propsPatch) {
16021                     apply = appendPatch(apply,
16022                         new VPatch(VPatch.PROPS, a, propsPatch))
16023                 }
16024                 apply = diffChildren(a, b, patch, apply, index)
16025             } else {
16026                 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
16027                 applyClear = true
16028             }
16029         } else {
16030             apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
16031             applyClear = true
16032         }
16033     } else if (isVText(b)) {
16034         if (!isVText(a)) {
16035             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
16036             applyClear = true
16037         } else if (a.text !== b.text) {
16038             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
16039         }
16040     } else if (isWidget(b)) {
16041         if (!isWidget(a)) {
16042             applyClear = true
16043         }
16044
16045         apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
16046     }
16047
16048     if (apply) {
16049         patch[index] = apply
16050     }
16051
16052     if (applyClear) {
16053         clearState(a, patch, index)
16054     }
16055 }
16056
16057 function diffChildren(a, b, patch, apply, index) {
16058     var aChildren = a.children
16059     var orderedSet = reorder(aChildren, b.children)
16060     var bChildren = orderedSet.children
16061
16062     var aLen = aChildren.length
16063     var bLen = bChildren.length
16064     var len = aLen > bLen ? aLen : bLen
16065
16066     for (var i = 0; i < len; i++) {
16067         var leftNode = aChildren[i]
16068         var rightNode = bChildren[i]
16069         index += 1
16070
16071         if (!leftNode) {
16072             if (rightNode) {
16073                 // Excess nodes in b need to be added
16074                 apply = appendPatch(apply,
16075                     new VPatch(VPatch.INSERT, null, rightNode))
16076             }
16077         } else {
16078             walk(leftNode, rightNode, patch, index)
16079         }
16080
16081         if (isVNode(leftNode) && leftNode.count) {
16082             index += leftNode.count
16083         }
16084     }
16085
16086     if (orderedSet.moves) {
16087         // Reorder nodes last
16088         apply = appendPatch(apply, new VPatch(
16089             VPatch.ORDER,
16090             a,
16091             orderedSet.moves
16092         ))
16093     }
16094
16095     return apply
16096 }
16097
16098 function clearState(vNode, patch, index) {
16099     // TODO: Make this a single walk, not two
16100     unhook(vNode, patch, index)
16101     destroyWidgets(vNode, patch, index)
16102 }
16103
16104 // Patch records for all destroyed widgets must be added because we need
16105 // a DOM node reference for the destroy function
16106 function destroyWidgets(vNode, patch, index) {
16107     if (isWidget(vNode)) {
16108         if (typeof vNode.destroy === "function") {
16109             patch[index] = appendPatch(
16110                 patch[index],
16111                 new VPatch(VPatch.REMOVE, vNode, null)
16112             )
16113         }
16114     } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
16115         var children = vNode.children
16116         var len = children.length
16117         for (var i = 0; i < len; i++) {
16118             var child = children[i]
16119             index += 1
16120
16121             destroyWidgets(child, patch, index)
16122
16123             if (isVNode(child) && child.count) {
16124                 index += child.count
16125             }
16126         }
16127     } else if (isThunk(vNode)) {
16128         thunks(vNode, null, patch, index)
16129     }
16130 }
16131
16132 // Create a sub-patch for thunks
16133 function thunks(a, b, patch, index) {
16134     var nodes = handleThunk(a, b)
16135     var thunkPatch = diff(nodes.a, nodes.b)
16136     if (hasPatches(thunkPatch)) {
16137         patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
16138     }
16139 }
16140
16141 function hasPatches(patch) {
16142     for (var index in patch) {
16143         if (index !== "a") {
16144             return true
16145         }
16146     }
16147
16148     return false
16149 }
16150
16151 // Execute hooks when two nodes are identical
16152 function unhook(vNode, patch, index) {
16153     if (isVNode(vNode)) {
16154         if (vNode.hooks) {
16155             patch[index] = appendPatch(
16156                 patch[index],
16157                 new VPatch(
16158                     VPatch.PROPS,
16159                     vNode,
16160                     undefinedKeys(vNode.hooks)
16161                 )
16162             )
16163         }
16164
16165         if (vNode.descendantHooks || vNode.hasThunks) {
16166             var children = vNode.children
16167             var len = children.length
16168             for (var i = 0; i < len; i++) {
16169                 var child = children[i]
16170                 index += 1
16171
16172                 unhook(child, patch, index)
16173
16174                 if (isVNode(child) && child.count) {
16175                     index += child.count
16176                 }
16177             }
16178         }
16179     } else if (isThunk(vNode)) {
16180         thunks(vNode, null, patch, index)
16181     }
16182 }
16183
16184 function undefinedKeys(obj) {
16185     var result = {}
16186
16187     for (var key in obj) {
16188         result[key] = undefined
16189     }
16190
16191     return result
16192 }
16193
16194 // List diff, naive left to right reordering
16195 function reorder(aChildren, bChildren) {
16196     // O(M) time, O(M) memory
16197     var bChildIndex = keyIndex(bChildren)
16198     var bKeys = bChildIndex.keys
16199     var bFree = bChildIndex.free
16200
16201     if (bFree.length === bChildren.length) {
16202         return {
16203             children: bChildren,
16204             moves: null
16205         }
16206     }
16207
16208     // O(N) time, O(N) memory
16209     var aChildIndex = keyIndex(aChildren)
16210     var aKeys = aChildIndex.keys
16211     var aFree = aChildIndex.free
16212
16213     if (aFree.length === aChildren.length) {
16214         return {
16215             children: bChildren,
16216             moves: null
16217         }
16218     }
16219
16220     // O(MAX(N, M)) memory
16221     var newChildren = []
16222
16223     var freeIndex = 0
16224     var freeCount = bFree.length
16225     var deletedItems = 0
16226
16227     // Iterate through a and match a node in b
16228     // O(N) time,
16229     for (var i = 0 ; i < aChildren.length; i++) {
16230         var aItem = aChildren[i]
16231         var itemIndex
16232
16233         if (aItem.key) {
16234             if (bKeys.hasOwnProperty(aItem.key)) {
16235                 // Match up the old keys
16236                 itemIndex = bKeys[aItem.key]
16237                 newChildren.push(bChildren[itemIndex])
16238
16239             } else {
16240                 // Remove old keyed items
16241                 itemIndex = i - deletedItems++
16242                 newChildren.push(null)
16243             }
16244         } else {
16245             // Match the item in a with the next free item in b
16246             if (freeIndex < freeCount) {
16247                 itemIndex = bFree[freeIndex++]
16248                 newChildren.push(bChildren[itemIndex])
16249             } else {
16250                 // There are no free items in b to match with
16251                 // the free items in a, so the extra free nodes
16252                 // are deleted.
16253                 itemIndex = i - deletedItems++
16254                 newChildren.push(null)
16255             }
16256         }
16257     }
16258
16259     var lastFreeIndex = freeIndex >= bFree.length ?
16260         bChildren.length :
16261         bFree[freeIndex]
16262
16263     // Iterate through b and append any new keys
16264     // O(M) time
16265     for (var j = 0; j < bChildren.length; j++) {
16266         var newItem = bChildren[j]
16267
16268         if (newItem.key) {
16269             if (!aKeys.hasOwnProperty(newItem.key)) {
16270                 // Add any new keyed items
16271                 // We are adding new items to the end and then sorting them
16272                 // in place. In future we should insert new items in place.
16273                 newChildren.push(newItem)
16274             }
16275         } else if (j >= lastFreeIndex) {
16276             // Add any leftover non-keyed items
16277             newChildren.push(newItem)
16278         }
16279     }
16280
16281     var simulate = newChildren.slice()
16282     var simulateIndex = 0
16283     var removes = []
16284     var inserts = []
16285     var simulateItem
16286
16287     for (var k = 0; k < bChildren.length;) {
16288         var wantedItem = bChildren[k]
16289         simulateItem = simulate[simulateIndex]
16290
16291         // remove items
16292         while (simulateItem === null && simulate.length) {
16293             removes.push(remove(simulate, simulateIndex, null))
16294             simulateItem = simulate[simulateIndex]
16295         }
16296
16297         if (!simulateItem || simulateItem.key !== wantedItem.key) {
16298             // if we need a key in this position...
16299             if (wantedItem.key) {
16300                 if (simulateItem && simulateItem.key) {
16301                     // if an insert doesn't put this key in place, it needs to move
16302                     if (bKeys[simulateItem.key] !== k + 1) {
16303                         removes.push(remove(simulate, simulateIndex, simulateItem.key))
16304                         simulateItem = simulate[simulateIndex]
16305                         // if the remove didn't put the wanted item in place, we need to insert it
16306                         if (!simulateItem || simulateItem.key !== wantedItem.key) {
16307                             inserts.push({key: wantedItem.key, to: k})
16308                         }
16309                         // items are matching, so skip ahead
16310                         else {
16311                             simulateIndex++
16312                         }
16313                     }
16314                     else {
16315                         inserts.push({key: wantedItem.key, to: k})
16316                     }
16317                 }
16318                 else {
16319                     inserts.push({key: wantedItem.key, to: k})
16320                 }
16321                 k++
16322             }
16323             // a key in simulate has no matching wanted key, remove it
16324             else if (simulateItem && simulateItem.key) {
16325                 removes.push(remove(simulate, simulateIndex, simulateItem.key))
16326             }
16327         }
16328         else {
16329             simulateIndex++
16330             k++
16331         }
16332     }
16333
16334     // remove all the remaining nodes from simulate
16335     while(simulateIndex < simulate.length) {
16336         simulateItem = simulate[simulateIndex]
16337         removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
16338     }
16339
16340     // If the only moves we have are deletes then we can just
16341     // let the delete patch remove these items.
16342     if (removes.length === deletedItems && !inserts.length) {
16343         return {
16344             children: newChildren,
16345             moves: null
16346         }
16347     }
16348
16349     return {
16350         children: newChildren,
16351         moves: {
16352             removes: removes,
16353             inserts: inserts
16354         }
16355     }
16356 }
16357
16358 function remove(arr, index, key) {
16359     arr.splice(index, 1)
16360
16361     return {
16362         from: index,
16363         key: key
16364     }
16365 }
16366
16367 function keyIndex(children) {
16368     var keys = {}
16369     var free = []
16370     var length = children.length
16371
16372     for (var i = 0; i < length; i++) {
16373         var child = children[i]
16374
16375         if (child.key) {
16376             keys[child.key] = i
16377         } else {
16378             free.push(i)
16379         }
16380     }
16381
16382     return {
16383         keys: keys,     // A hash of key name to index
16384         free: free      // An array of unkeyed item indices
16385     }
16386 }
16387
16388 function appendPatch(apply, patch) {
16389     if (apply) {
16390         if (isArray(apply)) {
16391             apply.push(patch)
16392         } else {
16393             apply = [apply, patch]
16394         }
16395
16396         return apply
16397     } else {
16398         return patch
16399     }
16400 }
16401
16402 },{"../vnode/handle-thunk":185,"../vnode/is-thunk":186,"../vnode/is-vnode":188,"../vnode/is-vtext":189,"../vnode/is-widget":190,"../vnode/vpatch":193,"./diff-props":195,"x-is-array":215}],197:[function(require,module,exports){
16403 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16404 /** @author Brian Cavalier */
16405 /** @author John Hann */
16406
16407 (function(define) { 'use strict';
16408 define(function (require) {
16409
16410         var makePromise = require('./makePromise');
16411         var Scheduler = require('./Scheduler');
16412         var async = require('./env').asap;
16413
16414         return makePromise({
16415                 scheduler: new Scheduler(async)
16416         });
16417
16418 });
16419 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
16420
16421 },{"./Scheduler":198,"./env":210,"./makePromise":212}],198:[function(require,module,exports){
16422 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16423 /** @author Brian Cavalier */
16424 /** @author John Hann */
16425
16426 (function(define) { 'use strict';
16427 define(function() {
16428
16429         // Credit to Twisol (https://github.com/Twisol) for suggesting
16430         // this type of extensible queue + trampoline approach for next-tick conflation.
16431
16432         /**
16433          * Async task scheduler
16434          * @param {function} async function to schedule a single async function
16435          * @constructor
16436          */
16437         function Scheduler(async) {
16438                 this._async = async;
16439                 this._running = false;
16440
16441                 this._queue = this;
16442                 this._queueLen = 0;
16443                 this._afterQueue = {};
16444                 this._afterQueueLen = 0;
16445
16446                 var self = this;
16447                 this.drain = function() {
16448                         self._drain();
16449                 };
16450         }
16451
16452         /**
16453          * Enqueue a task
16454          * @param {{ run:function }} task
16455          */
16456         Scheduler.prototype.enqueue = function(task) {
16457                 this._queue[this._queueLen++] = task;
16458                 this.run();
16459         };
16460
16461         /**
16462          * Enqueue a task to run after the main task queue
16463          * @param {{ run:function }} task
16464          */
16465         Scheduler.prototype.afterQueue = function(task) {
16466                 this._afterQueue[this._afterQueueLen++] = task;
16467                 this.run();
16468         };
16469
16470         Scheduler.prototype.run = function() {
16471                 if (!this._running) {
16472                         this._running = true;
16473                         this._async(this.drain);
16474                 }
16475         };
16476
16477         /**
16478          * Drain the handler queue entirely, and then the after queue
16479          */
16480         Scheduler.prototype._drain = function() {
16481                 var i = 0;
16482                 for (; i < this._queueLen; ++i) {
16483                         this._queue[i].run();
16484                         this._queue[i] = void 0;
16485                 }
16486
16487                 this._queueLen = 0;
16488                 this._running = false;
16489
16490                 for (i = 0; i < this._afterQueueLen; ++i) {
16491                         this._afterQueue[i].run();
16492                         this._afterQueue[i] = void 0;
16493                 }
16494
16495                 this._afterQueueLen = 0;
16496         };
16497
16498         return Scheduler;
16499
16500 });
16501 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16502
16503 },{}],199:[function(require,module,exports){
16504 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16505 /** @author Brian Cavalier */
16506 /** @author John Hann */
16507
16508 (function(define) { 'use strict';
16509 define(function() {
16510
16511         /**
16512          * Custom error type for promises rejected by promise.timeout
16513          * @param {string} message
16514          * @constructor
16515          */
16516         function TimeoutError (message) {
16517                 Error.call(this);
16518                 this.message = message;
16519                 this.name = TimeoutError.name;
16520                 if (typeof Error.captureStackTrace === 'function') {
16521                         Error.captureStackTrace(this, TimeoutError);
16522                 }
16523         }
16524
16525         TimeoutError.prototype = Object.create(Error.prototype);
16526         TimeoutError.prototype.constructor = TimeoutError;
16527
16528         return TimeoutError;
16529 });
16530 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16531 },{}],200:[function(require,module,exports){
16532 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16533 /** @author Brian Cavalier */
16534 /** @author John Hann */
16535
16536 (function(define) { 'use strict';
16537 define(function() {
16538
16539         makeApply.tryCatchResolve = tryCatchResolve;
16540
16541         return makeApply;
16542
16543         function makeApply(Promise, call) {
16544                 if(arguments.length < 2) {
16545                         call = tryCatchResolve;
16546                 }
16547
16548                 return apply;
16549
16550                 function apply(f, thisArg, args) {
16551                         var p = Promise._defer();
16552                         var l = args.length;
16553                         var params = new Array(l);
16554                         callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
16555
16556                         return p;
16557                 }
16558
16559                 function callAndResolve(c, h) {
16560                         if(c.i < 0) {
16561                                 return call(c.f, c.thisArg, c.params, h);
16562                         }
16563
16564                         var handler = Promise._handler(c.args[c.i]);
16565                         handler.fold(callAndResolveNext, c, void 0, h);
16566                 }
16567
16568                 function callAndResolveNext(c, x, h) {
16569                         c.params[c.i] = x;
16570                         c.i -= 1;
16571                         callAndResolve(c, h);
16572                 }
16573         }
16574
16575         function tryCatchResolve(f, thisArg, args, resolver) {
16576                 try {
16577                         resolver.resolve(f.apply(thisArg, args));
16578                 } catch(e) {
16579                         resolver.reject(e);
16580                 }
16581         }
16582
16583 });
16584 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16585
16586
16587
16588 },{}],201:[function(require,module,exports){
16589 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16590 /** @author Brian Cavalier */
16591 /** @author John Hann */
16592
16593 (function(define) { 'use strict';
16594 define(function(require) {
16595
16596         var state = require('../state');
16597         var applier = require('../apply');
16598
16599         return function array(Promise) {
16600
16601                 var applyFold = applier(Promise);
16602                 var toPromise = Promise.resolve;
16603                 var all = Promise.all;
16604
16605                 var ar = Array.prototype.reduce;
16606                 var arr = Array.prototype.reduceRight;
16607                 var slice = Array.prototype.slice;
16608
16609                 // Additional array combinators
16610
16611                 Promise.any = any;
16612                 Promise.some = some;
16613                 Promise.settle = settle;
16614
16615                 Promise.map = map;
16616                 Promise.filter = filter;
16617                 Promise.reduce = reduce;
16618                 Promise.reduceRight = reduceRight;
16619
16620                 /**
16621                  * When this promise fulfills with an array, do
16622                  * onFulfilled.apply(void 0, array)
16623                  * @param {function} onFulfilled function to apply
16624                  * @returns {Promise} promise for the result of applying onFulfilled
16625                  */
16626                 Promise.prototype.spread = function(onFulfilled) {
16627                         return this.then(all).then(function(array) {
16628                                 return onFulfilled.apply(this, array);
16629                         });
16630                 };
16631
16632                 return Promise;
16633
16634                 /**
16635                  * One-winner competitive race.
16636                  * Return a promise that will fulfill when one of the promises
16637                  * in the input array fulfills, or will reject when all promises
16638                  * have rejected.
16639                  * @param {array} promises
16640                  * @returns {Promise} promise for the first fulfilled value
16641                  */
16642                 function any(promises) {
16643                         var p = Promise._defer();
16644                         var resolver = p._handler;
16645                         var l = promises.length>>>0;
16646
16647                         var pending = l;
16648                         var errors = [];
16649
16650                         for (var h, x, i = 0; i < l; ++i) {
16651                                 x = promises[i];
16652                                 if(x === void 0 && !(i in promises)) {
16653                                         --pending;
16654                                         continue;
16655                                 }
16656
16657                                 h = Promise._handler(x);
16658                                 if(h.state() > 0) {
16659                                         resolver.become(h);
16660                                         Promise._visitRemaining(promises, i, h);
16661                                         break;
16662                                 } else {
16663                                         h.visit(resolver, handleFulfill, handleReject);
16664                                 }
16665                         }
16666
16667                         if(pending === 0) {
16668                                 resolver.reject(new RangeError('any(): array must not be empty'));
16669                         }
16670
16671                         return p;
16672
16673                         function handleFulfill(x) {
16674                                 /*jshint validthis:true*/
16675                                 errors = null;
16676                                 this.resolve(x); // this === resolver
16677                         }
16678
16679                         function handleReject(e) {
16680                                 /*jshint validthis:true*/
16681                                 if(this.resolved) { // this === resolver
16682                                         return;
16683                                 }
16684
16685                                 errors.push(e);
16686                                 if(--pending === 0) {
16687                                         this.reject(errors);
16688                                 }
16689                         }
16690                 }
16691
16692                 /**
16693                  * N-winner competitive race
16694                  * Return a promise that will fulfill when n input promises have
16695                  * fulfilled, or will reject when it becomes impossible for n
16696                  * input promises to fulfill (ie when promises.length - n + 1
16697                  * have rejected)
16698                  * @param {array} promises
16699                  * @param {number} n
16700                  * @returns {Promise} promise for the earliest n fulfillment values
16701                  *
16702                  * @deprecated
16703                  */
16704                 function some(promises, n) {
16705                         /*jshint maxcomplexity:7*/
16706                         var p = Promise._defer();
16707                         var resolver = p._handler;
16708
16709                         var results = [];
16710                         var errors = [];
16711
16712                         var l = promises.length>>>0;
16713                         var nFulfill = 0;
16714                         var nReject;
16715                         var x, i; // reused in both for() loops
16716
16717                         // First pass: count actual array items
16718                         for(i=0; i<l; ++i) {
16719                                 x = promises[i];
16720                                 if(x === void 0 && !(i in promises)) {
16721                                         continue;
16722                                 }
16723                                 ++nFulfill;
16724                         }
16725
16726                         // Compute actual goals
16727                         n = Math.max(n, 0);
16728                         nReject = (nFulfill - n + 1);
16729                         nFulfill = Math.min(n, nFulfill);
16730
16731                         if(n > nFulfill) {
16732                                 resolver.reject(new RangeError('some(): array must contain at least '
16733                                 + n + ' item(s), but had ' + nFulfill));
16734                         } else if(nFulfill === 0) {
16735                                 resolver.resolve(results);
16736                         }
16737
16738                         // Second pass: observe each array item, make progress toward goals
16739                         for(i=0; i<l; ++i) {
16740                                 x = promises[i];
16741                                 if(x === void 0 && !(i in promises)) {
16742                                         continue;
16743                                 }
16744
16745                                 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
16746                         }
16747
16748                         return p;
16749
16750                         function fulfill(x) {
16751                                 /*jshint validthis:true*/
16752                                 if(this.resolved) { // this === resolver
16753                                         return;
16754                                 }
16755
16756                                 results.push(x);
16757                                 if(--nFulfill === 0) {
16758                                         errors = null;
16759                                         this.resolve(results);
16760                                 }
16761                         }
16762
16763                         function reject(e) {
16764                                 /*jshint validthis:true*/
16765                                 if(this.resolved) { // this === resolver
16766                                         return;
16767                                 }
16768
16769                                 errors.push(e);
16770                                 if(--nReject === 0) {
16771                                         results = null;
16772                                         this.reject(errors);
16773                                 }
16774                         }
16775                 }
16776
16777                 /**
16778                  * Apply f to the value of each promise in a list of promises
16779                  * and return a new list containing the results.
16780                  * @param {array} promises
16781                  * @param {function(x:*, index:Number):*} f mapping function
16782                  * @returns {Promise}
16783                  */
16784                 function map(promises, f) {
16785                         return Promise._traverse(f, promises);
16786                 }
16787
16788                 /**
16789                  * Filter the provided array of promises using the provided predicate.  Input may
16790                  * contain promises and values
16791                  * @param {Array} promises array of promises and values
16792                  * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
16793                  *  Must return truthy (or promise for truthy) for items to retain.
16794                  * @returns {Promise} promise that will fulfill with an array containing all items
16795                  *  for which predicate returned truthy.
16796                  */
16797                 function filter(promises, predicate) {
16798                         var a = slice.call(promises);
16799                         return Promise._traverse(predicate, a).then(function(keep) {
16800                                 return filterSync(a, keep);
16801                         });
16802                 }
16803
16804                 function filterSync(promises, keep) {
16805                         // Safe because we know all promises have fulfilled if we've made it this far
16806                         var l = keep.length;
16807                         var filtered = new Array(l);
16808                         for(var i=0, j=0; i<l; ++i) {
16809                                 if(keep[i]) {
16810                                         filtered[j++] = Promise._handler(promises[i]).value;
16811                                 }
16812                         }
16813                         filtered.length = j;
16814                         return filtered;
16815
16816                 }
16817
16818                 /**
16819                  * Return a promise that will always fulfill with an array containing
16820                  * the outcome states of all input promises.  The returned promise
16821                  * will never reject.
16822                  * @param {Array} promises
16823                  * @returns {Promise} promise for array of settled state descriptors
16824                  */
16825                 function settle(promises) {
16826                         return all(promises.map(settleOne));
16827                 }
16828
16829                 function settleOne(p) {
16830                         var h = Promise._handler(p);
16831                         if(h.state() === 0) {
16832                                 return toPromise(p).then(state.fulfilled, state.rejected);
16833                         }
16834
16835                         h._unreport();
16836                         return state.inspect(h);
16837                 }
16838
16839                 /**
16840                  * Traditional reduce function, similar to `Array.prototype.reduce()`, but
16841                  * input may contain promises and/or values, and reduceFunc
16842                  * may return either a value or a promise, *and* initialValue may
16843                  * be a promise for the starting value.
16844                  * @param {Array|Promise} promises array or promise for an array of anything,
16845                  *      may contain a mix of promises and values.
16846                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
16847                  * @returns {Promise} that will resolve to the final reduced value
16848                  */
16849                 function reduce(promises, f /*, initialValue */) {
16850                         return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
16851                                         : ar.call(promises, liftCombine(f));
16852                 }
16853
16854                 /**
16855                  * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
16856                  * input may contain promises and/or values, and reduceFunc
16857                  * may return either a value or a promise, *and* initialValue may
16858                  * be a promise for the starting value.
16859                  * @param {Array|Promise} promises array or promise for an array of anything,
16860                  *      may contain a mix of promises and values.
16861                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
16862                  * @returns {Promise} that will resolve to the final reduced value
16863                  */
16864                 function reduceRight(promises, f /*, initialValue */) {
16865                         return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
16866                                         : arr.call(promises, liftCombine(f));
16867                 }
16868
16869                 function liftCombine(f) {
16870                         return function(z, x, i) {
16871                                 return applyFold(f, void 0, [z,x,i]);
16872                         };
16873                 }
16874         };
16875
16876 });
16877 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
16878
16879 },{"../apply":200,"../state":213}],202:[function(require,module,exports){
16880 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16881 /** @author Brian Cavalier */
16882 /** @author John Hann */
16883
16884 (function(define) { 'use strict';
16885 define(function() {
16886
16887         return function flow(Promise) {
16888
16889                 var resolve = Promise.resolve;
16890                 var reject = Promise.reject;
16891                 var origCatch = Promise.prototype['catch'];
16892
16893                 /**
16894                  * Handle the ultimate fulfillment value or rejection reason, and assume
16895                  * responsibility for all errors.  If an error propagates out of result
16896                  * or handleFatalError, it will be rethrown to the host, resulting in a
16897                  * loud stack track on most platforms and a crash on some.
16898                  * @param {function?} onResult
16899                  * @param {function?} onError
16900                  * @returns {undefined}
16901                  */
16902                 Promise.prototype.done = function(onResult, onError) {
16903                         this._handler.visit(this._handler.receiver, onResult, onError);
16904                 };
16905
16906                 /**
16907                  * Add Error-type and predicate matching to catch.  Examples:
16908                  * promise.catch(TypeError, handleTypeError)
16909                  *   .catch(predicate, handleMatchedErrors)
16910                  *   .catch(handleRemainingErrors)
16911                  * @param onRejected
16912                  * @returns {*}
16913                  */
16914                 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
16915                         if (arguments.length < 2) {
16916                                 return origCatch.call(this, onRejected);
16917                         }
16918
16919                         if(typeof onRejected !== 'function') {
16920                                 return this.ensure(rejectInvalidPredicate);
16921                         }
16922
16923                         return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
16924                 };
16925
16926                 /**
16927                  * Wraps the provided catch handler, so that it will only be called
16928                  * if the predicate evaluates truthy
16929                  * @param {?function} handler
16930                  * @param {function} predicate
16931                  * @returns {function} conditional catch handler
16932                  */
16933                 function createCatchFilter(handler, predicate) {
16934                         return function(e) {
16935                                 return evaluatePredicate(e, predicate)
16936                                         ? handler.call(this, e)
16937                                         : reject(e);
16938                         };
16939                 }
16940
16941                 /**
16942                  * Ensures that onFulfilledOrRejected will be called regardless of whether
16943                  * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
16944                  * receive the promises' value or reason.  Any returned value will be disregarded.
16945                  * onFulfilledOrRejected may throw or return a rejected promise to signal
16946                  * an additional error.
16947                  * @param {function} handler handler to be called regardless of
16948                  *  fulfillment or rejection
16949                  * @returns {Promise}
16950                  */
16951                 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
16952                         if(typeof handler !== 'function') {
16953                                 return this;
16954                         }
16955
16956                         return this.then(function(x) {
16957                                 return runSideEffect(handler, this, identity, x);
16958                         }, function(e) {
16959                                 return runSideEffect(handler, this, reject, e);
16960                         });
16961                 };
16962
16963                 function runSideEffect (handler, thisArg, propagate, value) {
16964                         var result = handler.call(thisArg);
16965                         return maybeThenable(result)
16966                                 ? propagateValue(result, propagate, value)
16967                                 : propagate(value);
16968                 }
16969
16970                 function propagateValue (result, propagate, x) {
16971                         return resolve(result).then(function () {
16972                                 return propagate(x);
16973                         });
16974                 }
16975
16976                 /**
16977                  * Recover from a failure by returning a defaultValue.  If defaultValue
16978                  * is a promise, it's fulfillment value will be used.  If defaultValue is
16979                  * a promise that rejects, the returned promise will reject with the
16980                  * same reason.
16981                  * @param {*} defaultValue
16982                  * @returns {Promise} new promise
16983                  */
16984                 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
16985                         return this.then(void 0, function() {
16986                                 return defaultValue;
16987                         });
16988                 };
16989
16990                 /**
16991                  * Shortcut for .then(function() { return value; })
16992                  * @param  {*} value
16993                  * @return {Promise} a promise that:
16994                  *  - is fulfilled if value is not a promise, or
16995                  *  - if value is a promise, will fulfill with its value, or reject
16996                  *    with its reason.
16997                  */
16998                 Promise.prototype['yield'] = function(value) {
16999                         return this.then(function() {
17000                                 return value;
17001                         });
17002                 };
17003
17004                 /**
17005                  * Runs a side effect when this promise fulfills, without changing the
17006                  * fulfillment value.
17007                  * @param {function} onFulfilledSideEffect
17008                  * @returns {Promise}
17009                  */
17010                 Promise.prototype.tap = function(onFulfilledSideEffect) {
17011                         return this.then(onFulfilledSideEffect)['yield'](this);
17012                 };
17013
17014                 return Promise;
17015         };
17016
17017         function rejectInvalidPredicate() {
17018                 throw new TypeError('catch predicate must be a function');
17019         }
17020
17021         function evaluatePredicate(e, predicate) {
17022                 return isError(predicate) ? e instanceof predicate : predicate(e);
17023         }
17024
17025         function isError(predicate) {
17026                 return predicate === Error
17027                         || (predicate != null && predicate.prototype instanceof Error);
17028         }
17029
17030         function maybeThenable(x) {
17031                 return (typeof x === 'object' || typeof x === 'function') && x !== null;
17032         }
17033
17034         function identity(x) {
17035                 return x;
17036         }
17037
17038 });
17039 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17040
17041 },{}],203:[function(require,module,exports){
17042 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17043 /** @author Brian Cavalier */
17044 /** @author John Hann */
17045 /** @author Jeff Escalante */
17046
17047 (function(define) { 'use strict';
17048 define(function() {
17049
17050         return function fold(Promise) {
17051
17052                 Promise.prototype.fold = function(f, z) {
17053                         var promise = this._beget();
17054
17055                         this._handler.fold(function(z, x, to) {
17056                                 Promise._handler(z).fold(function(x, z, to) {
17057                                         to.resolve(f.call(this, z, x));
17058                                 }, x, this, to);
17059                         }, z, promise._handler.receiver, promise._handler);
17060
17061                         return promise;
17062                 };
17063
17064                 return Promise;
17065         };
17066
17067 });
17068 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17069
17070 },{}],204:[function(require,module,exports){
17071 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17072 /** @author Brian Cavalier */
17073 /** @author John Hann */
17074
17075 (function(define) { 'use strict';
17076 define(function(require) {
17077
17078         var inspect = require('../state').inspect;
17079
17080         return function inspection(Promise) {
17081
17082                 Promise.prototype.inspect = function() {
17083                         return inspect(Promise._handler(this));
17084                 };
17085
17086                 return Promise;
17087         };
17088
17089 });
17090 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17091
17092 },{"../state":213}],205:[function(require,module,exports){
17093 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17094 /** @author Brian Cavalier */
17095 /** @author John Hann */
17096
17097 (function(define) { 'use strict';
17098 define(function() {
17099
17100         return function generate(Promise) {
17101
17102                 var resolve = Promise.resolve;
17103
17104                 Promise.iterate = iterate;
17105                 Promise.unfold = unfold;
17106
17107                 return Promise;
17108
17109                 /**
17110                  * @deprecated Use github.com/cujojs/most streams and most.iterate
17111                  * Generate a (potentially infinite) stream of promised values:
17112                  * x, f(x), f(f(x)), etc. until condition(x) returns true
17113                  * @param {function} f function to generate a new x from the previous x
17114                  * @param {function} condition function that, given the current x, returns
17115                  *  truthy when the iterate should stop
17116                  * @param {function} handler function to handle the value produced by f
17117                  * @param {*|Promise} x starting value, may be a promise
17118                  * @return {Promise} the result of the last call to f before
17119                  *  condition returns true
17120                  */
17121                 function iterate(f, condition, handler, x) {
17122                         return unfold(function(x) {
17123                                 return [x, f(x)];
17124                         }, condition, handler, x);
17125                 }
17126
17127                 /**
17128                  * @deprecated Use github.com/cujojs/most streams and most.unfold
17129                  * Generate a (potentially infinite) stream of promised values
17130                  * by applying handler(generator(seed)) iteratively until
17131                  * condition(seed) returns true.
17132                  * @param {function} unspool function that generates a [value, newSeed]
17133                  *  given a seed.
17134                  * @param {function} condition function that, given the current seed, returns
17135                  *  truthy when the unfold should stop
17136                  * @param {function} handler function to handle the value produced by unspool
17137                  * @param x {*|Promise} starting value, may be a promise
17138                  * @return {Promise} the result of the last value produced by unspool before
17139                  *  condition returns true
17140                  */
17141                 function unfold(unspool, condition, handler, x) {
17142                         return resolve(x).then(function(seed) {
17143                                 return resolve(condition(seed)).then(function(done) {
17144                                         return done ? seed : resolve(unspool(seed)).spread(next);
17145                                 });
17146                         });
17147
17148                         function next(item, newSeed) {
17149                                 return resolve(handler(item)).then(function() {
17150                                         return unfold(unspool, condition, handler, newSeed);
17151                                 });
17152                         }
17153                 }
17154         };
17155
17156 });
17157 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17158
17159 },{}],206:[function(require,module,exports){
17160 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17161 /** @author Brian Cavalier */
17162 /** @author John Hann */
17163
17164 (function(define) { 'use strict';
17165 define(function() {
17166
17167         return function progress(Promise) {
17168
17169                 /**
17170                  * @deprecated
17171                  * Register a progress handler for this promise
17172                  * @param {function} onProgress
17173                  * @returns {Promise}
17174                  */
17175                 Promise.prototype.progress = function(onProgress) {
17176                         return this.then(void 0, void 0, onProgress);
17177                 };
17178
17179                 return Promise;
17180         };
17181
17182 });
17183 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17184
17185 },{}],207:[function(require,module,exports){
17186 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17187 /** @author Brian Cavalier */
17188 /** @author John Hann */
17189
17190 (function(define) { 'use strict';
17191 define(function(require) {
17192
17193         var env = require('../env');
17194         var TimeoutError = require('../TimeoutError');
17195
17196         function setTimeout(f, ms, x, y) {
17197                 return env.setTimer(function() {
17198                         f(x, y, ms);
17199                 }, ms);
17200         }
17201
17202         return function timed(Promise) {
17203                 /**
17204                  * Return a new promise whose fulfillment value is revealed only
17205                  * after ms milliseconds
17206                  * @param {number} ms milliseconds
17207                  * @returns {Promise}
17208                  */
17209                 Promise.prototype.delay = function(ms) {
17210                         var p = this._beget();
17211                         this._handler.fold(handleDelay, ms, void 0, p._handler);
17212                         return p;
17213                 };
17214
17215                 function handleDelay(ms, x, h) {
17216                         setTimeout(resolveDelay, ms, x, h);
17217                 }
17218
17219                 function resolveDelay(x, h) {
17220                         h.resolve(x);
17221                 }
17222
17223                 /**
17224                  * Return a new promise that rejects after ms milliseconds unless
17225                  * this promise fulfills earlier, in which case the returned promise
17226                  * fulfills with the same value.
17227                  * @param {number} ms milliseconds
17228                  * @param {Error|*=} reason optional rejection reason to use, defaults
17229                  *   to a TimeoutError if not provided
17230                  * @returns {Promise}
17231                  */
17232                 Promise.prototype.timeout = function(ms, reason) {
17233                         var p = this._beget();
17234                         var h = p._handler;
17235
17236                         var t = setTimeout(onTimeout, ms, reason, p._handler);
17237
17238                         this._handler.visit(h,
17239                                 function onFulfill(x) {
17240                                         env.clearTimer(t);
17241                                         this.resolve(x); // this = h
17242                                 },
17243                                 function onReject(x) {
17244                                         env.clearTimer(t);
17245                                         this.reject(x); // this = h
17246                                 },
17247                                 h.notify);
17248
17249                         return p;
17250                 };
17251
17252                 function onTimeout(reason, h, ms) {
17253                         var e = typeof reason === 'undefined'
17254                                 ? new TimeoutError('timed out after ' + ms + 'ms')
17255                                 : reason;
17256                         h.reject(e);
17257                 }
17258
17259                 return Promise;
17260         };
17261
17262 });
17263 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17264
17265 },{"../TimeoutError":199,"../env":210}],208:[function(require,module,exports){
17266 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17267 /** @author Brian Cavalier */
17268 /** @author John Hann */
17269
17270 (function(define) { 'use strict';
17271 define(function(require) {
17272
17273         var setTimer = require('../env').setTimer;
17274         var format = require('../format');
17275
17276         return function unhandledRejection(Promise) {
17277
17278                 var logError = noop;
17279                 var logInfo = noop;
17280                 var localConsole;
17281
17282                 if(typeof console !== 'undefined') {
17283                         // Alias console to prevent things like uglify's drop_console option from
17284                         // removing console.log/error. Unhandled rejections fall into the same
17285                         // category as uncaught exceptions, and build tools shouldn't silence them.
17286                         localConsole = console;
17287                         logError = typeof localConsole.error !== 'undefined'
17288                                 ? function (e) { localConsole.error(e); }
17289                                 : function (e) { localConsole.log(e); };
17290
17291                         logInfo = typeof localConsole.info !== 'undefined'
17292                                 ? function (e) { localConsole.info(e); }
17293                                 : function (e) { localConsole.log(e); };
17294                 }
17295
17296                 Promise.onPotentiallyUnhandledRejection = function(rejection) {
17297                         enqueue(report, rejection);
17298                 };
17299
17300                 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
17301                         enqueue(unreport, rejection);
17302                 };
17303
17304                 Promise.onFatalRejection = function(rejection) {
17305                         enqueue(throwit, rejection.value);
17306                 };
17307
17308                 var tasks = [];
17309                 var reported = [];
17310                 var running = null;
17311
17312                 function report(r) {
17313                         if(!r.handled) {
17314                                 reported.push(r);
17315                                 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
17316                         }
17317                 }
17318
17319                 function unreport(r) {
17320                         var i = reported.indexOf(r);
17321                         if(i >= 0) {
17322                                 reported.splice(i, 1);
17323                                 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
17324                         }
17325                 }
17326
17327                 function enqueue(f, x) {
17328                         tasks.push(f, x);
17329                         if(running === null) {
17330                                 running = setTimer(flush, 0);
17331                         }
17332                 }
17333
17334                 function flush() {
17335                         running = null;
17336                         while(tasks.length > 0) {
17337                                 tasks.shift()(tasks.shift());
17338                         }
17339                 }
17340
17341                 return Promise;
17342         };
17343
17344         function throwit(e) {
17345                 throw e;
17346         }
17347
17348         function noop() {}
17349
17350 });
17351 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17352
17353 },{"../env":210,"../format":211}],209:[function(require,module,exports){
17354 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17355 /** @author Brian Cavalier */
17356 /** @author John Hann */
17357
17358 (function(define) { 'use strict';
17359 define(function() {
17360
17361         return function addWith(Promise) {
17362                 /**
17363                  * Returns a promise whose handlers will be called with `this` set to
17364                  * the supplied receiver.  Subsequent promises derived from the
17365                  * returned promise will also have their handlers called with receiver
17366                  * as `this`. Calling `with` with undefined or no arguments will return
17367                  * a promise whose handlers will again be called in the usual Promises/A+
17368                  * way (no `this`) thus safely undoing any previous `with` in the
17369                  * promise chain.
17370                  *
17371                  * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
17372                  * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
17373                  *
17374                  * @param {object} receiver `this` value for all handlers attached to
17375                  *  the returned promise.
17376                  * @returns {Promise}
17377                  */
17378                 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
17379                         var p = this._beget();
17380                         var child = p._handler;
17381                         child.receiver = receiver;
17382                         this._handler.chain(child, receiver);
17383                         return p;
17384                 };
17385
17386                 return Promise;
17387         };
17388
17389 });
17390 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17391
17392
17393 },{}],210:[function(require,module,exports){
17394 (function (process){
17395 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17396 /** @author Brian Cavalier */
17397 /** @author John Hann */
17398
17399 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
17400 (function(define) { 'use strict';
17401 define(function(require) {
17402         /*jshint maxcomplexity:6*/
17403
17404         // Sniff "best" async scheduling option
17405         // Prefer process.nextTick or MutationObserver, then check for
17406         // setTimeout, and finally vertx, since its the only env that doesn't
17407         // have setTimeout
17408
17409         var MutationObs;
17410         var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
17411
17412         // Default env
17413         var setTimer = function(f, ms) { return setTimeout(f, ms); };
17414         var clearTimer = function(t) { return clearTimeout(t); };
17415         var asap = function (f) { return capturedSetTimeout(f, 0); };
17416
17417         // Detect specific env
17418         if (isNode()) { // Node
17419                 asap = function (f) { return process.nextTick(f); };
17420
17421         } else if (MutationObs = hasMutationObserver()) { // Modern browser
17422                 asap = initMutationObserver(MutationObs);
17423
17424         } else if (!capturedSetTimeout) { // vert.x
17425                 var vertxRequire = require;
17426                 var vertx = vertxRequire('vertx');
17427                 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
17428                 clearTimer = vertx.cancelTimer;
17429                 asap = vertx.runOnLoop || vertx.runOnContext;
17430         }
17431
17432         return {
17433                 setTimer: setTimer,
17434                 clearTimer: clearTimer,
17435                 asap: asap
17436         };
17437
17438         function isNode () {
17439                 return typeof process !== 'undefined' &&
17440                         Object.prototype.toString.call(process) === '[object process]';
17441         }
17442
17443         function hasMutationObserver () {
17444                 return (typeof MutationObserver === 'function' && MutationObserver) ||
17445                         (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver);
17446         }
17447
17448         function initMutationObserver(MutationObserver) {
17449                 var scheduled;
17450                 var node = document.createTextNode('');
17451                 var o = new MutationObserver(run);
17452                 o.observe(node, { characterData: true });
17453
17454                 function run() {
17455                         var f = scheduled;
17456                         scheduled = void 0;
17457                         f();
17458                 }
17459
17460                 var i = 0;
17461                 return function (f) {
17462                         scheduled = f;
17463                         node.data = (i ^= 1);
17464                 };
17465         }
17466 });
17467 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17468
17469 }).call(this,require('_process'))
17470
17471 },{"_process":4}],211:[function(require,module,exports){
17472 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17473 /** @author Brian Cavalier */
17474 /** @author John Hann */
17475
17476 (function(define) { 'use strict';
17477 define(function() {
17478
17479         return {
17480                 formatError: formatError,
17481                 formatObject: formatObject,
17482                 tryStringify: tryStringify
17483         };
17484
17485         /**
17486          * Format an error into a string.  If e is an Error and has a stack property,
17487          * it's returned.  Otherwise, e is formatted using formatObject, with a
17488          * warning added about e not being a proper Error.
17489          * @param {*} e
17490          * @returns {String} formatted string, suitable for output to developers
17491          */
17492         function formatError(e) {
17493                 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
17494                 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
17495         }
17496
17497         /**
17498          * Format an object, detecting "plain" objects and running them through
17499          * JSON.stringify if possible.
17500          * @param {Object} o
17501          * @returns {string}
17502          */
17503         function formatObject(o) {
17504                 var s = String(o);
17505                 if(s === '[object Object]' && typeof JSON !== 'undefined') {
17506                         s = tryStringify(o, s);
17507                 }
17508                 return s;
17509         }
17510
17511         /**
17512          * Try to return the result of JSON.stringify(x).  If that fails, return
17513          * defaultValue
17514          * @param {*} x
17515          * @param {*} defaultValue
17516          * @returns {String|*} JSON.stringify(x) or defaultValue
17517          */
17518         function tryStringify(x, defaultValue) {
17519                 try {
17520                         return JSON.stringify(x);
17521                 } catch(e) {
17522                         return defaultValue;
17523                 }
17524         }
17525
17526 });
17527 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17528
17529 },{}],212:[function(require,module,exports){
17530 (function (process){
17531 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17532 /** @author Brian Cavalier */
17533 /** @author John Hann */
17534
17535 (function(define) { 'use strict';
17536 define(function() {
17537
17538         return function makePromise(environment) {
17539
17540                 var tasks = environment.scheduler;
17541                 var emitRejection = initEmitRejection();
17542
17543                 var objectCreate = Object.create ||
17544                         function(proto) {
17545                                 function Child() {}
17546                                 Child.prototype = proto;
17547                                 return new Child();
17548                         };
17549
17550                 /**
17551                  * Create a promise whose fate is determined by resolver
17552                  * @constructor
17553                  * @returns {Promise} promise
17554                  * @name Promise
17555                  */
17556                 function Promise(resolver, handler) {
17557                         this._handler = resolver === Handler ? handler : init(resolver);
17558                 }
17559
17560                 /**
17561                  * Run the supplied resolver
17562                  * @param resolver
17563                  * @returns {Pending}
17564                  */
17565                 function init(resolver) {
17566                         var handler = new Pending();
17567
17568                         try {
17569                                 resolver(promiseResolve, promiseReject, promiseNotify);
17570                         } catch (e) {
17571                                 promiseReject(e);
17572                         }
17573
17574                         return handler;
17575
17576                         /**
17577                          * Transition from pre-resolution state to post-resolution state, notifying
17578                          * all listeners of the ultimate fulfillment or rejection
17579                          * @param {*} x resolution value
17580                          */
17581                         function promiseResolve (x) {
17582                                 handler.resolve(x);
17583                         }
17584                         /**
17585                          * Reject this promise with reason, which will be used verbatim
17586                          * @param {Error|*} reason rejection reason, strongly suggested
17587                          *   to be an Error type
17588                          */
17589                         function promiseReject (reason) {
17590                                 handler.reject(reason);
17591                         }
17592
17593                         /**
17594                          * @deprecated
17595                          * Issue a progress event, notifying all progress listeners
17596                          * @param {*} x progress event payload to pass to all listeners
17597                          */
17598                         function promiseNotify (x) {
17599                                 handler.notify(x);
17600                         }
17601                 }
17602
17603                 // Creation
17604
17605                 Promise.resolve = resolve;
17606                 Promise.reject = reject;
17607                 Promise.never = never;
17608
17609                 Promise._defer = defer;
17610                 Promise._handler = getHandler;
17611
17612                 /**
17613                  * Returns a trusted promise. If x is already a trusted promise, it is
17614                  * returned, otherwise returns a new trusted Promise which follows x.
17615                  * @param  {*} x
17616                  * @return {Promise} promise
17617                  */
17618                 function resolve(x) {
17619                         return isPromise(x) ? x
17620                                 : new Promise(Handler, new Async(getHandler(x)));
17621                 }
17622
17623                 /**
17624                  * Return a reject promise with x as its reason (x is used verbatim)
17625                  * @param {*} x
17626                  * @returns {Promise} rejected promise
17627                  */
17628                 function reject(x) {
17629                         return new Promise(Handler, new Async(new Rejected(x)));
17630                 }
17631
17632                 /**
17633                  * Return a promise that remains pending forever
17634                  * @returns {Promise} forever-pending promise.
17635                  */
17636                 function never() {
17637                         return foreverPendingPromise; // Should be frozen
17638                 }
17639
17640                 /**
17641                  * Creates an internal {promise, resolver} pair
17642                  * @private
17643                  * @returns {Promise}
17644                  */
17645                 function defer() {
17646                         return new Promise(Handler, new Pending());
17647                 }
17648
17649                 // Transformation and flow control
17650
17651                 /**
17652                  * Transform this promise's fulfillment value, returning a new Promise
17653                  * for the transformed result.  If the promise cannot be fulfilled, onRejected
17654                  * is called with the reason.  onProgress *may* be called with updates toward
17655                  * this promise's fulfillment.
17656                  * @param {function=} onFulfilled fulfillment handler
17657                  * @param {function=} onRejected rejection handler
17658                  * @param {function=} onProgress @deprecated progress handler
17659                  * @return {Promise} new promise
17660                  */
17661                 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
17662                         var parent = this._handler;
17663                         var state = parent.join().state();
17664
17665                         if ((typeof onFulfilled !== 'function' && state > 0) ||
17666                                 (typeof onRejected !== 'function' && state < 0)) {
17667                                 // Short circuit: value will not change, simply share handler
17668                                 return new this.constructor(Handler, parent);
17669                         }
17670
17671                         var p = this._beget();
17672                         var child = p._handler;
17673
17674                         parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
17675
17676                         return p;
17677                 };
17678
17679                 /**
17680                  * If this promise cannot be fulfilled due to an error, call onRejected to
17681                  * handle the error. Shortcut for .then(undefined, onRejected)
17682                  * @param {function?} onRejected
17683                  * @return {Promise}
17684                  */
17685                 Promise.prototype['catch'] = function(onRejected) {
17686                         return this.then(void 0, onRejected);
17687                 };
17688
17689                 /**
17690                  * Creates a new, pending promise of the same type as this promise
17691                  * @private
17692                  * @returns {Promise}
17693                  */
17694                 Promise.prototype._beget = function() {
17695                         return begetFrom(this._handler, this.constructor);
17696                 };
17697
17698                 function begetFrom(parent, Promise) {
17699                         var child = new Pending(parent.receiver, parent.join().context);
17700                         return new Promise(Handler, child);
17701                 }
17702
17703                 // Array combinators
17704
17705                 Promise.all = all;
17706                 Promise.race = race;
17707                 Promise._traverse = traverse;
17708
17709                 /**
17710                  * Return a promise that will fulfill when all promises in the
17711                  * input array have fulfilled, or will reject when one of the
17712                  * promises rejects.
17713                  * @param {array} promises array of promises
17714                  * @returns {Promise} promise for array of fulfillment values
17715                  */
17716                 function all(promises) {
17717                         return traverseWith(snd, null, promises);
17718                 }
17719
17720                 /**
17721                  * Array<Promise<X>> -> Promise<Array<f(X)>>
17722                  * @private
17723                  * @param {function} f function to apply to each promise's value
17724                  * @param {Array} promises array of promises
17725                  * @returns {Promise} promise for transformed values
17726                  */
17727                 function traverse(f, promises) {
17728                         return traverseWith(tryCatch2, f, promises);
17729                 }
17730
17731                 function traverseWith(tryMap, f, promises) {
17732                         var handler = typeof f === 'function' ? mapAt : settleAt;
17733
17734                         var resolver = new Pending();
17735                         var pending = promises.length >>> 0;
17736                         var results = new Array(pending);
17737
17738                         for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
17739                                 x = promises[i];
17740
17741                                 if (x === void 0 && !(i in promises)) {
17742                                         --pending;
17743                                         continue;
17744                                 }
17745
17746                                 traverseAt(promises, handler, i, x, resolver);
17747                         }
17748
17749                         if(pending === 0) {
17750                                 resolver.become(new Fulfilled(results));
17751                         }
17752
17753                         return new Promise(Handler, resolver);
17754
17755                         function mapAt(i, x, resolver) {
17756                                 if(!resolver.resolved) {
17757                                         traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
17758                                 }
17759                         }
17760
17761                         function settleAt(i, x, resolver) {
17762                                 results[i] = x;
17763                                 if(--pending === 0) {
17764                                         resolver.become(new Fulfilled(results));
17765                                 }
17766                         }
17767                 }
17768
17769                 function traverseAt(promises, handler, i, x, resolver) {
17770                         if (maybeThenable(x)) {
17771                                 var h = getHandlerMaybeThenable(x);
17772                                 var s = h.state();
17773
17774                                 if (s === 0) {
17775                                         h.fold(handler, i, void 0, resolver);
17776                                 } else if (s > 0) {
17777                                         handler(i, h.value, resolver);
17778                                 } else {
17779                                         resolver.become(h);
17780                                         visitRemaining(promises, i+1, h);
17781                                 }
17782                         } else {
17783                                 handler(i, x, resolver);
17784                         }
17785                 }
17786
17787                 Promise._visitRemaining = visitRemaining;
17788                 function visitRemaining(promises, start, handler) {
17789                         for(var i=start; i<promises.length; ++i) {
17790                                 markAsHandled(getHandler(promises[i]), handler);
17791                         }
17792                 }
17793
17794                 function markAsHandled(h, handler) {
17795                         if(h === handler) {
17796                                 return;
17797                         }
17798
17799                         var s = h.state();
17800                         if(s === 0) {
17801                                 h.visit(h, void 0, h._unreport);
17802                         } else if(s < 0) {
17803                                 h._unreport();
17804                         }
17805                 }
17806
17807                 /**
17808                  * Fulfill-reject competitive race. Return a promise that will settle
17809                  * to the same state as the earliest input promise to settle.
17810                  *
17811                  * WARNING: The ES6 Promise spec requires that race()ing an empty array
17812                  * must return a promise that is pending forever.  This implementation
17813                  * returns a singleton forever-pending promise, the same singleton that is
17814                  * returned by Promise.never(), thus can be checked with ===
17815                  *
17816                  * @param {array} promises array of promises to race
17817                  * @returns {Promise} if input is non-empty, a promise that will settle
17818                  * to the same outcome as the earliest input promise to settle. if empty
17819                  * is empty, returns a promise that will never settle.
17820                  */
17821                 function race(promises) {
17822                         if(typeof promises !== 'object' || promises === null) {
17823                                 return reject(new TypeError('non-iterable passed to race()'));
17824                         }
17825
17826                         // Sigh, race([]) is untestable unless we return *something*
17827                         // that is recognizable without calling .then() on it.
17828                         return promises.length === 0 ? never()
17829                                  : promises.length === 1 ? resolve(promises[0])
17830                                  : runRace(promises);
17831                 }
17832
17833                 function runRace(promises) {
17834                         var resolver = new Pending();
17835                         var i, x, h;
17836                         for(i=0; i<promises.length; ++i) {
17837                                 x = promises[i];
17838                                 if (x === void 0 && !(i in promises)) {
17839                                         continue;
17840                                 }
17841
17842                                 h = getHandler(x);
17843                                 if(h.state() !== 0) {
17844                                         resolver.become(h);
17845                                         visitRemaining(promises, i+1, h);
17846                                         break;
17847                                 } else {
17848                                         h.visit(resolver, resolver.resolve, resolver.reject);
17849                                 }
17850                         }
17851                         return new Promise(Handler, resolver);
17852                 }
17853
17854                 // Promise internals
17855                 // Below this, everything is @private
17856
17857                 /**
17858                  * Get an appropriate handler for x, without checking for cycles
17859                  * @param {*} x
17860                  * @returns {object} handler
17861                  */
17862                 function getHandler(x) {
17863                         if(isPromise(x)) {
17864                                 return x._handler.join();
17865                         }
17866                         return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
17867                 }
17868
17869                 /**
17870                  * Get a handler for thenable x.
17871                  * NOTE: You must only call this if maybeThenable(x) == true
17872                  * @param {object|function|Promise} x
17873                  * @returns {object} handler
17874                  */
17875                 function getHandlerMaybeThenable(x) {
17876                         return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
17877                 }
17878
17879                 /**
17880                  * Get a handler for potentially untrusted thenable x
17881                  * @param {*} x
17882                  * @returns {object} handler
17883                  */
17884                 function getHandlerUntrusted(x) {
17885                         try {
17886                                 var untrustedThen = x.then;
17887                                 return typeof untrustedThen === 'function'
17888                                         ? new Thenable(untrustedThen, x)
17889                                         : new Fulfilled(x);
17890                         } catch(e) {
17891                                 return new Rejected(e);
17892                         }
17893                 }
17894
17895                 /**
17896                  * Handler for a promise that is pending forever
17897                  * @constructor
17898                  */
17899                 function Handler() {}
17900
17901                 Handler.prototype.when
17902                         = Handler.prototype.become
17903                         = Handler.prototype.notify // deprecated
17904                         = Handler.prototype.fail
17905                         = Handler.prototype._unreport
17906                         = Handler.prototype._report
17907                         = noop;
17908
17909                 Handler.prototype._state = 0;
17910
17911                 Handler.prototype.state = function() {
17912                         return this._state;
17913                 };
17914
17915                 /**
17916                  * Recursively collapse handler chain to find the handler
17917                  * nearest to the fully resolved value.
17918                  * @returns {object} handler nearest the fully resolved value
17919                  */
17920                 Handler.prototype.join = function() {
17921                         var h = this;
17922                         while(h.handler !== void 0) {
17923                                 h = h.handler;
17924                         }
17925                         return h;
17926                 };
17927
17928                 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
17929                         this.when({
17930                                 resolver: to,
17931                                 receiver: receiver,
17932                                 fulfilled: fulfilled,
17933                                 rejected: rejected,
17934                                 progress: progress
17935                         });
17936                 };
17937
17938                 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
17939                         this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
17940                 };
17941
17942                 Handler.prototype.fold = function(f, z, c, to) {
17943                         this.when(new Fold(f, z, c, to));
17944                 };
17945
17946                 /**
17947                  * Handler that invokes fail() on any handler it becomes
17948                  * @constructor
17949                  */
17950                 function FailIfRejected() {}
17951
17952                 inherit(Handler, FailIfRejected);
17953
17954                 FailIfRejected.prototype.become = function(h) {
17955                         h.fail();
17956                 };
17957
17958                 var failIfRejected = new FailIfRejected();
17959
17960                 /**
17961                  * Handler that manages a queue of consumers waiting on a pending promise
17962                  * @constructor
17963                  */
17964                 function Pending(receiver, inheritedContext) {
17965                         Promise.createContext(this, inheritedContext);
17966
17967                         this.consumers = void 0;
17968                         this.receiver = receiver;
17969                         this.handler = void 0;
17970                         this.resolved = false;
17971                 }
17972
17973                 inherit(Handler, Pending);
17974
17975                 Pending.prototype._state = 0;
17976
17977                 Pending.prototype.resolve = function(x) {
17978                         this.become(getHandler(x));
17979                 };
17980
17981                 Pending.prototype.reject = function(x) {
17982                         if(this.resolved) {
17983                                 return;
17984                         }
17985
17986                         this.become(new Rejected(x));
17987                 };
17988
17989                 Pending.prototype.join = function() {
17990                         if (!this.resolved) {
17991                                 return this;
17992                         }
17993
17994                         var h = this;
17995
17996                         while (h.handler !== void 0) {
17997                                 h = h.handler;
17998                                 if (h === this) {
17999                                         return this.handler = cycle();
18000                                 }
18001                         }
18002
18003                         return h;
18004                 };
18005
18006                 Pending.prototype.run = function() {
18007                         var q = this.consumers;
18008                         var handler = this.handler;
18009                         this.handler = this.handler.join();
18010                         this.consumers = void 0;
18011
18012                         for (var i = 0; i < q.length; ++i) {
18013                                 handler.when(q[i]);
18014                         }
18015                 };
18016
18017                 Pending.prototype.become = function(handler) {
18018                         if(this.resolved) {
18019                                 return;
18020                         }
18021
18022                         this.resolved = true;
18023                         this.handler = handler;
18024                         if(this.consumers !== void 0) {
18025                                 tasks.enqueue(this);
18026                         }
18027
18028                         if(this.context !== void 0) {
18029                                 handler._report(this.context);
18030                         }
18031                 };
18032
18033                 Pending.prototype.when = function(continuation) {
18034                         if(this.resolved) {
18035                                 tasks.enqueue(new ContinuationTask(continuation, this.handler));
18036                         } else {
18037                                 if(this.consumers === void 0) {
18038                                         this.consumers = [continuation];
18039                                 } else {
18040                                         this.consumers.push(continuation);
18041                                 }
18042                         }
18043                 };
18044
18045                 /**
18046                  * @deprecated
18047                  */
18048                 Pending.prototype.notify = function(x) {
18049                         if(!this.resolved) {
18050                                 tasks.enqueue(new ProgressTask(x, this));
18051                         }
18052                 };
18053
18054                 Pending.prototype.fail = function(context) {
18055                         var c = typeof context === 'undefined' ? this.context : context;
18056                         this.resolved && this.handler.join().fail(c);
18057                 };
18058
18059                 Pending.prototype._report = function(context) {
18060                         this.resolved && this.handler.join()._report(context);
18061                 };
18062
18063                 Pending.prototype._unreport = function() {
18064                         this.resolved && this.handler.join()._unreport();
18065                 };
18066
18067                 /**
18068                  * Wrap another handler and force it into a future stack
18069                  * @param {object} handler
18070                  * @constructor
18071                  */
18072                 function Async(handler) {
18073                         this.handler = handler;
18074                 }
18075
18076                 inherit(Handler, Async);
18077
18078                 Async.prototype.when = function(continuation) {
18079                         tasks.enqueue(new ContinuationTask(continuation, this));
18080                 };
18081
18082                 Async.prototype._report = function(context) {
18083                         this.join()._report(context);
18084                 };
18085
18086                 Async.prototype._unreport = function() {
18087                         this.join()._unreport();
18088                 };
18089
18090                 /**
18091                  * Handler that wraps an untrusted thenable and assimilates it in a future stack
18092                  * @param {function} then
18093                  * @param {{then: function}} thenable
18094                  * @constructor
18095                  */
18096                 function Thenable(then, thenable) {
18097                         Pending.call(this);
18098                         tasks.enqueue(new AssimilateTask(then, thenable, this));
18099                 }
18100
18101                 inherit(Pending, Thenable);
18102
18103                 /**
18104                  * Handler for a fulfilled promise
18105                  * @param {*} x fulfillment value
18106                  * @constructor
18107                  */
18108                 function Fulfilled(x) {
18109                         Promise.createContext(this);
18110                         this.value = x;
18111                 }
18112
18113                 inherit(Handler, Fulfilled);
18114
18115                 Fulfilled.prototype._state = 1;
18116
18117                 Fulfilled.prototype.fold = function(f, z, c, to) {
18118                         runContinuation3(f, z, this, c, to);
18119                 };
18120
18121                 Fulfilled.prototype.when = function(cont) {
18122                         runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
18123                 };
18124
18125                 var errorId = 0;
18126
18127                 /**
18128                  * Handler for a rejected promise
18129                  * @param {*} x rejection reason
18130                  * @constructor
18131                  */
18132                 function Rejected(x) {
18133                         Promise.createContext(this);
18134
18135                         this.id = ++errorId;
18136                         this.value = x;
18137                         this.handled = false;
18138                         this.reported = false;
18139
18140                         this._report();
18141                 }
18142
18143                 inherit(Handler, Rejected);
18144
18145                 Rejected.prototype._state = -1;
18146
18147                 Rejected.prototype.fold = function(f, z, c, to) {
18148                         to.become(this);
18149                 };
18150
18151                 Rejected.prototype.when = function(cont) {
18152                         if(typeof cont.rejected === 'function') {
18153                                 this._unreport();
18154                         }
18155                         runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
18156                 };
18157
18158                 Rejected.prototype._report = function(context) {
18159                         tasks.afterQueue(new ReportTask(this, context));
18160                 };
18161
18162                 Rejected.prototype._unreport = function() {
18163                         if(this.handled) {
18164                                 return;
18165                         }
18166                         this.handled = true;
18167                         tasks.afterQueue(new UnreportTask(this));
18168                 };
18169
18170                 Rejected.prototype.fail = function(context) {
18171                         this.reported = true;
18172                         emitRejection('unhandledRejection', this);
18173                         Promise.onFatalRejection(this, context === void 0 ? this.context : context);
18174                 };
18175
18176                 function ReportTask(rejection, context) {
18177                         this.rejection = rejection;
18178                         this.context = context;
18179                 }
18180
18181                 ReportTask.prototype.run = function() {
18182                         if(!this.rejection.handled && !this.rejection.reported) {
18183                                 this.rejection.reported = true;
18184                                 emitRejection('unhandledRejection', this.rejection) ||
18185                                         Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
18186                         }
18187                 };
18188
18189                 function UnreportTask(rejection) {
18190                         this.rejection = rejection;
18191                 }
18192
18193                 UnreportTask.prototype.run = function() {
18194                         if(this.rejection.reported) {
18195                                 emitRejection('rejectionHandled', this.rejection) ||
18196                                         Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
18197                         }
18198                 };
18199
18200                 // Unhandled rejection hooks
18201                 // By default, everything is a noop
18202
18203                 Promise.createContext
18204                         = Promise.enterContext
18205                         = Promise.exitContext
18206                         = Promise.onPotentiallyUnhandledRejection
18207                         = Promise.onPotentiallyUnhandledRejectionHandled
18208                         = Promise.onFatalRejection
18209                         = noop;
18210
18211                 // Errors and singletons
18212
18213                 var foreverPendingHandler = new Handler();
18214                 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
18215
18216                 function cycle() {
18217                         return new Rejected(new TypeError('Promise cycle'));
18218                 }
18219
18220                 // Task runners
18221
18222                 /**
18223                  * Run a single consumer
18224                  * @constructor
18225                  */
18226                 function ContinuationTask(continuation, handler) {
18227                         this.continuation = continuation;
18228                         this.handler = handler;
18229                 }
18230
18231                 ContinuationTask.prototype.run = function() {
18232                         this.handler.join().when(this.continuation);
18233                 };
18234
18235                 /**
18236                  * Run a queue of progress handlers
18237                  * @constructor
18238                  */
18239                 function ProgressTask(value, handler) {
18240                         this.handler = handler;
18241                         this.value = value;
18242                 }
18243
18244                 ProgressTask.prototype.run = function() {
18245                         var q = this.handler.consumers;
18246                         if(q === void 0) {
18247                                 return;
18248                         }
18249
18250                         for (var c, i = 0; i < q.length; ++i) {
18251                                 c = q[i];
18252                                 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
18253                         }
18254                 };
18255
18256                 /**
18257                  * Assimilate a thenable, sending it's value to resolver
18258                  * @param {function} then
18259                  * @param {object|function} thenable
18260                  * @param {object} resolver
18261                  * @constructor
18262                  */
18263                 function AssimilateTask(then, thenable, resolver) {
18264                         this._then = then;
18265                         this.thenable = thenable;
18266                         this.resolver = resolver;
18267                 }
18268
18269                 AssimilateTask.prototype.run = function() {
18270                         var h = this.resolver;
18271                         tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
18272
18273                         function _resolve(x) { h.resolve(x); }
18274                         function _reject(x)  { h.reject(x); }
18275                         function _notify(x)  { h.notify(x); }
18276                 };
18277
18278                 function tryAssimilate(then, thenable, resolve, reject, notify) {
18279                         try {
18280                                 then.call(thenable, resolve, reject, notify);
18281                         } catch (e) {
18282                                 reject(e);
18283                         }
18284                 }
18285
18286                 /**
18287                  * Fold a handler value with z
18288                  * @constructor
18289                  */
18290                 function Fold(f, z, c, to) {
18291                         this.f = f; this.z = z; this.c = c; this.to = to;
18292                         this.resolver = failIfRejected;
18293                         this.receiver = this;
18294                 }
18295
18296                 Fold.prototype.fulfilled = function(x) {
18297                         this.f.call(this.c, this.z, x, this.to);
18298                 };
18299
18300                 Fold.prototype.rejected = function(x) {
18301                         this.to.reject(x);
18302                 };
18303
18304                 Fold.prototype.progress = function(x) {
18305                         this.to.notify(x);
18306                 };
18307
18308                 // Other helpers
18309
18310                 /**
18311                  * @param {*} x
18312                  * @returns {boolean} true iff x is a trusted Promise
18313                  */
18314                 function isPromise(x) {
18315                         return x instanceof Promise;
18316                 }
18317
18318                 /**
18319                  * Test just enough to rule out primitives, in order to take faster
18320                  * paths in some code
18321                  * @param {*} x
18322                  * @returns {boolean} false iff x is guaranteed *not* to be a thenable
18323                  */
18324                 function maybeThenable(x) {
18325                         return (typeof x === 'object' || typeof x === 'function') && x !== null;
18326                 }
18327
18328                 function runContinuation1(f, h, receiver, next) {
18329                         if(typeof f !== 'function') {
18330                                 return next.become(h);
18331                         }
18332
18333                         Promise.enterContext(h);
18334                         tryCatchReject(f, h.value, receiver, next);
18335                         Promise.exitContext();
18336                 }
18337
18338                 function runContinuation3(f, x, h, receiver, next) {
18339                         if(typeof f !== 'function') {
18340                                 return next.become(h);
18341                         }
18342
18343                         Promise.enterContext(h);
18344                         tryCatchReject3(f, x, h.value, receiver, next);
18345                         Promise.exitContext();
18346                 }
18347
18348                 /**
18349                  * @deprecated
18350                  */
18351                 function runNotify(f, x, h, receiver, next) {
18352                         if(typeof f !== 'function') {
18353                                 return next.notify(x);
18354                         }
18355
18356                         Promise.enterContext(h);
18357                         tryCatchReturn(f, x, receiver, next);
18358                         Promise.exitContext();
18359                 }
18360
18361                 function tryCatch2(f, a, b) {
18362                         try {
18363                                 return f(a, b);
18364                         } catch(e) {
18365                                 return reject(e);
18366                         }
18367                 }
18368
18369                 /**
18370                  * Return f.call(thisArg, x), or if it throws return a rejected promise for
18371                  * the thrown exception
18372                  */
18373                 function tryCatchReject(f, x, thisArg, next) {
18374                         try {
18375                                 next.become(getHandler(f.call(thisArg, x)));
18376                         } catch(e) {
18377                                 next.become(new Rejected(e));
18378                         }
18379                 }
18380
18381                 /**
18382                  * Same as above, but includes the extra argument parameter.
18383                  */
18384                 function tryCatchReject3(f, x, y, thisArg, next) {
18385                         try {
18386                                 f.call(thisArg, x, y, next);
18387                         } catch(e) {
18388                                 next.become(new Rejected(e));
18389                         }
18390                 }
18391
18392                 /**
18393                  * @deprecated
18394                  * Return f.call(thisArg, x), or if it throws, *return* the exception
18395                  */
18396                 function tryCatchReturn(f, x, thisArg, next) {
18397                         try {
18398                                 next.notify(f.call(thisArg, x));
18399                         } catch(e) {
18400                                 next.notify(e);
18401                         }
18402                 }
18403
18404                 function inherit(Parent, Child) {
18405                         Child.prototype = objectCreate(Parent.prototype);
18406                         Child.prototype.constructor = Child;
18407                 }
18408
18409                 function snd(x, y) {
18410                         return y;
18411                 }
18412
18413                 function noop() {}
18414
18415                 function initEmitRejection() {
18416                         /*global process, self, CustomEvent*/
18417                         if(typeof process !== 'undefined' && process !== null
18418                                 && typeof process.emit === 'function') {
18419                                 // Returning falsy here means to call the default
18420                                 // onPotentiallyUnhandledRejection API.  This is safe even in
18421                                 // browserify since process.emit always returns falsy in browserify:
18422                                 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
18423                                 return function(type, rejection) {
18424                                         return type === 'unhandledRejection'
18425                                                 ? process.emit(type, rejection.value, rejection)
18426                                                 : process.emit(type, rejection);
18427                                 };
18428                         } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') {
18429                                 return (function(noop, self, CustomEvent) {
18430                                         var hasCustomEvent = false;
18431                                         try {
18432                                                 var ev = new CustomEvent('unhandledRejection');
18433                                                 hasCustomEvent = ev instanceof CustomEvent;
18434                                         } catch (e) {}
18435
18436                                         return !hasCustomEvent ? noop : function(type, rejection) {
18437                                                 var ev = new CustomEvent(type, {
18438                                                         detail: {
18439                                                                 reason: rejection.value,
18440                                                                 key: rejection
18441                                                         },
18442                                                         bubbles: false,
18443                                                         cancelable: true
18444                                                 });
18445
18446                                                 return !self.dispatchEvent(ev);
18447                                         };
18448                                 }(noop, self, CustomEvent));
18449                         }
18450
18451                         return noop;
18452                 }
18453
18454                 return Promise;
18455         };
18456 });
18457 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18458
18459 }).call(this,require('_process'))
18460
18461 },{"_process":4}],213:[function(require,module,exports){
18462 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18463 /** @author Brian Cavalier */
18464 /** @author John Hann */
18465
18466 (function(define) { 'use strict';
18467 define(function() {
18468
18469         return {
18470                 pending: toPendingState,
18471                 fulfilled: toFulfilledState,
18472                 rejected: toRejectedState,
18473                 inspect: inspect
18474         };
18475
18476         function toPendingState() {
18477                 return { state: 'pending' };
18478         }
18479
18480         function toRejectedState(e) {
18481                 return { state: 'rejected', reason: e };
18482         }
18483
18484         function toFulfilledState(x) {
18485                 return { state: 'fulfilled', value: x };
18486         }
18487
18488         function inspect(handler) {
18489                 var state = handler.state();
18490                 return state === 0 ? toPendingState()
18491                          : state > 0   ? toFulfilledState(handler.value)
18492                                        : toRejectedState(handler.value);
18493         }
18494
18495 });
18496 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18497
18498 },{}],214:[function(require,module,exports){
18499 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18500
18501 /**
18502  * Promises/A+ and when() implementation
18503  * when is part of the cujoJS family of libraries (http://cujojs.com/)
18504  * @author Brian Cavalier
18505  * @author John Hann
18506  */
18507 (function(define) { 'use strict';
18508 define(function (require) {
18509
18510         var timed = require('./lib/decorators/timed');
18511         var array = require('./lib/decorators/array');
18512         var flow = require('./lib/decorators/flow');
18513         var fold = require('./lib/decorators/fold');
18514         var inspect = require('./lib/decorators/inspect');
18515         var generate = require('./lib/decorators/iterate');
18516         var progress = require('./lib/decorators/progress');
18517         var withThis = require('./lib/decorators/with');
18518         var unhandledRejection = require('./lib/decorators/unhandledRejection');
18519         var TimeoutError = require('./lib/TimeoutError');
18520
18521         var Promise = [array, flow, fold, generate, progress,
18522                 inspect, withThis, timed, unhandledRejection]
18523                 .reduce(function(Promise, feature) {
18524                         return feature(Promise);
18525                 }, require('./lib/Promise'));
18526
18527         var apply = require('./lib/apply')(Promise);
18528
18529         // Public API
18530
18531         when.promise     = promise;              // Create a pending promise
18532         when.resolve     = Promise.resolve;      // Create a resolved promise
18533         when.reject      = Promise.reject;       // Create a rejected promise
18534
18535         when.lift        = lift;                 // lift a function to return promises
18536         when['try']      = attempt;              // call a function and return a promise
18537         when.attempt     = attempt;              // alias for when.try
18538
18539         when.iterate     = Promise.iterate;      // DEPRECATED (use cujojs/most streams) Generate a stream of promises
18540         when.unfold      = Promise.unfold;       // DEPRECATED (use cujojs/most streams) Generate a stream of promises
18541
18542         when.join        = join;                 // Join 2 or more promises
18543
18544         when.all         = all;                  // Resolve a list of promises
18545         when.settle      = settle;               // Settle a list of promises
18546
18547         when.any         = lift(Promise.any);    // One-winner race
18548         when.some        = lift(Promise.some);   // Multi-winner race
18549         when.race        = lift(Promise.race);   // First-to-settle race
18550
18551         when.map         = map;                  // Array.map() for promises
18552         when.filter      = filter;               // Array.filter() for promises
18553         when.reduce      = lift(Promise.reduce);       // Array.reduce() for promises
18554         when.reduceRight = lift(Promise.reduceRight);  // Array.reduceRight() for promises
18555
18556         when.isPromiseLike = isPromiseLike;      // Is something promise-like, aka thenable
18557
18558         when.Promise     = Promise;              // Promise constructor
18559         when.defer       = defer;                // Create a {promise, resolve, reject} tuple
18560
18561         // Error types
18562
18563         when.TimeoutError = TimeoutError;
18564
18565         /**
18566          * Get a trusted promise for x, or by transforming x with onFulfilled
18567          *
18568          * @param {*} x
18569          * @param {function?} onFulfilled callback to be called when x is
18570          *   successfully fulfilled.  If promiseOrValue is an immediate value, callback
18571          *   will be invoked immediately.
18572          * @param {function?} onRejected callback to be called when x is
18573          *   rejected.
18574          * @param {function?} onProgress callback to be called when progress updates
18575          *   are issued for x. @deprecated
18576          * @returns {Promise} a new promise that will fulfill with the return
18577          *   value of callback or errback or the completion value of promiseOrValue if
18578          *   callback and/or errback is not supplied.
18579          */
18580         function when(x, onFulfilled, onRejected, onProgress) {
18581                 var p = Promise.resolve(x);
18582                 if (arguments.length < 2) {
18583                         return p;
18584                 }
18585
18586                 return p.then(onFulfilled, onRejected, onProgress);
18587         }
18588
18589         /**
18590          * Creates a new promise whose fate is determined by resolver.
18591          * @param {function} resolver function(resolve, reject, notify)
18592          * @returns {Promise} promise whose fate is determine by resolver
18593          */
18594         function promise(resolver) {
18595                 return new Promise(resolver);
18596         }
18597
18598         /**
18599          * Lift the supplied function, creating a version of f that returns
18600          * promises, and accepts promises as arguments.
18601          * @param {function} f
18602          * @returns {Function} version of f that returns promises
18603          */
18604         function lift(f) {
18605                 return function() {
18606                         for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
18607                                 a[i] = arguments[i];
18608                         }
18609                         return apply(f, this, a);
18610                 };
18611         }
18612
18613         /**
18614          * Call f in a future turn, with the supplied args, and return a promise
18615          * for the result.
18616          * @param {function} f
18617          * @returns {Promise}
18618          */
18619         function attempt(f /*, args... */) {
18620                 /*jshint validthis:true */
18621                 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
18622                         a[i] = arguments[i+1];
18623                 }
18624                 return apply(f, this, a);
18625         }
18626
18627         /**
18628          * Creates a {promise, resolver} pair, either or both of which
18629          * may be given out safely to consumers.
18630          * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
18631          */
18632         function defer() {
18633                 return new Deferred();
18634         }
18635
18636         function Deferred() {
18637                 var p = Promise._defer();
18638
18639                 function resolve(x) { p._handler.resolve(x); }
18640                 function reject(x) { p._handler.reject(x); }
18641                 function notify(x) { p._handler.notify(x); }
18642
18643                 this.promise = p;
18644                 this.resolve = resolve;
18645                 this.reject = reject;
18646                 this.notify = notify;
18647                 this.resolver = { resolve: resolve, reject: reject, notify: notify };
18648         }
18649
18650         /**
18651          * Determines if x is promise-like, i.e. a thenable object
18652          * NOTE: Will return true for *any thenable object*, and isn't truly
18653          * safe, since it may attempt to access the `then` property of x (i.e.
18654          *  clever/malicious getters may do weird things)
18655          * @param {*} x anything
18656          * @returns {boolean} true if x is promise-like
18657          */
18658         function isPromiseLike(x) {
18659                 return x && typeof x.then === 'function';
18660         }
18661
18662         /**
18663          * Return a promise that will resolve only once all the supplied arguments
18664          * have resolved. The resolution value of the returned promise will be an array
18665          * containing the resolution values of each of the arguments.
18666          * @param {...*} arguments may be a mix of promises and values
18667          * @returns {Promise}
18668          */
18669         function join(/* ...promises */) {
18670                 return Promise.all(arguments);
18671         }
18672
18673         /**
18674          * Return a promise that will fulfill once all input promises have
18675          * fulfilled, or reject when any one input promise rejects.
18676          * @param {array|Promise} promises array (or promise for an array) of promises
18677          * @returns {Promise}
18678          */
18679         function all(promises) {
18680                 return when(promises, Promise.all);
18681         }
18682
18683         /**
18684          * Return a promise that will always fulfill with an array containing
18685          * the outcome states of all input promises.  The returned promise
18686          * will only reject if `promises` itself is a rejected promise.
18687          * @param {array|Promise} promises array (or promise for an array) of promises
18688          * @returns {Promise} promise for array of settled state descriptors
18689          */
18690         function settle(promises) {
18691                 return when(promises, Promise.settle);
18692         }
18693
18694         /**
18695          * Promise-aware array map function, similar to `Array.prototype.map()`,
18696          * but input array may contain promises or values.
18697          * @param {Array|Promise} promises array of anything, may contain promises and values
18698          * @param {function(x:*, index:Number):*} mapFunc map function which may
18699          *  return a promise or value
18700          * @returns {Promise} promise that will fulfill with an array of mapped values
18701          *  or reject if any input promise rejects.
18702          */
18703         function map(promises, mapFunc) {
18704                 return when(promises, function(promises) {
18705                         return Promise.map(promises, mapFunc);
18706                 });
18707         }
18708
18709         /**
18710          * Filter the provided array of promises using the provided predicate.  Input may
18711          * contain promises and values
18712          * @param {Array|Promise} promises array of promises and values
18713          * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
18714          *  Must return truthy (or promise for truthy) for items to retain.
18715          * @returns {Promise} promise that will fulfill with an array containing all items
18716          *  for which predicate returned truthy.
18717          */
18718         function filter(promises, predicate) {
18719                 return when(promises, function(promises) {
18720                         return Promise.filter(promises, predicate);
18721                 });
18722         }
18723
18724         return when;
18725 });
18726 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
18727
18728 },{"./lib/Promise":197,"./lib/TimeoutError":199,"./lib/apply":200,"./lib/decorators/array":201,"./lib/decorators/flow":202,"./lib/decorators/fold":203,"./lib/decorators/inspect":204,"./lib/decorators/iterate":205,"./lib/decorators/progress":206,"./lib/decorators/timed":207,"./lib/decorators/unhandledRejection":208,"./lib/decorators/with":209}],215:[function(require,module,exports){
18729 var nativeIsArray = Array.isArray
18730 var toString = Object.prototype.toString
18731
18732 module.exports = nativeIsArray || isArray
18733
18734 function isArray(obj) {
18735     return toString.call(obj) === "[object Array]"
18736 }
18737
18738 },{}],216:[function(require,module,exports){
18739 "use strict";
18740 var APIv3_1 = require("./api/APIv3");
18741 exports.APIv3 = APIv3_1.APIv3;
18742 var ModelCreator_1 = require("./api/ModelCreator");
18743 exports.ModelCreator = ModelCreator_1.ModelCreator;
18744
18745 },{"./api/APIv3":228,"./api/ModelCreator":229}],217:[function(require,module,exports){
18746 "use strict";
18747 var Component_1 = require("./component/Component");
18748 exports.Component = Component_1.Component;
18749 var ComponentService_1 = require("./component/ComponentService");
18750 exports.ComponentService = ComponentService_1.ComponentService;
18751 var AttributionComponent_1 = require("./component/AttributionComponent");
18752 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
18753 var BackgroundComponent_1 = require("./component/BackgroundComponent");
18754 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
18755 var BearingComponent_1 = require("./component/BearingComponent");
18756 exports.BearingComponent = BearingComponent_1.BearingComponent;
18757 var CacheComponent_1 = require("./component/CacheComponent");
18758 exports.CacheComponent = CacheComponent_1.CacheComponent;
18759 var CoverComponent_1 = require("./component/CoverComponent");
18760 exports.CoverComponent = CoverComponent_1.CoverComponent;
18761 var DebugComponent_1 = require("./component/DebugComponent");
18762 exports.DebugComponent = DebugComponent_1.DebugComponent;
18763 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
18764 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
18765 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
18766 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
18767 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
18768 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
18769 var ImageComponent_1 = require("./component/ImageComponent");
18770 exports.ImageComponent = ImageComponent_1.ImageComponent;
18771 var KeyboardComponent_1 = require("./component/KeyboardComponent");
18772 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
18773 var LoadingComponent_1 = require("./component/LoadingComponent");
18774 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
18775 var Marker_1 = require("./component/marker/Marker");
18776 exports.Marker = Marker_1.Marker;
18777 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
18778 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
18779 var MouseComponent_1 = require("./component/MouseComponent");
18780 exports.MouseComponent = MouseComponent_1.MouseComponent;
18781 var NavigationComponent_1 = require("./component/NavigationComponent");
18782 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
18783 var RouteComponent_1 = require("./component/RouteComponent");
18784 exports.RouteComponent = RouteComponent_1.RouteComponent;
18785 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
18786 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
18787 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
18788 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
18789 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
18790 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
18791 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
18792 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
18793 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
18794 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
18795 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
18796 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
18797 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
18798 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
18799 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
18800 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
18801 var SimpleMarker_1 = require("./component/marker/SimpleMarker");
18802 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
18803 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
18804 exports.SliderComponent = SliderComponent_1.SliderComponent;
18805 var StatsComponent_1 = require("./component/StatsComponent");
18806 exports.StatsComponent = StatsComponent_1.StatsComponent;
18807 var Tag_1 = require("./component/tag/tag/Tag");
18808 exports.Tag = Tag_1.Tag;
18809 var Alignment_1 = require("./component/tag/tag/Alignment");
18810 exports.Alignment = Alignment_1.Alignment;
18811 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
18812 exports.OutlineTag = OutlineTag_1.OutlineTag;
18813 var RenderTag_1 = require("./component/tag/tag/RenderTag");
18814 exports.RenderTag = RenderTag_1.RenderTag;
18815 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
18816 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
18817 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
18818 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
18819 var SpotTag_1 = require("./component/tag/tag/SpotTag");
18820 exports.SpotTag = SpotTag_1.SpotTag;
18821 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
18822 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
18823 var TagComponent_1 = require("./component/tag/TagComponent");
18824 exports.TagComponent = TagComponent_1.TagComponent;
18825 var TagCreator_1 = require("./component/tag/TagCreator");
18826 exports.TagCreator = TagCreator_1.TagCreator;
18827 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
18828 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
18829 var TagGLRenderer_1 = require("./component/tag/TagGLRenderer");
18830 exports.TagGLRenderer = TagGLRenderer_1.TagGLRenderer;
18831 var TagOperation_1 = require("./component/tag/TagOperation");
18832 exports.TagOperation = TagOperation_1.TagOperation;
18833 var TagSet_1 = require("./component/tag/TagSet");
18834 exports.TagSet = TagSet_1.TagSet;
18835 var Geometry_1 = require("./component/tag/geometry/Geometry");
18836 exports.Geometry = Geometry_1.Geometry;
18837 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
18838 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
18839 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
18840 exports.RectGeometry = RectGeometry_1.RectGeometry;
18841 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
18842 exports.PointGeometry = PointGeometry_1.PointGeometry;
18843 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
18844 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
18845 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
18846 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
18847
18848 },{"./component/AttributionComponent":230,"./component/BackgroundComponent":231,"./component/BearingComponent":232,"./component/CacheComponent":233,"./component/Component":234,"./component/ComponentService":235,"./component/CoverComponent":236,"./component/DebugComponent":237,"./component/ImageComponent":238,"./component/KeyboardComponent":239,"./component/LoadingComponent":240,"./component/MouseComponent":241,"./component/NavigationComponent":242,"./component/RouteComponent":243,"./component/StatsComponent":244,"./component/direction/DirectionComponent":245,"./component/direction/DirectionDOMCalculator":246,"./component/direction/DirectionDOMRenderer":247,"./component/imageplane/ImagePlaneComponent":248,"./component/imageplane/ImagePlaneFactory":249,"./component/imageplane/ImagePlaneGLRenderer":250,"./component/imageplane/ImagePlaneScene":251,"./component/imageplane/ImagePlaneShaders":252,"./component/imageplane/SliderComponent":253,"./component/marker/Marker":254,"./component/marker/MarkerComponent":255,"./component/marker/SimpleMarker":256,"./component/sequence/SequenceComponent":257,"./component/sequence/SequenceDOMInteraction":258,"./component/sequence/SequenceDOMRenderer":259,"./component/tag/TagComponent":261,"./component/tag/TagCreator":262,"./component/tag/TagDOMRenderer":263,"./component/tag/TagGLRenderer":264,"./component/tag/TagOperation":265,"./component/tag/TagSet":266,"./component/tag/error/GeometryTagError":267,"./component/tag/geometry/Geometry":268,"./component/tag/geometry/PointGeometry":269,"./component/tag/geometry/PolygonGeometry":270,"./component/tag/geometry/RectGeometry":271,"./component/tag/geometry/VertexGeometry":272,"./component/tag/tag/Alignment":273,"./component/tag/tag/OutlineCreateTag":274,"./component/tag/tag/OutlineRenderTag":275,"./component/tag/tag/OutlineTag":276,"./component/tag/tag/RenderTag":277,"./component/tag/tag/SpotRenderTag":278,"./component/tag/tag/SpotTag":279,"./component/tag/tag/Tag":280}],218:[function(require,module,exports){
18849 "use strict";
18850 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
18851 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
18852 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
18853 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
18854 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
18855 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
18856 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
18857 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
18858 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
18859 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
18860
18861 },{"./graph/edge/EdgeCalculator":298,"./graph/edge/EdgeCalculatorCoefficients":299,"./graph/edge/EdgeCalculatorDirections":300,"./graph/edge/EdgeCalculatorSettings":301,"./graph/edge/EdgeDirection":302}],219:[function(require,module,exports){
18862 "use strict";
18863 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
18864 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
18865 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
18866 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
18867 var MapillaryError_1 = require("./error/MapillaryError");
18868 exports.MapillaryError = MapillaryError_1.MapillaryError;
18869
18870 },{"./error/ArgumentMapillaryError":281,"./error/GraphMapillaryError":282,"./error/MapillaryError":283}],220:[function(require,module,exports){
18871 "use strict";
18872 var Camera_1 = require("./geo/Camera");
18873 exports.Camera = Camera_1.Camera;
18874 var GeoCoords_1 = require("./geo/GeoCoords");
18875 exports.GeoCoords = GeoCoords_1.GeoCoords;
18876 var ViewportCoords_1 = require("./geo/ViewportCoords");
18877 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
18878 var Spatial_1 = require("./geo/Spatial");
18879 exports.Spatial = Spatial_1.Spatial;
18880 var Transform_1 = require("./geo/Transform");
18881 exports.Transform = Transform_1.Transform;
18882
18883 },{"./geo/Camera":284,"./geo/GeoCoords":285,"./geo/Spatial":286,"./geo/Transform":287,"./geo/ViewportCoords":288}],221:[function(require,module,exports){
18884 "use strict";
18885 var FilterCreator_1 = require("./graph/FilterCreator");
18886 exports.FilterCreator = FilterCreator_1.FilterCreator;
18887 var Graph_1 = require("./graph/Graph");
18888 exports.Graph = Graph_1.Graph;
18889 var GraphCalculator_1 = require("./graph/GraphCalculator");
18890 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
18891 var GraphService_1 = require("./graph/GraphService");
18892 exports.GraphService = GraphService_1.GraphService;
18893 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
18894 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
18895 var MeshReader_1 = require("./graph/MeshReader");
18896 exports.MeshReader = MeshReader_1.MeshReader;
18897 var Node_1 = require("./graph/Node");
18898 exports.Node = Node_1.Node;
18899 var NodeCache_1 = require("./graph/NodeCache");
18900 exports.NodeCache = NodeCache_1.NodeCache;
18901 var Sequence_1 = require("./graph/Sequence");
18902 exports.Sequence = Sequence_1.Sequence;
18903
18904 },{"./graph/FilterCreator":289,"./graph/Graph":290,"./graph/GraphCalculator":291,"./graph/GraphService":292,"./graph/ImageLoadingService":293,"./graph/MeshReader":294,"./graph/Node":295,"./graph/NodeCache":296,"./graph/Sequence":297}],222:[function(require,module,exports){
18905 /**
18906  * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
18907  * @name Mapillary
18908  */
18909 "use strict";
18910 var Edge_1 = require("./Edge");
18911 exports.EdgeDirection = Edge_1.EdgeDirection;
18912 var Render_1 = require("./Render");
18913 exports.RenderMode = Render_1.RenderMode;
18914 var Viewer_1 = require("./Viewer");
18915 exports.ImageSize = Viewer_1.ImageSize;
18916 exports.Viewer = Viewer_1.Viewer;
18917 var TagComponent = require("./component/tag/Tag");
18918 exports.TagComponent = TagComponent;
18919
18920 },{"./Edge":218,"./Render":223,"./Viewer":227,"./component/tag/Tag":260}],223:[function(require,module,exports){
18921 "use strict";
18922 var DOMRenderer_1 = require("./render/DOMRenderer");
18923 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
18924 var GLRenderer_1 = require("./render/GLRenderer");
18925 exports.GLRenderer = GLRenderer_1.GLRenderer;
18926 var GLRenderStage_1 = require("./render/GLRenderStage");
18927 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
18928 var RenderCamera_1 = require("./render/RenderCamera");
18929 exports.RenderCamera = RenderCamera_1.RenderCamera;
18930 var RenderMode_1 = require("./render/RenderMode");
18931 exports.RenderMode = RenderMode_1.RenderMode;
18932 var RenderService_1 = require("./render/RenderService");
18933 exports.RenderService = RenderService_1.RenderService;
18934
18935 },{"./render/DOMRenderer":303,"./render/GLRenderStage":304,"./render/GLRenderer":305,"./render/RenderCamera":306,"./render/RenderMode":307,"./render/RenderService":308}],224:[function(require,module,exports){
18936 "use strict";
18937 var State_1 = require("./state/State");
18938 exports.State = State_1.State;
18939 var StateBase_1 = require("./state/states/StateBase");
18940 exports.StateBase = StateBase_1.StateBase;
18941 var StateContext_1 = require("./state/StateContext");
18942 exports.StateContext = StateContext_1.StateContext;
18943 var StateService_1 = require("./state/StateService");
18944 exports.StateService = StateService_1.StateService;
18945 var TraversingState_1 = require("./state/states/TraversingState");
18946 exports.TraversingState = TraversingState_1.TraversingState;
18947 var WaitingState_1 = require("./state/states/WaitingState");
18948 exports.WaitingState = WaitingState_1.WaitingState;
18949
18950 },{"./state/State":309,"./state/StateContext":310,"./state/StateService":311,"./state/states/StateBase":312,"./state/states/TraversingState":313,"./state/states/WaitingState":314}],225:[function(require,module,exports){
18951 "use strict";
18952 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
18953 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
18954 var ImageTileStore_1 = require("./tiles/ImageTileStore");
18955 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
18956 var TextureProvider_1 = require("./tiles/TextureProvider");
18957 exports.TextureProvider = TextureProvider_1.TextureProvider;
18958 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
18959 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
18960
18961 },{"./tiles/ImageTileLoader":315,"./tiles/ImageTileStore":316,"./tiles/RegionOfInterestCalculator":317,"./tiles/TextureProvider":318}],226:[function(require,module,exports){
18962 "use strict";
18963 var EventEmitter_1 = require("./utils/EventEmitter");
18964 exports.EventEmitter = EventEmitter_1.EventEmitter;
18965 var Settings_1 = require("./utils/Settings");
18966 exports.Settings = Settings_1.Settings;
18967 var Urls_1 = require("./utils/Urls");
18968 exports.Urls = Urls_1.Urls;
18969
18970 },{"./utils/EventEmitter":319,"./utils/Settings":320,"./utils/Urls":321}],227:[function(require,module,exports){
18971 "use strict";
18972 var Container_1 = require("./viewer/Container");
18973 exports.Container = Container_1.Container;
18974 var CacheService_1 = require("./viewer/CacheService");
18975 exports.CacheService = CacheService_1.CacheService;
18976 var EventLauncher_1 = require("./viewer/EventLauncher");
18977 exports.EventLauncher = EventLauncher_1.EventLauncher;
18978 var ImageSize_1 = require("./viewer/ImageSize");
18979 exports.ImageSize = ImageSize_1.ImageSize;
18980 var LoadingService_1 = require("./viewer/LoadingService");
18981 exports.LoadingService = LoadingService_1.LoadingService;
18982 var MouseService_1 = require("./viewer/MouseService");
18983 exports.MouseService = MouseService_1.MouseService;
18984 var Navigator_1 = require("./viewer/Navigator");
18985 exports.Navigator = Navigator_1.Navigator;
18986 var ComponentController_1 = require("./viewer/ComponentController");
18987 exports.ComponentController = ComponentController_1.ComponentController;
18988 var SpriteAlignment_1 = require("./viewer/SpriteAlignment");
18989 exports.SpriteAlignment = SpriteAlignment_1.SpriteAlignment;
18990 var SpriteService_1 = require("./viewer/SpriteService");
18991 exports.SpriteService = SpriteService_1.SpriteService;
18992 var TouchService_1 = require("./viewer/TouchService");
18993 exports.TouchService = TouchService_1.TouchService;
18994 exports.TouchMove = TouchService_1.TouchMove;
18995 var Viewer_1 = require("./viewer/Viewer");
18996 exports.Viewer = Viewer_1.Viewer;
18997
18998 },{"./viewer/CacheService":322,"./viewer/ComponentController":323,"./viewer/Container":324,"./viewer/EventLauncher":325,"./viewer/ImageSize":326,"./viewer/LoadingService":327,"./viewer/MouseService":328,"./viewer/Navigator":329,"./viewer/SpriteAlignment":330,"./viewer/SpriteService":331,"./viewer/TouchService":332,"./viewer/Viewer":333}],228:[function(require,module,exports){
18999 /// <reference path="../../typings/index.d.ts" />
19000 "use strict";
19001 var Observable_1 = require("rxjs/Observable");
19002 require("rxjs/add/observable/defer");
19003 require("rxjs/add/observable/fromPromise");
19004 require("rxjs/add/operator/catch");
19005 require("rxjs/add/operator/map");
19006 var API_1 = require("../API");
19007 var APIv3 = (function () {
19008     function APIv3(clientId, token, creator) {
19009         this._clientId = clientId;
19010         this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
19011         this._model = this._modelCreator.createModel(clientId, token);
19012         this._pageCount = 999;
19013         this._pathImageByKey = "imageByKey";
19014         this._pathImageCloseTo = "imageCloseTo";
19015         this._pathImagesByH = "imagesByH";
19016         this._pathImageViewAdd = "imageViewAdd";
19017         this._pathSequenceByKey = "sequenceByKey";
19018         this._pathSequenceViewAdd = "sequenceViewAdd";
19019         this._propertiesCore = [
19020             "cl",
19021             "l",
19022             "sequence",
19023         ];
19024         this._propertiesFill = [
19025             "captured_at",
19026             "user",
19027             "project",
19028         ];
19029         this._propertiesKey = [
19030             "key",
19031         ];
19032         this._propertiesSequence = [
19033             "keys",
19034         ];
19035         this._propertiesSpatial = [
19036             "atomic_scale",
19037             "ca",
19038             "calt",
19039             "cca",
19040             "cfocal",
19041             "gpano",
19042             "height",
19043             "merge_cc",
19044             "merge_version",
19045             "c_rotation",
19046             "orientation",
19047             "width",
19048         ];
19049         this._propertiesUser = [
19050             "username",
19051         ];
19052     }
19053     ;
19054     APIv3.prototype.imageByKeyFill$ = function (keys) {
19055         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19056             this._pathImageByKey,
19057             keys,
19058             this._propertiesKey
19059                 .concat(this._propertiesFill)
19060                 .concat(this._propertiesSpatial),
19061             this._propertiesKey
19062                 .concat(this._propertiesUser)
19063         ]))
19064             .map(function (value) {
19065             return value.json.imageByKey;
19066         }), this._pathImageByKey, keys);
19067     };
19068     APIv3.prototype.imageByKeyFull$ = function (keys) {
19069         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19070             this._pathImageByKey,
19071             keys,
19072             this._propertiesKey
19073                 .concat(this._propertiesCore)
19074                 .concat(this._propertiesFill)
19075                 .concat(this._propertiesSpatial),
19076             this._propertiesKey
19077                 .concat(this._propertiesUser)
19078         ]))
19079             .map(function (value) {
19080             return value.json.imageByKey;
19081         }), this._pathImageByKey, keys);
19082     };
19083     APIv3.prototype.imageCloseTo$ = function (lat, lon) {
19084         var lonLat = lon + ":" + lat;
19085         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19086             this._pathImageCloseTo,
19087             [lonLat],
19088             this._propertiesKey
19089                 .concat(this._propertiesCore)
19090                 .concat(this._propertiesFill)
19091                 .concat(this._propertiesSpatial),
19092             this._propertiesKey
19093                 .concat(this._propertiesUser)
19094         ]))
19095             .map(function (value) {
19096             return value != null ? value.json.imageCloseTo[lonLat] : null;
19097         }), this._pathImageCloseTo, [lonLat]);
19098     };
19099     APIv3.prototype.imagesByH$ = function (hs) {
19100         var _this = this;
19101         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19102             this._pathImagesByH,
19103             hs,
19104             { from: 0, to: this._pageCount },
19105             this._propertiesKey
19106                 .concat(this._propertiesCore),
19107             this._propertiesKey
19108         ]))
19109             .map(function (value) {
19110             if (value == null) {
19111                 value = { json: { imagesByH: {} } };
19112                 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
19113                     var h = hs_1[_i];
19114                     value.json.imagesByH[h] = {};
19115                     for (var i = 0; i <= _this._pageCount; i++) {
19116                         value.json.imagesByH[h][i] = null;
19117                     }
19118                 }
19119             }
19120             return value.json.imagesByH;
19121         }), this._pathImagesByH, hs);
19122     };
19123     APIv3.prototype.imageViewAdd$ = function (keys) {
19124         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
19125     };
19126     APIv3.prototype.invalidateImageByKey = function (keys) {
19127         this._invalidateGet(this._pathImageByKey, keys);
19128     };
19129     APIv3.prototype.invalidateImagesByH = function (hs) {
19130         this._invalidateGet(this._pathImagesByH, hs);
19131     };
19132     APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
19133         this._invalidateGet(this._pathSequenceByKey, sKeys);
19134     };
19135     APIv3.prototype.setToken = function (token) {
19136         this._model.invalidate([]);
19137         this._model = null;
19138         this._model = this._modelCreator.createModel(this._clientId, token);
19139     };
19140     APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
19141         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19142             this._pathSequenceByKey,
19143             sequenceKeys,
19144             this._propertiesKey
19145                 .concat(this._propertiesSequence)
19146         ]))
19147             .map(function (value) {
19148             return value.json.sequenceByKey;
19149         }), this._pathSequenceByKey, sequenceKeys);
19150     };
19151     APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
19152         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
19153     };
19154     Object.defineProperty(APIv3.prototype, "clientId", {
19155         get: function () {
19156             return this._clientId;
19157         },
19158         enumerable: true,
19159         configurable: true
19160     });
19161     APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
19162         var _this = this;
19163         return observable
19164             .catch(function (error) {
19165             _this._invalidateGet(path, paths);
19166             throw error;
19167         });
19168     };
19169     APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
19170         var _this = this;
19171         return observable
19172             .catch(function (error) {
19173             _this._invalidateCall(path, paths);
19174             throw error;
19175         });
19176     };
19177     APIv3.prototype._invalidateGet = function (path, paths) {
19178         this._model.invalidate([path, paths]);
19179     };
19180     APIv3.prototype._invalidateCall = function (path, paths) {
19181         this._model.invalidate([path], [paths]);
19182     };
19183     APIv3.prototype._wrapPromise$ = function (promise) {
19184         return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
19185     };
19186     return APIv3;
19187 }());
19188 exports.APIv3 = APIv3;
19189 Object.defineProperty(exports, "__esModule", { value: true });
19190 exports.default = APIv3;
19191
19192 },{"../API":216,"rxjs/Observable":28,"rxjs/add/observable/defer":38,"rxjs/add/observable/fromPromise":42,"rxjs/add/operator/catch":49,"rxjs/add/operator/map":62}],229:[function(require,module,exports){
19193 /// <reference path="../../typings/index.d.ts" />
19194 "use strict";
19195 var falcor = require("falcor");
19196 var HttpDataSource = require("falcor-http-datasource");
19197 var Utils_1 = require("../Utils");
19198 var ModelCreator = (function () {
19199     function ModelCreator() {
19200     }
19201     ModelCreator.prototype.createModel = function (clientId, token) {
19202         var configuration = {
19203             crossDomain: true,
19204             withCredentials: false,
19205         };
19206         if (token != null) {
19207             configuration.headers = { "Authorization": "Bearer " + token };
19208         }
19209         return new falcor.Model({
19210             maxSize: 16 * 1024 * 1024,
19211             source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
19212         });
19213     };
19214     return ModelCreator;
19215 }());
19216 exports.ModelCreator = ModelCreator;
19217 Object.defineProperty(exports, "__esModule", { value: true });
19218 exports.default = ModelCreator;
19219
19220 },{"../Utils":226,"falcor":13,"falcor-http-datasource":8}],230:[function(require,module,exports){
19221 /// <reference path="../../typings/index.d.ts" />
19222 "use strict";
19223 var __extends = (this && this.__extends) || function (d, b) {
19224     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19225     function __() { this.constructor = d; }
19226     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19227 };
19228 var vd = require("virtual-dom");
19229 var Component_1 = require("../Component");
19230 var AttributionComponent = (function (_super) {
19231     __extends(AttributionComponent, _super);
19232     function AttributionComponent(name, container, navigator) {
19233         return _super.call(this, name, container, navigator) || this;
19234     }
19235     AttributionComponent.prototype._activate = function () {
19236         var _this = this;
19237         this._disposable = this._navigator.stateService.currentNode$
19238             .map(function (node) {
19239             return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
19240         })
19241             .subscribe(this._container.domRenderer.render$);
19242     };
19243     AttributionComponent.prototype._deactivate = function () {
19244         this._disposable.unsubscribe();
19245     };
19246     AttributionComponent.prototype._getDefaultConfiguration = function () {
19247         return {};
19248     };
19249     AttributionComponent.prototype._getAttributionNode = function (username, photoId) {
19250         return vd.h("div.Attribution", {}, [
19251             vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
19252                 target: "_blank",
19253                 textContent: "@" + username,
19254             }, []),
19255             vd.h("span", { textContent: "|" }, []),
19256             vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo",
19257                 target: "_blank",
19258                 textContent: "mapillary.com",
19259             }, []),
19260         ]);
19261     };
19262     return AttributionComponent;
19263 }(Component_1.Component));
19264 AttributionComponent.componentName = "attribution";
19265 exports.AttributionComponent = AttributionComponent;
19266 Component_1.ComponentService.register(AttributionComponent);
19267 Object.defineProperty(exports, "__esModule", { value: true });
19268 exports.default = AttributionComponent;
19269
19270 },{"../Component":217,"virtual-dom":173}],231:[function(require,module,exports){
19271 /// <reference path="../../typings/index.d.ts" />
19272 "use strict";
19273 var __extends = (this && this.__extends) || function (d, b) {
19274     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19275     function __() { this.constructor = d; }
19276     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19277 };
19278 var vd = require("virtual-dom");
19279 var Component_1 = require("../Component");
19280 var BackgroundComponent = (function (_super) {
19281     __extends(BackgroundComponent, _super);
19282     function BackgroundComponent(name, container, navigator) {
19283         return _super.call(this, name, container, navigator) || this;
19284     }
19285     BackgroundComponent.prototype._activate = function () {
19286         this._container.domRenderer.render$
19287             .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") });
19288     };
19289     BackgroundComponent.prototype._deactivate = function () {
19290         return;
19291     };
19292     BackgroundComponent.prototype._getDefaultConfiguration = function () {
19293         return {};
19294     };
19295     BackgroundComponent.prototype._getBackgroundNode = function (notice) {
19296         // todo: add condition for when to display the DOM node
19297         return vd.h("div.BackgroundWrapper", {}, [
19298             vd.h("p", { textContent: notice }, []),
19299         ]);
19300     };
19301     return BackgroundComponent;
19302 }(Component_1.Component));
19303 BackgroundComponent.componentName = "background";
19304 exports.BackgroundComponent = BackgroundComponent;
19305 Component_1.ComponentService.register(BackgroundComponent);
19306 Object.defineProperty(exports, "__esModule", { value: true });
19307 exports.default = BackgroundComponent;
19308
19309 },{"../Component":217,"virtual-dom":173}],232:[function(require,module,exports){
19310 /// <reference path="../../typings/index.d.ts" />
19311 "use strict";
19312 var __extends = (this && this.__extends) || function (d, b) {
19313     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19314     function __() { this.constructor = d; }
19315     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19316 };
19317 var vd = require("virtual-dom");
19318 var Observable_1 = require("rxjs/Observable");
19319 var Component_1 = require("../Component");
19320 var Geo_1 = require("../Geo");
19321 var BearingComponent = (function (_super) {
19322     __extends(BearingComponent, _super);
19323     function BearingComponent(name, container, navigator) {
19324         var _this = _super.call(this, name, container, navigator) || this;
19325         _this._spatial = new Geo_1.Spatial();
19326         _this._svgNamespace = "http://www.w3.org/2000/svg";
19327         _this._distinctThreshold = Math.PI / 90;
19328         return _this;
19329     }
19330     BearingComponent.prototype._activate = function () {
19331         var _this = this;
19332         var nodeBearingFov$ = this._navigator.stateService.currentState$
19333             .distinctUntilChanged(undefined, function (frame) {
19334             return frame.state.currentNode.key;
19335         })
19336             .map(function (frame) {
19337             var node = frame.state.currentNode;
19338             var transform = frame.state.currentTransform;
19339             if (node.pano) {
19340                 var hFov_1 = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
19341                 return [_this._spatial.degToRad(node.ca), hFov_1];
19342             }
19343             var size = Math.max(transform.basicWidth, transform.basicHeight);
19344             if (size <= 0) {
19345                 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
19346                     "Not showing available fov.");
19347             }
19348             var hFov = size > 0 ?
19349                 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
19350                 0;
19351             return [_this._spatial.degToRad(node.ca), hFov];
19352         })
19353             .distinctUntilChanged(function (a1, a2) {
19354             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
19355                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
19356         });
19357         var cameraBearingFov$ = this._container.renderService.renderCamera$
19358             .map(function (rc) {
19359             var vFov = _this._spatial.degToRad(rc.perspective.fov);
19360             var hFov = Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
19361             return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
19362         })
19363             .distinctUntilChanged(function (a1, a2) {
19364             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
19365                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
19366         });
19367         this._renderSubscription = Observable_1.Observable
19368             .combineLatest(nodeBearingFov$, cameraBearingFov$)
19369             .map(function (args) {
19370             var background = vd.h("div.BearingIndicatorBackground", {}, [
19371                 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
19372                 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
19373             ]);
19374             var north = vd.h("div.BearingIndicatorNorth", {}, []);
19375             var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
19376             var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
19377             var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
19378             return {
19379                 name: _this._name,
19380                 vnode: vd.h("div.BearingIndicator", {}, [
19381                     background,
19382                     north,
19383                     compass,
19384                 ]),
19385             };
19386         })
19387             .subscribe(this._container.domRenderer.render$);
19388     };
19389     BearingComponent.prototype._deactivate = function () {
19390         this._renderSubscription.unsubscribe();
19391     };
19392     BearingComponent.prototype._getDefaultConfiguration = function () {
19393         return {};
19394     };
19395     BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
19396         var group = vd.h("g", {
19397             attributes: { transform: "translate(1,1)" },
19398             namespace: this._svgNamespace,
19399         }, [nodeSector, cameraSector]);
19400         var centerCircle = vd.h("circle", {
19401             attributes: {
19402                 cx: "1",
19403                 cy: "1",
19404                 fill: "#abb1b9",
19405                 r: "0.291667",
19406                 stroke: "#000",
19407                 "stroke-width": "0.0833333",
19408             },
19409             namespace: this._svgNamespace,
19410         }, []);
19411         var svg = vd.h("svg", {
19412             attributes: { viewBox: "0 0 2 2" },
19413             namespace: this._svgNamespace,
19414             style: {
19415                 bottom: "4px",
19416                 height: "48px",
19417                 left: "4px",
19418                 position: "absolute",
19419                 width: "48px",
19420             },
19421         }, [group, centerCircle]);
19422         return svg;
19423     };
19424     BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
19425         if (fov > 2 * Math.PI - Math.PI / 90) {
19426             return vd.h("circle", {
19427                 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
19428                 namespace: this._svgNamespace,
19429             }, []);
19430         }
19431         var arcStart = bearing - fov / 2 - Math.PI / 2;
19432         var arcEnd = arcStart + fov;
19433         var startX = Math.cos(arcStart);
19434         var startY = Math.sin(arcStart);
19435         var endX = Math.cos(arcEnd);
19436         var endY = Math.sin(arcEnd);
19437         var largeArc = fov >= Math.PI ? 1 : 0;
19438         var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
19439         return vd.h("path", {
19440             attributes: { d: description, fill: fill },
19441             namespace: this._svgNamespace,
19442         }, []);
19443     };
19444     return BearingComponent;
19445 }(Component_1.Component));
19446 BearingComponent.componentName = "bearing";
19447 exports.BearingComponent = BearingComponent;
19448 Component_1.ComponentService.register(BearingComponent);
19449 Object.defineProperty(exports, "__esModule", { value: true });
19450 exports.default = BearingComponent;
19451
19452 },{"../Component":217,"../Geo":220,"rxjs/Observable":28,"virtual-dom":173}],233:[function(require,module,exports){
19453 "use strict";
19454 var __extends = (this && this.__extends) || function (d, b) {
19455     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19456     function __() { this.constructor = d; }
19457     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19458 };
19459 var Observable_1 = require("rxjs/Observable");
19460 require("rxjs/add/observable/combineLatest");
19461 require("rxjs/add/observable/from");
19462 require("rxjs/add/observable/merge");
19463 require("rxjs/add/observable/of");
19464 require("rxjs/add/observable/zip");
19465 require("rxjs/add/operator/catch");
19466 require("rxjs/add/operator/combineLatest");
19467 require("rxjs/add/operator/distinct");
19468 require("rxjs/add/operator/expand");
19469 require("rxjs/add/operator/filter");
19470 require("rxjs/add/operator/map");
19471 require("rxjs/add/operator/merge");
19472 require("rxjs/add/operator/mergeMap");
19473 require("rxjs/add/operator/mergeAll");
19474 require("rxjs/add/operator/skip");
19475 require("rxjs/add/operator/switchMap");
19476 var Edge_1 = require("../Edge");
19477 var Component_1 = require("../Component");
19478 var CacheComponent = (function (_super) {
19479     __extends(CacheComponent, _super);
19480     function CacheComponent(name, container, navigator) {
19481         return _super.call(this, name, container, navigator) || this;
19482     }
19483     /**
19484      * Set the cache depth.
19485      *
19486      * Configures the cache depth. The cache depth can be different for
19487      * different edge direction types.
19488      *
19489      * @param {ICacheDepth} depth - Cache depth structure.
19490      */
19491     CacheComponent.prototype.setDepth = function (depth) {
19492         this.configure({ depth: depth });
19493     };
19494     CacheComponent.prototype._activate = function () {
19495         var _this = this;
19496         this._sequenceSubscription = Observable_1.Observable
19497             .combineLatest(this._navigator.stateService.currentNode$
19498             .switchMap(function (node) {
19499             return node.sequenceEdges$;
19500         })
19501             .filter(function (status) {
19502             return status.cached;
19503         }), this._configuration$)
19504             .switchMap(function (nc) {
19505             var status = nc[0];
19506             var configuration = nc[1];
19507             var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
19508             var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
19509             var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
19510             return Observable_1.Observable
19511                 .merge(next$, prev$)
19512                 .catch(function (error, caught) {
19513                 console.error("Failed to cache sequence edges.", error);
19514                 return Observable_1.Observable.empty();
19515             });
19516         })
19517             .subscribe(function () { });
19518         this._spatialSubscription = this._navigator.stateService.currentNode$
19519             .switchMap(function (node) {
19520             return Observable_1.Observable
19521                 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
19522                 .filter(function (status) {
19523                 return status.cached;
19524             }));
19525         })
19526             .combineLatest(this._configuration$, function (ns, configuration) {
19527             return [ns[0], ns[1], configuration];
19528         })
19529             .switchMap(function (args) {
19530             var node = args[0];
19531             var edges = args[1].edges;
19532             var depth = args[2].depth;
19533             var panoDepth = Math.max(0, Math.min(2, depth.pano));
19534             var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
19535             var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
19536             var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
19537             var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
19538             var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
19539             var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
19540             var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
19541             var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
19542             var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
19543             var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
19544             return Observable_1.Observable
19545                 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
19546                 .catch(function (error, caught) {
19547                 console.error("Failed to cache spatial edges.", error);
19548                 return Observable_1.Observable.empty();
19549             });
19550         })
19551             .subscribe(function () { });
19552     };
19553     CacheComponent.prototype._deactivate = function () {
19554         this._sequenceSubscription.unsubscribe();
19555         this._spatialSubscription.unsubscribe();
19556     };
19557     CacheComponent.prototype._getDefaultConfiguration = function () {
19558         return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
19559     };
19560     CacheComponent.prototype._cache$ = function (edges, direction, depth) {
19561         var _this = this;
19562         return Observable_1.Observable
19563             .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
19564             .expand(function (ed) {
19565             var es = ed[0];
19566             var d = ed[1];
19567             var edgesDepths$ = [];
19568             if (d > 0) {
19569                 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
19570                     var edge = es_1[_i];
19571                     if (edge.data.direction === direction) {
19572                         edgesDepths$.push(Observable_1.Observable
19573                             .zip(_this._navigator.graphService.cacheNode$(edge.to)
19574                             .mergeMap(function (n) {
19575                             return _this._nodeToEdges$(n, direction);
19576                         }), Observable_1.Observable.of(d - 1)));
19577                     }
19578                 }
19579             }
19580             return Observable_1.Observable
19581                 .from(edgesDepths$)
19582                 .mergeAll();
19583         })
19584             .skip(1);
19585     };
19586     CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
19587         return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
19588             node.sequenceEdges$ :
19589             node.spatialEdges$)
19590             .first(function (status) {
19591             return status.cached;
19592         })
19593             .map(function (status) {
19594             return status.edges;
19595         });
19596     };
19597     return CacheComponent;
19598 }(Component_1.Component));
19599 CacheComponent.componentName = "cache";
19600 exports.CacheComponent = CacheComponent;
19601 Component_1.ComponentService.register(CacheComponent);
19602 Object.defineProperty(exports, "__esModule", { value: true });
19603 exports.default = CacheComponent;
19604
19605 },{"../Component":217,"../Edge":218,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/from":40,"rxjs/add/observable/merge":43,"rxjs/add/observable/of":44,"rxjs/add/observable/zip":46,"rxjs/add/operator/catch":49,"rxjs/add/operator/combineLatest":50,"rxjs/add/operator/distinct":54,"rxjs/add/operator/expand":57,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/merge":63,"rxjs/add/operator/mergeAll":64,"rxjs/add/operator/mergeMap":65,"rxjs/add/operator/skip":72,"rxjs/add/operator/switchMap":76}],234:[function(require,module,exports){
19606 "use strict";
19607 var __extends = (this && this.__extends) || function (d, b) {
19608     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19609     function __() { this.constructor = d; }
19610     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19611 };
19612 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
19613 var Subject_1 = require("rxjs/Subject");
19614 require("rxjs/add/operator/publishReplay");
19615 require("rxjs/add/operator/scan");
19616 require("rxjs/add/operator/startWith");
19617 var Utils_1 = require("../Utils");
19618 var Component = (function (_super) {
19619     __extends(Component, _super);
19620     function Component(name, container, navigator) {
19621         var _this = _super.call(this) || this;
19622         _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
19623         _this._configurationSubject$ = new Subject_1.Subject();
19624         _this._activated = false;
19625         _this._container = container;
19626         _this._name = name;
19627         _this._navigator = navigator;
19628         _this._configuration$ =
19629             _this._configurationSubject$
19630                 .startWith(_this.defaultConfiguration)
19631                 .scan(function (conf, newConf) {
19632                 for (var key in newConf) {
19633                     if (newConf.hasOwnProperty(key)) {
19634                         conf[key] = newConf[key];
19635                     }
19636                 }
19637                 return conf;
19638             })
19639                 .publishReplay(1)
19640                 .refCount();
19641         _this._configuration$.subscribe(function () { });
19642         return _this;
19643     }
19644     Object.defineProperty(Component.prototype, "activated", {
19645         get: function () {
19646             return this._activated;
19647         },
19648         enumerable: true,
19649         configurable: true
19650     });
19651     Object.defineProperty(Component.prototype, "activated$", {
19652         get: function () {
19653             return this._activated$;
19654         },
19655         enumerable: true,
19656         configurable: true
19657     });
19658     Object.defineProperty(Component.prototype, "defaultConfiguration", {
19659         /**
19660          * Get default configuration.
19661          *
19662          * @returns {TConfiguration} Default configuration for component.
19663          */
19664         get: function () {
19665             return this._getDefaultConfiguration();
19666         },
19667         enumerable: true,
19668         configurable: true
19669     });
19670     Object.defineProperty(Component.prototype, "configuration$", {
19671         get: function () {
19672             return this._configuration$;
19673         },
19674         enumerable: true,
19675         configurable: true
19676     });
19677     Component.prototype.activate = function (conf) {
19678         if (this._activated) {
19679             return;
19680         }
19681         if (conf !== undefined) {
19682             this._configurationSubject$.next(conf);
19683         }
19684         this._activate();
19685         this._activated = true;
19686         this._activated$.next(true);
19687     };
19688     ;
19689     Component.prototype.configure = function (conf) {
19690         this._configurationSubject$.next(conf);
19691     };
19692     Component.prototype.deactivate = function () {
19693         if (!this._activated) {
19694             return;
19695         }
19696         this._deactivate();
19697         this._container.domRenderer.clear(this._name);
19698         this._container.glRenderer.clear(this._name);
19699         this._activated = false;
19700         this._activated$.next(false);
19701     };
19702     ;
19703     /**
19704      * Detect the viewer's new width and height and resize the component's
19705      * rendered elements accordingly if applicable.
19706      */
19707     Component.prototype.resize = function () { return; };
19708     return Component;
19709 }(Utils_1.EventEmitter));
19710 /**
19711  * Component name. Used when interacting with component through the Viewer's API.
19712  */
19713 Component.componentName = "not_worthy";
19714 exports.Component = Component;
19715 Object.defineProperty(exports, "__esModule", { value: true });
19716 exports.default = Component;
19717
19718 },{"../Utils":226,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/startWith":75}],235:[function(require,module,exports){
19719 /// <reference path="../../typings/index.d.ts" />
19720 "use strict";
19721 var _ = require("underscore");
19722 var Error_1 = require("../Error");
19723 var ComponentService = (function () {
19724     function ComponentService(container, navigator) {
19725         this._components = {};
19726         this._container = container;
19727         this._navigator = navigator;
19728         for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
19729             var component = _a[_i];
19730             this._components[component.componentName] = {
19731                 active: false,
19732                 component: new component(component.componentName, container, navigator),
19733             };
19734         }
19735         this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
19736         this._coverComponent.activate();
19737         this._coverActivated = true;
19738     }
19739     ComponentService.register = function (component) {
19740         if (ComponentService.registeredComponents[component.componentName] === undefined) {
19741             ComponentService.registeredComponents[component.componentName] = component;
19742         }
19743     };
19744     ComponentService.registerCover = function (coverComponent) {
19745         ComponentService.registeredCoverComponent = coverComponent;
19746     };
19747     ComponentService.prototype.activateCover = function () {
19748         if (this._coverActivated) {
19749             return;
19750         }
19751         this._coverActivated = true;
19752         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
19753             var component = _a[_i];
19754             if (component.active) {
19755                 component.component.deactivate();
19756             }
19757         }
19758         return;
19759     };
19760     ComponentService.prototype.deactivateCover = function () {
19761         if (!this._coverActivated) {
19762             return;
19763         }
19764         this._coverActivated = false;
19765         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
19766             var component = _a[_i];
19767             if (component.active) {
19768                 component.component.activate();
19769             }
19770         }
19771         return;
19772     };
19773     ComponentService.prototype.activate = function (name) {
19774         this._checkName(name);
19775         this._components[name].active = true;
19776         if (!this._coverActivated) {
19777             this.get(name).activate();
19778         }
19779     };
19780     ComponentService.prototype.configure = function (name, conf) {
19781         this._checkName(name);
19782         this.get(name).configure(conf);
19783     };
19784     ComponentService.prototype.deactivate = function (name) {
19785         this._checkName(name);
19786         this._components[name].active = false;
19787         if (!this._coverActivated) {
19788             this.get(name).deactivate();
19789         }
19790     };
19791     ComponentService.prototype.resize = function () {
19792         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
19793             var component = _a[_i];
19794             component.component.resize();
19795         }
19796     };
19797     ComponentService.prototype.get = function (name) {
19798         return this._components[name].component;
19799     };
19800     ComponentService.prototype.getCover = function () {
19801         return this._coverComponent;
19802     };
19803     ComponentService.prototype._checkName = function (name) {
19804         if (!(name in this._components)) {
19805             throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
19806         }
19807     };
19808     return ComponentService;
19809 }());
19810 ComponentService.registeredComponents = {};
19811 exports.ComponentService = ComponentService;
19812 Object.defineProperty(exports, "__esModule", { value: true });
19813 exports.default = ComponentService;
19814
19815 },{"../Error":219,"underscore":168}],236:[function(require,module,exports){
19816 /// <reference path="../../typings/index.d.ts" />
19817 "use strict";
19818 var __extends = (this && this.__extends) || function (d, b) {
19819     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19820     function __() { this.constructor = d; }
19821     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19822 };
19823 var vd = require("virtual-dom");
19824 require("rxjs/add/operator/filter");
19825 require("rxjs/add/operator/map");
19826 require("rxjs/add/operator/withLatestFrom");
19827 var Component_1 = require("../Component");
19828 var CoverComponent = (function (_super) {
19829     __extends(CoverComponent, _super);
19830     function CoverComponent(name, container, navigator) {
19831         return _super.call(this, name, container, navigator) || this;
19832     }
19833     CoverComponent.prototype._activate = function () {
19834         var _this = this;
19835         this._keyDisposable = this._navigator.stateService.currentNode$
19836             .withLatestFrom(this._configuration$, function (node, configuration) {
19837             return [node, configuration];
19838         })
19839             .filter(function (nc) {
19840             return nc[0].key !== nc[1].key;
19841         })
19842             .map(function (nc) { return nc[0]; })
19843             .map(function (node) {
19844             return { key: node.key, src: node.image.src };
19845         })
19846             .subscribe(this._configurationSubject$);
19847         this._disposable = this._configuration$
19848             .map(function (conf) {
19849             if (!conf.key) {
19850                 return { name: _this._name, vnode: vd.h("div", []) };
19851             }
19852             if (!conf.visible) {
19853                 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
19854             }
19855             return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
19856         })
19857             .subscribe(this._container.domRenderer.render$);
19858     };
19859     CoverComponent.prototype._deactivate = function () {
19860         this._disposable.unsubscribe();
19861         this._keyDisposable.unsubscribe();
19862     };
19863     CoverComponent.prototype._getDefaultConfiguration = function () {
19864         return { "loading": false, "visible": true };
19865     };
19866     CoverComponent.prototype._getCoverButtonVNode = function (conf) {
19867         var _this = this;
19868         var cover = conf.loading ? "div.Cover.CoverLoading" : "div.Cover";
19869         return vd.h(cover, [
19870             this._getCoverBackgroundVNode(conf),
19871             vd.h("button.CoverButton", { onclick: function () { _this.configure({ loading: true }); } }, ["Explore"]),
19872             vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
19873         ]);
19874     };
19875     CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
19876         var url = conf.src != null ?
19877             "url(" + conf.src + ")" :
19878             "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
19879         var properties = { style: { backgroundImage: url } };
19880         var children = [];
19881         if (conf.loading) {
19882             children.push(vd.h("div.Spinner", {}, []));
19883         }
19884         children.push(vd.h("div.CoverBackgroundGradient", {}, []));
19885         return vd.h("div.CoverBackground", properties, children);
19886     };
19887     return CoverComponent;
19888 }(Component_1.Component));
19889 CoverComponent.componentName = "cover";
19890 exports.CoverComponent = CoverComponent;
19891 Component_1.ComponentService.registerCover(CoverComponent);
19892 Object.defineProperty(exports, "__esModule", { value: true });
19893 exports.default = CoverComponent;
19894
19895 },{"../Component":217,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/withLatestFrom":80,"virtual-dom":173}],237:[function(require,module,exports){
19896 /// <reference path="../../typings/index.d.ts" />
19897 "use strict";
19898 var __extends = (this && this.__extends) || function (d, b) {
19899     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19900     function __() { this.constructor = d; }
19901     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19902 };
19903 var _ = require("underscore");
19904 var vd = require("virtual-dom");
19905 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
19906 require("rxjs/add/operator/combineLatest");
19907 var Component_1 = require("../Component");
19908 var DebugComponent = (function (_super) {
19909     __extends(DebugComponent, _super);
19910     function DebugComponent(name, container, navigator) {
19911         var _this = _super.call(this, name, container, navigator) || this;
19912         _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
19913         _this._displaying = false;
19914         return _this;
19915     }
19916     DebugComponent.prototype._activate = function () {
19917         var _this = this;
19918         this._disposable = this._navigator.stateService.currentState$
19919             .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
19920             return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
19921         })
19922             .subscribe(this._container.domRenderer.render$);
19923     };
19924     DebugComponent.prototype._deactivate = function () {
19925         this._disposable.unsubscribe();
19926     };
19927     DebugComponent.prototype._getDefaultConfiguration = function () {
19928         return {};
19929     };
19930     DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
19931         var ret = [];
19932         ret.push(vd.h("h2", "Node"));
19933         if (frame.state.currentNode) {
19934             ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
19935         }
19936         if (frame.state.previousNode) {
19937             ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
19938         }
19939         ret.push(vd.h("h2", "Loading"));
19940         var total = 0;
19941         var loaded = 0;
19942         var loading = 0;
19943         for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
19944             var loadStat = _a[_i];
19945             total += loadStat.loaded;
19946             if (loadStat.loaded !== loadStat.total) {
19947                 loading++;
19948             }
19949             else {
19950                 loaded++;
19951             }
19952         }
19953         ret.push(vd.h("p", "Loaded Images: " + loaded));
19954         ret.push(vd.h("p", "Loading Images: " + loading));
19955         ret.push(vd.h("p", "Total bytes loaded: " + total));
19956         ret.push(vd.h("h2", "Camera"));
19957         ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
19958         ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
19959         ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
19960         ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
19961         ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
19962         ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
19963         ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
19964         ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
19965         ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
19966         return ret;
19967     };
19968     DebugComponent.prototype._getDebugVNode = function (open, info) {
19969         if (open) {
19970             return vd.h("div.Debug", {}, [
19971                 vd.h("h2", {}, ["Debug"]),
19972                 this._getDebugVNodeButton(open),
19973                 vd.h("pre", {}, info),
19974             ]);
19975         }
19976         else {
19977             return this._getDebugVNodeButton(open);
19978         }
19979     };
19980     DebugComponent.prototype._getDebugVNodeButton = function (open) {
19981         var buttonText = open ? "Disable Debug" : "D";
19982         var buttonCssClass = open ? "" : ".DebugButtonFixed";
19983         if (open) {
19984             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
19985         }
19986         else {
19987             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
19988         }
19989     };
19990     DebugComponent.prototype._closeDebugElement = function (open) {
19991         this._open$.next(false);
19992     };
19993     DebugComponent.prototype._openDebugElement = function () {
19994         this._open$.next(true);
19995     };
19996     return DebugComponent;
19997 }(Component_1.Component));
19998 DebugComponent.componentName = "debug";
19999 exports.DebugComponent = DebugComponent;
20000 Component_1.ComponentService.register(DebugComponent);
20001 Object.defineProperty(exports, "__esModule", { value: true });
20002 exports.default = DebugComponent;
20003
20004 },{"../Component":217,"rxjs/BehaviorSubject":25,"rxjs/add/operator/combineLatest":50,"underscore":168,"virtual-dom":173}],238:[function(require,module,exports){
20005 /// <reference path="../../typings/index.d.ts" />
20006 "use strict";
20007 var __extends = (this && this.__extends) || function (d, b) {
20008     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20009     function __() { this.constructor = d; }
20010     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20011 };
20012 var vd = require("virtual-dom");
20013 require("rxjs/add/operator/combineLatest");
20014 var Component_1 = require("../Component");
20015 var ImageComponent = (function (_super) {
20016     __extends(ImageComponent, _super);
20017     function ImageComponent(name, container, navigator) {
20018         var _this = _super.call(this, name, container, navigator) || this;
20019         _this._canvasId = container.id + "-" + _this._name;
20020         return _this;
20021     }
20022     ImageComponent.prototype._activate = function () {
20023         var _this = this;
20024         this.drawSubscription = this._container.domRenderer.element$
20025             .combineLatest(this._navigator.stateService.currentNode$, function (element, node) {
20026             var canvas = document.getElementById(_this._canvasId);
20027             return { canvas: canvas, node: node };
20028         })
20029             .subscribe(function (canvasNode) {
20030             var canvas = canvasNode.canvas;
20031             var node = canvasNode.node;
20032             if (!node || !canvas) {
20033                 return null;
20034             }
20035             var adaptableDomRenderer = canvas.parentElement;
20036             var width = adaptableDomRenderer.offsetWidth;
20037             var height = adaptableDomRenderer.offsetHeight;
20038             canvas.width = width;
20039             canvas.height = height;
20040             var ctx = canvas.getContext("2d");
20041             ctx.drawImage(node.image, 0, 0, width, height);
20042         });
20043         this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
20044     };
20045     ImageComponent.prototype._deactivate = function () {
20046         this.drawSubscription.unsubscribe();
20047     };
20048     ImageComponent.prototype._getDefaultConfiguration = function () {
20049         return {};
20050     };
20051     return ImageComponent;
20052 }(Component_1.Component));
20053 ImageComponent.componentName = "image";
20054 exports.ImageComponent = ImageComponent;
20055 Component_1.ComponentService.register(ImageComponent);
20056 Object.defineProperty(exports, "__esModule", { value: true });
20057 exports.default = ImageComponent;
20058
20059 },{"../Component":217,"rxjs/add/operator/combineLatest":50,"virtual-dom":173}],239:[function(require,module,exports){
20060 "use strict";
20061 var __extends = (this && this.__extends) || function (d, b) {
20062     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20063     function __() { this.constructor = d; }
20064     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20065 };
20066 var Observable_1 = require("rxjs/Observable");
20067 require("rxjs/add/observable/fromEvent");
20068 require("rxjs/add/operator/withLatestFrom");
20069 var Edge_1 = require("../Edge");
20070 var Component_1 = require("../Component");
20071 var Geo_1 = require("../Geo");
20072 var KeyboardComponent = (function (_super) {
20073     __extends(KeyboardComponent, _super);
20074     function KeyboardComponent(name, container, navigator) {
20075         var _this = _super.call(this, name, container, navigator) || this;
20076         _this._spatial = new Geo_1.Spatial();
20077         _this._perspectiveDirections = [
20078             Edge_1.EdgeDirection.StepForward,
20079             Edge_1.EdgeDirection.StepBackward,
20080             Edge_1.EdgeDirection.StepLeft,
20081             Edge_1.EdgeDirection.StepRight,
20082             Edge_1.EdgeDirection.TurnLeft,
20083             Edge_1.EdgeDirection.TurnRight,
20084             Edge_1.EdgeDirection.TurnU,
20085         ];
20086         return _this;
20087     }
20088     KeyboardComponent.prototype._activate = function () {
20089         var _this = this;
20090         var sequenceEdges$ = this._navigator.stateService.currentNode$
20091             .switchMap(function (node) {
20092             return node.sequenceEdges$;
20093         });
20094         var spatialEdges$ = this._navigator.stateService.currentNode$
20095             .switchMap(function (node) {
20096             return node.spatialEdges$;
20097         });
20098         this._disposable = Observable_1.Observable
20099             .fromEvent(document, "keydown")
20100             .withLatestFrom(this._navigator.stateService.currentState$, sequenceEdges$, spatialEdges$, function (event, frame, sequenceEdges, spatialEdges) {
20101             return { event: event, frame: frame, sequenceEdges: sequenceEdges, spatialEdges: spatialEdges };
20102         })
20103             .subscribe(function (kf) {
20104             if (!kf.frame.state.currentNode.pano) {
20105                 _this._navigatePerspective(kf.event, kf.sequenceEdges, kf.spatialEdges);
20106             }
20107             else {
20108                 _this._navigatePanorama(kf.event, kf.sequenceEdges, kf.spatialEdges, kf.frame.state.camera);
20109             }
20110         });
20111     };
20112     KeyboardComponent.prototype._deactivate = function () {
20113         this._disposable.unsubscribe();
20114     };
20115     KeyboardComponent.prototype._getDefaultConfiguration = function () {
20116         return {};
20117     };
20118     KeyboardComponent.prototype._navigatePanorama = function (event, sequenceEdges, spatialEdges, camera) {
20119         var navigationAngle = 0;
20120         var stepDirection = null;
20121         var sequenceDirection = null;
20122         var phi = this._rotationFromCamera(camera).phi;
20123         switch (event.keyCode) {
20124             case 37:
20125                 if (event.shiftKey || event.altKey) {
20126                     break;
20127                 }
20128                 navigationAngle = Math.PI / 2 + phi;
20129                 stepDirection = Edge_1.EdgeDirection.StepLeft;
20130                 break;
20131             case 38:
20132                 if (event.shiftKey) {
20133                     break;
20134                 }
20135                 if (event.altKey) {
20136                     sequenceDirection = Edge_1.EdgeDirection.Next;
20137                     break;
20138                 }
20139                 navigationAngle = phi;
20140                 stepDirection = Edge_1.EdgeDirection.StepForward;
20141                 break;
20142             case 39:
20143                 if (event.shiftKey || event.altKey) {
20144                     break;
20145                 }
20146                 navigationAngle = -Math.PI / 2 + phi;
20147                 stepDirection = Edge_1.EdgeDirection.StepRight;
20148                 break;
20149             case 40:
20150                 if (event.shiftKey) {
20151                     break;
20152                 }
20153                 if (event.altKey) {
20154                     sequenceDirection = Edge_1.EdgeDirection.Prev;
20155                     break;
20156                 }
20157                 navigationAngle = Math.PI + phi;
20158                 stepDirection = Edge_1.EdgeDirection.StepBackward;
20159                 break;
20160             default:
20161                 return;
20162         }
20163         event.preventDefault();
20164         if (sequenceDirection != null) {
20165             this._moveInDir(sequenceDirection, sequenceEdges);
20166             return;
20167         }
20168         if (stepDirection == null || !spatialEdges.cached) {
20169             return;
20170         }
20171         navigationAngle = this._spatial.wrapAngle(navigationAngle);
20172         var threshold = Math.PI / 4;
20173         var edges = spatialEdges.edges.filter(function (e) {
20174             return e.data.direction === Edge_1.EdgeDirection.Pano ||
20175                 e.data.direction === stepDirection;
20176         });
20177         var smallestAngle = Number.MAX_VALUE;
20178         var toKey = null;
20179         for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
20180             var edge = edges_1[_i];
20181             var angle = Math.abs(this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
20182             if (angle < Math.min(smallestAngle, threshold)) {
20183                 smallestAngle = angle;
20184                 toKey = edge.to;
20185             }
20186         }
20187         if (toKey == null) {
20188             return;
20189         }
20190         this._navigator.moveToKey$(toKey)
20191             .subscribe(function (n) { return; }, function (e) { console.error(e); });
20192     };
20193     KeyboardComponent.prototype._rotationFromCamera = function (camera) {
20194         var direction = camera.lookat.clone().sub(camera.position);
20195         var upProjection = direction.clone().dot(camera.up);
20196         var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
20197         var phi = Math.atan2(planeProjection.y, planeProjection.x);
20198         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
20199         return { phi: phi, theta: theta };
20200     };
20201     KeyboardComponent.prototype._navigatePerspective = function (event, sequenceEdges, spatialEdges) {
20202         var direction = null;
20203         var sequenceDirection = null;
20204         switch (event.keyCode) {
20205             case 37:
20206                 if (event.altKey) {
20207                     break;
20208                 }
20209                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
20210                 break;
20211             case 38:
20212                 if (event.altKey) {
20213                     sequenceDirection = Edge_1.EdgeDirection.Next;
20214                     break;
20215                 }
20216                 direction = event.shiftKey ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
20217                 break;
20218             case 39:
20219                 if (event.altKey) {
20220                     break;
20221                 }
20222                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
20223                 break;
20224             case 40:
20225                 if (event.altKey) {
20226                     sequenceDirection = Edge_1.EdgeDirection.Prev;
20227                     break;
20228                 }
20229                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
20230                 break;
20231             default:
20232                 return;
20233         }
20234         event.preventDefault();
20235         if (sequenceDirection != null) {
20236             this._moveInDir(sequenceDirection, sequenceEdges);
20237             return;
20238         }
20239         this._moveInDir(direction, spatialEdges);
20240     };
20241     KeyboardComponent.prototype._moveInDir = function (direction, edgeStatus) {
20242         if (!edgeStatus.cached) {
20243             return;
20244         }
20245         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
20246             var edge = _a[_i];
20247             if (edge.data.direction === direction) {
20248                 this._navigator.moveToKey$(edge.to)
20249                     .subscribe(function (n) { return; }, function (e) { console.error(e); });
20250                 return;
20251             }
20252         }
20253     };
20254     return KeyboardComponent;
20255 }(Component_1.Component));
20256 KeyboardComponent.componentName = "keyboard";
20257 exports.KeyboardComponent = KeyboardComponent;
20258 Component_1.ComponentService.register(KeyboardComponent);
20259 Object.defineProperty(exports, "__esModule", { value: true });
20260 exports.default = KeyboardComponent;
20261
20262 },{"../Component":217,"../Edge":218,"../Geo":220,"rxjs/Observable":28,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/withLatestFrom":80}],240:[function(require,module,exports){
20263 /// <reference path="../../typings/index.d.ts" />
20264 "use strict";
20265 var __extends = (this && this.__extends) || function (d, b) {
20266     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20267     function __() { this.constructor = d; }
20268     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20269 };
20270 var _ = require("underscore");
20271 var vd = require("virtual-dom");
20272 require("rxjs/add/operator/combineLatest");
20273 var Component_1 = require("../Component");
20274 var LoadingComponent = (function (_super) {
20275     __extends(LoadingComponent, _super);
20276     function LoadingComponent(name, container, navigator) {
20277         return _super.call(this, name, container, navigator) || this;
20278     }
20279     LoadingComponent.prototype._activate = function () {
20280         var _this = this;
20281         this._loadingSubscription = this._navigator.loadingService.loading$
20282             .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) {
20283             if (!loading) {
20284                 return { name: "loading", vnode: _this._getBarVNode(100) };
20285             }
20286             var total = 0;
20287             var loaded = 0;
20288             for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
20289                 var loadStat = _a[_i];
20290                 if (loadStat.loaded !== loadStat.total) {
20291                     loaded += loadStat.loaded;
20292                     total += loadStat.total;
20293                 }
20294             }
20295             var percentage = 100;
20296             if (total !== 0) {
20297                 percentage = (loaded / total) * 100;
20298             }
20299             return { name: _this._name, vnode: _this._getBarVNode(percentage) };
20300         })
20301             .subscribe(this._container.domRenderer.render$);
20302     };
20303     LoadingComponent.prototype._deactivate = function () {
20304         this._loadingSubscription.unsubscribe();
20305     };
20306     LoadingComponent.prototype._getDefaultConfiguration = function () {
20307         return {};
20308     };
20309     LoadingComponent.prototype._getBarVNode = function (percentage) {
20310         var loadingBarStyle = {};
20311         var loadingContainerStyle = {};
20312         if (percentage !== 100) {
20313             loadingBarStyle.width = percentage.toFixed(0) + "%";
20314             loadingBarStyle.opacity = "1";
20315         }
20316         else {
20317             loadingBarStyle.width = "100%";
20318             loadingBarStyle.opacity = "0";
20319         }
20320         return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
20321     };
20322     return LoadingComponent;
20323 }(Component_1.Component));
20324 LoadingComponent.componentName = "loading";
20325 exports.LoadingComponent = LoadingComponent;
20326 Component_1.ComponentService.register(LoadingComponent);
20327 Object.defineProperty(exports, "__esModule", { value: true });
20328 exports.default = LoadingComponent;
20329
20330 },{"../Component":217,"rxjs/add/operator/combineLatest":50,"underscore":168,"virtual-dom":173}],241:[function(require,module,exports){
20331 /// <reference path="../../typings/index.d.ts" />
20332 "use strict";
20333 var __extends = (this && this.__extends) || function (d, b) {
20334     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20335     function __() { this.constructor = d; }
20336     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20337 };
20338 var THREE = require("three");
20339 var vd = require("virtual-dom");
20340 var Observable_1 = require("rxjs/Observable");
20341 require("rxjs/add/observable/merge");
20342 require("rxjs/add/operator/filter");
20343 require("rxjs/add/operator/map");
20344 require("rxjs/add/operator/withLatestFrom");
20345 var Component_1 = require("../Component");
20346 var Geo_1 = require("../Geo");
20347 /**
20348  * @class MouseComponent
20349  * @classdesc Component handling mouse and touch events for camera movement.
20350  */
20351 var MouseComponent = (function (_super) {
20352     __extends(MouseComponent, _super);
20353     function MouseComponent(name, container, navigator) {
20354         var _this = _super.call(this, name, container, navigator) || this;
20355         _this._basicDistanceThreshold = 1e-3;
20356         _this._basicRotationThreshold = 5e-2;
20357         _this._bounceCoeff = 1e-1;
20358         _this._forceCoeff = 2e-1;
20359         _this._viewportCoords = new Geo_1.ViewportCoords();
20360         _this._spatial = new Geo_1.Spatial();
20361         return _this;
20362     }
20363     MouseComponent.prototype._activate = function () {
20364         var _this = this;
20365         var draggingStarted$ = this._container.mouseService
20366             .filtered$(this._name, this._container.mouseService.mouseDragStart$)
20367             .map(function (event) {
20368             return true;
20369         });
20370         var draggingStopped$ = this._container.mouseService
20371             .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
20372             .map(function (event) {
20373             return false;
20374         });
20375         var dragging$ = Observable_1.Observable
20376             .merge(draggingStarted$, draggingStopped$)
20377             .startWith(false)
20378             .share();
20379         this._activeMouseSubscription = dragging$
20380             .subscribe(this._container.mouseService.activate$);
20381         var touchMovingStarted$ = this._container.touchService.singleTouchMoveStart$
20382             .map(function (event) {
20383             return true;
20384         });
20385         var touchMovingStopped$ = this._container.touchService.singleTouchMoveEnd$
20386             .map(function (event) {
20387             return false;
20388         });
20389         var touchMoving$ = Observable_1.Observable
20390             .merge(touchMovingStarted$, touchMovingStopped$)
20391             .startWith(false)
20392             .share();
20393         this._activeTouchSubscription = touchMoving$
20394             .subscribe(this._container.touchService.activate$);
20395         this._cursorSubscription = dragging$
20396             .map(function (dragging) {
20397             var className = dragging ? "MouseContainerGrabbing" : "MouseContainerGrab";
20398             var vNode = vd.h("div." + className, {}, []);
20399             return { name: _this._name, vnode: vNode };
20400         })
20401             .subscribe(this._container.domRenderer.render$);
20402         var mouseMovement$ = this._container.mouseService
20403             .filtered$(this._name, this._container.mouseService.mouseDrag$)
20404             .map(function (e) {
20405             return {
20406                 clientX: e.clientX,
20407                 clientY: e.clientY,
20408                 movementX: e.movementX,
20409                 movementY: e.movementY,
20410             };
20411         });
20412         var touchMovement$ = this._container.touchService.singleTouchMove$
20413             .map(function (touch) {
20414             return {
20415                 clientX: touch.clientX,
20416                 clientY: touch.clientY,
20417                 movementX: touch.movementX,
20418                 movementY: touch.movementY,
20419             };
20420         });
20421         this._movementSubscription = Observable_1.Observable
20422             .merge(mouseMovement$, touchMovement$)
20423             .withLatestFrom(this._navigator.stateService.currentState$, function (m, f) {
20424             return [m, f];
20425         })
20426             .filter(function (args) {
20427             var state = args[1].state;
20428             return state.currentNode.fullPano || state.nodesAhead < 1;
20429         })
20430             .map(function (args) {
20431             return args[0];
20432         })
20433             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$, function (m, r, t, c) {
20434             return [m, r, t, c];
20435         })
20436             .map(function (args) {
20437             var movement = args[0];
20438             var render = args[1];
20439             var transform = args[2];
20440             var camera = args[3].clone();
20441             var element = _this._container.element;
20442             var offsetWidth = element.offsetWidth;
20443             var offsetHeight = element.offsetHeight;
20444             var clientRect = element.getBoundingClientRect();
20445             var canvasX = movement.clientX - clientRect.left;
20446             var canvasY = movement.clientY - clientRect.top;
20447             var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, offsetWidth, offsetHeight, render.perspective)
20448                 .sub(render.perspective.position);
20449             var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movement.movementX, canvasY, offsetWidth, offsetHeight, render.perspective)
20450                 .sub(render.perspective.position);
20451             var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movement.movementY, offsetWidth, offsetHeight, render.perspective)
20452                 .sub(render.perspective.position);
20453             var deltaPhi = (movement.movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
20454             var deltaTheta = (movement.movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
20455             var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
20456             var upQuaternionInverse = upQuaternion.clone().inverse();
20457             var offset = new THREE.Vector3();
20458             offset.copy(camera.lookat).sub(camera.position);
20459             offset.applyQuaternion(upQuaternion);
20460             var length = offset.length();
20461             var phi = Math.atan2(offset.y, offset.x);
20462             phi += deltaPhi;
20463             var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
20464             theta += deltaTheta;
20465             theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
20466             offset.x = Math.sin(theta) * Math.cos(phi);
20467             offset.y = Math.sin(theta) * Math.sin(phi);
20468             offset.z = Math.cos(theta);
20469             offset.applyQuaternion(upQuaternionInverse);
20470             var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
20471             var basic = transform.projectBasic(lookat.toArray());
20472             var original = transform.projectBasic(camera.lookat.toArray());
20473             var x = basic[0] - original[0];
20474             var y = basic[1] - original[1];
20475             if (Math.abs(x) > 1) {
20476                 x = 0;
20477             }
20478             else if (x > 0.5) {
20479                 x = x - 1;
20480             }
20481             else if (x < -0.5) {
20482                 x = x + 1;
20483             }
20484             var rotationThreshold = _this._basicRotationThreshold;
20485             x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
20486             y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
20487             if (transform.fullPano) {
20488                 return [x, y];
20489             }
20490             var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element.offsetWidth, _this._container.element.offsetHeight, transform, render.perspective);
20491             var coeff = _this._forceCoeff;
20492             if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
20493                 y /= Math.max(1, coeff * pixelDistances[0]);
20494             }
20495             if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
20496                 x /= Math.max(1, coeff * pixelDistances[1]);
20497             }
20498             if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
20499                 y /= Math.max(1, coeff * pixelDistances[2]);
20500             }
20501             if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
20502                 x /= Math.max(1, coeff * pixelDistances[3]);
20503             }
20504             return [x, y];
20505         })
20506             .subscribe(function (basicRotation) {
20507             _this._navigator.stateService.rotateBasic(basicRotation);
20508         });
20509         this._mouseWheelSubscription = this._container.mouseService
20510             .filtered$(this._name, this._container.mouseService.mouseWheel$)
20511             .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
20512             return [w, f];
20513         })
20514             .filter(function (args) {
20515             var state = args[1].state;
20516             return state.currentNode.fullPano || state.nodesAhead < 1;
20517         })
20518             .map(function (args) {
20519             return args[0];
20520         })
20521             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
20522             return [w, r, t];
20523         })
20524             .subscribe(function (args) {
20525             var event = args[0];
20526             var render = args[1];
20527             var transform = args[2];
20528             var element = _this._container.element;
20529             var offsetWidth = element.offsetWidth;
20530             var offsetHeight = element.offsetHeight;
20531             var clientRect = element.getBoundingClientRect();
20532             var canvasX = event.clientX - clientRect.left;
20533             var canvasY = event.clientY - clientRect.top;
20534             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, offsetWidth, offsetHeight, render.perspective);
20535             var reference = transform.projectBasic(unprojected.toArray());
20536             var deltaY = event.deltaY;
20537             if (event.deltaMode === 1) {
20538                 deltaY = 40 * deltaY;
20539             }
20540             else if (event.deltaMode === 2) {
20541                 deltaY = 800 * deltaY;
20542             }
20543             var zoom = -3 * deltaY / offsetHeight;
20544             _this._navigator.stateService.zoomIn(zoom, reference);
20545         });
20546         this._pinchSubscription = this._container.touchService.pinch$
20547             .withLatestFrom(this._navigator.stateService.currentState$, function (p, f) {
20548             return [p, f];
20549         })
20550             .filter(function (args) {
20551             var state = args[1].state;
20552             return state.currentNode.fullPano || state.nodesAhead < 1;
20553         })
20554             .map(function (args) {
20555             return args[0];
20556         })
20557             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (p, r, t) {
20558             return [p, r, t];
20559         })
20560             .subscribe(function (args) {
20561             var pinch = args[0];
20562             var render = args[1];
20563             var transform = args[2];
20564             var element = _this._container.element;
20565             var offsetWidth = element.offsetWidth;
20566             var offsetHeight = element.offsetHeight;
20567             var clientRect = element.getBoundingClientRect();
20568             var unprojected = _this._viewportCoords.unprojectFromCanvas(pinch.centerClientX - clientRect.left, pinch.centerClientY - clientRect.top, offsetWidth, offsetHeight, render.perspective);
20569             var reference = transform.projectBasic(unprojected.toArray());
20570             var zoom = 3 * pinch.distanceChange / Math.min(offsetHeight, offsetWidth);
20571             _this._navigator.stateService.zoomIn(zoom, reference);
20572         });
20573         this._bounceSubscription = Observable_1.Observable
20574             .combineLatest(this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
20575             .map(function (noForce) {
20576             return noForce[0] || noForce[1] || noForce[2];
20577         })
20578             .distinctUntilChanged()
20579             .switchMap(function (noForce) {
20580             return noForce ?
20581                 Observable_1.Observable.empty() :
20582                 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
20583         })
20584             .subscribe(function (args) {
20585             var renderCamera = args[0];
20586             var perspectiveCamera = renderCamera.perspective;
20587             var transform = args[1];
20588             var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
20589             var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
20590             if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
20591                 return;
20592             }
20593             var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
20594             var basicX = 0;
20595             var basicY = 0;
20596             if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
20597                 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
20598                 return;
20599             }
20600             if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
20601                 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
20602                 return;
20603             }
20604             var coeff = _this._bounceCoeff;
20605             if (basicDistances[1] > 0 && basicDistances[3] === 0) {
20606                 basicX = -coeff * basicDistances[1];
20607             }
20608             else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
20609                 basicX = coeff * basicDistances[3];
20610             }
20611             else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
20612                 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
20613             }
20614             if (basicDistances[0] > 0 && basicDistances[2] === 0) {
20615                 basicY = coeff * basicDistances[0];
20616             }
20617             else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
20618                 basicY = -coeff * basicDistances[2];
20619             }
20620             else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
20621                 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
20622             }
20623             var rotationThreshold = _this._basicRotationThreshold;
20624             basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
20625             basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
20626             _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
20627         });
20628         this._container.mouseService.claimMouse(this._name, 0);
20629     };
20630     MouseComponent.prototype._deactivate = function () {
20631         this._container.mouseService.unclaimMouse(this._name);
20632         this._activeMouseSubscription.unsubscribe();
20633         this._activeTouchSubscription.unsubscribe();
20634         this._bounceSubscription.unsubscribe();
20635         this._cursorSubscription.unsubscribe();
20636         this._movementSubscription.unsubscribe();
20637         this._mouseWheelSubscription.unsubscribe();
20638         this._pinchSubscription.unsubscribe();
20639     };
20640     MouseComponent.prototype._getDefaultConfiguration = function () {
20641         return {};
20642     };
20643     return MouseComponent;
20644 }(Component_1.Component));
20645 /** @inheritdoc */
20646 MouseComponent.componentName = "mouse";
20647 exports.MouseComponent = MouseComponent;
20648 Component_1.ComponentService.register(MouseComponent);
20649 Object.defineProperty(exports, "__esModule", { value: true });
20650 exports.default = MouseComponent;
20651
20652 },{"../Component":217,"../Geo":220,"rxjs/Observable":28,"rxjs/add/observable/merge":43,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/withLatestFrom":80,"three":167,"virtual-dom":173}],242:[function(require,module,exports){
20653 /// <reference path="../../typings/index.d.ts" />
20654 "use strict";
20655 var __extends = (this && this.__extends) || function (d, b) {
20656     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20657     function __() { this.constructor = d; }
20658     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20659 };
20660 var vd = require("virtual-dom");
20661 var Observable_1 = require("rxjs/Observable");
20662 require("rxjs/add/operator/map");
20663 require("rxjs/add/operator/first");
20664 var Edge_1 = require("../Edge");
20665 var Component_1 = require("../Component");
20666 var NavigationComponent = (function (_super) {
20667     __extends(NavigationComponent, _super);
20668     function NavigationComponent(name, container, navigator) {
20669         var _this = _super.call(this, name, container, navigator) || this;
20670         _this._dirNames = {};
20671         _this._dirNames[Edge_1.EdgeDirection.StepForward] = "Forward";
20672         _this._dirNames[Edge_1.EdgeDirection.StepBackward] = "Backward";
20673         _this._dirNames[Edge_1.EdgeDirection.StepLeft] = "Left";
20674         _this._dirNames[Edge_1.EdgeDirection.StepRight] = "Right";
20675         _this._dirNames[Edge_1.EdgeDirection.TurnLeft] = "Turnleft";
20676         _this._dirNames[Edge_1.EdgeDirection.TurnRight] = "Turnright";
20677         _this._dirNames[Edge_1.EdgeDirection.TurnU] = "Turnaround";
20678         return _this;
20679     }
20680     NavigationComponent.prototype._activate = function () {
20681         var _this = this;
20682         this._renderSubscription = this._navigator.stateService.currentNode$
20683             .switchMap(function (node) {
20684             return node.pano ?
20685                 Observable_1.Observable.of([]) :
20686                 Observable_1.Observable.combineLatest(node.sequenceEdges$, node.spatialEdges$, function (seq, spa) {
20687                     return seq.edges.concat(spa.edges);
20688                 });
20689         })
20690             .map(function (edges) {
20691             var btns = [];
20692             for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
20693                 var edge = edges_1[_i];
20694                 var direction = edge.data.direction;
20695                 var name_1 = _this._dirNames[direction];
20696                 if (name_1 == null) {
20697                     continue;
20698                 }
20699                 btns.push(_this._createVNode(direction, name_1));
20700             }
20701             return { name: _this._name, vnode: vd.h("div.NavigationComponent", btns) };
20702         })
20703             .subscribe(this._container.domRenderer.render$);
20704     };
20705     NavigationComponent.prototype._deactivate = function () {
20706         this._renderSubscription.unsubscribe();
20707     };
20708     NavigationComponent.prototype._getDefaultConfiguration = function () {
20709         return {};
20710     };
20711     NavigationComponent.prototype._createVNode = function (direction, name) {
20712         var _this = this;
20713         return vd.h("span.Direction.Direction" + name, {
20714             onclick: function (ev) {
20715                 _this._navigator.moveDir$(direction)
20716                     .subscribe(function (node) { return; }, function (error) { console.error(error); });
20717             },
20718         }, []);
20719     };
20720     return NavigationComponent;
20721 }(Component_1.Component));
20722 NavigationComponent.componentName = "navigation";
20723 exports.NavigationComponent = NavigationComponent;
20724 Component_1.ComponentService.register(NavigationComponent);
20725 Object.defineProperty(exports, "__esModule", { value: true });
20726 exports.default = NavigationComponent;
20727
20728 },{"../Component":217,"../Edge":218,"rxjs/Observable":28,"rxjs/add/operator/first":60,"rxjs/add/operator/map":62,"virtual-dom":173}],243:[function(require,module,exports){
20729 /// <reference path="../../typings/index.d.ts" />
20730 "use strict";
20731 var __extends = (this && this.__extends) || function (d, b) {
20732     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20733     function __() { this.constructor = d; }
20734     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20735 };
20736 var _ = require("underscore");
20737 var vd = require("virtual-dom");
20738 var Observable_1 = require("rxjs/Observable");
20739 require("rxjs/add/observable/fromPromise");
20740 require("rxjs/add/observable/of");
20741 require("rxjs/add/operator/combineLatest");
20742 require("rxjs/add/operator/distinct");
20743 require("rxjs/add/operator/distinctUntilChanged");
20744 require("rxjs/add/operator/filter");
20745 require("rxjs/add/operator/map");
20746 require("rxjs/add/operator/mergeMap");
20747 require("rxjs/add/operator/pluck");
20748 require("rxjs/add/operator/scan");
20749 var Component_1 = require("../Component");
20750 var DescriptionState = (function () {
20751     function DescriptionState() {
20752     }
20753     return DescriptionState;
20754 }());
20755 var RouteState = (function () {
20756     function RouteState() {
20757     }
20758     return RouteState;
20759 }());
20760 var RouteTrack = (function () {
20761     function RouteTrack() {
20762         this.nodeInstructions = [];
20763         this.nodeInstructionsOrdered = [];
20764     }
20765     return RouteTrack;
20766 }());
20767 var RouteComponent = (function (_super) {
20768     __extends(RouteComponent, _super);
20769     function RouteComponent(name, container, navigator) {
20770         return _super.call(this, name, container, navigator) || this;
20771     }
20772     RouteComponent.prototype._activate = function () {
20773         var _this = this;
20774         var _slowedStream$;
20775         _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
20776             return (frame.id % 2) === 0;
20777         }).filter(function (frame) {
20778             return frame.state.nodesAhead < 15;
20779         }).distinctUntilChanged(undefined, function (frame) {
20780             return frame.state.lastNode.key;
20781         });
20782         var _routeTrack$;
20783         _routeTrack$ = this.configuration$.mergeMap(function (conf) {
20784             return Observable_1.Observable.from(conf.paths);
20785         }).distinct(function (p) {
20786             return p.sequenceKey;
20787         }).mergeMap(function (path) {
20788             return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
20789                 .map(function (sequenceByKey) {
20790                 return sequenceByKey[path.sequenceKey];
20791             });
20792         }).combineLatest(this.configuration$, function (sequence, conf) {
20793             var i = 0;
20794             var instructionPlaces = [];
20795             for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
20796                 var path = _a[_i];
20797                 if (path.sequenceKey === sequence.key) {
20798                     var nodeInstructions = [];
20799                     var saveKey = false;
20800                     for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
20801                         var key = _c[_b];
20802                         if (path.startKey === key) {
20803                             saveKey = true;
20804                         }
20805                         if (saveKey) {
20806                             var description = null;
20807                             for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
20808                                 var infoKey = _e[_d];
20809                                 if (infoKey.key === key) {
20810                                     description = infoKey.description;
20811                                 }
20812                             }
20813                             nodeInstructions.push({ description: description, key: key });
20814                         }
20815                         if (path.stopKey === key) {
20816                             saveKey = false;
20817                         }
20818                     }
20819                     instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
20820                 }
20821                 i++;
20822             }
20823             return instructionPlaces;
20824         }).scan(function (routeTrack, instructionPlaces) {
20825             for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
20826                 var instructionPlace = instructionPlaces_1[_i];
20827                 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
20828             }
20829             routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
20830             return routeTrack;
20831         }, new RouteTrack());
20832         this._disposable = _slowedStream$
20833             .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
20834             return { conf: conf, frame: frame, routeTrack: routeTrack };
20835         }).scan(function (routeState, rtAndFrame) {
20836             if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
20837                 routeState.routeTrack = rtAndFrame.routeTrack;
20838                 routeState.currentNode = rtAndFrame.frame.state.currentNode;
20839                 routeState.lastNode = rtAndFrame.frame.state.lastNode;
20840                 routeState.playing = true;
20841             }
20842             else {
20843                 _this._navigator.stateService.cutNodes();
20844                 routeState.playing = false;
20845             }
20846             return routeState;
20847         }, new RouteState())
20848             .filter(function (routeState) {
20849             return routeState.playing;
20850         }).filter(function (routeState) {
20851             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
20852                 var nodeInstruction = _a[_i];
20853                 if (!nodeInstruction) {
20854                     continue;
20855                 }
20856                 if (nodeInstruction.key === routeState.lastNode.key) {
20857                     return true;
20858                 }
20859             }
20860             return false;
20861         }).distinctUntilChanged(undefined, function (routeState) {
20862             return routeState.lastNode.key;
20863         }).mergeMap(function (routeState) {
20864             var i = 0;
20865             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
20866                 var nodeInstruction = _a[_i];
20867                 if (nodeInstruction.key === routeState.lastNode.key) {
20868                     break;
20869                 }
20870                 i++;
20871             }
20872             var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
20873             if (!nextInstruction) {
20874                 return Observable_1.Observable.of(null);
20875             }
20876             return _this._navigator.graphService.cacheNode$(nextInstruction.key);
20877         }).combineLatest(this.configuration$, function (node, conf) {
20878             return { conf: conf, node: node };
20879         }).filter(function (cAN) {
20880             return cAN.node !== null && cAN.conf.playing;
20881         }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
20882         this._disposableDescription = this._navigator.stateService.currentNode$
20883             .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
20884             if (conf.playing !== undefined && !conf.playing) {
20885                 return "quit";
20886             }
20887             var description = null;
20888             for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
20889                 var nodeInstruction = _a[_i];
20890                 if (nodeInstruction.key === node.key) {
20891                     description = nodeInstruction.description;
20892                     break;
20893                 }
20894             }
20895             return description;
20896         }).scan(function (descriptionState, description) {
20897             if (description !== descriptionState.description && description !== null) {
20898                 descriptionState.description = description;
20899                 descriptionState.showsLeft = 6;
20900             }
20901             else {
20902                 descriptionState.showsLeft--;
20903             }
20904             if (description === "quit") {
20905                 descriptionState.description = null;
20906             }
20907             return descriptionState;
20908         }, new DescriptionState()).map(function (descriptionState) {
20909             if (descriptionState.showsLeft > 0 && descriptionState.description) {
20910                 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
20911             }
20912             else {
20913                 return { name: _this._name, vnode: vd.h("div", []) };
20914             }
20915         }).subscribe(this._container.domRenderer.render$);
20916     };
20917     RouteComponent.prototype._deactivate = function () {
20918         this._disposable.unsubscribe();
20919         this._disposableDescription.unsubscribe();
20920     };
20921     RouteComponent.prototype._getDefaultConfiguration = function () {
20922         return {};
20923     };
20924     RouteComponent.prototype.play = function () {
20925         this.configure({ playing: true });
20926     };
20927     RouteComponent.prototype.stop = function () {
20928         this.configure({ playing: false });
20929     };
20930     RouteComponent.prototype._getRouteAnnotationNode = function (description) {
20931         return vd.h("div.RouteFrame", {}, [
20932             vd.h("p", { textContent: description }, []),
20933         ]);
20934     };
20935     return RouteComponent;
20936 }(Component_1.Component));
20937 RouteComponent.componentName = "route";
20938 exports.RouteComponent = RouteComponent;
20939 Component_1.ComponentService.register(RouteComponent);
20940 Object.defineProperty(exports, "__esModule", { value: true });
20941 exports.default = RouteComponent;
20942
20943 },{"../Component":217,"rxjs/Observable":28,"rxjs/add/observable/fromPromise":42,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":50,"rxjs/add/operator/distinct":54,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/mergeMap":65,"rxjs/add/operator/pluck":67,"rxjs/add/operator/scan":70,"underscore":168,"virtual-dom":173}],244:[function(require,module,exports){
20944 "use strict";
20945 var __extends = (this && this.__extends) || function (d, b) {
20946     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20947     function __() { this.constructor = d; }
20948     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20949 };
20950 var Observable_1 = require("rxjs/Observable");
20951 require("rxjs/add/operator/buffer");
20952 require("rxjs/add/operator/debounceTime");
20953 require("rxjs/add/operator/filter");
20954 require("rxjs/add/operator/map");
20955 require("rxjs/add/operator/scan");
20956 var Component_1 = require("../Component");
20957 var StatsComponent = (function (_super) {
20958     __extends(StatsComponent, _super);
20959     function StatsComponent(name, container, navigator) {
20960         return _super.call(this, name, container, navigator) || this;
20961     }
20962     StatsComponent.prototype._activate = function () {
20963         var _this = this;
20964         this._sequenceSubscription = this._navigator.stateService.currentNode$
20965             .scan(function (keys, node) {
20966             var sKey = node.sequenceKey;
20967             keys.report = [];
20968             if (!(sKey in keys.reported)) {
20969                 keys.report = [sKey];
20970                 keys.reported[sKey] = true;
20971             }
20972             return keys;
20973         }, { report: [], reported: {} })
20974             .filter(function (keys) {
20975             return keys.report.length > 0;
20976         })
20977             .mergeMap(function (keys) {
20978             return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
20979                 .catch(function (error, caught) {
20980                 console.error("Failed to report sequence stats (" + keys.report + ")", error);
20981                 return Observable_1.Observable.empty();
20982             });
20983         })
20984             .subscribe(function () { });
20985         this._imageSubscription = this._navigator.stateService.currentNode$
20986             .map(function (node) {
20987             return node.key;
20988         })
20989             .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
20990             .scan(function (keys, newKeys) {
20991             keys.report = [];
20992             for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
20993                 var key = newKeys_1[_i];
20994                 if (!(key in keys.reported)) {
20995                     keys.report.push(key);
20996                     keys.reported[key] = true;
20997                 }
20998             }
20999             return keys;
21000         }, { report: [], reported: {} })
21001             .filter(function (keys) {
21002             return keys.report.length > 0;
21003         })
21004             .mergeMap(function (keys) {
21005             return _this._navigator.apiV3.imageViewAdd$(keys.report)
21006                 .catch(function (error, caught) {
21007                 console.error("Failed to report image stats (" + keys.report + ")", error);
21008                 return Observable_1.Observable.empty();
21009             });
21010         })
21011             .subscribe(function () { });
21012     };
21013     StatsComponent.prototype._deactivate = function () {
21014         this._sequenceSubscription.unsubscribe();
21015         this._imageSubscription.unsubscribe();
21016     };
21017     StatsComponent.prototype._getDefaultConfiguration = function () {
21018         return {};
21019     };
21020     return StatsComponent;
21021 }(Component_1.Component));
21022 StatsComponent.componentName = "stats";
21023 exports.StatsComponent = StatsComponent;
21024 Component_1.ComponentService.register(StatsComponent);
21025 Object.defineProperty(exports, "__esModule", { value: true });
21026 exports.default = StatsComponent;
21027
21028 },{"../Component":217,"rxjs/Observable":28,"rxjs/add/operator/buffer":47,"rxjs/add/operator/debounceTime":52,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/scan":70}],245:[function(require,module,exports){
21029 /// <reference path="../../../typings/index.d.ts" />
21030 "use strict";
21031 var __extends = (this && this.__extends) || function (d, b) {
21032     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21033     function __() { this.constructor = d; }
21034     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21035 };
21036 var vd = require("virtual-dom");
21037 var Observable_1 = require("rxjs/Observable");
21038 var Subject_1 = require("rxjs/Subject");
21039 require("rxjs/add/observable/combineLatest");
21040 require("rxjs/add/operator/do");
21041 require("rxjs/add/operator/distinctUntilChanged");
21042 require("rxjs/add/operator/filter");
21043 require("rxjs/add/operator/map");
21044 require("rxjs/add/operator/share");
21045 var Component_1 = require("../../Component");
21046 /**
21047  * @class DirectionComponent
21048  * @classdesc Component showing navigation arrows for steps and turns.
21049  */
21050 var DirectionComponent = (function (_super) {
21051     __extends(DirectionComponent, _super);
21052     function DirectionComponent(name, container, navigator) {
21053         var _this = _super.call(this, name, container, navigator) || this;
21054         _this._renderer = new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
21055         _this._hoveredKeySubject$ = new Subject_1.Subject();
21056         _this._hoveredKey$ = _this._hoveredKeySubject$.share();
21057         return _this;
21058     }
21059     Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
21060         /**
21061          * Get hovered key observable.
21062          *
21063          * @description An observable emitting the key of the node for the direction
21064          * arrow that is being hovered. When the mouse leaves a direction arrow null
21065          * is emitted.
21066          *
21067          * @returns {Observable<string>}
21068          */
21069         get: function () {
21070             return this._hoveredKey$;
21071         },
21072         enumerable: true,
21073         configurable: true
21074     });
21075     /**
21076      * Set highlight key.
21077      *
21078      * @description The arrow pointing towards the node corresponding to the
21079      * highlight key will be highlighted.
21080      *
21081      * @param {string} highlightKey Key of node to be highlighted if existing
21082      * among arrows.
21083      */
21084     DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
21085         this.configure({ highlightKey: highlightKey });
21086     };
21087     /**
21088      * Set min width of container element.
21089      *
21090      * @description  Set min width of the non transformed container element holding
21091      * the navigation arrows. If the min width is larger than the max width the
21092      * min width value will be used.
21093      *
21094      * The container element is automatically resized when the resize
21095      * method on the Viewer class is called.
21096      *
21097      * @param {number} minWidth
21098      */
21099     DirectionComponent.prototype.setMinWidth = function (minWidth) {
21100         this.configure({ minWidth: minWidth });
21101     };
21102     /**
21103      * Set max width of container element.
21104      *
21105      * @description Set max width of the non transformed container element holding
21106      * the navigation arrows. If the min width is larger than the max width the
21107      * min width value will be used.
21108      *
21109      * The container element is automatically resized when the resize
21110      * method on the Viewer class is called.
21111      *
21112      * @param {number} minWidth
21113      */
21114     DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
21115         this.configure({ maxWidth: maxWidth });
21116     };
21117     /** @inheritdoc */
21118     DirectionComponent.prototype.resize = function () {
21119         this._renderer.resize(this._container.element);
21120     };
21121     DirectionComponent.prototype._activate = function () {
21122         var _this = this;
21123         this._configurationSubscription = this._configuration$
21124             .subscribe(function (configuration) {
21125             _this._renderer.setConfiguration(configuration);
21126         });
21127         this._nodeSubscription = this._navigator.stateService.currentNode$
21128             .do(function (node) {
21129             _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
21130             _this._renderer.setNode(node);
21131         })
21132             .withLatestFrom(this._configuration$)
21133             .switchMap(function (nc) {
21134             var node = nc[0];
21135             var configuration = nc[1];
21136             return node.spatialEdges$
21137                 .withLatestFrom(configuration.distinguishSequence ?
21138                 _this._navigator.graphService
21139                     .cacheSequence$(node.sequenceKey)
21140                     .catch(function (error, caught) {
21141                     console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
21142                     return Observable_1.Observable.empty();
21143                 }) :
21144                 Observable_1.Observable.of(null));
21145         })
21146             .subscribe(function (es) {
21147             _this._renderer.setEdges(es[0], es[1]);
21148         });
21149         this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
21150             .do(function (renderCamera) {
21151             _this._renderer.setRenderCamera(renderCamera);
21152         })
21153             .map(function (renderCamera) {
21154             return _this._renderer;
21155         })
21156             .filter(function (renderer) {
21157             return renderer.needsRender;
21158         })
21159             .map(function (renderer) {
21160             return { name: _this._name, vnode: renderer.render(_this._navigator) };
21161         })
21162             .subscribe(this._container.domRenderer.render$);
21163         this._hoveredKeySubscription = Observable_1.Observable
21164             .combineLatest([
21165             this._container.domRenderer.element$,
21166             this._container.renderService.renderCamera$,
21167             this._container.mouseService.mouseMove$.startWith(null),
21168             this._container.mouseService.mouseUp$.startWith(null),
21169         ], function (e, rc, mm, mu) {
21170             return e;
21171         })
21172             .map(function (element) {
21173             var elements = element.getElementsByClassName("DirectionsPerspective");
21174             for (var i = 0; i < elements.length; i++) {
21175                 var hovered = elements.item(i).querySelector(":hover");
21176                 if (hovered != null && hovered.hasAttribute("data-key")) {
21177                     return hovered.getAttribute("data-key");
21178                 }
21179             }
21180             return null;
21181         })
21182             .distinctUntilChanged()
21183             .subscribe(this._hoveredKeySubject$);
21184     };
21185     DirectionComponent.prototype._deactivate = function () {
21186         this._configurationSubscription.unsubscribe();
21187         this._nodeSubscription.unsubscribe();
21188         this._renderCameraSubscription.unsubscribe();
21189         this._hoveredKeySubscription.unsubscribe();
21190     };
21191     DirectionComponent.prototype._getDefaultConfiguration = function () {
21192         return {
21193             distinguishSequence: false,
21194             maxWidth: 460,
21195             minWidth: 260,
21196         };
21197     };
21198     return DirectionComponent;
21199 }(Component_1.Component));
21200 /** @inheritdoc */
21201 DirectionComponent.componentName = "direction";
21202 exports.DirectionComponent = DirectionComponent;
21203 Component_1.ComponentService.register(DirectionComponent);
21204 Object.defineProperty(exports, "__esModule", { value: true });
21205 exports.default = DirectionComponent;
21206
21207 },{"../../Component":217,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/do":56,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/share":71,"virtual-dom":173}],246:[function(require,module,exports){
21208 "use strict";
21209 var Geo_1 = require("../../Geo");
21210 /**
21211  * @class DirectionDOMCalculator
21212  * @classdesc Helper class for calculating DOM CSS properties.
21213  */
21214 var DirectionDOMCalculator = (function () {
21215     function DirectionDOMCalculator(configuration, element) {
21216         this._spatial = new Geo_1.Spatial();
21217         this._minThresholdWidth = 320;
21218         this._maxThresholdWidth = 1480;
21219         this._minThresholdHeight = 240;
21220         this._maxThresholdHeight = 820;
21221         this._configure(configuration);
21222         this._resize(element);
21223         this._reset();
21224     }
21225     Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
21226         get: function () {
21227             return this._minWidth;
21228         },
21229         enumerable: true,
21230         configurable: true
21231     });
21232     Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
21233         get: function () {
21234             return this._maxWidth;
21235         },
21236         enumerable: true,
21237         configurable: true
21238     });
21239     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
21240         get: function () {
21241             return this._containerWidth;
21242         },
21243         enumerable: true,
21244         configurable: true
21245     });
21246     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
21247         get: function () {
21248             return this._containerWidthCss;
21249         },
21250         enumerable: true,
21251         configurable: true
21252     });
21253     Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
21254         get: function () {
21255             return this._containerMarginCss;
21256         },
21257         enumerable: true,
21258         configurable: true
21259     });
21260     Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
21261         get: function () {
21262             return this._containerLeftCss;
21263         },
21264         enumerable: true,
21265         configurable: true
21266     });
21267     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
21268         get: function () {
21269             return this._containerHeight;
21270         },
21271         enumerable: true,
21272         configurable: true
21273     });
21274     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
21275         get: function () {
21276             return this._containerHeightCss;
21277         },
21278         enumerable: true,
21279         configurable: true
21280     });
21281     Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
21282         get: function () {
21283             return this._containerBottomCss;
21284         },
21285         enumerable: true,
21286         configurable: true
21287     });
21288     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
21289         get: function () {
21290             return this._stepCircleSize;
21291         },
21292         enumerable: true,
21293         configurable: true
21294     });
21295     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
21296         get: function () {
21297             return this._stepCircleSizeCss;
21298         },
21299         enumerable: true,
21300         configurable: true
21301     });
21302     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
21303         get: function () {
21304             return this._stepCircleMarginCss;
21305         },
21306         enumerable: true,
21307         configurable: true
21308     });
21309     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
21310         get: function () {
21311             return this._turnCircleSize;
21312         },
21313         enumerable: true,
21314         configurable: true
21315     });
21316     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
21317         get: function () {
21318             return this._turnCircleSizeCss;
21319         },
21320         enumerable: true,
21321         configurable: true
21322     });
21323     Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
21324         get: function () {
21325             return this._outerRadius;
21326         },
21327         enumerable: true,
21328         configurable: true
21329     });
21330     Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
21331         get: function () {
21332             return this._innerRadius;
21333         },
21334         enumerable: true,
21335         configurable: true
21336     });
21337     Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
21338         get: function () {
21339             return this._shadowOffset;
21340         },
21341         enumerable: true,
21342         configurable: true
21343     });
21344     /**
21345      * Configures the min and max width values.
21346      *
21347      * @param {IDirectionConfiguration} configuration Configuration
21348      * with min and max width values.
21349      */
21350     DirectionDOMCalculator.prototype.configure = function (configuration) {
21351         this._configure(configuration);
21352         this._reset();
21353     };
21354     /**
21355      * Resizes all properties according to the width and height
21356      * of the element.
21357      *
21358      * @param {HTMLElement} element The container element from which to extract
21359      * the width and height.
21360      */
21361     DirectionDOMCalculator.prototype.resize = function (element) {
21362         this._resize(element);
21363         this._reset();
21364     };
21365     /**
21366      * Calculates the coordinates on the unit circle for an angle.
21367      *
21368      * @param {number} angle Angle in radians.
21369      * @returns {Array<number>} The x and y coordinates on the unit circle.
21370      */
21371     DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
21372         return [Math.cos(angle), Math.sin(angle)];
21373     };
21374     /**
21375      * Calculates the coordinates on the unit circle for the
21376      * relative angle between the first and second angle.
21377      *
21378      * @param {number} first Angle in radians.
21379      * @param {number} second Angle in radians.
21380      * @returns {Array<number>} The x and y coordinates on the unit circle
21381      * for the relative angle between the first and second angle.
21382      */
21383     DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
21384         var relativeAngle = this._spatial.wrapAngle(first - second);
21385         return this.angleToCoordinates(relativeAngle);
21386     };
21387     DirectionDOMCalculator.prototype._configure = function (configuration) {
21388         this._minWidth = configuration.minWidth;
21389         this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
21390     };
21391     DirectionDOMCalculator.prototype._resize = function (element) {
21392         this._elementWidth = element.offsetWidth;
21393         this._elementHeight = element.offsetHeight;
21394     };
21395     DirectionDOMCalculator.prototype._reset = function () {
21396         this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
21397         this._containerHeight = this._getContainerHeight(this.containerWidth);
21398         this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
21399         this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
21400         this._outerRadius = this._getOuterRadius(this._containerHeight);
21401         this._innerRadius = this._getInnerRadius(this._containerHeight);
21402         this._shadowOffset = 3;
21403         this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
21404         this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
21405         this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
21406         this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
21407         this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
21408         this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
21409         this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
21410         this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
21411     };
21412     DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
21413         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
21414         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
21415         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
21416         coeff = 0.04 * Math.round(25 * coeff);
21417         return this._minWidth + coeff * (this._maxWidth - this._minWidth);
21418     };
21419     DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
21420         return 0.77 * containerWidth;
21421     };
21422     DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
21423         return 0.34 * containerHeight;
21424     };
21425     DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
21426         return 0.3 * containerHeight;
21427     };
21428     DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
21429         return 0.31 * containerHeight;
21430     };
21431     DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
21432         return 0.125 * containerHeight;
21433     };
21434     DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
21435         return value + "px";
21436     };
21437     DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
21438         return value > minWidth ? value : minWidth;
21439     };
21440     return DirectionDOMCalculator;
21441 }());
21442 exports.DirectionDOMCalculator = DirectionDOMCalculator;
21443 Object.defineProperty(exports, "__esModule", { value: true });
21444 exports.default = DirectionDOMCalculator;
21445
21446 },{"../../Geo":220}],247:[function(require,module,exports){
21447 /// <reference path="../../../typings/index.d.ts" />
21448 "use strict";
21449 var vd = require("virtual-dom");
21450 var Component_1 = require("../../Component");
21451 var Edge_1 = require("../../Edge");
21452 var Geo_1 = require("../../Geo");
21453 /**
21454  * @class DirectionDOMRenderer
21455  * @classdesc DOM renderer for direction arrows.
21456  */
21457 var DirectionDOMRenderer = (function () {
21458     function DirectionDOMRenderer(configuration, element) {
21459         this._isEdge = false;
21460         this._spatial = new Geo_1.Spatial();
21461         this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
21462         this._node = null;
21463         this._rotation = { phi: 0, theta: 0 };
21464         this._epsilon = 0.5 * Math.PI / 180;
21465         this._highlightKey = null;
21466         this._distinguishSequence = false;
21467         this._needsRender = false;
21468         this._stepEdges = [];
21469         this._turnEdges = [];
21470         this._panoEdges = [];
21471         this._sequenceEdgeKeys = [];
21472         this._stepDirections = [
21473             Edge_1.EdgeDirection.StepForward,
21474             Edge_1.EdgeDirection.StepBackward,
21475             Edge_1.EdgeDirection.StepLeft,
21476             Edge_1.EdgeDirection.StepRight,
21477         ];
21478         this._turnDirections = [
21479             Edge_1.EdgeDirection.TurnLeft,
21480             Edge_1.EdgeDirection.TurnRight,
21481             Edge_1.EdgeDirection.TurnU,
21482         ];
21483         this._turnNames = {};
21484         this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
21485         this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
21486         this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
21487         // detects IE 8-11, then Edge 20+.
21488         var isIE = !!document.documentMode;
21489         this._isEdge = !isIE && !!window.StyleMedia;
21490     }
21491     Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
21492         /**
21493          * Get needs render.
21494          *
21495          * @returns {boolean} Value indicating whether render should be called.
21496          */
21497         get: function () {
21498             return this._needsRender;
21499         },
21500         enumerable: true,
21501         configurable: true
21502     });
21503     /**
21504      * Renders virtual DOM elements.
21505      *
21506      * @description Calling render resets the needs render property.
21507      */
21508     DirectionDOMRenderer.prototype.render = function (navigator) {
21509         this._needsRender = false;
21510         var rotation = this._rotation;
21511         var steps = [];
21512         var turns = [];
21513         if (this._node.pano) {
21514             steps = steps.concat(this._createPanoArrows(navigator, rotation));
21515         }
21516         else {
21517             steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
21518             steps = steps.concat(this._createStepArrows(navigator, rotation));
21519             turns = turns.concat(this._createTurnArrows(navigator));
21520         }
21521         return this._getContainer(steps, turns, rotation);
21522     };
21523     DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
21524         this._setEdges(edgeStatus, sequence);
21525         this._setNeedsRender();
21526     };
21527     /**
21528      * Set node for which to show edges.
21529      *
21530      * @param {Node} node
21531      */
21532     DirectionDOMRenderer.prototype.setNode = function (node) {
21533         this._node = node;
21534         this._clearEdges();
21535         this._setNeedsRender();
21536     };
21537     /**
21538      * Set the render camera to use for calculating rotations.
21539      *
21540      * @param {RenderCamera} renderCamera
21541      */
21542     DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
21543         var rotation = renderCamera.rotation;
21544         if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
21545             return;
21546         }
21547         this._rotation = rotation;
21548         this._setNeedsRender();
21549     };
21550     /**
21551      * Set configuration values.
21552      *
21553      * @param {IDirectionConfiguration} configuration
21554      */
21555     DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
21556         var needsRender = false;
21557         if (this._highlightKey !== configuration.highlightKey ||
21558             this._distinguishSequence !== configuration.distinguishSequence) {
21559             this._highlightKey = configuration.highlightKey;
21560             this._distinguishSequence = configuration.distinguishSequence;
21561             needsRender = true;
21562         }
21563         if (this._calculator.minWidth !== configuration.minWidth ||
21564             this._calculator.maxWidth !== configuration.maxWidth) {
21565             this._calculator.configure(configuration);
21566             needsRender = true;
21567         }
21568         if (needsRender) {
21569             this._setNeedsRender();
21570         }
21571     };
21572     /**
21573      * Detect the element's width and height and resize
21574      * elements accordingly.
21575      *
21576      * @param {HTMLElement} element Viewer container element.
21577      */
21578     DirectionDOMRenderer.prototype.resize = function (element) {
21579         this._calculator.resize(element);
21580         this._setNeedsRender();
21581     };
21582     DirectionDOMRenderer.prototype._setNeedsRender = function () {
21583         if (this._node != null) {
21584             this._needsRender = true;
21585         }
21586     };
21587     DirectionDOMRenderer.prototype._clearEdges = function () {
21588         this._stepEdges = [];
21589         this._turnEdges = [];
21590         this._panoEdges = [];
21591         this._sequenceEdgeKeys = [];
21592     };
21593     DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
21594         this._stepEdges = [];
21595         this._turnEdges = [];
21596         this._panoEdges = [];
21597         this._sequenceEdgeKeys = [];
21598         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
21599             var edge = _a[_i];
21600             var direction = edge.data.direction;
21601             if (this._stepDirections.indexOf(direction) > -1) {
21602                 this._stepEdges.push(edge);
21603                 continue;
21604             }
21605             if (this._turnDirections.indexOf(direction) > -1) {
21606                 this._turnEdges.push(edge);
21607                 continue;
21608             }
21609             if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
21610                 this._panoEdges.push(edge);
21611             }
21612         }
21613         if (this._distinguishSequence && sequence != null) {
21614             var edges = this._panoEdges
21615                 .concat(this._stepEdges)
21616                 .concat(this._turnEdges);
21617             for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
21618                 var edge = edges_1[_b];
21619                 var edgeKey = edge.to;
21620                 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
21621                     var sequenceKey = _d[_c];
21622                     if (sequenceKey === edgeKey) {
21623                         this._sequenceEdgeKeys.push(edgeKey);
21624                         break;
21625                     }
21626                 }
21627             }
21628         }
21629     };
21630     DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
21631         var arrows = [];
21632         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
21633             var panoEdge = _a[_i];
21634             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
21635         }
21636         for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
21637             var stepEdge = _c[_b];
21638             arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
21639         }
21640         return arrows;
21641     };
21642     DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
21643         var threshold = Math.PI / 8;
21644         var relativePhi = rotation.phi;
21645         switch (direction) {
21646             case Edge_1.EdgeDirection.StepBackward:
21647                 relativePhi = rotation.phi - Math.PI;
21648                 break;
21649             case Edge_1.EdgeDirection.StepLeft:
21650                 relativePhi = rotation.phi + Math.PI / 2;
21651                 break;
21652             case Edge_1.EdgeDirection.StepRight:
21653                 relativePhi = rotation.phi - Math.PI / 2;
21654                 break;
21655             default:
21656                 break;
21657         }
21658         if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
21659             return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
21660         }
21661         return this._createVNodeDisabled(key, azimuth, rotation);
21662     };
21663     DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
21664         var arrows = [];
21665         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
21666             var panoEdge = _a[_i];
21667             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
21668         }
21669         return arrows;
21670     };
21671     DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
21672         var arrows = [];
21673         for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
21674             var stepEdge = _a[_i];
21675             arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
21676         }
21677         return arrows;
21678     };
21679     DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
21680         var turns = [];
21681         for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
21682             var turnEdge = _a[_i];
21683             var direction = turnEdge.data.direction;
21684             var name_1 = this._turnNames[direction];
21685             turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
21686         }
21687         return turns;
21688     };
21689     DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
21690         var onClick = function (e) {
21691             navigator.moveToKey$(key)
21692                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
21693         };
21694         return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
21695     };
21696     DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
21697         var onClick = function (e) {
21698             navigator.moveDir$(direction)
21699                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
21700         };
21701         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
21702     };
21703     DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
21704         var onClick = function (e) {
21705             navigator.moveDir$(direction)
21706                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
21707         };
21708         var style = {
21709             height: this._calculator.turnCircleSizeCss,
21710             transform: "rotate(0)",
21711             width: this._calculator.turnCircleSizeCss,
21712         };
21713         switch (direction) {
21714             case Edge_1.EdgeDirection.TurnLeft:
21715                 style.left = "5px";
21716                 style.top = "5px";
21717                 break;
21718             case Edge_1.EdgeDirection.TurnRight:
21719                 style.right = "5px";
21720                 style.top = "5px";
21721                 break;
21722             case Edge_1.EdgeDirection.TurnU:
21723                 style.left = "5px";
21724                 style.bottom = "5px";
21725                 break;
21726             default:
21727                 break;
21728         }
21729         var circleProperties = {
21730             attributes: {
21731                 "data-key": key,
21732             },
21733             onclick: onClick,
21734             style: style,
21735         };
21736         var circleClassName = "TurnCircle";
21737         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
21738             circleClassName += "Sequence";
21739         }
21740         if (this._highlightKey === key) {
21741             circleClassName += "Highlight";
21742         }
21743         var turn = vd.h("div." + className, {}, []);
21744         return vd.h("div." + circleClassName, circleProperties, [turn]);
21745     };
21746     DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
21747         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
21748     };
21749     DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
21750         var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
21751         // rotate 90 degrees clockwise and flip over X-axis
21752         var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
21753         var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
21754         var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
21755         var shadowOffset = this._calculator.shadowOffset;
21756         var shadowTranslationX = -shadowOffset * shadowTranslation[1];
21757         var shadowTranslationY = shadowOffset * shadowTranslation[0];
21758         var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
21759         var properties = {
21760             style: {
21761                 "-webkit-filter": filter,
21762                 filter: filter,
21763             },
21764         };
21765         var chevron = vd.h("div." + className, properties, []);
21766         var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
21767         var circleTransform = shiftVertically ?
21768             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
21769             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
21770         var circleProperties = {
21771             attributes: { "data-key": key },
21772             onclick: onClick,
21773             style: {
21774                 height: this._calculator.stepCircleSizeCss,
21775                 marginLeft: this._calculator.stepCircleMarginCss,
21776                 marginTop: this._calculator.stepCircleMarginCss,
21777                 transform: circleTransform,
21778                 width: this._calculator.stepCircleSizeCss,
21779             },
21780         };
21781         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
21782             circleClassName += "Sequence";
21783         }
21784         if (this._highlightKey === key) {
21785             circleClassName += "Highlight";
21786         }
21787         return vd.h("div." + circleClassName, circleProperties, [chevron]);
21788     };
21789     DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
21790         // edge does not handle hover on perspective transforms.
21791         var transform = this._isEdge ?
21792             "rotateX(60deg)" :
21793             "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
21794         var perspectiveStyle = {
21795             bottom: this._calculator.containerBottomCss,
21796             height: this._calculator.containerHeightCss,
21797             left: this._calculator.containerLeftCss,
21798             marginLeft: this._calculator.containerMarginCss,
21799             transform: transform,
21800             width: this._calculator.containerWidthCss,
21801         };
21802         return vd.h("div.DirectionsPerspective", { style: perspectiveStyle }, turns.concat(steps));
21803     };
21804     return DirectionDOMRenderer;
21805 }());
21806 exports.DirectionDOMRenderer = DirectionDOMRenderer;
21807 Object.defineProperty(exports, "__esModule", { value: true });
21808 exports.default = DirectionDOMRenderer;
21809
21810 },{"../../Component":217,"../../Edge":218,"../../Geo":220,"virtual-dom":173}],248:[function(require,module,exports){
21811 "use strict";
21812 var __extends = (this && this.__extends) || function (d, b) {
21813     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21814     function __() { this.constructor = d; }
21815     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21816 };
21817 var Observable_1 = require("rxjs/Observable");
21818 var Subject_1 = require("rxjs/Subject");
21819 require("rxjs/add/operator/catch");
21820 require("rxjs/add/operator/combineLatest");
21821 require("rxjs/add/operator/debounceTime");
21822 require("rxjs/add/operator/distinctUntilChanged");
21823 require("rxjs/add/operator/filter");
21824 require("rxjs/add/operator/map");
21825 require("rxjs/add/operator/pairwise");
21826 require("rxjs/add/operator/publish");
21827 require("rxjs/add/operator/publishReplay");
21828 require("rxjs/add/operator/scan");
21829 require("rxjs/add/operator/skipWhile");
21830 require("rxjs/add/operator/startWith");
21831 require("rxjs/add/operator/switchMap");
21832 require("rxjs/add/operator/takeUntil");
21833 require("rxjs/add/operator/withLatestFrom");
21834 var Component_1 = require("../../Component");
21835 var Render_1 = require("../../Render");
21836 var Tiles_1 = require("../../Tiles");
21837 var Utils_1 = require("../../Utils");
21838 var ImagePlaneComponent = (function (_super) {
21839     __extends(ImagePlaneComponent, _super);
21840     function ImagePlaneComponent(name, container, navigator) {
21841         var _this = _super.call(this, name, container, navigator) || this;
21842         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
21843         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
21844         _this._rendererOperation$ = new Subject_1.Subject();
21845         _this._rendererCreator$ = new Subject_1.Subject();
21846         _this._rendererDisposer$ = new Subject_1.Subject();
21847         _this._renderer$ = _this._rendererOperation$
21848             .scan(function (renderer, operation) {
21849             return operation(renderer);
21850         }, null)
21851             .filter(function (renderer) {
21852             return renderer != null;
21853         })
21854             .distinctUntilChanged(undefined, function (renderer) {
21855             return renderer.frameId;
21856         });
21857         _this._rendererCreator$
21858             .map(function () {
21859             return function (renderer) {
21860                 if (renderer != null) {
21861                     throw new Error("Multiple image plane states can not be created at the same time");
21862                 }
21863                 return new Component_1.ImagePlaneGLRenderer();
21864             };
21865         })
21866             .subscribe(_this._rendererOperation$);
21867         _this._rendererDisposer$
21868             .map(function () {
21869             return function (renderer) {
21870                 renderer.dispose();
21871                 return null;
21872             };
21873         })
21874             .subscribe(_this._rendererOperation$);
21875         return _this;
21876     }
21877     ImagePlaneComponent.prototype._activate = function () {
21878         var _this = this;
21879         this._rendererSubscription = this._renderer$
21880             .map(function (renderer) {
21881             var renderHash = {
21882                 name: _this._name,
21883                 render: {
21884                     frameId: renderer.frameId,
21885                     needsRender: renderer.needsRender,
21886                     render: renderer.render.bind(renderer),
21887                     stage: Render_1.GLRenderStage.Background,
21888                 },
21889             };
21890             renderer.clearNeedsRender();
21891             return renderHash;
21892         })
21893             .subscribe(this._container.glRenderer.render$);
21894         this._rendererCreator$.next(null);
21895         this._stateSubscription = this._navigator.stateService.currentState$
21896             .map(function (frame) {
21897             return function (renderer) {
21898                 renderer.updateFrame(frame);
21899                 return renderer;
21900             };
21901         })
21902             .subscribe(this._rendererOperation$);
21903         var textureProvider$ = this._navigator.stateService.currentState$
21904             .distinctUntilChanged(undefined, function (frame) {
21905             return frame.state.currentNode.key;
21906         })
21907             .combineLatest(this._configuration$)
21908             .filter(function (args) {
21909             return args[1].imageTiling === true;
21910         })
21911             .map(function (args) {
21912             return args[0];
21913         })
21914             .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
21915             .map(function (args) {
21916             var state = args[0].state;
21917             var renderer = args[1];
21918             var viewportSize = args[2];
21919             var currentNode = state.currentNode;
21920             var currentTransform = state.currentTransform;
21921             var tileSize = Math.max(viewportSize.width, viewportSize.height) > 1024 ? 1024 : 512;
21922             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
21923         })
21924             .publishReplay(1)
21925             .refCount();
21926         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
21927         this._setTextureProviderSubscription = textureProvider$
21928             .map(function (provider) {
21929             return function (renderer) {
21930                 renderer.setTextureProvider(provider.key, provider);
21931                 return renderer;
21932             };
21933         })
21934             .subscribe(this._rendererOperation$);
21935         this._abortTextureProviderSubscription = textureProvider$
21936             .pairwise()
21937             .subscribe(function (pair) {
21938             var previous = pair[0];
21939             previous.abort();
21940         });
21941         var roiTrigger$ = this._container.renderService.renderCameraFrame$
21942             .map(function (renderCamera) {
21943             return [
21944                 renderCamera.camera.position.clone(),
21945                 renderCamera.camera.lookat.clone(),
21946                 renderCamera.zoom.valueOf()
21947             ];
21948         })
21949             .pairwise()
21950             .skipWhile(function (pls) {
21951             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
21952         })
21953             .map(function (pls) {
21954             var samePosition = pls[0][0].equals(pls[1][0]);
21955             var sameLookat = pls[0][1].equals(pls[1][1]);
21956             var sameZoom = pls[0][2] === pls[1][2];
21957             return samePosition && sameLookat && sameZoom;
21958         })
21959             .distinctUntilChanged()
21960             .filter(function (stalled) {
21961             return stalled;
21962         })
21963             .switchMap(function (stalled) {
21964             return _this._container.renderService.renderCameraFrame$
21965                 .first();
21966         })
21967             .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
21968         this._setRegionOfInterestSubscription = textureProvider$
21969             .switchMap(function (provider) {
21970             return roiTrigger$
21971                 .map(function (args) {
21972                 return [
21973                     _this._roiCalculator.computeRegionOfInterest(args[0], args[1], args[2]),
21974                     provider,
21975                 ];
21976             });
21977         })
21978             .filter(function (args) {
21979             return !args[1].disposed;
21980         })
21981             .subscribe(function (args) {
21982             var roi = args[0];
21983             var provider = args[1];
21984             provider.setRegionOfInterest(roi);
21985         });
21986         var hasTexture$ = textureProvider$
21987             .switchMap(function (provider) {
21988             return provider.hasTexture$;
21989         })
21990             .startWith(false)
21991             .publishReplay(1)
21992             .refCount();
21993         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
21994         var nodeImage$ = this._navigator.stateService.currentNode$
21995             .debounceTime(1000)
21996             .withLatestFrom(hasTexture$)
21997             .filter(function (args) {
21998             return !args[1];
21999         })
22000             .map(function (args) {
22001             return args[0];
22002         })
22003             .filter(function (node) {
22004             return node.pano ?
22005                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
22006                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
22007         })
22008             .switchMap(function (node) {
22009             var baseImageSize = node.pano ?
22010                 Utils_1.Settings.basePanoramaSize :
22011                 Utils_1.Settings.baseImageSize;
22012             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
22013                 return Observable_1.Observable.empty();
22014             }
22015             var image$ = node
22016                 .cacheImage$(Utils_1.Settings.maxImageSize)
22017                 .map(function (n) {
22018                 return [n.image, n];
22019             });
22020             return image$
22021                 .takeUntil(hasTexture$
22022                 .filter(function (hasTexture) {
22023                 return hasTexture;
22024             }))
22025                 .catch(function (error, caught) {
22026                 console.error("Failed to fetch high res image (" + node.key + ")", error);
22027                 return Observable_1.Observable.empty();
22028             });
22029         })
22030             .publish()
22031             .refCount();
22032         this._updateBackgroundSubscription = nodeImage$
22033             .withLatestFrom(textureProvider$)
22034             .subscribe(function (args) {
22035             if (args[0][1].key !== args[1].key ||
22036                 args[1].disposed) {
22037                 return;
22038             }
22039             args[1].updateBackground(args[0][0]);
22040         });
22041         this._updateTextureImageSubscription = nodeImage$
22042             .map(function (imn) {
22043             return function (renderer) {
22044                 renderer.updateTextureImage(imn[0], imn[1]);
22045                 return renderer;
22046             };
22047         })
22048             .subscribe(this._rendererOperation$);
22049     };
22050     ImagePlaneComponent.prototype._deactivate = function () {
22051         this._rendererDisposer$.next(null);
22052         this._abortTextureProviderSubscription.unsubscribe();
22053         this._hasTextureSubscription.unsubscribe();
22054         this._rendererSubscription.unsubscribe();
22055         this._setRegionOfInterestSubscription.unsubscribe();
22056         this._setTextureProviderSubscription.unsubscribe();
22057         this._stateSubscription.unsubscribe();
22058         this._textureProviderSubscription.unsubscribe();
22059         this._updateBackgroundSubscription.unsubscribe();
22060         this._updateTextureImageSubscription.unsubscribe();
22061     };
22062     ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
22063         return { imageTiling: false };
22064     };
22065     return ImagePlaneComponent;
22066 }(Component_1.Component));
22067 ImagePlaneComponent.componentName = "imagePlane";
22068 exports.ImagePlaneComponent = ImagePlaneComponent;
22069 Component_1.ComponentService.register(ImagePlaneComponent);
22070 Object.defineProperty(exports, "__esModule", { value: true });
22071 exports.default = ImagePlaneComponent;
22072
22073 },{"../../Component":217,"../../Render":223,"../../Tiles":225,"../../Utils":226,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/catch":49,"rxjs/add/operator/combineLatest":50,"rxjs/add/operator/debounceTime":52,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/pairwise":66,"rxjs/add/operator/publish":68,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/skipWhile":74,"rxjs/add/operator/startWith":75,"rxjs/add/operator/switchMap":76,"rxjs/add/operator/takeUntil":78,"rxjs/add/operator/withLatestFrom":80}],249:[function(require,module,exports){
22074 /// <reference path="../../../typings/index.d.ts" />
22075 "use strict";
22076 var THREE = require("three");
22077 var Component_1 = require("../../Component");
22078 var ImagePlaneFactory = (function () {
22079     function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
22080         this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
22081         this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
22082     }
22083     ImagePlaneFactory.prototype.createMesh = function (node, transform) {
22084         var mesh = node.pano ?
22085             this._createImageSphere(node, transform) :
22086             this._createImagePlane(node, transform);
22087         return mesh;
22088     };
22089     ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
22090         var texture = this._createTexture(node.image);
22091         var materialParameters = this._createSphereMaterialParameters(transform, texture);
22092         var material = new THREE.ShaderMaterial(materialParameters);
22093         var mesh = this._useMesh(transform, node) ?
22094             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
22095             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
22096         return mesh;
22097     };
22098     ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
22099         var texture = this._createTexture(node.image);
22100         var materialParameters = this._createPlaneMaterialParameters(transform, texture);
22101         var material = new THREE.ShaderMaterial(materialParameters);
22102         var geometry = this._useMesh(transform, node) ?
22103             this._getImagePlaneGeo(transform, node) :
22104             this._getFlatImagePlaneGeo(transform);
22105         return new THREE.Mesh(geometry, material);
22106     };
22107     ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
22108         var gpano = transform.gpano;
22109         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
22110         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
22111         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
22112         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
22113         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
22114         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
22115         var materialParameters = {
22116             depthWrite: false,
22117             fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
22118             side: THREE.DoubleSide,
22119             transparent: true,
22120             uniforms: {
22121                 opacity: {
22122                     type: "f",
22123                     value: 1,
22124                 },
22125                 phiLength: {
22126                     type: "f",
22127                     value: phiLength,
22128                 },
22129                 phiShift: {
22130                     type: "f",
22131                     value: phiShift,
22132                 },
22133                 projectorMat: {
22134                     type: "m4",
22135                     value: transform.rt,
22136                 },
22137                 projectorTex: {
22138                     type: "t",
22139                     value: texture,
22140                 },
22141                 thetaLength: {
22142                     type: "f",
22143                     value: thetaLength,
22144                 },
22145                 thetaShift: {
22146                     type: "f",
22147                     value: thetaShift,
22148                 },
22149             },
22150             vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
22151         };
22152         return materialParameters;
22153     };
22154     ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
22155         var materialParameters = {
22156             depthWrite: false,
22157             fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
22158             side: THREE.DoubleSide,
22159             transparent: true,
22160             uniforms: {
22161                 bbox: {
22162                     type: "v4",
22163                     value: new THREE.Vector4(0, 0, 1, 1),
22164                 },
22165                 opacity: {
22166                     type: "f",
22167                     value: 1,
22168                 },
22169                 projectorMat: {
22170                     type: "m4",
22171                     value: transform.projectorMatrix(),
22172                 },
22173                 projectorTex: {
22174                     type: "t",
22175                     value: texture,
22176                 },
22177             },
22178             vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
22179         };
22180         return materialParameters;
22181     };
22182     ImagePlaneFactory.prototype._createTexture = function (image) {
22183         var texture = new THREE.Texture(image);
22184         texture.minFilter = THREE.LinearFilter;
22185         texture.needsUpdate = true;
22186         return texture;
22187     };
22188     ImagePlaneFactory.prototype._useMesh = function (transform, node) {
22189         return node.mesh.vertices.length &&
22190             transform.scale > 1e-2 &&
22191             transform.scale < 50;
22192     };
22193     ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
22194         var t = new THREE.Matrix4().getInverse(transform.srt);
22195         // push everything at least 5 meters in front of the camera
22196         var minZ = 5.0 * transform.scale;
22197         var maxZ = this._imageSphereRadius * transform.scale;
22198         var vertices = node.mesh.vertices;
22199         var numVertices = vertices.length / 3;
22200         var positions = new Float32Array(vertices.length);
22201         for (var i = 0; i < numVertices; ++i) {
22202             var index = 3 * i;
22203             var x = vertices[index + 0];
22204             var y = vertices[index + 1];
22205             var z = vertices[index + 2];
22206             var l = Math.sqrt(x * x + y * y + z * z);
22207             var boundedL = Math.max(minZ, Math.min(l, maxZ));
22208             var factor = boundedL / l;
22209             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
22210             p.applyMatrix4(t);
22211             positions[index + 0] = p.x;
22212             positions[index + 1] = p.y;
22213             positions[index + 2] = p.z;
22214         }
22215         var faces = node.mesh.faces;
22216         var indices = new Uint16Array(faces.length);
22217         for (var i = 0; i < faces.length; ++i) {
22218             indices[i] = faces[i];
22219         }
22220         var geometry = new THREE.BufferGeometry();
22221         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22222         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22223         return geometry;
22224     };
22225     ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
22226         var t = new THREE.Matrix4().getInverse(transform.srt);
22227         // push everything at least 5 meters in front of the camera
22228         var minZ = 5.0 * transform.scale;
22229         var maxZ = this._imagePlaneDepth * transform.scale;
22230         var vertices = node.mesh.vertices;
22231         var numVertices = vertices.length / 3;
22232         var positions = new Float32Array(vertices.length);
22233         for (var i = 0; i < numVertices; ++i) {
22234             var index = 3 * i;
22235             var x = vertices[index + 0];
22236             var y = vertices[index + 1];
22237             var z = vertices[index + 2];
22238             var boundedZ = Math.max(minZ, Math.min(z, maxZ));
22239             var factor = boundedZ / z;
22240             var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
22241             p.applyMatrix4(t);
22242             positions[index + 0] = p.x;
22243             positions[index + 1] = p.y;
22244             positions[index + 2] = p.z;
22245         }
22246         var faces = node.mesh.faces;
22247         var indices = new Uint16Array(faces.length);
22248         for (var i = 0; i < faces.length; ++i) {
22249             indices[i] = faces[i];
22250         }
22251         var geometry = new THREE.BufferGeometry();
22252         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22253         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22254         return geometry;
22255     };
22256     ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
22257         var gpano = transform.gpano;
22258         var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
22259         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
22260         var thetaStart = Math.PI *
22261             (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
22262             gpano.FullPanoHeightPixels;
22263         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
22264         var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
22265         geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
22266         return geometry;
22267     };
22268     ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
22269         var width = transform.width;
22270         var height = transform.height;
22271         var size = Math.max(width, height);
22272         var dx = width / 2.0 / size;
22273         var dy = height / 2.0 / size;
22274         var vertices = [];
22275         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
22276         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
22277         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
22278         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
22279         var positions = new Float32Array(12);
22280         for (var i = 0; i < vertices.length; i++) {
22281             var index = 3 * i;
22282             positions[index + 0] = vertices[i][0];
22283             positions[index + 1] = vertices[i][1];
22284             positions[index + 2] = vertices[i][2];
22285         }
22286         var indices = new Uint16Array(6);
22287         indices[0] = 0;
22288         indices[1] = 1;
22289         indices[2] = 3;
22290         indices[3] = 1;
22291         indices[4] = 2;
22292         indices[5] = 3;
22293         var geometry = new THREE.BufferGeometry();
22294         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22295         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22296         return geometry;
22297     };
22298     return ImagePlaneFactory;
22299 }());
22300 exports.ImagePlaneFactory = ImagePlaneFactory;
22301 Object.defineProperty(exports, "__esModule", { value: true });
22302 exports.default = ImagePlaneFactory;
22303
22304 },{"../../Component":217,"three":167}],250:[function(require,module,exports){
22305 /// <reference path="../../../typings/index.d.ts" />
22306 "use strict";
22307 var Component_1 = require("../../Component");
22308 var Geo_1 = require("../../Geo");
22309 var ImagePlaneGLRenderer = (function () {
22310     function ImagePlaneGLRenderer() {
22311         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
22312         this._imagePlaneScene = new Component_1.ImagePlaneScene();
22313         this._alpha = 0;
22314         this._alphaOld = 0;
22315         this._fadeOutSpeed = 0.05;
22316         this._lastCamera = new Geo_1.Camera();
22317         this._epsilon = 0.000001;
22318         this._currentKey = null;
22319         this._previousKey = null;
22320         this._providerDisposers = {};
22321         this._frameId = 0;
22322         this._needsRender = false;
22323     }
22324     Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
22325         get: function () {
22326             return this._frameId;
22327         },
22328         enumerable: true,
22329         configurable: true
22330     });
22331     Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
22332         get: function () {
22333             return this._needsRender;
22334         },
22335         enumerable: true,
22336         configurable: true
22337     });
22338     ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
22339         this._needsRender = true;
22340     };
22341     ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
22342         this._updateFrameId(frame.id);
22343         this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
22344         this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
22345         this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
22346     };
22347     ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
22348         var _this = this;
22349         if (key !== this._currentKey) {
22350             return;
22351         }
22352         var createdSubscription = provider.textureCreated$
22353             .subscribe(function (texture) {
22354             _this._updateTexture(texture);
22355         });
22356         var updatedSubscription = provider.textureUpdated$
22357             .subscribe(function (updated) {
22358             _this._needsRender = true;
22359         });
22360         var dispose = function () {
22361             createdSubscription.unsubscribe();
22362             updatedSubscription.unsubscribe();
22363             provider.dispose();
22364         };
22365         if (key in this._providerDisposers) {
22366             var disposeProvider = this._providerDisposers[key];
22367             disposeProvider();
22368             delete this._providerDisposers[key];
22369         }
22370         this._providerDisposers[key] = dispose;
22371     };
22372     ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
22373         this._needsRender = true;
22374         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
22375             var plane = _a[_i];
22376             var material = plane.material;
22377             var oldTexture = material.uniforms.projectorTex.value;
22378             material.uniforms.projectorTex.value = null;
22379             oldTexture.dispose();
22380             material.uniforms.projectorTex.value = texture;
22381         }
22382     };
22383     ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
22384         if (this._currentKey !== node.key) {
22385             return;
22386         }
22387         this._needsRender = true;
22388         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
22389             var plane = _a[_i];
22390             var material = plane.material;
22391             var texture = material.uniforms.projectorTex.value;
22392             texture.image = image;
22393             texture.needsUpdate = true;
22394         }
22395     };
22396     ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
22397         var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
22398         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
22399             var plane = _a[_i];
22400             plane.material.uniforms.opacity.value = planeAlpha;
22401         }
22402         for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
22403             var plane = _c[_b];
22404             plane.material.uniforms.opacity.value = this._alphaOld;
22405         }
22406         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
22407         renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
22408         for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
22409             var plane = _e[_d];
22410             plane.material.uniforms.opacity.value = this._alpha;
22411         }
22412         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
22413     };
22414     ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
22415         this._needsRender = false;
22416     };
22417     ImagePlaneGLRenderer.prototype.dispose = function () {
22418         this._imagePlaneScene.clear();
22419     };
22420     ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
22421         this._frameId = frameId;
22422     };
22423     ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
22424         if (alpha === this._alpha) {
22425             return false;
22426         }
22427         this._alpha = alpha;
22428         return true;
22429     };
22430     ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
22431         if (alpha < 1 || this._alphaOld === 0) {
22432             return false;
22433         }
22434         this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
22435         return true;
22436     };
22437     ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
22438         if (state.currentNode == null || state.currentNode.key === this._currentKey) {
22439             return false;
22440         }
22441         var previousKey = state.previousNode != null ? state.previousNode.key : null;
22442         var currentKey = state.currentNode.key;
22443         if (this._previousKey !== previousKey &&
22444             this._previousKey !== currentKey &&
22445             this._previousKey in this._providerDisposers) {
22446             var disposeProvider = this._providerDisposers[this._previousKey];
22447             disposeProvider();
22448             delete this._providerDisposers[this._previousKey];
22449         }
22450         if (previousKey != null) {
22451             if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
22452                 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
22453                 this._imagePlaneScene.updateImagePlanes([previousMesh]);
22454             }
22455             this._previousKey = previousKey;
22456         }
22457         this._currentKey = currentKey;
22458         var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
22459         this._imagePlaneScene.updateImagePlanes([currentMesh]);
22460         this._alphaOld = 1;
22461         return true;
22462     };
22463     return ImagePlaneGLRenderer;
22464 }());
22465 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
22466 Object.defineProperty(exports, "__esModule", { value: true });
22467 exports.default = ImagePlaneGLRenderer;
22468
22469 },{"../../Component":217,"../../Geo":220}],251:[function(require,module,exports){
22470 /// <reference path="../../../typings/index.d.ts" />
22471 "use strict";
22472 var THREE = require("three");
22473 var ImagePlaneScene = (function () {
22474     function ImagePlaneScene() {
22475         this.scene = new THREE.Scene();
22476         this.sceneOld = new THREE.Scene();
22477         this.imagePlanes = [];
22478         this.imagePlanesOld = [];
22479     }
22480     ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
22481         this._dispose(this.imagePlanesOld, this.sceneOld);
22482         for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
22483             var plane = _a[_i];
22484             this.scene.remove(plane);
22485             this.sceneOld.add(plane);
22486         }
22487         for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
22488             var plane = planes_1[_b];
22489             this.scene.add(plane);
22490         }
22491         this.imagePlanesOld = this.imagePlanes;
22492         this.imagePlanes = planes;
22493     };
22494     ImagePlaneScene.prototype.addImagePlanes = function (planes) {
22495         for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
22496             var plane = planes_2[_i];
22497             this.scene.add(plane);
22498             this.imagePlanes.push(plane);
22499         }
22500     };
22501     ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
22502         for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
22503             var plane = planes_3[_i];
22504             this.sceneOld.add(plane);
22505             this.imagePlanesOld.push(plane);
22506         }
22507     };
22508     ImagePlaneScene.prototype.setImagePlanes = function (planes) {
22509         this._clear();
22510         this.addImagePlanes(planes);
22511     };
22512     ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
22513         this._clearOld();
22514         this.addImagePlanesOld(planes);
22515     };
22516     ImagePlaneScene.prototype.clear = function () {
22517         this._clear();
22518         this._clearOld();
22519     };
22520     ImagePlaneScene.prototype._clear = function () {
22521         this._dispose(this.imagePlanes, this.scene);
22522         this.imagePlanes.length = 0;
22523     };
22524     ImagePlaneScene.prototype._clearOld = function () {
22525         this._dispose(this.imagePlanesOld, this.sceneOld);
22526         this.imagePlanesOld.length = 0;
22527     };
22528     ImagePlaneScene.prototype._dispose = function (planes, scene) {
22529         for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
22530             var plane = planes_4[_i];
22531             scene.remove(plane);
22532             plane.geometry.dispose();
22533             plane.material.dispose();
22534             var texture = plane.material.uniforms.projectorTex.value;
22535             if (texture != null) {
22536                 texture.dispose();
22537             }
22538         }
22539     };
22540     return ImagePlaneScene;
22541 }());
22542 exports.ImagePlaneScene = ImagePlaneScene;
22543 Object.defineProperty(exports, "__esModule", { value: true });
22544 exports.default = ImagePlaneScene;
22545
22546 },{"three":167}],252:[function(require,module,exports){
22547 /// <reference path="../../../typings/index.d.ts" />
22548 "use strict";
22549
22550 var path = require("path");
22551 var ImagePlaneShaders = (function () {
22552     function ImagePlaneShaders() {
22553     }
22554     return ImagePlaneShaders;
22555 }());
22556 ImagePlaneShaders.equirectangular = {
22557     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}",
22558     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}",
22559 };
22560 ImagePlaneShaders.perspective = {
22561     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}",
22562     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}",
22563 };
22564 exports.ImagePlaneShaders = ImagePlaneShaders;
22565
22566 },{"path":21}],253:[function(require,module,exports){
22567 /// <reference path="../../../typings/index.d.ts" />
22568 "use strict";
22569 var __extends = (this && this.__extends) || function (d, b) {
22570     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
22571     function __() { this.constructor = d; }
22572     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22573 };
22574 var vd = require("virtual-dom");
22575 var Observable_1 = require("rxjs/Observable");
22576 var Subject_1 = require("rxjs/Subject");
22577 require("rxjs/add/observable/combineLatest");
22578 require("rxjs/add/observable/fromEvent");
22579 require("rxjs/add/observable/of");
22580 require("rxjs/add/observable/zip");
22581 require("rxjs/add/operator/distinctUntilChanged");
22582 require("rxjs/add/operator/filter");
22583 require("rxjs/add/operator/first");
22584 require("rxjs/add/operator/map");
22585 require("rxjs/add/operator/merge");
22586 require("rxjs/add/operator/mergeMap");
22587 require("rxjs/add/operator/scan");
22588 require("rxjs/add/operator/switchMap");
22589 require("rxjs/add/operator/withLatestFrom");
22590 require("rxjs/add/operator/zip");
22591 var State_1 = require("../../State");
22592 var Render_1 = require("../../Render");
22593 var Utils_1 = require("../../Utils");
22594 var Component_1 = require("../../Component");
22595 var SliderState = (function () {
22596     function SliderState() {
22597         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
22598         this._imagePlaneScene = new Component_1.ImagePlaneScene();
22599         this._currentKey = null;
22600         this._previousKey = null;
22601         this._currentPano = false;
22602         this._frameId = 0;
22603         this._glNeedsRender = false;
22604         this._domNeedsRender = true;
22605         this._curtain = 1;
22606     }
22607     Object.defineProperty(SliderState.prototype, "frameId", {
22608         get: function () {
22609             return this._frameId;
22610         },
22611         enumerable: true,
22612         configurable: true
22613     });
22614     Object.defineProperty(SliderState.prototype, "curtain", {
22615         get: function () {
22616             return this._curtain;
22617         },
22618         enumerable: true,
22619         configurable: true
22620     });
22621     Object.defineProperty(SliderState.prototype, "glNeedsRender", {
22622         get: function () {
22623             return this._glNeedsRender;
22624         },
22625         enumerable: true,
22626         configurable: true
22627     });
22628     Object.defineProperty(SliderState.prototype, "domNeedsRender", {
22629         get: function () {
22630             return this._domNeedsRender;
22631         },
22632         enumerable: true,
22633         configurable: true
22634     });
22635     Object.defineProperty(SliderState.prototype, "sliderVisible", {
22636         get: function () {
22637             return this._sliderVisible;
22638         },
22639         set: function (value) {
22640             this._sliderVisible = value;
22641             this._domNeedsRender = true;
22642         },
22643         enumerable: true,
22644         configurable: true
22645     });
22646     Object.defineProperty(SliderState.prototype, "disabled", {
22647         get: function () {
22648             return this._currentKey == null ||
22649                 this._previousKey == null ||
22650                 this._currentPano;
22651         },
22652         enumerable: true,
22653         configurable: true
22654     });
22655     SliderState.prototype.update = function (frame) {
22656         this._updateFrameId(frame.id);
22657         var needsRender = this._updateImagePlanes(frame.state);
22658         this._domNeedsRender = needsRender || this._domNeedsRender;
22659         needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
22660         this._glNeedsRender = needsRender || this._glNeedsRender;
22661     };
22662     SliderState.prototype.updateTexture = function (image, node) {
22663         var imagePlanes = node.key === this._currentKey ?
22664             this._imagePlaneScene.imagePlanes :
22665             node.key === this._previousKey ?
22666                 this._imagePlaneScene.imagePlanesOld :
22667                 [];
22668         if (imagePlanes.length === 0) {
22669             return;
22670         }
22671         this._glNeedsRender = true;
22672         for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
22673             var plane = imagePlanes_1[_i];
22674             var material = plane.material;
22675             var texture = material.uniforms.projectorTex.value;
22676             texture.image = image;
22677             texture.needsUpdate = true;
22678         }
22679     };
22680     SliderState.prototype.render = function (perspectiveCamera, renderer) {
22681         if (!this.disabled) {
22682             renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
22683         }
22684         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
22685     };
22686     SliderState.prototype.dispose = function () {
22687         this._imagePlaneScene.clear();
22688     };
22689     SliderState.prototype.clearGLNeedsRender = function () {
22690         this._glNeedsRender = false;
22691     };
22692     SliderState.prototype.clearDomNeedsRender = function () {
22693         this._domNeedsRender = false;
22694     };
22695     SliderState.prototype._updateFrameId = function (frameId) {
22696         this._frameId = frameId;
22697     };
22698     SliderState.prototype._updateImagePlanes = function (state) {
22699         if (state.currentNode == null) {
22700             return;
22701         }
22702         var needsRender = false;
22703         if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
22704             needsRender = true;
22705             this._previousKey = state.previousNode.key;
22706             this._imagePlaneScene.setImagePlanesOld([
22707                 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
22708             ]);
22709         }
22710         if (this._currentKey !== state.currentNode.key) {
22711             needsRender = true;
22712             this._currentKey = state.currentNode.key;
22713             this._currentPano = state.currentNode.pano;
22714             this._imagePlaneScene.setImagePlanes([
22715                 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
22716             ]);
22717             if (!this.disabled) {
22718                 this._updateBbox();
22719             }
22720         }
22721         return needsRender;
22722     };
22723     SliderState.prototype._updateCurtain = function (alpha) {
22724         if (this.disabled ||
22725             Math.abs(this._curtain - alpha) < 0.001) {
22726             return false;
22727         }
22728         this._curtain = alpha;
22729         this._updateBbox();
22730         return true;
22731     };
22732     SliderState.prototype._updateBbox = function () {
22733         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
22734             var plane = _a[_i];
22735             var shaderMaterial = plane.material;
22736             var bbox = shaderMaterial.uniforms.bbox.value;
22737             bbox.z = this._curtain;
22738         }
22739     };
22740     return SliderState;
22741 }());
22742 var SliderComponent = (function (_super) {
22743     __extends(SliderComponent, _super);
22744     /**
22745      * Create a new slider component instance.
22746      * @class SliderComponent
22747      */
22748     function SliderComponent(name, container, navigator) {
22749         var _this = _super.call(this, name, container, navigator) || this;
22750         _this._sliderStateOperation$ = new Subject_1.Subject();
22751         _this._sliderStateCreator$ = new Subject_1.Subject();
22752         _this._sliderStateDisposer$ = new Subject_1.Subject();
22753         _this._sliderState$ = _this._sliderStateOperation$
22754             .scan(function (sliderState, operation) {
22755             return operation(sliderState);
22756         }, null)
22757             .filter(function (sliderState) {
22758             return sliderState != null;
22759         })
22760             .distinctUntilChanged(undefined, function (sliderState) {
22761             return sliderState.frameId;
22762         });
22763         _this._sliderStateCreator$
22764             .map(function () {
22765             return function (sliderState) {
22766                 if (sliderState != null) {
22767                     throw new Error("Multiple slider states can not be created at the same time");
22768                 }
22769                 return new SliderState();
22770             };
22771         })
22772             .subscribe(_this._sliderStateOperation$);
22773         _this._sliderStateDisposer$
22774             .map(function () {
22775             return function (sliderState) {
22776                 sliderState.dispose();
22777                 return null;
22778             };
22779         })
22780             .subscribe(_this._sliderStateOperation$);
22781         return _this;
22782     }
22783     /**
22784      * Set the image keys.
22785      *
22786      * Configures the component to show the image planes for the supplied image keys.
22787      *
22788      * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
22789      */
22790     SliderComponent.prototype.setKeys = function (keys) {
22791         this.configure({ keys: keys });
22792     };
22793     /**
22794      * Set the initial position.
22795      *
22796      * Configures the intial position of the slider. The inital position value will be used when the component is activated.
22797      *
22798      * @param {number} initialPosition - Initial slider position.
22799      */
22800     SliderComponent.prototype.setInitialPosition = function (initialPosition) {
22801         this.configure({ initialPosition: initialPosition });
22802     };
22803     /**
22804      * Set the value controlling if the slider is visible.
22805      *
22806      * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
22807      */
22808     SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
22809         this.configure({ sliderVisible: sliderVisible });
22810     };
22811     SliderComponent.prototype._activate = function () {
22812         var _this = this;
22813         this._container.mouseService.preventDefaultMouseDown$.next(false);
22814         this._container.touchService.preventDefaultTouchMove$.next(false);
22815         Observable_1.Observable
22816             .combineLatest(this._navigator.stateService.state$, this._configuration$)
22817             .first()
22818             .subscribe(function (stateConfig) {
22819             if (stateConfig[0] === State_1.State.Traversing) {
22820                 _this._navigator.stateService.wait();
22821                 var position = stateConfig[1].initialPosition;
22822                 _this._navigator.stateService.moveTo(position != null ? position : 1);
22823             }
22824         });
22825         this._glRenderSubscription = this._sliderState$
22826             .map(function (sliderState) {
22827             var renderHash = {
22828                 name: _this._name,
22829                 render: {
22830                     frameId: sliderState.frameId,
22831                     needsRender: sliderState.glNeedsRender,
22832                     render: sliderState.render.bind(sliderState),
22833                     stage: Render_1.GLRenderStage.Background,
22834                 },
22835             };
22836             sliderState.clearGLNeedsRender();
22837             return renderHash;
22838         })
22839             .subscribe(this._container.glRenderer.render$);
22840         this._domRenderSubscription = this._sliderState$
22841             .filter(function (sliderState) {
22842             return sliderState.domNeedsRender;
22843         })
22844             .map(function (sliderState) {
22845             var sliderInput = vd.h("input.SliderControl", {
22846                 max: 1000,
22847                 min: 0,
22848                 type: "range",
22849                 value: 1000 * sliderState.curtain,
22850             }, []);
22851             var vNode = sliderState.disabled || !sliderState.sliderVisible ?
22852                 null :
22853                 vd.h("div.SliderWrapper", {}, [sliderInput]);
22854             var hash = {
22855                 name: _this._name,
22856                 vnode: vNode,
22857             };
22858             sliderState.clearDomNeedsRender();
22859             return hash;
22860         })
22861             .subscribe(this._container.domRenderer.render$);
22862         this._elementSubscription = this._container.domRenderer.element$
22863             .map(function (e) {
22864             var nodeList = e.getElementsByClassName("SliderControl");
22865             var slider = nodeList.length > 0 ? nodeList[0] : null;
22866             return slider;
22867         })
22868             .filter(function (input) {
22869             return input != null;
22870         })
22871             .switchMap(function (input) {
22872             return Observable_1.Observable.fromEvent(input, "input");
22873         })
22874             .map(function (e) {
22875             return Number(e.target.value) / 1000;
22876         })
22877             .subscribe(function (curtain) {
22878             _this._navigator.stateService.moveTo(curtain);
22879         });
22880         this._sliderStateCreator$.next(null);
22881         this._stateSubscription = this._navigator.stateService.currentState$
22882             .map(function (frame) {
22883             return function (sliderState) {
22884                 sliderState.update(frame);
22885                 return sliderState;
22886             };
22887         })
22888             .subscribe(this._sliderStateOperation$);
22889         this._setSliderVisibleSubscription = this._configuration$
22890             .map(function (configuration) {
22891             return configuration.sliderVisible == null || configuration.sliderVisible;
22892         })
22893             .distinctUntilChanged()
22894             .map(function (sliderVisible) {
22895             return function (sliderState) {
22896                 sliderState.sliderVisible = sliderVisible;
22897                 return sliderState;
22898             };
22899         })
22900             .subscribe(this._sliderStateOperation$);
22901         this._setKeysSubscription = this._configuration$
22902             .filter(function (configuration) {
22903             return configuration.keys != null;
22904         })
22905             .switchMap(function (configuration) {
22906             return Observable_1.Observable
22907                 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
22908                 .map(function (nodes) {
22909                 return { background: nodes[0], foreground: nodes[1] };
22910             })
22911                 .zip(_this._navigator.stateService.currentState$.first())
22912                 .map(function (nf) {
22913                 return { nodes: nf[0], state: nf[1].state };
22914             });
22915         })
22916             .subscribe(function (co) {
22917             if (co.state.currentNode != null &&
22918                 co.state.previousNode != null &&
22919                 co.state.currentNode.key === co.nodes.foreground.key &&
22920                 co.state.previousNode.key === co.nodes.background.key) {
22921                 return;
22922             }
22923             if (co.state.currentNode.key === co.nodes.background.key) {
22924                 _this._navigator.stateService.setNodes([co.nodes.foreground]);
22925                 return;
22926             }
22927             if (co.state.currentNode.key === co.nodes.foreground.key &&
22928                 co.state.trajectory.length === 1) {
22929                 _this._navigator.stateService.prependNodes([co.nodes.background]);
22930                 return;
22931             }
22932             _this._navigator.stateService.setNodes([co.nodes.background]);
22933             _this._navigator.stateService.setNodes([co.nodes.foreground]);
22934         }, function (e) {
22935             console.error(e);
22936         });
22937         var previousNode$ = this._navigator.stateService.currentState$
22938             .map(function (frame) {
22939             return frame.state.previousNode;
22940         })
22941             .filter(function (node) {
22942             return node != null;
22943         })
22944             .distinctUntilChanged(undefined, function (node) {
22945             return node.key;
22946         });
22947         this._nodeSubscription = Observable_1.Observable
22948             .merge(previousNode$, this._navigator.stateService.currentNode$)
22949             .filter(function (node) {
22950             return node.pano ?
22951                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
22952                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
22953         })
22954             .mergeMap(function (node) {
22955             var baseImageSize = node.pano ?
22956                 Utils_1.Settings.basePanoramaSize :
22957                 Utils_1.Settings.baseImageSize;
22958             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
22959                 return Observable_1.Observable.empty();
22960             }
22961             return node.cacheImage$(Utils_1.Settings.maxImageSize)
22962                 .map(function (n) {
22963                 return [n.image, n];
22964             })
22965                 .catch(function (error, caught) {
22966                 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
22967                 return Observable_1.Observable.empty();
22968             });
22969         })
22970             .map(function (imn) {
22971             return function (sliderState) {
22972                 sliderState.updateTexture(imn[0], imn[1]);
22973                 return sliderState;
22974             };
22975         })
22976             .subscribe(this._sliderStateOperation$);
22977     };
22978     SliderComponent.prototype._deactivate = function () {
22979         var _this = this;
22980         this._container.mouseService.preventDefaultMouseDown$.next(true);
22981         this._container.touchService.preventDefaultTouchMove$.next(true);
22982         this._navigator.stateService.state$
22983             .first()
22984             .subscribe(function (state) {
22985             if (state === State_1.State.Waiting) {
22986                 _this._navigator.stateService.traverse();
22987             }
22988         });
22989         this._sliderStateDisposer$.next(null);
22990         this._setKeysSubscription.unsubscribe();
22991         this._setSliderVisibleSubscription.unsubscribe();
22992         this._elementSubscription.unsubscribe();
22993         this._stateSubscription.unsubscribe();
22994         this._glRenderSubscription.unsubscribe();
22995         this._domRenderSubscription.unsubscribe();
22996         this._nodeSubscription.unsubscribe();
22997         this.configure({ keys: null });
22998     };
22999     SliderComponent.prototype._getDefaultConfiguration = function () {
23000         return {};
23001     };
23002     SliderComponent.prototype._catchCacheNode$ = function (key) {
23003         return this._navigator.graphService.cacheNode$(key)
23004             .catch(function (error, caught) {
23005             console.error("Failed to cache slider node (" + key + ")", error);
23006             return Observable_1.Observable.empty();
23007         });
23008     };
23009     return SliderComponent;
23010 }(Component_1.Component));
23011 SliderComponent.componentName = "slider";
23012 exports.SliderComponent = SliderComponent;
23013 Component_1.ComponentService.register(SliderComponent);
23014 Object.defineProperty(exports, "__esModule", { value: true });
23015 exports.default = SliderComponent;
23016
23017 },{"../../Component":217,"../../Render":223,"../../State":224,"../../Utils":226,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/fromEvent":41,"rxjs/add/observable/of":44,"rxjs/add/observable/zip":46,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/filter":58,"rxjs/add/operator/first":60,"rxjs/add/operator/map":62,"rxjs/add/operator/merge":63,"rxjs/add/operator/mergeMap":65,"rxjs/add/operator/scan":70,"rxjs/add/operator/switchMap":76,"rxjs/add/operator/withLatestFrom":80,"rxjs/add/operator/zip":81,"virtual-dom":173}],254:[function(require,module,exports){
23018 "use strict";
23019 var Marker = (function () {
23020     function Marker(latLonAlt, markerOptions) {
23021         this.visibleInKeys = [];
23022         this._id = markerOptions.id;
23023         this._latLonAlt = latLonAlt;
23024         this._markerOptions = markerOptions;
23025         this._type = markerOptions.type;
23026     }
23027     Object.defineProperty(Marker.prototype, "id", {
23028         get: function () {
23029             return this._id;
23030         },
23031         enumerable: true,
23032         configurable: true
23033     });
23034     Object.defineProperty(Marker.prototype, "type", {
23035         get: function () {
23036             return this._type;
23037         },
23038         enumerable: true,
23039         configurable: true
23040     });
23041     Object.defineProperty(Marker.prototype, "latLonAlt", {
23042         get: function () {
23043             return this._latLonAlt;
23044         },
23045         enumerable: true,
23046         configurable: true
23047     });
23048     return Marker;
23049 }());
23050 exports.Marker = Marker;
23051 Object.defineProperty(exports, "__esModule", { value: true });
23052 exports.default = Marker;
23053
23054 },{}],255:[function(require,module,exports){
23055 /// <reference path="../../../typings/index.d.ts" />
23056 "use strict";
23057 var __extends = (this && this.__extends) || function (d, b) {
23058     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23059     function __() { this.constructor = d; }
23060     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23061 };
23062 var _ = require("underscore");
23063 var THREE = require("three");
23064 var rbush = require("rbush");
23065 var Observable_1 = require("rxjs/Observable");
23066 var Subject_1 = require("rxjs/Subject");
23067 require("rxjs/add/observable/combineLatest");
23068 require("rxjs/add/operator/distinctUntilChanged");
23069 require("rxjs/add/operator/filter");
23070 require("rxjs/add/operator/map");
23071 require("rxjs/add/operator/publishReplay");
23072 require("rxjs/add/operator/scan");
23073 require("rxjs/add/operator/switchMap");
23074 var Component_1 = require("../../Component");
23075 var Render_1 = require("../../Render");
23076 var Geo_1 = require("../../Geo");
23077 var MarkerSet = (function () {
23078     function MarkerSet() {
23079         this._create$ = new Subject_1.Subject();
23080         this._remove$ = new Subject_1.Subject();
23081         this._update$ = new Subject_1.Subject();
23082         // markers list stream is the result of applying marker updates.
23083         this._markers$ = this._update$
23084             .scan(function (markers, operation) {
23085             return operation(markers);
23086         }, { hash: {}, spatial: rbush(16, [".lon", ".lat", ".lon", ".lat"]) })
23087             .map(function (markers) {
23088             return markers.spatial;
23089         })
23090             .publishReplay(1)
23091             .refCount();
23092         // creation stream generate creation updates from given markers.
23093         this._create$
23094             .map(function (marker) {
23095             return function (markers) {
23096                 if (markers.hash[marker.id]) {
23097                     markers.spatial.remove(markers.hash[marker.id]);
23098                 }
23099                 var rbushObj = {
23100                     id: marker.id,
23101                     lat: marker.latLonAlt.lat,
23102                     lon: marker.latLonAlt.lon,
23103                     marker: marker,
23104                 };
23105                 markers.spatial.insert(rbushObj);
23106                 markers.hash[marker.id] = rbushObj;
23107                 return markers;
23108             };
23109         })
23110             .subscribe(this._update$);
23111         // remove stream generates remove updates from given markers
23112         this._remove$
23113             .map(function (id) {
23114             return function (markers) {
23115                 var rbushObj = markers.hash[id];
23116                 markers.spatial.remove(rbushObj);
23117                 delete markers.hash[id];
23118                 return markers;
23119             };
23120         })
23121             .subscribe(this._update$);
23122     }
23123     MarkerSet.prototype.addMarker = function (marker) {
23124         this._create$.next(marker);
23125     };
23126     MarkerSet.prototype.removeMarker = function (id) {
23127         this._remove$.next(id);
23128     };
23129     Object.defineProperty(MarkerSet.prototype, "markers$", {
23130         get: function () {
23131             return this._markers$;
23132         },
23133         enumerable: true,
23134         configurable: true
23135     });
23136     return MarkerSet;
23137 }());
23138 exports.MarkerSet = MarkerSet;
23139 var MarkerComponent = (function (_super) {
23140     __extends(MarkerComponent, _super);
23141     function MarkerComponent(name, container, navigator) {
23142         return _super.call(this, name, container, navigator) || this;
23143     }
23144     MarkerComponent.prototype._activate = function () {
23145         var _this = this;
23146         this._scene = new THREE.Scene();
23147         this._markerSet = new MarkerSet();
23148         this._markerObjects = {};
23149         this._disposable = Observable_1.Observable
23150             .combineLatest([
23151             this._navigator.stateService.currentState$,
23152             this._markerSet.markers$,
23153         ], function (frame, markers) {
23154             return { frame: frame, markers: markers };
23155         })
23156             .distinctUntilChanged(undefined, function (args) {
23157             return args.frame.id;
23158         })
23159             .map(function (args) {
23160             return _this._renderHash(args);
23161         })
23162             .subscribe(this._container.glRenderer.render$);
23163     };
23164     MarkerComponent.prototype._deactivate = function () {
23165         // release memory
23166         this._disposeScene();
23167         this._disposable.unsubscribe();
23168     };
23169     MarkerComponent.prototype._getDefaultConfiguration = function () {
23170         return {};
23171     };
23172     MarkerComponent.prototype.createMarker = function (latLonAlt, markerOptions) {
23173         if (markerOptions.type === "marker") {
23174             return new Component_1.SimpleMarker(latLonAlt, markerOptions);
23175         }
23176         return null;
23177     };
23178     MarkerComponent.prototype.addMarker = function (marker) {
23179         this._markerSet.addMarker(marker);
23180     };
23181     Object.defineProperty(MarkerComponent.prototype, "markers$", {
23182         get: function () {
23183             return this._markerSet.markers$;
23184         },
23185         enumerable: true,
23186         configurable: true
23187     });
23188     MarkerComponent.prototype.removeMarker = function (id) {
23189         this._markerSet.removeMarker(id);
23190     };
23191     MarkerComponent.prototype._renderHash = function (args) {
23192         // determine if render is needed while updating scene
23193         // specific properies.
23194         var needsRender = this._updateScene(args);
23195         // return render hash with render function and
23196         // render in foreground.
23197         return {
23198             name: this._name,
23199             render: {
23200                 frameId: args.frame.id,
23201                 needsRender: needsRender,
23202                 render: this._render.bind(this),
23203                 stage: Render_1.GLRenderStage.Foreground,
23204             },
23205         };
23206     };
23207     MarkerComponent.prototype._updateScene = function (args) {
23208         if (!args.frame ||
23209             !args.markers ||
23210             !args.frame.state.currentNode) {
23211             return false;
23212         }
23213         var needRender = false;
23214         var oldObjects = this._markerObjects;
23215         var node = args.frame.state.currentNode;
23216         this._markerObjects = {};
23217         var boxWidth = 0.001;
23218         var minLon = node.latLon.lon - boxWidth / 2;
23219         var minLat = node.latLon.lat - boxWidth / 2;
23220         var maxLon = node.latLon.lon + boxWidth / 2;
23221         var maxLat = node.latLon.lat + boxWidth / 2;
23222         var markers = _.map(args.markers.search({ maxX: maxLon, maxY: maxLat, minX: minLon, minY: minLat }), function (item) {
23223             return item.marker;
23224         }).filter(function (marker) {
23225             return marker.visibleInKeys.length === 0 || _.contains(marker.visibleInKeys, node.key);
23226         });
23227         for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
23228             var marker = markers_1[_i];
23229             if (marker.id in oldObjects) {
23230                 this._markerObjects[marker.id] = oldObjects[marker.id];
23231                 delete oldObjects[marker.id];
23232             }
23233             else {
23234                 var reference = args.frame.state.reference;
23235                 var p = (new Geo_1.GeoCoords).geodeticToEnu(marker.latLonAlt.lat, marker.latLonAlt.lon, marker.latLonAlt.alt, reference.lat, reference.lon, reference.alt);
23236                 var o = marker.createGeometry();
23237                 o.position.set(p[0], p[1], p[2]);
23238                 this._scene.add(o);
23239                 this._markerObjects[marker.id] = o;
23240                 needRender = true;
23241             }
23242         }
23243         for (var i in oldObjects) {
23244             if (oldObjects.hasOwnProperty(i)) {
23245                 this._disposeObject(oldObjects[i]);
23246                 needRender = true;
23247             }
23248         }
23249         return needRender;
23250     };
23251     MarkerComponent.prototype._render = function (perspectiveCamera, renderer) {
23252         renderer.render(this._scene, perspectiveCamera);
23253     };
23254     MarkerComponent.prototype._disposeObject = function (object) {
23255         this._scene.remove(object);
23256         for (var i = 0; i < object.children.length; ++i) {
23257             var c = object.children[i];
23258             c.geometry.dispose();
23259             c.material.dispose();
23260         }
23261     };
23262     MarkerComponent.prototype._disposeScene = function () {
23263         for (var i in this._markerObjects) {
23264             if (this._markerObjects.hasOwnProperty(i)) {
23265                 this._disposeObject(this._markerObjects[i]);
23266             }
23267         }
23268         this._markerObjects = {};
23269     };
23270     return MarkerComponent;
23271 }(Component_1.Component));
23272 MarkerComponent.componentName = "marker";
23273 exports.MarkerComponent = MarkerComponent;
23274 Component_1.ComponentService.register(MarkerComponent);
23275 Object.defineProperty(exports, "__esModule", { value: true });
23276 exports.default = MarkerComponent;
23277
23278 },{"../../Component":217,"../../Geo":220,"../../Render":223,"rbush":24,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/switchMap":76,"three":167,"underscore":168}],256:[function(require,module,exports){
23279 "use strict";
23280 var __extends = (this && this.__extends) || function (d, b) {
23281     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23282     function __() { this.constructor = d; }
23283     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23284 };
23285 var THREE = require("three");
23286 var Component_1 = require("../../Component");
23287 var SimpleMarker = (function (_super) {
23288     __extends(SimpleMarker, _super);
23289     function SimpleMarker(latLonAlt, markerOptions) {
23290         var _this = _super.call(this, latLonAlt, markerOptions) || this;
23291         _this._circleToRayAngle = 2.0;
23292         _this._simpleMarkerStyle = markerOptions.style;
23293         return _this;
23294     }
23295     SimpleMarker.prototype.createGeometry = function () {
23296         var radius = 2;
23297         var cone = new THREE.Mesh(this._markerGeometry(radius, 16, 8), new THREE.MeshBasicMaterial({
23298             color: this._stringToRBG(this._simpleMarkerStyle.color),
23299             depthWrite: false,
23300             opacity: this._simpleMarkerStyle.opacity,
23301             shading: THREE.SmoothShading,
23302             transparent: true,
23303         }));
23304         var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 16, 8), new THREE.MeshBasicMaterial({
23305             color: this._stringToRBG(this._simpleMarkerStyle.ballColor),
23306             depthWrite: false,
23307             opacity: this._simpleMarkerStyle.ballOpacity,
23308             shading: THREE.SmoothShading,
23309             transparent: true,
23310         }));
23311         ball.position.z = this._markerHeight(radius);
23312         var group = new THREE.Object3D();
23313         group.add(ball);
23314         group.add(cone);
23315         return group;
23316     };
23317     SimpleMarker.prototype._markerHeight = function (radius) {
23318         var t = Math.tan(Math.PI - this._circleToRayAngle);
23319         return radius * Math.sqrt(1 + t * t);
23320     };
23321     SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
23322         var geometry = new THREE.Geometry();
23323         widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
23324         heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
23325         var height = this._markerHeight(radius);
23326         var vertices = [];
23327         for (var y = 0; y <= heightSegments; ++y) {
23328             var verticesRow = [];
23329             for (var x = 0; x <= widthSegments; ++x) {
23330                 var u = x / widthSegments * Math.PI * 2;
23331                 var v = y / heightSegments * Math.PI;
23332                 var r = void 0;
23333                 if (v < this._circleToRayAngle) {
23334                     r = radius;
23335                 }
23336                 else {
23337                     var t = Math.tan(v - this._circleToRayAngle);
23338                     r = radius * Math.sqrt(1 + t * t);
23339                 }
23340                 var vertex = new THREE.Vector3();
23341                 vertex.x = r * Math.cos(u) * Math.sin(v);
23342                 vertex.y = r * Math.sin(u) * Math.sin(v);
23343                 vertex.z = r * Math.cos(v) + height;
23344                 geometry.vertices.push(vertex);
23345                 verticesRow.push(geometry.vertices.length - 1);
23346             }
23347             vertices.push(verticesRow);
23348         }
23349         for (var y = 0; y < heightSegments; ++y) {
23350             for (var x = 0; x < widthSegments; ++x) {
23351                 var v1 = vertices[y][x + 1];
23352                 var v2 = vertices[y][x];
23353                 var v3 = vertices[y + 1][x];
23354                 var v4 = vertices[y + 1][x + 1];
23355                 var n1 = geometry.vertices[v1].clone().normalize();
23356                 var n2 = geometry.vertices[v2].clone().normalize();
23357                 var n3 = geometry.vertices[v3].clone().normalize();
23358                 var n4 = geometry.vertices[v4].clone().normalize();
23359                 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
23360                 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
23361             }
23362         }
23363         geometry.computeFaceNormals();
23364         geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
23365         return geometry;
23366     };
23367     SimpleMarker.prototype._stringToRBG = function (str) {
23368         var ret = 0;
23369         for (var i = 0; i < str.length; i++) {
23370             ret = str.charCodeAt(i) + ((ret << 5) - ret);
23371         }
23372         return ret;
23373     };
23374     return SimpleMarker;
23375 }(Component_1.Marker));
23376 exports.SimpleMarker = SimpleMarker;
23377 Object.defineProperty(exports, "__esModule", { value: true });
23378 exports.default = SimpleMarker;
23379
23380 },{"../../Component":217,"three":167}],257:[function(require,module,exports){
23381 /// <reference path="../../../typings/index.d.ts" />
23382 "use strict";
23383 var __extends = (this && this.__extends) || function (d, b) {
23384     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23385     function __() { this.constructor = d; }
23386     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23387 };
23388 var Observable_1 = require("rxjs/Observable");
23389 var Subject_1 = require("rxjs/Subject");
23390 require("rxjs/add/observable/combineLatest");
23391 require("rxjs/add/observable/of");
23392 require("rxjs/add/operator/bufferCount");
23393 require("rxjs/add/operator/concat");
23394 require("rxjs/add/operator/distinctUntilChanged");
23395 require("rxjs/add/operator/filter");
23396 require("rxjs/add/operator/finally");
23397 require("rxjs/add/operator/first");
23398 require("rxjs/add/operator/map");
23399 require("rxjs/add/operator/publishReplay");
23400 require("rxjs/add/operator/scan");
23401 require("rxjs/add/operator/share");
23402 require("rxjs/add/operator/switchMap");
23403 require("rxjs/add/operator/takeUntil");
23404 require("rxjs/add/operator/withLatestFrom");
23405 var Component_1 = require("../../Component");
23406 var Edge_1 = require("../../Edge");
23407 /**
23408  * @class SequenceComponent
23409  * @classdesc Component showing navigation arrows for sequence directions
23410  * as well as playing button. Exposes an API to start and stop play.
23411  */
23412 var SequenceComponent = (function (_super) {
23413     __extends(SequenceComponent, _super);
23414     function SequenceComponent(name, container, navigator) {
23415         var _this = _super.call(this, name, container, navigator) || this;
23416         _this._nodesAhead = 5;
23417         _this._configurationOperation$ = new Subject_1.Subject();
23418         _this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element);
23419         _this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
23420         _this._containerWidth$ = new Subject_1.Subject();
23421         _this._hoveredKeySubject$ = new Subject_1.Subject();
23422         _this._hoveredKey$ = _this._hoveredKeySubject$.share();
23423         _this._edgeStatus$ = _this._navigator.stateService.currentNode$
23424             .switchMap(function (node) {
23425             return node.sequenceEdges$;
23426         })
23427             .publishReplay(1)
23428             .refCount();
23429         return _this;
23430     }
23431     Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
23432         /**
23433          * Get hovered key observable.
23434          *
23435          * @description An observable emitting the key of the node for the direction
23436          * arrow that is being hovered. When the mouse leaves a direction arrow null
23437          * is emitted.
23438          *
23439          * @returns {Observable<string>}
23440          */
23441         get: function () {
23442             return this._hoveredKey$;
23443         },
23444         enumerable: true,
23445         configurable: true
23446     });
23447     /**
23448      * Start playing.
23449      *
23450      * @fires PlayerComponent#playingchanged
23451      */
23452     SequenceComponent.prototype.play = function () {
23453         this.configure({ playing: true });
23454     };
23455     /**
23456      * Stop playing.
23457      *
23458      * @fires PlayerComponent#playingchanged
23459      */
23460     SequenceComponent.prototype.stop = function () {
23461         this.configure({ playing: false });
23462     };
23463     /**
23464      * Set the direction to follow when playing.
23465      *
23466      * @param {EdgeDirection} direction - The direction that will be followed when playing.
23467      */
23468     SequenceComponent.prototype.setDirection = function (direction) {
23469         this.configure({ direction: direction });
23470     };
23471     /**
23472      * Set highlight key.
23473      *
23474      * @description The arrow pointing towards the node corresponding to the
23475      * highlight key will be highlighted.
23476      *
23477      * @param {string} highlightKey Key of node to be highlighted if existing.
23478      */
23479     SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
23480         this.configure({ highlightKey: highlightKey });
23481     };
23482     /**
23483      * Set max width of container element.
23484      *
23485      * @description Set max width of the container element holding
23486      * the sequence navigation elements. If the min width is larger than the
23487      * max width the min width value will be used.
23488      *
23489      * The container element is automatically resized when the resize
23490      * method on the Viewer class is called.
23491      *
23492      * @param {number} minWidth
23493      */
23494     SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
23495         this.configure({ maxWidth: maxWidth });
23496     };
23497     /**
23498      * Set min width of container element.
23499      *
23500      * @description Set min width of the container element holding
23501      * the sequence navigation elements. If the min width is larger than the
23502      * max width the min width value will be used.
23503      *
23504      * The container element is automatically resized when the resize
23505      * method on the Viewer class is called.
23506      *
23507      * @param {number} minWidth
23508      */
23509     SequenceComponent.prototype.setMinWidth = function (minWidth) {
23510         this.configure({ minWidth: minWidth });
23511     };
23512     /**
23513      * Set the value indicating whether the sequence UI elements should be visible.
23514      *
23515      * @param {boolean} visible
23516      */
23517     SequenceComponent.prototype.setVisible = function (visible) {
23518         this.configure({ visible: visible });
23519     };
23520     /** @inheritdoc */
23521     SequenceComponent.prototype.resize = function () {
23522         var _this = this;
23523         this._configuration$
23524             .first()
23525             .map(function (configuration) {
23526             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
23527         })
23528             .subscribe(function (containerWidth) {
23529             _this._containerWidth$.next(containerWidth);
23530         });
23531     };
23532     SequenceComponent.prototype._activate = function () {
23533         var _this = this;
23534         this._renderSubscription = Observable_1.Observable
23535             .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$)
23536             .map(function (ec) {
23537             var edgeStatus = ec[0];
23538             var configuration = ec[1];
23539             var containerWidth = ec[2];
23540             var vNode = _this._sequenceDOMRenderer
23541                 .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator);
23542             return { name: _this._name, vnode: vNode };
23543         })
23544             .subscribe(this._container.domRenderer.render$);
23545         this._containerWidthSubscription = this._configuration$
23546             .distinctUntilChanged(function (value1, value2) {
23547             return value1[0] === value2[0] && value1[1] === value2[1];
23548         }, function (configuration) {
23549             return [configuration.minWidth, configuration.maxWidth];
23550         })
23551             .map(function (configuration) {
23552             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
23553         })
23554             .subscribe(this._containerWidth$);
23555         this._configurationSubscription = this._configurationOperation$
23556             .scan(function (configuration, operation) {
23557             return operation(configuration);
23558         }, { playing: false })
23559             .finally(function () {
23560             if (_this._playingSubscription != null) {
23561                 _this._navigator.stateService.cutNodes();
23562                 _this._stop();
23563             }
23564         })
23565             .subscribe(function () { });
23566         this._configuration$
23567             .map(function (newConfiguration) {
23568             return function (configuration) {
23569                 if (newConfiguration.playing !== configuration.playing) {
23570                     _this._navigator.stateService.cutNodes();
23571                     if (newConfiguration.playing) {
23572                         _this._play();
23573                     }
23574                     else {
23575                         _this._stop();
23576                     }
23577                 }
23578                 configuration.playing = newConfiguration.playing;
23579                 return configuration;
23580             };
23581         })
23582             .subscribe(this._configurationOperation$);
23583         this._stopSubscription = this._configuration$
23584             .switchMap(function (configuration) {
23585             var edgeStatus$ = configuration.playing ?
23586                 _this._edgeStatus$ :
23587                 Observable_1.Observable.empty();
23588             var edgeDirection$ = Observable_1.Observable
23589                 .of(configuration.direction);
23590             return Observable_1.Observable
23591                 .combineLatest(edgeStatus$, edgeDirection$);
23592         })
23593             .map(function (ne) {
23594             var edgeStatus = ne[0];
23595             var direction = ne[1];
23596             if (!edgeStatus.cached) {
23597                 return true;
23598             }
23599             for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
23600                 var edge = _a[_i];
23601                 if (edge.data.direction === direction) {
23602                     return true;
23603                 }
23604             }
23605             return false;
23606         })
23607             .filter(function (hasEdge) {
23608             return !hasEdge;
23609         })
23610             .map(function (hasEdge) {
23611             return { playing: false };
23612         })
23613             .subscribe(this._configurationSubject$);
23614         this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
23615             .switchMap(function (direction) {
23616             return _this._edgeStatus$
23617                 .map(function (edgeStatus) {
23618                 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
23619                     var edge = _a[_i];
23620                     if (edge.data.direction === direction) {
23621                         return edge.to;
23622                     }
23623                 }
23624                 return null;
23625             })
23626                 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
23627                 .concat(Observable_1.Observable.of(null));
23628         })
23629             .distinctUntilChanged()
23630             .subscribe(this._hoveredKeySubject$);
23631     };
23632     SequenceComponent.prototype._deactivate = function () {
23633         this._stopSubscription.unsubscribe();
23634         this._renderSubscription.unsubscribe();
23635         this._configurationSubscription.unsubscribe();
23636         this._containerWidthSubscription.unsubscribe();
23637         this._hoveredKeySubscription.unsubscribe();
23638         this.stop();
23639     };
23640     SequenceComponent.prototype._getDefaultConfiguration = function () {
23641         return {
23642             direction: Edge_1.EdgeDirection.Next,
23643             maxWidth: 117,
23644             minWidth: 70,
23645             playing: false,
23646             visible: true,
23647         };
23648     };
23649     SequenceComponent.prototype._play = function () {
23650         var _this = this;
23651         this._playingSubscription = this._navigator.stateService.currentState$
23652             .filter(function (frame) {
23653             return frame.state.nodesAhead < _this._nodesAhead;
23654         })
23655             .map(function (frame) {
23656             return frame.state.lastNode;
23657         })
23658             .distinctUntilChanged(undefined, function (lastNode) {
23659             return lastNode.key;
23660         })
23661             .withLatestFrom(this._configuration$, function (lastNode, configuration) {
23662             return [lastNode, configuration.direction];
23663         })
23664             .switchMap(function (nd) {
23665             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ?
23666                 nd[0].sequenceEdges$ :
23667                 nd[0].spatialEdges$)
23668                 .filter(function (status) {
23669                 return status.cached;
23670             })
23671                 .zip(Observable_1.Observable.of(nd[1]), function (status, direction) {
23672                 return [status, direction];
23673             });
23674         })
23675             .map(function (ed) {
23676             var direction = ed[1];
23677             for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) {
23678                 var edge = _a[_i];
23679                 if (edge.data.direction === direction) {
23680                     return edge.to;
23681                 }
23682             }
23683             return null;
23684         })
23685             .filter(function (key) {
23686             return key != null;
23687         })
23688             .switchMap(function (key) {
23689             return _this._navigator.graphService.cacheNode$(key);
23690         })
23691             .subscribe(function (node) {
23692             _this._navigator.stateService.appendNodes([node]);
23693         }, function (error) {
23694             console.error(error);
23695             _this.stop();
23696         });
23697         this._clearSubscription = this._navigator.stateService.currentNode$
23698             .bufferCount(1, 7)
23699             .subscribe(function (nodes) {
23700             _this._navigator.stateService.clearPriorNodes();
23701         });
23702         this.fire(SequenceComponent.playingchanged, true);
23703     };
23704     SequenceComponent.prototype._stop = function () {
23705         this._playingSubscription.unsubscribe();
23706         this._playingSubscription = null;
23707         this._clearSubscription.unsubscribe();
23708         this._clearSubscription = null;
23709         this.fire(SequenceComponent.playingchanged, false);
23710     };
23711     return SequenceComponent;
23712 }(Component_1.Component));
23713 /** @inheritdoc */
23714 SequenceComponent.componentName = "sequence";
23715 /**
23716  * Event fired when playing starts or stops.
23717  *
23718  * @event PlayerComponent#playingchanged
23719  * @type {boolean} Indicates whether the player is playing.
23720  */
23721 SequenceComponent.playingchanged = "playingchanged";
23722 exports.SequenceComponent = SequenceComponent;
23723 Component_1.ComponentService.register(SequenceComponent);
23724 Object.defineProperty(exports, "__esModule", { value: true });
23725 exports.default = SequenceComponent;
23726
23727 },{"../../Component":217,"../../Edge":218,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/of":44,"rxjs/add/operator/bufferCount":48,"rxjs/add/operator/concat":51,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/filter":58,"rxjs/add/operator/finally":59,"rxjs/add/operator/first":60,"rxjs/add/operator/map":62,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/share":71,"rxjs/add/operator/switchMap":76,"rxjs/add/operator/takeUntil":78,"rxjs/add/operator/withLatestFrom":80}],258:[function(require,module,exports){
23728 "use strict";
23729 var Subject_1 = require("rxjs/Subject");
23730 var SequenceDOMInteraction = (function () {
23731     function SequenceDOMInteraction() {
23732         this._mouseEnterDirection$ = new Subject_1.Subject();
23733         this._mouseLeaveDirection$ = new Subject_1.Subject();
23734     }
23735     Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
23736         get: function () {
23737             return this._mouseEnterDirection$;
23738         },
23739         enumerable: true,
23740         configurable: true
23741     });
23742     Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
23743         get: function () {
23744             return this._mouseLeaveDirection$;
23745         },
23746         enumerable: true,
23747         configurable: true
23748     });
23749     return SequenceDOMInteraction;
23750 }());
23751 exports.SequenceDOMInteraction = SequenceDOMInteraction;
23752 Object.defineProperty(exports, "__esModule", { value: true });
23753 exports.default = SequenceDOMInteraction;
23754
23755 },{"rxjs/Subject":33}],259:[function(require,module,exports){
23756 /// <reference path="../../../typings/index.d.ts" />
23757 "use strict";
23758 var vd = require("virtual-dom");
23759 var Edge_1 = require("../../Edge");
23760 var SequenceDOMRenderer = (function () {
23761     function SequenceDOMRenderer(element) {
23762         this._minThresholdWidth = 320;
23763         this._maxThresholdWidth = 1480;
23764         this._minThresholdHeight = 240;
23765         this._maxThresholdHeight = 820;
23766     }
23767     SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
23768         if (configuration.visible === false) {
23769             return vd.h("div.SequenceContainer", {}, []);
23770         }
23771         var nextKey = null;
23772         var prevKey = null;
23773         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
23774             var edge = _a[_i];
23775             if (edge.data.direction === Edge_1.EdgeDirection.Next) {
23776                 nextKey = edge.to;
23777             }
23778             if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
23779                 prevKey = edge.to;
23780             }
23781         }
23782         var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
23783         var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator);
23784         var containerProperties = {
23785             style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" },
23786         };
23787         return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton]));
23788     };
23789     SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
23790         var elementWidth = element.offsetWidth;
23791         var elementHeight = element.offsetHeight;
23792         var minWidth = configuration.minWidth;
23793         var maxWidth = configuration.maxWidth;
23794         if (maxWidth < minWidth) {
23795             maxWidth = minWidth;
23796         }
23797         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
23798         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
23799         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
23800         return minWidth + coeff * (maxWidth - minWidth);
23801     };
23802     SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
23803         var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
23804             configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
23805         var onclick = configuration.playing ?
23806             function (e) { component.stop(); } :
23807             canPlay ? function (e) { component.play(); } : null;
23808         var buttonProperties = {
23809             onclick: onclick,
23810             style: {},
23811         };
23812         var iconClass = configuration.playing ?
23813             "Stop" :
23814             canPlay ? "Play" : "PlayDisabled";
23815         var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []);
23816         var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
23817         return vd.h("div." + buttonClass, buttonProperties, [icon]);
23818     };
23819     SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) {
23820         var nextProperties = {
23821             onclick: nextKey != null ?
23822                 function (e) {
23823                     navigator.moveDir$(Edge_1.EdgeDirection.Next)
23824                         .subscribe(function (node) { return; }, function (error) { console.error(error); });
23825                 } :
23826                 null,
23827             onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
23828             onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
23829             style: {},
23830         };
23831         var prevProperties = {
23832             onclick: prevKey != null ?
23833                 function (e) {
23834                     navigator.moveDir$(Edge_1.EdgeDirection.Prev)
23835                         .subscribe(function (node) { return; }, function (error) { console.error(error); });
23836                 } :
23837                 null,
23838             onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
23839             onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
23840             style: {},
23841         };
23842         var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
23843         var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
23844         var nextIcon = vd.h("div.SequenceComponentIcon", []);
23845         var prevIcon = vd.h("div.SequenceComponentIcon", []);
23846         return [
23847             vd.h("div." + nextClass, nextProperties, [nextIcon]),
23848             vd.h("div." + prevClass, prevProperties, [prevIcon]),
23849         ];
23850     };
23851     SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
23852         var className = direction === Edge_1.EdgeDirection.Next ?
23853             "SequenceStepNext" :
23854             "SequenceStepPrev";
23855         if (key == null) {
23856             className += "Disabled";
23857         }
23858         else {
23859             if (highlightKey === key) {
23860                 className += "Highlight";
23861             }
23862         }
23863         return className;
23864     };
23865     return SequenceDOMRenderer;
23866 }());
23867 exports.SequenceDOMRenderer = SequenceDOMRenderer;
23868 Object.defineProperty(exports, "__esModule", { value: true });
23869 exports.default = SequenceDOMRenderer;
23870
23871 },{"../../Edge":218,"virtual-dom":173}],260:[function(require,module,exports){
23872 "use strict";
23873 var GeometryTagError_1 = require("./error/GeometryTagError");
23874 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
23875 var PointGeometry_1 = require("./geometry/PointGeometry");
23876 exports.PointGeometry = PointGeometry_1.PointGeometry;
23877 var RectGeometry_1 = require("./geometry/RectGeometry");
23878 exports.RectGeometry = RectGeometry_1.RectGeometry;
23879 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
23880 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
23881 var OutlineTag_1 = require("./tag/OutlineTag");
23882 exports.OutlineTag = OutlineTag_1.OutlineTag;
23883 var SpotTag_1 = require("./tag/SpotTag");
23884 exports.SpotTag = SpotTag_1.SpotTag;
23885 var Alignment_1 = require("./tag/Alignment");
23886 exports.Alignment = Alignment_1.Alignment;
23887 var TagComponent_1 = require("./TagComponent");
23888 exports.TagComponent = TagComponent_1.TagComponent;
23889
23890 },{"./TagComponent":261,"./error/GeometryTagError":267,"./geometry/PointGeometry":269,"./geometry/PolygonGeometry":270,"./geometry/RectGeometry":271,"./tag/Alignment":273,"./tag/OutlineTag":276,"./tag/SpotTag":279}],261:[function(require,module,exports){
23891 /// <reference path="../../../typings/index.d.ts" />
23892 "use strict";
23893 var __extends = (this && this.__extends) || function (d, b) {
23894     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23895     function __() { this.constructor = d; }
23896     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23897 };
23898 var Observable_1 = require("rxjs/Observable");
23899 var Subject_1 = require("rxjs/Subject");
23900 require("rxjs/add/observable/combineLatest");
23901 require("rxjs/add/observable/empty");
23902 require("rxjs/add/observable/from");
23903 require("rxjs/add/observable/merge");
23904 require("rxjs/add/observable/of");
23905 require("rxjs/add/operator/combineLatest");
23906 require("rxjs/add/operator/concat");
23907 require("rxjs/add/operator/distinctUntilChanged");
23908 require("rxjs/add/operator/do");
23909 require("rxjs/add/operator/filter");
23910 require("rxjs/add/operator/map");
23911 require("rxjs/add/operator/merge");
23912 require("rxjs/add/operator/mergeMap");
23913 require("rxjs/add/operator/publishReplay");
23914 require("rxjs/add/operator/scan");
23915 require("rxjs/add/operator/share");
23916 require("rxjs/add/operator/skip");
23917 require("rxjs/add/operator/skipUntil");
23918 require("rxjs/add/operator/startWith");
23919 require("rxjs/add/operator/switchMap");
23920 require("rxjs/add/operator/take");
23921 require("rxjs/add/operator/takeUntil");
23922 require("rxjs/add/operator/withLatestFrom");
23923 var Component_1 = require("../../Component");
23924 var Geo_1 = require("../../Geo");
23925 var Render_1 = require("../../Render");
23926 /**
23927  * @class TagComponent
23928  * @classdesc Component for showing and editing tags with different geometries.
23929  */
23930 var TagComponent = (function (_super) {
23931     __extends(TagComponent, _super);
23932     function TagComponent(name, container, navigator) {
23933         var _this = _super.call(this, name, container, navigator) || this;
23934         _this._tagDomRenderer = new Component_1.TagDOMRenderer();
23935         _this._tagSet = new Component_1.TagSet();
23936         _this._tagCreator = new Component_1.TagCreator();
23937         _this._viewportCoords = new Geo_1.ViewportCoords();
23938         _this._tagGlRendererOperation$ = new Subject_1.Subject();
23939         _this._tagGlRenderer$ = _this._tagGlRendererOperation$
23940             .startWith(function (renderer) {
23941             return renderer;
23942         })
23943             .scan(function (renderer, operation) {
23944             return operation(renderer);
23945         }, new Component_1.TagGLRenderer());
23946         _this._tags$ = _this._tagSet.tagData$
23947             .map(function (tagData) {
23948             var tags = [];
23949             // ensure that tags are always rendered in the same order
23950             // to avoid hover tracking problems on first resize.
23951             for (var _i = 0, _a = Object.keys(tagData).sort(); _i < _a.length; _i++) {
23952                 var key = _a[_i];
23953                 tags.push(tagData[key]);
23954             }
23955             return tags;
23956         })
23957             .share();
23958         _this._renderTags$ = _this.tags$
23959             .withLatestFrom(_this._navigator.stateService.currentTransform$)
23960             .map(function (args) {
23961             var tags = args[0];
23962             var transform = args[1];
23963             var renderTags = tags
23964                 .map(function (tag) {
23965                 if (tag instanceof Component_1.OutlineTag) {
23966                     return new Component_1.OutlineRenderTag(tag, transform);
23967                 }
23968                 else if (tag instanceof Component_1.SpotTag) {
23969                     return new Component_1.SpotRenderTag(tag, transform);
23970                 }
23971                 throw new Error("Tag type not supported");
23972             });
23973             return renderTags;
23974         })
23975             .share();
23976         _this._tagChanged$ = _this._tags$
23977             .switchMap(function (tags) {
23978             return Observable_1.Observable
23979                 .from(tags)
23980                 .mergeMap(function (tag) {
23981                 return Observable_1.Observable
23982                     .merge(tag.changed$, tag.geometryChanged$);
23983             });
23984         })
23985             .share();
23986         _this._renderTagGLChanged$ = _this._renderTags$
23987             .switchMap(function (tags) {
23988             return Observable_1.Observable
23989                 .from(tags)
23990                 .mergeMap(function (tag) {
23991                 return tag.glObjectsChanged$;
23992             });
23993         })
23994             .share();
23995         _this._tagInterationInitiated$ = _this._renderTags$
23996             .switchMap(function (tags) {
23997             return Observable_1.Observable
23998                 .from(tags)
23999                 .mergeMap(function (tag) {
24000                 return tag.interact$
24001                     .map(function (interaction) {
24002                     return interaction.tag.id;
24003                 });
24004             });
24005         })
24006             .share();
24007         _this._tagInteractionAbort$ = Observable_1.Observable
24008             .merge(_this._container.mouseService.mouseUp$, _this._container.mouseService.mouseLeave$)
24009             .map(function (e) {
24010             return;
24011         })
24012             .share();
24013         _this._activeTag$ = _this._renderTags$
24014             .switchMap(function (tags) {
24015             return Observable_1.Observable
24016                 .from(tags)
24017                 .mergeMap(function (tag) {
24018                 return tag.interact$;
24019             });
24020         })
24021             .merge(_this._tagInteractionAbort$
24022             .map(function () {
24023             return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
24024         }))
24025             .share();
24026         _this._createGeometryChanged$ = _this._tagCreator.tag$
24027             .switchMap(function (tag) {
24028             return tag != null ?
24029                 tag.geometryChanged$ :
24030                 Observable_1.Observable.empty();
24031         })
24032             .share();
24033         _this._tagCreated$ = _this._tagCreator.tag$
24034             .switchMap(function (tag) {
24035             return tag != null ?
24036                 tag.created$ :
24037                 Observable_1.Observable.empty();
24038         })
24039             .share();
24040         _this._vertexGeometryCreated$ = _this._tagCreated$
24041             .map(function (tag) {
24042             return tag.geometry;
24043         })
24044             .share();
24045         _this._pointGeometryCreated$ = new Subject_1.Subject();
24046         _this._geometryCreated$ = Observable_1.Observable
24047             .merge(_this._vertexGeometryCreated$, _this._pointGeometryCreated$)
24048             .share();
24049         _this._basicClick$ = _this._container.mouseService.staticClick$
24050             .withLatestFrom(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$, function (event, renderCamera, transform) {
24051             return [event, renderCamera, transform];
24052         })
24053             .map(function (ert) {
24054             var event = ert[0];
24055             var camera = ert[1];
24056             var transform = ert[2];
24057             var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
24058             return basic;
24059         })
24060             .share();
24061         _this._validBasicClick$ = _this._basicClick$
24062             .filter(function (basic) {
24063             var x = basic[0];
24064             var y = basic[1];
24065             return 0 <= x && x <= 1 && 0 <= y && y <= 1;
24066         })
24067             .share();
24068         _this._creatingConfiguration$ = _this._configuration$
24069             .distinctUntilChanged(function (c1, c2) {
24070             return c1.creating === c2.creating && c1.createType === c2.createType;
24071         }, function (configuration) {
24072             return {
24073                 createColor: configuration.createColor,
24074                 createType: configuration.createType,
24075                 creating: configuration.creating,
24076             };
24077         })
24078             .publishReplay(1)
24079             .refCount();
24080         _this._creating$ = _this._creatingConfiguration$
24081             .map(function (configuration) {
24082             return configuration.creating;
24083         })
24084             .publishReplay(1)
24085             .refCount();
24086         _this._creating$
24087             .subscribe(function (creating) {
24088             _this.fire(TagComponent.creatingchanged, creating);
24089         });
24090         return _this;
24091     }
24092     Object.defineProperty(TagComponent.prototype, "tags$", {
24093         /**
24094          * Get tags observable.
24095          *
24096          * @description An observable emitting every time the items in the
24097          * tag array changes.
24098          *
24099          * @returns {Observable<Tag[]>}
24100          */
24101         get: function () {
24102             return this._tags$;
24103         },
24104         enumerable: true,
24105         configurable: true
24106     });
24107     Object.defineProperty(TagComponent.prototype, "geometryCreated$", {
24108         /**
24109          * Get geometry created observable.
24110          *
24111          * @description An observable emitting every time a geometry
24112          * has been created.
24113          *
24114          * @returns {Observable<Geometry>}
24115          */
24116         get: function () {
24117             return this._geometryCreated$;
24118         },
24119         enumerable: true,
24120         configurable: true
24121     });
24122     /**
24123      * Set the tags to display.
24124      *
24125      * @param {Tag[]} tags - The tags.
24126      */
24127     TagComponent.prototype.setTags = function (tags) {
24128         this._tagSet.set$.next(tags);
24129     };
24130     /**
24131      * Configure the component to enter create mode for
24132      * creating a geometry of a certain type.
24133      *
24134      * @description Supported geometry types are: rect
24135      *
24136      * @param {string} geometryType - String specifying the geometry type.
24137      */
24138     TagComponent.prototype.startCreate = function (geometryType) {
24139         this.configure({ createType: geometryType, creating: true });
24140     };
24141     /**
24142      * Configure the component to leave create mode.
24143      *
24144      * @description A non completed geometry will be removed.
24145      */
24146     TagComponent.prototype.stopCreate = function () {
24147         this.configure({ createType: null, creating: false });
24148     };
24149     TagComponent.prototype._activate = function () {
24150         var _this = this;
24151         this._geometryCreatedEventSubscription = this._geometryCreated$
24152             .subscribe(function (geometry) {
24153             _this.fire(TagComponent.geometrycreated, geometry);
24154         });
24155         this._tagsChangedEventSubscription = this._tags$
24156             .subscribe(function (tags) {
24157             _this.fire(TagComponent.tagschanged, tags);
24158         });
24159         var nodeChanged$ = this.configuration$
24160             .switchMap(function (configuration) {
24161             return configuration.creating ?
24162                 _this._navigator.stateService.currentNode$
24163                     .skip(1)
24164                     .take(1)
24165                     .map(function (n) { return null; }) :
24166                 Observable_1.Observable.empty();
24167         });
24168         var tagAborted$ = this._tagCreator.tag$
24169             .switchMap(function (tag) {
24170             return tag != null ?
24171                 tag.aborted$
24172                     .map(function (t) { return null; }) :
24173                 Observable_1.Observable.empty();
24174         });
24175         var tagCreated$ = this._tagCreated$
24176             .map(function (t) { return null; });
24177         var pointGeometryCreated$ = this._pointGeometryCreated$
24178             .map(function (p) { return null; });
24179         this._stopCreateSubscription = Observable_1.Observable
24180             .merge(nodeChanged$, tagAborted$, tagCreated$, pointGeometryCreated$)
24181             .subscribe(function () { _this.stopCreate(); });
24182         this._creatorConfigurationSubscription = this._configuration$
24183             .subscribe(this._tagCreator.configuration$);
24184         this._createSubscription = this._creatingConfiguration$
24185             .switchMap(function (configuration) {
24186             return configuration.creating &&
24187                 configuration.createType === "rect" ||
24188                 configuration.createType === "polygon" ?
24189                 _this._validBasicClick$.take(1) :
24190                 Observable_1.Observable.empty();
24191         })
24192             .subscribe(this._tagCreator.create$);
24193         this._createPointSubscription = this._creatingConfiguration$
24194             .switchMap(function (configuration) {
24195             return configuration.creating &&
24196                 configuration.createType === "point" ?
24197                 _this._validBasicClick$.take(1) :
24198                 Observable_1.Observable.empty();
24199         })
24200             .map(function (basic) {
24201             return new Component_1.PointGeometry(basic);
24202         })
24203             .subscribe(this._pointGeometryCreated$);
24204         this._setCreateVertexSubscription = Observable_1.Observable
24205             .combineLatest(this._container.mouseService.mouseMove$, this._tagCreator.tag$, this._container.renderService.renderCamera$)
24206             .filter(function (etr) {
24207             return etr[1] != null;
24208         })
24209             .withLatestFrom(this._navigator.stateService.currentTransform$, function (etr, transform) {
24210             return [etr[0], etr[1], etr[2], transform];
24211         })
24212             .subscribe(function (etrt) {
24213             var event = etrt[0];
24214             var tag = etrt[1];
24215             var camera = etrt[2];
24216             var transform = etrt[3];
24217             var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
24218             if (tag.geometry instanceof Component_1.RectGeometry) {
24219                 tag.geometry.setVertex2d(3, basic, transform);
24220             }
24221             else if (tag.geometry instanceof Component_1.PolygonGeometry) {
24222                 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basic, transform);
24223             }
24224         });
24225         this._addPointSubscription = this._creatingConfiguration$
24226             .switchMap(function (configuration) {
24227             var createType = configuration.createType;
24228             return configuration.creating &&
24229                 (createType === "rect" || createType === "polygon") ?
24230                 _this._basicClick$.skipUntil(_this._validBasicClick$).skip(1) :
24231                 Observable_1.Observable.empty();
24232         })
24233             .withLatestFrom(this._tagCreator.tag$, function (basic, tag) {
24234             return [basic, tag];
24235         })
24236             .subscribe(function (bt) {
24237             var basic = bt[0];
24238             var tag = bt[1];
24239             tag.addPoint(basic);
24240         });
24241         this._deleteCreatedSubscription = this._creating$
24242             .subscribe(function (creating) {
24243             _this._tagCreator.delete$.next(null);
24244         });
24245         this._setGLCreateTagSubscription = Observable_1.Observable
24246             .merge(this._tagCreator.tag$, this._createGeometryChanged$)
24247             .withLatestFrom(this._navigator.stateService.currentTransform$, function (tag, transform) {
24248             return [tag, transform];
24249         })
24250             .map(function (tt) {
24251             return function (renderer) {
24252                 var tag = tt[0];
24253                 var transform = tt[1];
24254                 if (tag == null) {
24255                     renderer.removeCreateTag();
24256                 }
24257                 else {
24258                     renderer.setCreateTag(tag, transform);
24259                 }
24260                 return renderer;
24261             };
24262         })
24263             .subscribe(this._tagGlRendererOperation$);
24264         this._claimMouseSubscription = this._tagInterationInitiated$
24265             .switchMap(function (id) {
24266             return _this._container.mouseService.mouseMove$
24267                 .takeUntil(_this._tagInteractionAbort$)
24268                 .take(1);
24269         })
24270             .subscribe(function (e) {
24271             _this._container.mouseService.claimMouse(_this._name, 1);
24272         });
24273         this._mouseDragSubscription = this._activeTag$
24274             .withLatestFrom(this._container.mouseService.mouseMove$, function (a, e) {
24275             return [a, e];
24276         })
24277             .switchMap(function (args) {
24278             var activeTag = args[0];
24279             var mouseMove = args[1];
24280             if (activeTag.operation === Component_1.TagOperation.None) {
24281                 return Observable_1.Observable.empty();
24282             }
24283             var mouseDrag$ = Observable_1.Observable
24284                 .of(mouseMove)
24285                 .concat(_this._container.mouseService.filtered$(_this._name, _this._container.mouseService.mouseDrag$));
24286             return Observable_1.Observable
24287                 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
24288                 .withLatestFrom(Observable_1.Observable.of(activeTag), _this._navigator.stateService.currentTransform$, function (ec, a, t) {
24289                 return [ec[0], ec[1], a, t];
24290             });
24291         })
24292             .subscribe(function (args) {
24293             var mouseEvent = args[0];
24294             var renderCamera = args[1];
24295             var activeTag = args[2];
24296             var transform = args[3];
24297             if (activeTag.operation === Component_1.TagOperation.None) {
24298                 return;
24299             }
24300             var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, activeTag.offsetX, activeTag.offsetY);
24301             if (activeTag.operation === Component_1.TagOperation.Centroid) {
24302                 activeTag.tag.geometry.setCentroid2d(basic, transform);
24303             }
24304             else if (activeTag.operation === Component_1.TagOperation.Vertex) {
24305                 var vertexGeometry = activeTag.tag.geometry;
24306                 vertexGeometry.setVertex2d(activeTag.vertexIndex, basic, transform);
24307             }
24308         });
24309         this._unclaimMouseSubscription = this._container.mouseService
24310             .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
24311             .subscribe(function (e) {
24312             _this._container.mouseService.unclaimMouse(_this._name);
24313         });
24314         this._setTagsSubscription = this._renderTags$
24315             .map(function (tags) {
24316             return function (renderer) {
24317                 renderer.setTags(tags);
24318                 return renderer;
24319             };
24320         })
24321             .subscribe(this._tagGlRendererOperation$);
24322         this._updateGLTagSubscription = this._renderTagGLChanged$
24323             .map(function (tag) {
24324             return function (renderer) {
24325                 renderer.updateTag(tag);
24326                 return renderer;
24327             };
24328         })
24329             .subscribe(this._tagGlRendererOperation$);
24330         this._setNeedsRenderSubscription = this._tagChanged$
24331             .map(function (tag) {
24332             return function (renderer) {
24333                 renderer.setNeedsRender();
24334                 return renderer;
24335             };
24336         })
24337             .subscribe(this._tagGlRendererOperation$);
24338         this._domSubscription = this._renderTags$
24339             .startWith([])
24340             .do(function (tags) {
24341             _this._container.domRenderer.render$.next({
24342                 name: _this._name,
24343                 vnode: _this._tagDomRenderer.clear(),
24344             });
24345         })
24346             .combineLatest(this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._tagChanged$.startWith(null), this._tagCreator.tag$.merge(this._createGeometryChanged$).startWith(null), this._configuration$, function (renderTags, rc, atlas, tag, ct, c) {
24347             return [rc, atlas, renderTags, tag, ct, c];
24348         })
24349             .withLatestFrom(this._navigator.stateService.currentTransform$, function (args, transform) {
24350             return [args[0], args[1], args[2], args[3], args[4], args[5], transform];
24351         })
24352             .map(function (args) {
24353             return {
24354                 name: _this._name,
24355                 vnode: _this._tagDomRenderer.render(args[2], args[4], args[1], args[0].perspective, args[6], args[5]),
24356             };
24357         })
24358             .subscribe(this._container.domRenderer.render$);
24359         this._glSubscription = this._navigator.stateService.currentState$
24360             .withLatestFrom(this._tagGlRenderer$, function (frame, renderer) {
24361             return [frame, renderer];
24362         })
24363             .map(function (fr) {
24364             var frame = fr[0];
24365             var renderer = fr[1];
24366             return {
24367                 name: _this._name,
24368                 render: {
24369                     frameId: frame.id,
24370                     needsRender: renderer.needsRender,
24371                     render: renderer.render.bind(renderer),
24372                     stage: Render_1.GLRenderStage.Foreground,
24373                 },
24374             };
24375         })
24376             .subscribe(this._container.glRenderer.render$);
24377     };
24378     TagComponent.prototype._deactivate = function () {
24379         this._tagGlRendererOperation$
24380             .next(function (renderer) {
24381             renderer.dispose();
24382             return renderer;
24383         });
24384         this._tagSet.set$.next([]);
24385         this._tagCreator.delete$.next(null);
24386         this._claimMouseSubscription.unsubscribe();
24387         this._mouseDragSubscription.unsubscribe();
24388         this._unclaimMouseSubscription.unsubscribe();
24389         this._setTagsSubscription.unsubscribe();
24390         this._updateGLTagSubscription.unsubscribe();
24391         this._setNeedsRenderSubscription.unsubscribe();
24392         this._stopCreateSubscription.unsubscribe();
24393         this._creatorConfigurationSubscription.unsubscribe();
24394         this._createSubscription.unsubscribe();
24395         this._createPointSubscription.unsubscribe();
24396         this._setCreateVertexSubscription.unsubscribe();
24397         this._addPointSubscription.unsubscribe();
24398         this._deleteCreatedSubscription.unsubscribe();
24399         this._setGLCreateTagSubscription.unsubscribe();
24400         this._domSubscription.unsubscribe();
24401         this._glSubscription.unsubscribe();
24402         this._geometryCreatedEventSubscription.unsubscribe();
24403         this._tagsChangedEventSubscription.unsubscribe();
24404     };
24405     TagComponent.prototype._getDefaultConfiguration = function () {
24406         return {
24407             createColor: 0xFFFFFF,
24408             creating: false,
24409         };
24410     };
24411     TagComponent.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
24412         offsetX = offsetX != null ? offsetX : 0;
24413         offsetY = offsetY != null ? offsetY : 0;
24414         var clientRect = element.getBoundingClientRect();
24415         var canvasX = event.clientX - clientRect.left - offsetX;
24416         var canvasY = event.clientY - clientRect.top - offsetY;
24417         var canvasWidth = element.offsetWidth;
24418         var canvasHeight = element.offsetHeight;
24419         var basic = this._viewportCoords.canvasToBasic(canvasX, canvasY, canvasWidth, canvasHeight, transform, camera.perspective);
24420         return basic;
24421     };
24422     return TagComponent;
24423 }(Component_1.Component));
24424 /** @inheritdoc */
24425 TagComponent.componentName = "tag";
24426 /**
24427  * Event fired when creation starts and stops.
24428  *
24429  * @event TagComponent#creatingchanged
24430  * @type {boolean} Indicates whether the component is creating a tag.
24431  */
24432 TagComponent.creatingchanged = "creatingchanged";
24433 /**
24434  * Event fired when a geometry has been created.
24435  *
24436  * @event TagComponent#geometrycreated
24437  * @type {Geometry} Created geometry.
24438  */
24439 TagComponent.geometrycreated = "geometrycreated";
24440 /**
24441  * Event fired when the tags collection has changed.
24442  *
24443  * @event TagComponent#tagschanged
24444  * @type {Array<Tag>} Current array of tags.
24445  */
24446 TagComponent.tagschanged = "tagschanged";
24447 exports.TagComponent = TagComponent;
24448 Component_1.ComponentService.register(TagComponent);
24449 Object.defineProperty(exports, "__esModule", { value: true });
24450 exports.default = TagComponent;
24451
24452 },{"../../Component":217,"../../Geo":220,"../../Render":223,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/empty":39,"rxjs/add/observable/from":40,"rxjs/add/observable/merge":43,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":50,"rxjs/add/operator/concat":51,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/do":56,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/merge":63,"rxjs/add/operator/mergeMap":65,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/share":71,"rxjs/add/operator/skip":72,"rxjs/add/operator/skipUntil":73,"rxjs/add/operator/startWith":75,"rxjs/add/operator/switchMap":76,"rxjs/add/operator/take":77,"rxjs/add/operator/takeUntil":78,"rxjs/add/operator/withLatestFrom":80}],262:[function(require,module,exports){
24453 "use strict";
24454 var Subject_1 = require("rxjs/Subject");
24455 require("rxjs/add/operator/map");
24456 require("rxjs/add/operator/scan");
24457 require("rxjs/add/operator/share");
24458 require("rxjs/add/operator/withLatestFrom");
24459 var Component_1 = require("../../Component");
24460 var TagCreator = (function () {
24461     function TagCreator() {
24462         this._tagOperation$ = new Subject_1.Subject();
24463         this._create$ = new Subject_1.Subject();
24464         this._delete$ = new Subject_1.Subject();
24465         this._configuration$ = new Subject_1.Subject();
24466         this._tag$ = this._tagOperation$
24467             .scan(function (tag, operation) {
24468             return operation(tag);
24469         }, null)
24470             .share();
24471         this._create$
24472             .withLatestFrom(this._configuration$, function (coordinate, type) {
24473             return [coordinate, type];
24474         })
24475             .map(function (ct) {
24476             return function (tag) {
24477                 var coordinate = ct[0];
24478                 var configuration = ct[1];
24479                 if (configuration.createType === "rect") {
24480                     var geometry = new Component_1.RectGeometry([
24481                         coordinate[0],
24482                         coordinate[1],
24483                         coordinate[0],
24484                         coordinate[1],
24485                     ]);
24486                     return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor });
24487                 }
24488                 else if (configuration.createType === "polygon") {
24489                     var geometry = new Component_1.PolygonGeometry([
24490                         [coordinate[0], coordinate[1]],
24491                         [coordinate[0], coordinate[1]],
24492                         [coordinate[0], coordinate[1]],
24493                     ]);
24494                     return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor });
24495                 }
24496                 return null;
24497             };
24498         })
24499             .subscribe(this._tagOperation$);
24500         this._delete$
24501             .map(function () {
24502             return function (tag) {
24503                 return null;
24504             };
24505         })
24506             .subscribe(this._tagOperation$);
24507     }
24508     Object.defineProperty(TagCreator.prototype, "create$", {
24509         get: function () {
24510             return this._create$;
24511         },
24512         enumerable: true,
24513         configurable: true
24514     });
24515     Object.defineProperty(TagCreator.prototype, "delete$", {
24516         get: function () {
24517             return this._delete$;
24518         },
24519         enumerable: true,
24520         configurable: true
24521     });
24522     Object.defineProperty(TagCreator.prototype, "configuration$", {
24523         get: function () {
24524             return this._configuration$;
24525         },
24526         enumerable: true,
24527         configurable: true
24528     });
24529     Object.defineProperty(TagCreator.prototype, "tag$", {
24530         get: function () {
24531             return this._tag$;
24532         },
24533         enumerable: true,
24534         configurable: true
24535     });
24536     return TagCreator;
24537 }());
24538 exports.TagCreator = TagCreator;
24539 Object.defineProperty(exports, "__esModule", { value: true });
24540 exports.default = TagCreator;
24541
24542 },{"../../Component":217,"rxjs/Subject":33,"rxjs/add/operator/map":62,"rxjs/add/operator/scan":70,"rxjs/add/operator/share":71,"rxjs/add/operator/withLatestFrom":80}],263:[function(require,module,exports){
24543 /// <reference path="../../../typings/index.d.ts" />
24544 "use strict";
24545 var THREE = require("three");
24546 var vd = require("virtual-dom");
24547 var TagDOMRenderer = (function () {
24548     function TagDOMRenderer() {
24549     }
24550     TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, transform, configuration) {
24551         var matrixWorldInverse = new THREE.Matrix4().getInverse(camera.matrixWorld);
24552         var projectionMatrix = camera.projectionMatrix;
24553         var vNodes = [];
24554         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
24555             var tag = tags_1[_i];
24556             vNodes = vNodes.concat(tag.getDOMObjects(atlas, matrixWorldInverse, projectionMatrix));
24557         }
24558         if (createTag != null) {
24559             vNodes = vNodes.concat(createTag.getDOMObjects(transform, matrixWorldInverse, projectionMatrix));
24560         }
24561         var properties = {
24562             style: {
24563                 "pointer-events": configuration.creating ? "all" : "none",
24564             },
24565         };
24566         return vd.h("div.TagContainer", properties, vNodes);
24567     };
24568     TagDOMRenderer.prototype.clear = function () {
24569         return vd.h("div", {}, []);
24570     };
24571     return TagDOMRenderer;
24572 }());
24573 exports.TagDOMRenderer = TagDOMRenderer;
24574
24575 },{"three":167,"virtual-dom":173}],264:[function(require,module,exports){
24576 /// <reference path="../../../typings/index.d.ts" />
24577 "use strict";
24578 var THREE = require("three");
24579 var TagGLRenderer = (function () {
24580     function TagGLRenderer() {
24581         this._scene = new THREE.Scene();
24582         this._tags = {};
24583         this._createTag = null;
24584         this._needsRender = false;
24585     }
24586     Object.defineProperty(TagGLRenderer.prototype, "needsRender", {
24587         get: function () {
24588             return this._needsRender;
24589         },
24590         enumerable: true,
24591         configurable: true
24592     });
24593     TagGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
24594         renderer.render(this._scene, perspectiveCamera);
24595         this._needsRender = false;
24596     };
24597     TagGLRenderer.prototype.setCreateTag = function (tag, transform) {
24598         this._disposeCreateTag();
24599         this._addCreateTag(tag, transform);
24600         this._needsRender = true;
24601     };
24602     TagGLRenderer.prototype.removeCreateTag = function () {
24603         this._disposeCreateTag();
24604         this._needsRender = true;
24605     };
24606     TagGLRenderer.prototype.setTags = function (tags) {
24607         this._disposeTags();
24608         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
24609             var tag = tags_1[_i];
24610             this._addTag(tag);
24611         }
24612         this._needsRender = true;
24613     };
24614     TagGLRenderer.prototype.updateTag = function (tag) {
24615         for (var _i = 0, _a = this._tags[tag.tag.id][1]; _i < _a.length; _i++) {
24616             var object3d = _a[_i];
24617             this._scene.remove(object3d);
24618         }
24619         this._addTag(tag);
24620     };
24621     TagGLRenderer.prototype.setNeedsRender = function () {
24622         this._needsRender = true;
24623     };
24624     TagGLRenderer.prototype.dispose = function () {
24625         this._disposeTags();
24626         this._disposeCreateTag();
24627         this._needsRender = false;
24628     };
24629     TagGLRenderer.prototype._addTag = function (tag) {
24630         var objects = tag.glObjects;
24631         this._tags[tag.tag.id] = [tag, []];
24632         for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) {
24633             var object = objects_1[_i];
24634             this._tags[tag.tag.id][1].push(object);
24635             this._scene.add(object);
24636         }
24637     };
24638     TagGLRenderer.prototype._addCreateTag = function (tag, transform) {
24639         var object = tag.getGLObject(transform);
24640         this._createTag = object;
24641         this._scene.add(object);
24642     };
24643     TagGLRenderer.prototype._disposeTags = function () {
24644         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
24645             var id = _a[_i];
24646             for (var _b = 0, _c = this._tags[id][1]; _b < _c.length; _b++) {
24647                 var object = _c[_b];
24648                 this._scene.remove(object);
24649             }
24650             this._tags[id][0].dispose();
24651             delete this._tags[id];
24652         }
24653     };
24654     TagGLRenderer.prototype._disposeCreateTag = function () {
24655         if (this._createTag == null) {
24656             return;
24657         }
24658         var mesh = this._createTag;
24659         this._scene.remove(mesh);
24660         mesh.geometry.dispose();
24661         mesh.material.dispose();
24662         this._createTag = null;
24663     };
24664     return TagGLRenderer;
24665 }());
24666 exports.TagGLRenderer = TagGLRenderer;
24667
24668 },{"three":167}],265:[function(require,module,exports){
24669 "use strict";
24670 var TagOperation;
24671 (function (TagOperation) {
24672     TagOperation[TagOperation["None"] = 0] = "None";
24673     TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
24674     TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
24675 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
24676 Object.defineProperty(exports, "__esModule", { value: true });
24677 exports.default = TagOperation;
24678
24679 },{}],266:[function(require,module,exports){
24680 "use strict";
24681 var Subject_1 = require("rxjs/Subject");
24682 require("rxjs/add/operator/map");
24683 require("rxjs/add/operator/scan");
24684 require("rxjs/add/operator/share");
24685 var TagSet = (function () {
24686     function TagSet() {
24687         this._tagDataOperation$ = new Subject_1.Subject();
24688         this._set$ = new Subject_1.Subject();
24689         this._tagData$ = this._tagDataOperation$
24690             .scan(function (tagData, operation) {
24691             return operation(tagData);
24692         }, {})
24693             .share();
24694         this._set$
24695             .map(function (tags) {
24696             return function (tagData) {
24697                 for (var _i = 0, _a = Object.keys(tagData); _i < _a.length; _i++) {
24698                     var key = _a[_i];
24699                     delete tagData[key];
24700                 }
24701                 for (var _b = 0, tags_1 = tags; _b < tags_1.length; _b++) {
24702                     var tag = tags_1[_b];
24703                     tagData[tag.id] = tag;
24704                 }
24705                 return tagData;
24706             };
24707         })
24708             .subscribe(this._tagDataOperation$);
24709     }
24710     Object.defineProperty(TagSet.prototype, "tagData$", {
24711         get: function () {
24712             return this._tagData$;
24713         },
24714         enumerable: true,
24715         configurable: true
24716     });
24717     Object.defineProperty(TagSet.prototype, "set$", {
24718         get: function () {
24719             return this._set$;
24720         },
24721         enumerable: true,
24722         configurable: true
24723     });
24724     return TagSet;
24725 }());
24726 exports.TagSet = TagSet;
24727 Object.defineProperty(exports, "__esModule", { value: true });
24728 exports.default = TagSet;
24729
24730 },{"rxjs/Subject":33,"rxjs/add/operator/map":62,"rxjs/add/operator/scan":70,"rxjs/add/operator/share":71}],267:[function(require,module,exports){
24731 "use strict";
24732 var __extends = (this && this.__extends) || function (d, b) {
24733     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24734     function __() { this.constructor = d; }
24735     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24736 };
24737 var Error_1 = require("../../../Error");
24738 var GeometryTagError = (function (_super) {
24739     __extends(GeometryTagError, _super);
24740     function GeometryTagError(message) {
24741         var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
24742         _this.name = "GeometryTagError";
24743         return _this;
24744     }
24745     return GeometryTagError;
24746 }(Error_1.MapillaryError));
24747 exports.GeometryTagError = GeometryTagError;
24748 Object.defineProperty(exports, "__esModule", { value: true });
24749 exports.default = Error_1.MapillaryError;
24750
24751 },{"../../../Error":219}],268:[function(require,module,exports){
24752 "use strict";
24753 var Subject_1 = require("rxjs/Subject");
24754 /**
24755  * @class Geometry
24756  * @abstract
24757  * @classdesc Represents a geometry.
24758  */
24759 var Geometry = (function () {
24760     /**
24761      * Create a geometry.
24762      *
24763      * @constructor
24764      */
24765     function Geometry() {
24766         this._notifyChanged$ = new Subject_1.Subject();
24767     }
24768     Object.defineProperty(Geometry.prototype, "changed$", {
24769         /**
24770          * Get changed observable.
24771          *
24772          * @description Emits the geometry itself every time the geometry
24773          * has changed.
24774          *
24775          * @returns {Observable<Geometry>} Observable emitting the geometry instance.
24776          */
24777         get: function () {
24778             return this._notifyChanged$;
24779         },
24780         enumerable: true,
24781         configurable: true
24782     });
24783     return Geometry;
24784 }());
24785 exports.Geometry = Geometry;
24786 Object.defineProperty(exports, "__esModule", { value: true });
24787 exports.default = Geometry;
24788
24789 },{"rxjs/Subject":33}],269:[function(require,module,exports){
24790 "use strict";
24791 var __extends = (this && this.__extends) || function (d, b) {
24792     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24793     function __() { this.constructor = d; }
24794     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24795 };
24796 var Component_1 = require("../../../Component");
24797 /**
24798  * @class PointGeometry
24799  * @classdesc Represents a point geometry in the basic coordinate system.
24800  */
24801 var PointGeometry = (function (_super) {
24802     __extends(PointGeometry, _super);
24803     /**
24804      * Create a point geometry.
24805      *
24806      * @constructor
24807      * @param {Array<number>} point - An array representing the basic coordinates of
24808      * the point.
24809      *
24810      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
24811      */
24812     function PointGeometry(point) {
24813         var _this = _super.call(this) || this;
24814         var x = point[0];
24815         var y = point[1];
24816         if (x < 0 || x > 1 || y < 0 || y > 1) {
24817             throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
24818         }
24819         _this._point = point.slice();
24820         return _this;
24821     }
24822     Object.defineProperty(PointGeometry.prototype, "point", {
24823         /**
24824          * Get point property.
24825          * @returns {Array<number>} Array representing the basic coordinates of the point.
24826          */
24827         get: function () {
24828             return this._point;
24829         },
24830         enumerable: true,
24831         configurable: true
24832     });
24833     /**
24834      * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
24835      * world coordinates of the point itself.
24836      *
24837      * @param {Transform} transform - The transform of the node related to the point.
24838      * @returns {Array<number>} 3D world coordinates representing the centroid.
24839      */
24840     PointGeometry.prototype.getCentroid3d = function (transform) {
24841         return transform.unprojectBasic(this._point, 200);
24842     };
24843     /**
24844      * Set the centroid of the point, i.e. the point coordinates.
24845      *
24846      * @param {Array<number>} value - The new value of the centroid.
24847      * @param {Transform} transform - The transform of the node related to the point.
24848      */
24849     PointGeometry.prototype.setCentroid2d = function (value, transform) {
24850         var changed = [
24851             Math.max(0, Math.min(1, value[0])),
24852             Math.max(0, Math.min(1, value[1])),
24853         ];
24854         this._point[0] = changed[0];
24855         this._point[1] = changed[1];
24856         this._notifyChanged$.next(this);
24857     };
24858     return PointGeometry;
24859 }(Component_1.Geometry));
24860 exports.PointGeometry = PointGeometry;
24861
24862 },{"../../../Component":217}],270:[function(require,module,exports){
24863 "use strict";
24864 var __extends = (this && this.__extends) || function (d, b) {
24865     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24866     function __() { this.constructor = d; }
24867     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24868 };
24869 var Component_1 = require("../../../Component");
24870 /**
24871  * @class PolygonGeometry
24872  * @classdesc Represents a polygon geometry in the basic coordinate system.
24873  */
24874 var PolygonGeometry = (function (_super) {
24875     __extends(PolygonGeometry, _super);
24876     /**
24877      * Create a polygon geometry.
24878      *
24879      * @constructor
24880      * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
24881      * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
24882      * Each array of holes vertices must be closed.
24883      *
24884      * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
24885      */
24886     function PolygonGeometry(polygon, holes) {
24887         var _this = _super.call(this) || this;
24888         var polygonLength = polygon.length;
24889         if (polygonLength < 3) {
24890             throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
24891         }
24892         if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
24893             polygon[0][1] !== polygon[polygonLength - 1][1]) {
24894             throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
24895         }
24896         _this._polygon = [];
24897         for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
24898             var vertex = polygon_1[_i];
24899             if (vertex[0] < 0 || vertex[0] > 1 ||
24900                 vertex[1] < 0 || vertex[1] > 1) {
24901                 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
24902             }
24903             _this._polygon.push(vertex.slice());
24904         }
24905         _this._holes = [];
24906         if (holes == null) {
24907             return _this;
24908         }
24909         for (var i = 0; i < holes.length; i++) {
24910             var hole = holes[i];
24911             var holeLength = hole.length;
24912             if (holeLength < 3) {
24913                 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
24914             }
24915             if (hole[0][0] !== hole[holeLength - 1][0] ||
24916                 hole[0][1] !== hole[holeLength - 1][1]) {
24917                 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
24918             }
24919             _this._holes.push([]);
24920             for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
24921                 var vertex = hole_1[_a];
24922                 if (vertex[0] < 0 || vertex[0] > 1 ||
24923                     vertex[1] < 0 || vertex[1] > 1) {
24924                     throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
24925                 }
24926                 _this._holes[i].push(vertex.slice());
24927             }
24928         }
24929         return _this;
24930     }
24931     Object.defineProperty(PolygonGeometry.prototype, "polygon", {
24932         /**
24933          * Get polygon property.
24934          * @returns {Array<Array<number>>} Closed 2d polygon.
24935          */
24936         get: function () {
24937             return this._polygon;
24938         },
24939         enumerable: true,
24940         configurable: true
24941     });
24942     Object.defineProperty(PolygonGeometry.prototype, "holes", {
24943         /**
24944          * Get holes property.
24945          * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
24946          */
24947         get: function () {
24948             return this._holes;
24949         },
24950         enumerable: true,
24951         configurable: true
24952     });
24953     /**
24954      * Add a vertex to the polygon by appending it after the last vertex.
24955      *
24956      * @param {Array<number>} vertex - Vertex to add.
24957      */
24958     PolygonGeometry.prototype.addVertex2d = function (vertex) {
24959         var clamped = [
24960             Math.max(0, Math.min(1, vertex[0])),
24961             Math.max(0, Math.min(1, vertex[1])),
24962         ];
24963         this._polygon.splice(this._polygon.length - 1, 0, clamped);
24964         this._notifyChanged$.next(this);
24965     };
24966     /**
24967      * Remove a vertex from the polygon.
24968      *
24969      * @param {number} index - The index of the vertex to remove.
24970      */
24971     PolygonGeometry.prototype.removeVertex2d = function (index) {
24972         if (index < 0 ||
24973             index >= this._polygon.length ||
24974             this._polygon.length < 4) {
24975             throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
24976         }
24977         if (index > 0 && index < this._polygon.length - 1) {
24978             this._polygon.splice(index, 1);
24979         }
24980         else {
24981             this._polygon.splice(0, 1);
24982             this._polygon.pop();
24983             var closing = this._polygon[0].slice();
24984             this._polygon.push(closing);
24985         }
24986         this._notifyChanged$.next(this);
24987     };
24988     /** @inheritdoc */
24989     PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
24990         var changed = [
24991             Math.max(0, Math.min(1, value[0])),
24992             Math.max(0, Math.min(1, value[1])),
24993         ];
24994         if (index === 0 || index === this._polygon.length - 1) {
24995             this._polygon[0] = changed.slice();
24996             this._polygon[this._polygon.length - 1] = changed.slice();
24997         }
24998         else {
24999             this._polygon[index] = changed.slice();
25000         }
25001         this._notifyChanged$.next(this);
25002     };
25003     /** @inheritdoc */
25004     PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
25005         var xs = this._polygon.map(function (point) { return point[0]; });
25006         var ys = this._polygon.map(function (point) { return point[1]; });
25007         var minX = Math.min.apply(Math, xs);
25008         var maxX = Math.max.apply(Math, xs);
25009         var minY = Math.min.apply(Math, ys);
25010         var maxY = Math.max.apply(Math, ys);
25011         var centroid = this._getCentroid2d();
25012         var minTranslationX = -minX;
25013         var maxTranslationX = 1 - maxX;
25014         var minTranslationY = -minY;
25015         var maxTranslationY = 1 - maxY;
25016         var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
25017         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
25018         for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
25019             var point = _a[_i];
25020             point[0] += translationX;
25021             point[1] += translationY;
25022         }
25023         this._notifyChanged$.next(this);
25024     };
25025     /** @inheritdoc */
25026     PolygonGeometry.prototype.getPoints3d = function (transform) {
25027         return this.getVertices3d(transform);
25028     };
25029     /** @inheritdoc */
25030     PolygonGeometry.prototype.getVertex3d = function (index, transform) {
25031         return transform.unprojectBasic(this._polygon[index], 200);
25032     };
25033     /** @inheritdoc */
25034     PolygonGeometry.prototype.getVertices3d = function (transform) {
25035         return this._polygon
25036             .map(function (point) {
25037             return transform.unprojectBasic(point, 200);
25038         });
25039     };
25040     /**
25041      * Get a polygon representation of the 3D coordinates for the vertices of each hole
25042      * of the geometry.
25043      *
25044      * @param {Transform} transform - The transform of the node related to the geometry.
25045      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
25046      * representing the vertices of each hole of the geometry.
25047      */
25048     PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
25049         var holes3d = [];
25050         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
25051             var hole = _a[_i];
25052             var hole3d = hole
25053                 .map(function (point) {
25054                 return transform.unprojectBasic(point, 200);
25055             });
25056             holes3d.push(hole3d);
25057         }
25058         return holes3d;
25059     };
25060     /** @inheritdoc */
25061     PolygonGeometry.prototype.getCentroid3d = function (transform) {
25062         var centroid2d = this._getCentroid2d();
25063         return transform.unprojectBasic(centroid2d, 200);
25064     };
25065     /** @inheritdoc */
25066     PolygonGeometry.prototype.getTriangles3d = function (transform) {
25067         return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
25068     };
25069     PolygonGeometry.prototype._getCentroid2d = function () {
25070         var polygon = this._polygon;
25071         var area = 0;
25072         var centroidX = 0;
25073         var centroidY = 0;
25074         for (var i = 0; i < polygon.length - 1; i++) {
25075             var xi = polygon[i][0];
25076             var yi = polygon[i][1];
25077             var xi1 = polygon[i + 1][0];
25078             var yi1 = polygon[i + 1][1];
25079             var a = xi * yi1 - xi1 * yi;
25080             area += a;
25081             centroidX += (xi + xi1) * a;
25082             centroidY += (yi + yi1) * a;
25083         }
25084         area /= 2;
25085         centroidX /= 6 * area;
25086         centroidY /= 6 * area;
25087         return [centroidX, centroidY];
25088     };
25089     return PolygonGeometry;
25090 }(Component_1.VertexGeometry));
25091 exports.PolygonGeometry = PolygonGeometry;
25092 Object.defineProperty(exports, "__esModule", { value: true });
25093 exports.default = PolygonGeometry;
25094
25095 },{"../../../Component":217}],271:[function(require,module,exports){
25096 "use strict";
25097 var __extends = (this && this.__extends) || function (d, b) {
25098     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25099     function __() { this.constructor = d; }
25100     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25101 };
25102 var Component_1 = require("../../../Component");
25103 /**
25104  * @class RectGeometry
25105  * @classdesc Represents a rectangle geometry in the basic coordinate system.
25106  */
25107 var RectGeometry = (function (_super) {
25108     __extends(RectGeometry, _super);
25109     /**
25110      * Create a rectangle geometry.
25111      *
25112      * @constructor
25113      * @param {Array<number>} rect - An array representing the top-left and bottom-right
25114      * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
25115      *
25116      * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
25117      */
25118     function RectGeometry(rect) {
25119         var _this = _super.call(this) || this;
25120         if (rect[1] > rect[3]) {
25121             throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
25122         }
25123         for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
25124             var coord = rect_1[_i];
25125             if (coord < 0 || coord > 1) {
25126                 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
25127             }
25128         }
25129         _this._rect = rect.slice(0, 4);
25130         if (_this._rect[0] > _this._rect[2]) {
25131             _this._inverted = true;
25132         }
25133         return _this;
25134     }
25135     Object.defineProperty(RectGeometry.prototype, "rect", {
25136         /**
25137          * Get rect property.
25138          * @returns {Array<number>} Array representing the top-left and bottom-right
25139          * corners of the rectangle in basic coordinates.
25140          */
25141         get: function () {
25142             return this._rect;
25143         },
25144         enumerable: true,
25145         configurable: true
25146     });
25147     /**
25148      * Set the value of a vertex in the polygon representation of the rectangle.
25149      *
25150      * @description The polygon is defined to have the first vertex at the
25151      * bottom-left corner with the rest of the vertices following in clockwise order.
25152      *
25153      * @param {number} index - The index of the vertex to be set.
25154      * @param {Array<number>} value - The new value of the vertex.
25155      * @param {Transform} transform - The transform of the node related to the rectangle.
25156      */
25157     RectGeometry.prototype.setVertex2d = function (index, value, transform) {
25158         var original = this._rect.slice();
25159         var changed = [
25160             Math.max(0, Math.min(1, value[0])),
25161             Math.max(0, Math.min(1, value[1])),
25162         ];
25163         var rect = [];
25164         if (index === 0) {
25165             rect[0] = changed[0];
25166             rect[1] = original[1];
25167             rect[2] = original[2];
25168             rect[3] = changed[1];
25169         }
25170         else if (index === 1) {
25171             rect[0] = changed[0];
25172             rect[1] = changed[1];
25173             rect[2] = original[2];
25174             rect[3] = original[3];
25175         }
25176         else if (index === 2) {
25177             rect[0] = original[0];
25178             rect[1] = changed[1];
25179             rect[2] = changed[0];
25180             rect[3] = original[3];
25181         }
25182         else if (index === 3) {
25183             rect[0] = original[0];
25184             rect[1] = original[1];
25185             rect[2] = changed[0];
25186             rect[3] = changed[1];
25187         }
25188         if (transform.gpano) {
25189             var passingBoundaryLeft = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
25190                 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
25191             var passingBoundaryRight = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
25192                 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
25193             if (passingBoundaryLeft || passingBoundaryRight) {
25194                 this._inverted = !this._inverted;
25195             }
25196             else {
25197                 if (rect[0] - original[0] < -0.25) {
25198                     rect[0] = original[0];
25199                 }
25200                 if (rect[2] - original[2] > 0.25) {
25201                     rect[2] = original[2];
25202                 }
25203             }
25204             if (!this._inverted && rect[0] > rect[2] ||
25205                 this._inverted && rect[0] < rect[2]) {
25206                 rect[0] = original[0];
25207                 rect[2] = original[2];
25208             }
25209         }
25210         else {
25211             if (rect[0] > rect[2]) {
25212                 rect[0] = original[0];
25213                 rect[2] = original[2];
25214             }
25215         }
25216         if (rect[1] > rect[3]) {
25217             rect[1] = original[1];
25218             rect[3] = original[3];
25219         }
25220         this._rect[0] = rect[0];
25221         this._rect[1] = rect[1];
25222         this._rect[2] = rect[2];
25223         this._rect[3] = rect[3];
25224         this._notifyChanged$.next(this);
25225     };
25226     /** @inheritdoc */
25227     RectGeometry.prototype.setCentroid2d = function (value, transform) {
25228         var original = this._rect.slice();
25229         var x0 = original[0];
25230         var x1 = this._inverted ? original[2] + 1 : original[2];
25231         var y0 = original[1];
25232         var y1 = original[3];
25233         var centerX = x0 + (x1 - x0) / 2;
25234         var centerY = y0 + (y1 - y0) / 2;
25235         var translationX = 0;
25236         if (transform.gpano != null &&
25237             transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
25238             translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
25239         }
25240         else {
25241             var minTranslationX = -x0;
25242             var maxTranslationX = 1 - x1;
25243             translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
25244         }
25245         var minTranslationY = -y0;
25246         var maxTranslationY = 1 - y1;
25247         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
25248         this._rect[0] = original[0] + translationX;
25249         this._rect[1] = original[1] + translationY;
25250         this._rect[2] = original[2] + translationX;
25251         this._rect[3] = original[3] + translationY;
25252         if (this._rect[0] < 0) {
25253             this._rect[0] += 1;
25254             this._inverted = !this._inverted;
25255         }
25256         else if (this._rect[0] > 1) {
25257             this._rect[0] -= 1;
25258             this._inverted = !this._inverted;
25259         }
25260         if (this._rect[2] < 0) {
25261             this._rect[2] += 1;
25262             this._inverted = !this._inverted;
25263         }
25264         else if (this._rect[2] > 1) {
25265             this._rect[2] -= 1;
25266             this._inverted = !this._inverted;
25267         }
25268         this._notifyChanged$.next(this);
25269     };
25270     /**
25271      * Get the 3D coordinates for the vertices of the rectangle with
25272      * interpolated points along the lines.
25273      *
25274      * @param {Transform} transform - The transform of the node related to
25275      * the rectangle.
25276      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
25277      * representing the rectangle.
25278      */
25279     RectGeometry.prototype.getPoints3d = function (transform) {
25280         return this._getPoints2d(transform)
25281             .map(function (point) {
25282             return transform.unprojectBasic(point, 200);
25283         });
25284     };
25285     /**
25286      * Get a vertex from the polygon representation of the 3D coordinates for the
25287      * vertices of the geometry.
25288      *
25289      * @description The first vertex represents the bottom-left corner with the rest of
25290      * the vertices following in clockwise order.
25291      *
25292      * @param {number} index - Vertex index.
25293      * @param {Transform} transform - The transform of the node related to the geometry.
25294      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
25295      * the vertices of the geometry.
25296      */
25297     RectGeometry.prototype.getVertex3d = function (index, transform) {
25298         return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
25299     };
25300     /**
25301      * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
25302      *
25303      * @description The first vertex represents the bottom-left corner with the rest of
25304      * the vertices following in clockwise order.
25305      *
25306      * @param {Transform} transform - The transform of the node related to the rectangle.
25307      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
25308      * the rectangle vertices.
25309      */
25310     RectGeometry.prototype.getVertices3d = function (transform) {
25311         return this._rectToVertices2d(this._rect)
25312             .map(function (vertex) {
25313             return transform.unprojectBasic(vertex, 200);
25314         });
25315     };
25316     /** @inheritdoc */
25317     RectGeometry.prototype.getCentroid3d = function (transform) {
25318         var rect = this._rect;
25319         var x0 = rect[0];
25320         var x1 = this._inverted ? rect[2] + 1 : rect[2];
25321         var y0 = rect[1];
25322         var y1 = rect[3];
25323         var centroidX = x0 + (x1 - x0) / 2;
25324         var centroidY = y0 + (y1 - y0) / 2;
25325         return transform.unprojectBasic([centroidX, centroidY], 200);
25326     };
25327     /** @inheritdoc */
25328     RectGeometry.prototype.getTriangles3d = function (transform) {
25329         return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
25330     };
25331     /**
25332      * Check if a particular bottom-right value is valid according to the current
25333      * rectangle coordinates.
25334      *
25335      * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
25336      * @returns {boolean} Value indicating whether the provided bottom-right coordinates
25337      * are valid.
25338      */
25339     RectGeometry.prototype.validate = function (bottomRight) {
25340         var rect = this._rect;
25341         if (!this._inverted && bottomRight[0] < rect[0] ||
25342             bottomRight[0] - rect[2] > 0.25 ||
25343             bottomRight[1] < rect[1]) {
25344             return false;
25345         }
25346         return true;
25347     };
25348     /**
25349      * Get the 2D coordinates for the vertices of the rectangle with
25350      * interpolated points along the lines.
25351      *
25352      * @param {Transform} transform - The transform of the node related to
25353      * the rectangle.
25354      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
25355      * representing the rectangle.
25356      */
25357     RectGeometry.prototype._getPoints2d = function (transform) {
25358         var vertices2d = this._rectToVertices2d(this._rect);
25359         var sides = vertices2d.length - 1;
25360         var sections = 10;
25361         var points2d = [];
25362         for (var i = 0; i < sides; ++i) {
25363             var startX = vertices2d[i][0];
25364             var startY = vertices2d[i][1];
25365             var endX = vertices2d[i + 1][0];
25366             var endY = vertices2d[i + 1][1];
25367             var intervalX = (endX - startX) / (sections - 1);
25368             var intervalY = (endY - startY) / (sections - 1);
25369             for (var j = 0; j < sections; ++j) {
25370                 var point = [
25371                     startX + j * intervalX,
25372                     startY + j * intervalY,
25373                 ];
25374                 points2d.push(point);
25375             }
25376         }
25377         return points2d;
25378     };
25379     /**
25380      * Convert the top-left, bottom-right representation of a rectangle to a polygon
25381      * representation of the vertices starting at the bottom-right corner going
25382      * clockwise.
25383      *
25384      * @param {Array<number>} rect - Top-left, bottom-right representation of a
25385      * rectangle.
25386      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
25387      * rectangle.
25388      */
25389     RectGeometry.prototype._rectToVertices2d = function (rect) {
25390         return [
25391             [rect[0], rect[3]],
25392             [rect[0], rect[1]],
25393             [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
25394             [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
25395             [rect[0], rect[3]],
25396         ];
25397     };
25398     return RectGeometry;
25399 }(Component_1.VertexGeometry));
25400 exports.RectGeometry = RectGeometry;
25401 Object.defineProperty(exports, "__esModule", { value: true });
25402 exports.default = RectGeometry;
25403
25404 },{"../../../Component":217}],272:[function(require,module,exports){
25405 /// <reference path="../../../../typings/index.d.ts" />
25406 "use strict";
25407 var __extends = (this && this.__extends) || function (d, b) {
25408     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25409     function __() { this.constructor = d; }
25410     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25411 };
25412 var earcut = require("earcut");
25413 var Component_1 = require("../../../Component");
25414 /**
25415  * @class VertexGeometry
25416  * @abstract
25417  * @classdesc Represents a vertex geometry.
25418  */
25419 var VertexGeometry = (function (_super) {
25420     __extends(VertexGeometry, _super);
25421     /**
25422      * Create a vertex geometry.
25423      *
25424      * @constructor
25425      */
25426     function VertexGeometry() {
25427         return _super.call(this) || this;
25428     }
25429     /**
25430      * Triangulates a 2d polygon and returns the triangle
25431      * representation as a flattened array of 3d points.
25432      *
25433      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
25434      * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
25435      * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
25436      * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
25437      * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
25438      */
25439     VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
25440         var data = [points2d.slice(0, -1)];
25441         for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
25442             var hole2d = _a[_i];
25443             data.push(hole2d.slice(0, -1));
25444         }
25445         var points = points3d.slice(0, -1);
25446         for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
25447             var hole3d = _c[_b];
25448             points = points.concat(hole3d.slice(0, -1));
25449         }
25450         var flattened = earcut.flatten(data);
25451         var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
25452         var triangles = [];
25453         for (var i = 0; i < indices.length; ++i) {
25454             var point = points[indices[i]];
25455             triangles.push(point[0]);
25456             triangles.push(point[1]);
25457             triangles.push(point[2]);
25458         }
25459         return triangles;
25460     };
25461     return VertexGeometry;
25462 }(Component_1.Geometry));
25463 exports.VertexGeometry = VertexGeometry;
25464 Object.defineProperty(exports, "__esModule", { value: true });
25465 exports.default = VertexGeometry;
25466
25467 },{"../../../Component":217,"earcut":6}],273:[function(require,module,exports){
25468 "use strict";
25469 var Alignment;
25470 (function (Alignment) {
25471     Alignment[Alignment["Center"] = 0] = "Center";
25472     Alignment[Alignment["Outer"] = 1] = "Outer";
25473 })(Alignment = exports.Alignment || (exports.Alignment = {}));
25474 Object.defineProperty(exports, "__esModule", { value: true });
25475 exports.default = Alignment;
25476
25477 },{}],274:[function(require,module,exports){
25478 /// <reference path="../../../../typings/index.d.ts" />
25479 "use strict";
25480 var THREE = require("three");
25481 var vd = require("virtual-dom");
25482 var Subject_1 = require("rxjs/Subject");
25483 var Component_1 = require("../../../Component");
25484 var OutlineCreateTag = (function () {
25485     function OutlineCreateTag(geometry, options) {
25486         this._geometry = geometry;
25487         this._options = { color: options.color == null ? 0xFFFFFF : options.color };
25488         this._created$ = new Subject_1.Subject();
25489         this._aborted$ = new Subject_1.Subject();
25490     }
25491     Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
25492         get: function () {
25493             return this._geometry;
25494         },
25495         enumerable: true,
25496         configurable: true
25497     });
25498     Object.defineProperty(OutlineCreateTag.prototype, "created$", {
25499         get: function () {
25500             return this._created$;
25501         },
25502         enumerable: true,
25503         configurable: true
25504     });
25505     Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
25506         get: function () {
25507             return this._aborted$;
25508         },
25509         enumerable: true,
25510         configurable: true
25511     });
25512     Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
25513         get: function () {
25514             var _this = this;
25515             return this._geometry.changed$
25516                 .map(function (geometry) {
25517                 return _this;
25518             });
25519         },
25520         enumerable: true,
25521         configurable: true
25522     });
25523     OutlineCreateTag.prototype.getGLObject = function (transform) {
25524         var polygon3d = this._geometry.getPoints3d(transform);
25525         var positions = this._getPositions(polygon3d);
25526         var geometry = new THREE.BufferGeometry();
25527         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
25528         var material = new THREE.LineBasicMaterial({
25529             color: this._options.color,
25530             linewidth: 1,
25531         });
25532         return new THREE.Line(geometry, material);
25533     };
25534     OutlineCreateTag.prototype.getDOMObjects = function (transform, matrixWorldInverse, projectionMatrix) {
25535         var _this = this;
25536         var vNodes = [];
25537         var abort = function (e) {
25538             e.stopPropagation();
25539             _this._aborted$.next(_this);
25540         };
25541         if (this._geometry instanceof Component_1.RectGeometry) {
25542             var topLeftPoint3d = this._geometry.getVertex3d(1, transform);
25543             var topLeftCameraSpace = this._convertToCameraSpace(topLeftPoint3d, matrixWorldInverse);
25544             if (topLeftCameraSpace.z < 0) {
25545                 var centerCanvas = this._projectToCanvas(topLeftCameraSpace, projectionMatrix);
25546                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
25547                 var pointProperties = {
25548                     style: {
25549                         background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
25550                         left: centerCss[0],
25551                         position: "absolute",
25552                         top: centerCss[1],
25553                     },
25554                 };
25555                 var completerProperties = {
25556                     onclick: abort,
25557                     style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
25558                 };
25559                 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
25560                 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
25561             }
25562         }
25563         else if (this._geometry instanceof Component_1.PolygonGeometry) {
25564             var polygonGeometry_1 = this._geometry;
25565             var firstVertex3d = this._geometry.getVertex3d(0, transform);
25566             var firstCameraSpace = this._convertToCameraSpace(firstVertex3d, matrixWorldInverse);
25567             if (firstCameraSpace.z < 0) {
25568                 var centerCanvas = this._projectToCanvas(firstCameraSpace, projectionMatrix);
25569                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
25570                 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
25571                     function (e) {
25572                         e.stopPropagation();
25573                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
25574                         _this._created$.next(_this);
25575                     } :
25576                     abort;
25577                 var completerProperties = {
25578                     onclick: firstOnclick,
25579                     style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
25580                 };
25581                 var firstClass = polygonGeometry_1.polygon.length > 4 ?
25582                     "TagCompleter" :
25583                     "TagInteractor";
25584                 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
25585             }
25586             if (polygonGeometry_1.polygon.length > 3) {
25587                 var lastVertex3d = this._geometry.getVertex3d(polygonGeometry_1.polygon.length - 3, transform);
25588                 var lastCameraSpace = this._convertToCameraSpace(lastVertex3d, matrixWorldInverse);
25589                 if (lastCameraSpace.z < 0) {
25590                     var centerCanvas = this._projectToCanvas(lastCameraSpace, projectionMatrix);
25591                     var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
25592                     var remove = function (e) {
25593                         e.stopPropagation();
25594                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
25595                     };
25596                     var completerProperties = {
25597                         onclick: remove,
25598                         style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
25599                     };
25600                     vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
25601                 }
25602             }
25603             var vertices3d = this._geometry.getVertices3d(transform);
25604             vertices3d.splice(-2, 2);
25605             for (var _i = 0, vertices3d_1 = vertices3d; _i < vertices3d_1.length; _i++) {
25606                 var vertex = vertices3d_1[_i];
25607                 var vertexCameraSpace = this._convertToCameraSpace(vertex, matrixWorldInverse);
25608                 if (vertexCameraSpace.z < 0) {
25609                     var centerCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
25610                     var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
25611                     var pointProperties = {
25612                         style: {
25613                             background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
25614                             left: centerCss[0],
25615                             position: "absolute",
25616                             top: centerCss[1],
25617                         },
25618                     };
25619                     vNodes.push(vd.h("div.TagVertex", pointProperties, []));
25620                 }
25621             }
25622         }
25623         return vNodes;
25624     };
25625     OutlineCreateTag.prototype.addPoint = function (point) {
25626         if (this._geometry instanceof Component_1.RectGeometry) {
25627             var rectGeometry = this._geometry;
25628             if (!rectGeometry.validate(point)) {
25629                 return;
25630             }
25631             this._created$.next(this);
25632         }
25633         else if (this._geometry instanceof Component_1.PolygonGeometry) {
25634             var polygonGeometry = this._geometry;
25635             polygonGeometry.addVertex2d(point);
25636         }
25637     };
25638     OutlineCreateTag.prototype._getPositions = function (polygon3d) {
25639         var length = polygon3d.length;
25640         var positions = new Float32Array(length * 3);
25641         for (var i = 0; i < length; ++i) {
25642             var index = 3 * i;
25643             var position = polygon3d[i];
25644             positions[index] = position[0];
25645             positions[index + 1] = position[1];
25646             positions[index + 2] = position[2];
25647         }
25648         return positions;
25649     };
25650     OutlineCreateTag.prototype._projectToCanvas = function (point, projectionMatrix) {
25651         var projected = new THREE.Vector3(point.x, point.y, point.z)
25652             .applyProjection(projectionMatrix);
25653         return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
25654     };
25655     OutlineCreateTag.prototype._convertToCameraSpace = function (point, matrixWorldInverse) {
25656         return new THREE.Vector3(point[0], point[1], point[2]).applyMatrix4(matrixWorldInverse);
25657     };
25658     return OutlineCreateTag;
25659 }());
25660 exports.OutlineCreateTag = OutlineCreateTag;
25661 Object.defineProperty(exports, "__esModule", { value: true });
25662 exports.default = OutlineCreateTag;
25663
25664 },{"../../../Component":217,"rxjs/Subject":33,"three":167,"virtual-dom":173}],275:[function(require,module,exports){
25665 /// <reference path="../../../../typings/index.d.ts" />
25666 "use strict";
25667 var __extends = (this && this.__extends) || function (d, b) {
25668     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25669     function __() { this.constructor = d; }
25670     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25671 };
25672 var THREE = require("three");
25673 var vd = require("virtual-dom");
25674 var Component_1 = require("../../../Component");
25675 var Viewer_1 = require("../../../Viewer");
25676 /**
25677  * @class OutlineRenderTag
25678  * @classdesc Tag visualizing the properties of an OutlineTag.
25679  */
25680 var OutlineRenderTag = (function (_super) {
25681     __extends(OutlineRenderTag, _super);
25682     function OutlineRenderTag(tag, transform) {
25683         var _this = _super.call(this, tag, transform) || this;
25684         _this._fill = _this._tag.fillOpacity > 0 && !transform.gpano ?
25685             _this._createFill() :
25686             null;
25687         _this._holes = _this._tag.lineWidth >= 1 ?
25688             _this._createHoles() :
25689             [];
25690         _this._outline = _this._tag.lineWidth >= 1 ?
25691             _this._createOutline() :
25692             null;
25693         _this._glObjects = _this._createGLObjects();
25694         _this._tag.geometry.changed$
25695             .subscribe(function (geometry) {
25696             if (_this._fill != null) {
25697                 _this._updateFillGeometry();
25698             }
25699             if (_this._holes.length > 0) {
25700                 _this._updateHoleGeometries();
25701             }
25702             if (_this._outline != null) {
25703                 _this._updateOulineGeometry();
25704             }
25705         });
25706         _this._tag.changed$
25707             .subscribe(function (changedTag) {
25708             var glObjectsChanged = false;
25709             if (_this._fill == null) {
25710                 if (_this._tag.fillOpacity > 0 && !_this._transform.gpano) {
25711                     _this._fill = _this._createFill();
25712                     glObjectsChanged = true;
25713                 }
25714             }
25715             else {
25716                 _this._updateFillMaterial();
25717             }
25718             if (_this._outline == null) {
25719                 if (_this._tag.lineWidth > 0) {
25720                     _this._holes = _this._createHoles();
25721                     _this._outline = _this._createOutline();
25722                     glObjectsChanged = true;
25723                 }
25724             }
25725             else {
25726                 _this._updateHoleMaterials();
25727                 _this._updateOutlineMaterial();
25728             }
25729             if (glObjectsChanged) {
25730                 _this._glObjects = _this._createGLObjects();
25731                 _this._glObjectsChanged$.next(_this);
25732             }
25733         });
25734         return _this;
25735     }
25736     OutlineRenderTag.prototype.dispose = function () {
25737         this._disposeFill();
25738         this._disposeHoles();
25739         this._disposeOutline();
25740     };
25741     OutlineRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
25742         var _this = this;
25743         var vNodes = [];
25744         if (this._tag.geometry instanceof Component_1.RectGeometry) {
25745             if (this._tag.icon != null) {
25746                 var iconVertex = this._tag.geometry.getVertex3d(this._tag.iconIndex, this._transform);
25747                 var iconCameraSpace = this._convertToCameraSpace(iconVertex, matrixWorldInverse);
25748                 if (iconCameraSpace.z < 0) {
25749                     var interact = function (e) {
25750                         _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
25751                     };
25752                     if (atlas.loaded) {
25753                         var spriteAlignments = this._getSpriteAlignment(this._tag.iconIndex, this._tag.iconAlignment);
25754                         var sprite = atlas.getDOMSprite(this._tag.icon, spriteAlignments[0], spriteAlignments[1]);
25755                         var click = function (e) {
25756                             e.stopPropagation();
25757                             _this._tag.click$.next(_this._tag);
25758                         };
25759                         var iconCanvas = this._projectToCanvas(iconCameraSpace, projectionMatrix);
25760                         var iconCss = iconCanvas.map(function (coord) { return (100 * coord) + "%"; });
25761                         var properties = {
25762                             onclick: click,
25763                             onmousedown: interact,
25764                             style: {
25765                                 left: iconCss[0],
25766                                 pointerEvents: "all",
25767                                 position: "absolute",
25768                                 top: iconCss[1],
25769                             },
25770                         };
25771                         vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
25772                     }
25773                 }
25774             }
25775             else if (this._tag.text != null) {
25776                 var textVertex = this._tag.geometry.getVertex3d(3, this._transform);
25777                 var textCameraSpace = this._convertToCameraSpace(textVertex, matrixWorldInverse);
25778                 if (textCameraSpace.z < 0) {
25779                     var interact = function (e) {
25780                         _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
25781                     };
25782                     var labelCanvas = this._projectToCanvas(textCameraSpace, projectionMatrix);
25783                     var labelCss = labelCanvas.map(function (coord) { return (100 * coord) + "%"; });
25784                     var properties = {
25785                         onmousedown: interact,
25786                         style: {
25787                             color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
25788                             left: labelCss[0],
25789                             pointerEvents: "all",
25790                             position: "absolute",
25791                             top: labelCss[1],
25792                         },
25793                         textContent: this._tag.text,
25794                     };
25795                     vNodes.push(vd.h("span.TagSymbol", properties, []));
25796                 }
25797             }
25798         }
25799         if (!this._tag.editable) {
25800             return vNodes;
25801         }
25802         var lineColor = "#" + ("000000" + this._tag.lineColor.toString(16)).substr(-6);
25803         if (this._tag.geometry instanceof Component_1.RectGeometry) {
25804             var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
25805             var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
25806             if (centroidCameraSpace.z < 0) {
25807                 var interact = this._interact(Component_1.TagOperation.Centroid);
25808                 var centerCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
25809                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
25810                 var properties = {
25811                     onmousedown: interact,
25812                     style: { background: lineColor, left: centerCss[0], position: "absolute", top: centerCss[1] },
25813                 };
25814                 vNodes.push(vd.h("div.TagMover", properties, []));
25815             }
25816         }
25817         var vertices3d = this._tag.geometry.getVertices3d(this._transform);
25818         for (var i = 0; i < vertices3d.length - 1; i++) {
25819             var isRectGeometry = this._tag.geometry instanceof Component_1.RectGeometry;
25820             if (isRectGeometry &&
25821                 ((this._tag.icon != null && i === this._tag.iconIndex) ||
25822                     (this._tag.icon == null && this._tag.text != null && i === 3))) {
25823                 continue;
25824             }
25825             var vertexCameraSpace = this._convertToCameraSpace(vertices3d[i], matrixWorldInverse);
25826             if (vertexCameraSpace.z > 0) {
25827                 continue;
25828             }
25829             var interact = this._interact(Component_1.TagOperation.Vertex, i);
25830             var vertexCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
25831             var vertexCss = vertexCanvas.map(function (coord) { return (100 * coord) + "%"; });
25832             var properties = {
25833                 onmousedown: interact,
25834                 style: {
25835                     background: lineColor,
25836                     left: vertexCss[0],
25837                     position: "absolute",
25838                     top: vertexCss[1],
25839                 },
25840             };
25841             if (isRectGeometry) {
25842                 properties.style.cursor = i % 2 === 0 ? "nesw-resize" : "nwse-resize";
25843             }
25844             vNodes.push(vd.h("div.TagResizer", properties, []));
25845             if (!this._tag.indicateVertices) {
25846                 continue;
25847             }
25848             var pointProperties = {
25849                 style: {
25850                     background: lineColor,
25851                     left: vertexCss[0],
25852                     position: "absolute",
25853                     top: vertexCss[1],
25854                 },
25855             };
25856             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
25857         }
25858         return vNodes;
25859     };
25860     OutlineRenderTag.prototype._createFill = function () {
25861         var triangles = this._tag.geometry.getTriangles3d(this._transform);
25862         var positions = new Float32Array(triangles);
25863         var geometry = new THREE.BufferGeometry();
25864         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
25865         geometry.computeBoundingSphere();
25866         var material = new THREE.MeshBasicMaterial({
25867             color: this._tag.fillColor,
25868             opacity: this._tag.fillOpacity,
25869             side: THREE.DoubleSide,
25870             transparent: true,
25871         });
25872         return new THREE.Mesh(geometry, material);
25873     };
25874     OutlineRenderTag.prototype._createGLObjects = function () {
25875         var glObjects = [];
25876         if (this._fill != null) {
25877             glObjects.push(this._fill);
25878         }
25879         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
25880             var hole = _a[_i];
25881             glObjects.push(hole);
25882         }
25883         if (this._outline != null) {
25884             glObjects.push(this._outline);
25885         }
25886         return glObjects;
25887     };
25888     OutlineRenderTag.prototype._createHoles = function () {
25889         var holes = [];
25890         if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
25891             var polygonGeometry = this._tag.geometry;
25892             var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
25893             for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
25894                 var holePoints3d = holes3d_1[_i];
25895                 var hole = this._createLine(holePoints3d);
25896                 holes.push(hole);
25897             }
25898         }
25899         return holes;
25900     };
25901     OutlineRenderTag.prototype._createLine = function (points3d) {
25902         var positions = this._getLinePositions(points3d);
25903         var geometry = new THREE.BufferGeometry();
25904         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
25905         geometry.computeBoundingSphere();
25906         var material = new THREE.LineBasicMaterial({
25907             color: this._tag.lineColor,
25908             linewidth: this._tag.lineWidth,
25909         });
25910         return new THREE.Line(geometry, material);
25911     };
25912     OutlineRenderTag.prototype._createOutline = function () {
25913         var points3d = this._tag.geometry.getPoints3d(this._transform);
25914         return this._createLine(points3d);
25915     };
25916     OutlineRenderTag.prototype._disposeFill = function () {
25917         if (this._fill == null) {
25918             return;
25919         }
25920         this._fill.geometry.dispose();
25921         this._fill.material.dispose();
25922         this._fill = null;
25923     };
25924     OutlineRenderTag.prototype._disposeHoles = function () {
25925         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
25926             var hole = _a[_i];
25927             hole.geometry.dispose();
25928             hole.material.dispose();
25929         }
25930         this._holes = [];
25931     };
25932     OutlineRenderTag.prototype._disposeOutline = function () {
25933         if (this._outline == null) {
25934             return;
25935         }
25936         this._outline.geometry.dispose();
25937         this._outline.material.dispose();
25938         this._outline = null;
25939     };
25940     OutlineRenderTag.prototype._getLinePositions = function (points3d) {
25941         var length = points3d.length;
25942         var positions = new Float32Array(length * 3);
25943         for (var i = 0; i < length; ++i) {
25944             var index = 3 * i;
25945             var position = points3d[i];
25946             positions[index + 0] = position[0];
25947             positions[index + 1] = position[1];
25948             positions[index + 2] = position[2];
25949         }
25950         return positions;
25951     };
25952     OutlineRenderTag.prototype._getSpriteAlignment = function (index, alignment) {
25953         var horizontalAlignment = Viewer_1.SpriteAlignment.Center;
25954         var verticalAlignment = Viewer_1.SpriteAlignment.Center;
25955         if (alignment === Component_1.Alignment.Outer) {
25956             switch (index) {
25957                 case 0:
25958                     horizontalAlignment = Viewer_1.SpriteAlignment.End;
25959                     verticalAlignment = Viewer_1.SpriteAlignment.Start;
25960                     break;
25961                 case 1:
25962                     horizontalAlignment = Viewer_1.SpriteAlignment.End;
25963                     verticalAlignment = Viewer_1.SpriteAlignment.End;
25964                     break;
25965                 case 2:
25966                     horizontalAlignment = Viewer_1.SpriteAlignment.Start;
25967                     verticalAlignment = Viewer_1.SpriteAlignment.End;
25968                     break;
25969                 case 3:
25970                     horizontalAlignment = Viewer_1.SpriteAlignment.Start;
25971                     verticalAlignment = Viewer_1.SpriteAlignment.Start;
25972                     break;
25973                 default:
25974                     break;
25975             }
25976         }
25977         return [horizontalAlignment, verticalAlignment];
25978     };
25979     OutlineRenderTag.prototype._interact = function (operation, vertexIndex) {
25980         var _this = this;
25981         return function (e) {
25982             var offsetX = e.offsetX - e.target.offsetWidth / 2;
25983             var offsetY = e.offsetY - e.target.offsetHeight / 2;
25984             _this._interact$.next({
25985                 offsetX: offsetX,
25986                 offsetY: offsetY,
25987                 operation: operation,
25988                 tag: _this._tag,
25989                 vertexIndex: vertexIndex,
25990             });
25991         };
25992     };
25993     OutlineRenderTag.prototype._updateFillGeometry = function () {
25994         var triangles = this._tag.geometry.getTriangles3d(this._transform);
25995         var positions = new Float32Array(triangles);
25996         var geometry = this._fill.geometry;
25997         var attribute = geometry.getAttribute("position");
25998         if (attribute.array.length === positions.length) {
25999             attribute.set(positions);
26000             attribute.needsUpdate = true;
26001         }
26002         else {
26003             geometry.removeAttribute("position");
26004             geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
26005         }
26006         geometry.computeBoundingSphere();
26007     };
26008     OutlineRenderTag.prototype._updateFillMaterial = function () {
26009         var material = this._fill.material;
26010         material.color = new THREE.Color(this._tag.fillColor);
26011         material.opacity = this._tag.fillOpacity;
26012         material.needsUpdate = true;
26013     };
26014     OutlineRenderTag.prototype._updateHoleGeometries = function () {
26015         var polygonGeometry = this._tag.geometry;
26016         var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
26017         if (holes3d.length !== this._holes.length) {
26018             throw new Error("Changing the number of holes is not supported.");
26019         }
26020         for (var i = 0; i < this._holes.length; i++) {
26021             var holePoints3d = holes3d[i];
26022             var hole = this._holes[i];
26023             this._updateLine(hole, holePoints3d);
26024         }
26025     };
26026     OutlineRenderTag.prototype._updateHoleMaterials = function () {
26027         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
26028             var hole = _a[_i];
26029             var material = hole.material;
26030             this._updateLineBasicMaterial(material);
26031         }
26032     };
26033     OutlineRenderTag.prototype._updateLine = function (line, points3d) {
26034         var positions = this._getLinePositions(points3d);
26035         var geometry = line.geometry;
26036         var attribute = geometry.getAttribute("position");
26037         attribute.set(positions);
26038         attribute.needsUpdate = true;
26039         geometry.computeBoundingSphere();
26040     };
26041     OutlineRenderTag.prototype._updateOulineGeometry = function () {
26042         var points3d = this._tag.geometry.getPoints3d(this._transform);
26043         this._updateLine(this._outline, points3d);
26044     };
26045     OutlineRenderTag.prototype._updateOutlineMaterial = function () {
26046         var material = this._outline.material;
26047         this._updateLineBasicMaterial(material);
26048     };
26049     OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
26050         material.color = new THREE.Color(this._tag.lineColor);
26051         material.linewidth = Math.max(this._tag.lineWidth, 1);
26052         material.opacity = this._tag.lineWidth >= 1 ? 1 : 0;
26053         material.transparent = this._tag.lineWidth <= 0;
26054         material.needsUpdate = true;
26055     };
26056     return OutlineRenderTag;
26057 }(Component_1.RenderTag));
26058 exports.OutlineRenderTag = OutlineRenderTag;
26059
26060 },{"../../../Component":217,"../../../Viewer":227,"three":167,"virtual-dom":173}],276:[function(require,module,exports){
26061 "use strict";
26062 var __extends = (this && this.__extends) || function (d, b) {
26063     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26064     function __() { this.constructor = d; }
26065     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26066 };
26067 var Subject_1 = require("rxjs/Subject");
26068 var Component_1 = require("../../../Component");
26069 /**
26070  * @class OutlineTag
26071  * @classdesc Tag holding properties for visualizing a geometry outline.
26072  */
26073 var OutlineTag = (function (_super) {
26074     __extends(OutlineTag, _super);
26075     /**
26076      * Create an outline tag.
26077      *
26078      * @override
26079      * @constructor
26080      * @param {string} id
26081      * @param {Geometry} geometry
26082      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
26083      * behavior of the outline tag.
26084      */
26085     function OutlineTag(id, geometry, options) {
26086         var _this = _super.call(this, id, geometry) || this;
26087         _this._editable = options.editable == null ? false : options.editable;
26088         _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
26089         _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
26090         _this._icon = options.icon === undefined ? null : options.icon;
26091         _this._iconAlignment = options.iconAlignment == null ? Component_1.Alignment.Outer : options.iconAlignment;
26092         _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
26093         _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
26094         _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
26095         _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
26096         _this._text = options.text === undefined ? null : options.text;
26097         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
26098         _this._click$ = new Subject_1.Subject();
26099         _this._click$
26100             .subscribe(function (t) {
26101             _this.fire(OutlineTag.click, _this);
26102         });
26103         return _this;
26104     }
26105     Object.defineProperty(OutlineTag.prototype, "click$", {
26106         /**
26107          * Click observable.
26108          *
26109          * @description An observable emitting the tag when the icon of the
26110          * tag has been clicked.
26111          *
26112          * @returns {Observable<Tag>}
26113          */
26114         get: function () {
26115             return this._click$;
26116         },
26117         enumerable: true,
26118         configurable: true
26119     });
26120     Object.defineProperty(OutlineTag.prototype, "editable", {
26121         /**
26122          * Get editable property.
26123          * @returns {boolean} Value indicating if tag is editable.
26124          */
26125         get: function () {
26126             return this._editable;
26127         },
26128         /**
26129          * Set editable property.
26130          * @param {boolean}
26131          *
26132          * @fires Tag#changed
26133          */
26134         set: function (value) {
26135             this._editable = value;
26136             this._notifyChanged$.next(this);
26137         },
26138         enumerable: true,
26139         configurable: true
26140     });
26141     Object.defineProperty(OutlineTag.prototype, "fillColor", {
26142         /**
26143          * Get fill color property.
26144          * @returns {number}
26145          */
26146         get: function () {
26147             return this._fillColor;
26148         },
26149         /**
26150          * Set fill color property.
26151          * @param {number}
26152          *
26153          * @fires Tag#changed
26154          */
26155         set: function (value) {
26156             this._fillColor = value;
26157             this._notifyChanged$.next(this);
26158         },
26159         enumerable: true,
26160         configurable: true
26161     });
26162     Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
26163         /**
26164          * Get fill opacity property.
26165          * @returns {number}
26166          */
26167         get: function () {
26168             return this._fillOpacity;
26169         },
26170         /**
26171          * Set fill opacity property.
26172          * @param {number}
26173          *
26174          * @fires Tag#changed
26175          */
26176         set: function (value) {
26177             this._fillOpacity = value;
26178             this._notifyChanged$.next(this);
26179         },
26180         enumerable: true,
26181         configurable: true
26182     });
26183     Object.defineProperty(OutlineTag.prototype, "geometry", {
26184         get: function () {
26185             return this._geometry;
26186         },
26187         enumerable: true,
26188         configurable: true
26189     });
26190     Object.defineProperty(OutlineTag.prototype, "icon", {
26191         /**
26192          * Get icon property.
26193          * @returns {string}
26194          */
26195         get: function () {
26196             return this._icon;
26197         },
26198         /**
26199          * Set icon property.
26200          * @param {string}
26201          *
26202          * @fires Tag#changed
26203          */
26204         set: function (value) {
26205             this._icon = value;
26206             this._notifyChanged$.next(this);
26207         },
26208         enumerable: true,
26209         configurable: true
26210     });
26211     Object.defineProperty(OutlineTag.prototype, "iconAlignment", {
26212         /**
26213          * Get icon alignment property.
26214          * @returns {Alignment}
26215          */
26216         get: function () {
26217             return this._iconAlignment;
26218         },
26219         /**
26220          * Set icon alignment property.
26221          * @param {Alignment}
26222          *
26223          * @fires Tag#changed
26224          */
26225         set: function (value) {
26226             this._iconAlignment = value;
26227             this._notifyChanged$.next(this);
26228         },
26229         enumerable: true,
26230         configurable: true
26231     });
26232     Object.defineProperty(OutlineTag.prototype, "iconIndex", {
26233         /**
26234          * Get icon index property.
26235          * @returns {number}
26236          */
26237         get: function () {
26238             return this._iconIndex;
26239         },
26240         /**
26241          * Set icon index property.
26242          * @param {number}
26243          *
26244          * @fires Tag#changed
26245          */
26246         set: function (value) {
26247             this._iconIndex = value;
26248             this._notifyChanged$.next(this);
26249         },
26250         enumerable: true,
26251         configurable: true
26252     });
26253     Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
26254         /**
26255          * Get indicate vertices property.
26256          * @returns {boolean} Value indicating if vertices should be indicated
26257          * when tag is editable.
26258          */
26259         get: function () {
26260             return this._indicateVertices;
26261         },
26262         /**
26263          * Set indicate vertices property.
26264          * @param {boolean}
26265          *
26266          * @fires Tag#changed
26267          */
26268         set: function (value) {
26269             this._indicateVertices = value;
26270             this._notifyChanged$.next(this);
26271         },
26272         enumerable: true,
26273         configurable: true
26274     });
26275     Object.defineProperty(OutlineTag.prototype, "lineColor", {
26276         /**
26277          * Get line color property.
26278          * @returns {number}
26279          */
26280         get: function () {
26281             return this._lineColor;
26282         },
26283         /**
26284          * Set line color property.
26285          * @param {number}
26286          *
26287          * @fires Tag#changed
26288          */
26289         set: function (value) {
26290             this._lineColor = value;
26291             this._notifyChanged$.next(this);
26292         },
26293         enumerable: true,
26294         configurable: true
26295     });
26296     Object.defineProperty(OutlineTag.prototype, "lineWidth", {
26297         /**
26298          * Get line width property.
26299          * @returns {number}
26300          */
26301         get: function () {
26302             return this._lineWidth;
26303         },
26304         /**
26305          * Set line width property.
26306          * @param {number}
26307          *
26308          * @fires Tag#changed
26309          */
26310         set: function (value) {
26311             this._lineWidth = value;
26312             this._notifyChanged$.next(this);
26313         },
26314         enumerable: true,
26315         configurable: true
26316     });
26317     Object.defineProperty(OutlineTag.prototype, "text", {
26318         /**
26319          * Get text property.
26320          * @returns {string}
26321          */
26322         get: function () {
26323             return this._text;
26324         },
26325         /**
26326          * Set text property.
26327          * @param {string}
26328          *
26329          * @fires Tag#changed
26330          */
26331         set: function (value) {
26332             this._text = value;
26333             this._notifyChanged$.next(this);
26334         },
26335         enumerable: true,
26336         configurable: true
26337     });
26338     Object.defineProperty(OutlineTag.prototype, "textColor", {
26339         /**
26340          * Get text color property.
26341          * @returns {number}
26342          */
26343         get: function () {
26344             return this._textColor;
26345         },
26346         /**
26347          * Set text color property.
26348          * @param {number}
26349          *
26350          * @fires Tag#changed
26351          */
26352         set: function (value) {
26353             this._textColor = value;
26354             this._notifyChanged$.next(this);
26355         },
26356         enumerable: true,
26357         configurable: true
26358     });
26359     /**
26360      * Set options for tag.
26361      *
26362      * @description Sets all the option properties provided and keps
26363      * the rest of the values as is.
26364      *
26365      * @param {IOutlineTagOptions} options - Outline tag options
26366      *
26367      * @fires {Tag#changed}
26368      */
26369     OutlineTag.prototype.setOptions = function (options) {
26370         this._editable = options.editable == null ? this._editable : options.editable;
26371         this._icon = options.icon === undefined ? this._icon : options.icon;
26372         this._iconAlignment = options.iconAlignment == null ? this._iconAlignment : options.iconAlignment;
26373         this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
26374         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
26375         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
26376         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
26377         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
26378         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
26379         this._text = options.text === undefined ? this._text : options.text;
26380         this._textColor = options.textColor == null ? this._textColor : options.textColor;
26381         this._notifyChanged$.next(this);
26382     };
26383     return OutlineTag;
26384 }(Component_1.Tag));
26385 /**
26386  * Event fired when the icon of the outline tag is clicked.
26387  *
26388  * @event OutlineTag#click
26389  * @type {OutlineTag} The tag instance that was clicked.
26390  */
26391 OutlineTag.click = "click";
26392 exports.OutlineTag = OutlineTag;
26393 Object.defineProperty(exports, "__esModule", { value: true });
26394 exports.default = OutlineTag;
26395
26396 },{"../../../Component":217,"rxjs/Subject":33}],277:[function(require,module,exports){
26397 /// <reference path="../../../../typings/index.d.ts" />
26398 "use strict";
26399 var THREE = require("three");
26400 var Subject_1 = require("rxjs/Subject");
26401 var RenderTag = (function () {
26402     function RenderTag(tag, transform) {
26403         this._tag = tag;
26404         this._transform = transform;
26405         this._glObjects = [];
26406         this._glObjectsChanged$ = new Subject_1.Subject();
26407         this._interact$ = new Subject_1.Subject();
26408     }
26409     Object.defineProperty(RenderTag.prototype, "glObjects", {
26410         /**
26411          * Get the GL objects for rendering of the tag.
26412          * @return {Array<Object3D>}
26413          */
26414         get: function () {
26415             return this._glObjects;
26416         },
26417         enumerable: true,
26418         configurable: true
26419     });
26420     Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
26421         get: function () {
26422             return this._glObjectsChanged$;
26423         },
26424         enumerable: true,
26425         configurable: true
26426     });
26427     Object.defineProperty(RenderTag.prototype, "interact$", {
26428         get: function () {
26429             return this._interact$;
26430         },
26431         enumerable: true,
26432         configurable: true
26433     });
26434     Object.defineProperty(RenderTag.prototype, "tag", {
26435         get: function () {
26436             return this._tag;
26437         },
26438         enumerable: true,
26439         configurable: true
26440     });
26441     RenderTag.prototype._projectToCanvas = function (point3d, projectionMatrix) {
26442         var projected = new THREE.Vector3(point3d.x, point3d.y, point3d.z)
26443             .applyProjection(projectionMatrix);
26444         return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
26445     };
26446     RenderTag.prototype._convertToCameraSpace = function (point3d, matrixWorldInverse) {
26447         return new THREE.Vector3(point3d[0], point3d[1], point3d[2]).applyMatrix4(matrixWorldInverse);
26448     };
26449     return RenderTag;
26450 }());
26451 exports.RenderTag = RenderTag;
26452 Object.defineProperty(exports, "__esModule", { value: true });
26453 exports.default = RenderTag;
26454
26455 },{"rxjs/Subject":33,"three":167}],278:[function(require,module,exports){
26456 /// <reference path="../../../../typings/index.d.ts" />
26457 "use strict";
26458 var __extends = (this && this.__extends) || function (d, b) {
26459     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26460     function __() { this.constructor = d; }
26461     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26462 };
26463 var vd = require("virtual-dom");
26464 var Component_1 = require("../../../Component");
26465 var Viewer_1 = require("../../../Viewer");
26466 /**
26467  * @class SpotRenderTag
26468  * @classdesc Tag visualizing the properties of a SpotTag.
26469  */
26470 var SpotRenderTag = (function (_super) {
26471     __extends(SpotRenderTag, _super);
26472     function SpotRenderTag() {
26473         return _super !== null && _super.apply(this, arguments) || this;
26474     }
26475     SpotRenderTag.prototype.dispose = function () { return; };
26476     SpotRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
26477         var _this = this;
26478         var vNodes = [];
26479         var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
26480         var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
26481         if (centroidCameraSpace.z < 0) {
26482             var centroidCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
26483             var centroidCss = centroidCanvas.map(function (coord) { return (100 * coord) + "%"; });
26484             var interactNone = function (e) {
26485                 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
26486             };
26487             if (this._tag.icon != null) {
26488                 if (atlas.loaded) {
26489                     var sprite = atlas.getDOMSprite(this._tag.icon, Viewer_1.SpriteAlignment.Center, Viewer_1.SpriteAlignment.End);
26490                     var properties = {
26491                         onmousedown: interactNone,
26492                         style: {
26493                             bottom: 100 * (1 - centroidCanvas[1]) + "%",
26494                             left: centroidCss[0],
26495                             pointerEvents: "all",
26496                             position: "absolute",
26497                             transform: "translate(0px, -8px)",
26498                         },
26499                     };
26500                     vNodes.push(vd.h("div", properties, [sprite]));
26501                 }
26502             }
26503             else if (this._tag.text != null) {
26504                 var properties = {
26505                     onmousedown: interactNone,
26506                     style: {
26507                         bottom: 100 * (1 - centroidCanvas[1]) + "%",
26508                         color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
26509                         left: centroidCss[0],
26510                         pointerEvents: "all",
26511                         position: "absolute",
26512                         transform: "translate(-50%, -7px)",
26513                     },
26514                     textContent: this._tag.text,
26515                 };
26516                 vNodes.push(vd.h("span.TagSymbol", properties, []));
26517             }
26518             var interact = this._interact(Component_1.TagOperation.Centroid);
26519             var background = "#" + ("000000" + this._tag.color.toString(16)).substr(-6);
26520             if (this._tag.editable) {
26521                 var interactorProperties = {
26522                     onmousedown: interact,
26523                     style: {
26524                         background: background,
26525                         left: centroidCss[0],
26526                         pointerEvents: "all",
26527                         position: "absolute",
26528                         top: centroidCss[1],
26529                     },
26530                 };
26531                 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
26532             }
26533             var pointProperties = {
26534                 style: {
26535                     background: background,
26536                     left: centroidCss[0],
26537                     position: "absolute",
26538                     top: centroidCss[1],
26539                 },
26540             };
26541             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
26542         }
26543         return vNodes;
26544     };
26545     SpotRenderTag.prototype._interact = function (operation, vertexIndex) {
26546         var _this = this;
26547         return function (e) {
26548             var offsetX = e.offsetX - e.target.offsetWidth / 2;
26549             var offsetY = e.offsetY - e.target.offsetHeight / 2;
26550             _this._interact$.next({
26551                 offsetX: offsetX,
26552                 offsetY: offsetY,
26553                 operation: operation,
26554                 tag: _this._tag,
26555                 vertexIndex: vertexIndex,
26556             });
26557         };
26558     };
26559     return SpotRenderTag;
26560 }(Component_1.RenderTag));
26561 exports.SpotRenderTag = SpotRenderTag;
26562
26563 },{"../../../Component":217,"../../../Viewer":227,"virtual-dom":173}],279:[function(require,module,exports){
26564 "use strict";
26565 var __extends = (this && this.__extends) || function (d, b) {
26566     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26567     function __() { this.constructor = d; }
26568     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26569 };
26570 var Component_1 = require("../../../Component");
26571 /**
26572  * @class SpotTag
26573  * @classdesc Tag holding properties for visualizing the centroid of a geometry.
26574  */
26575 var SpotTag = (function (_super) {
26576     __extends(SpotTag, _super);
26577     /**
26578      * Create a spot tag.
26579      *
26580      * @override
26581      * @constructor
26582      * @param {string} id
26583      * @param {Geometry} geometry
26584      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
26585      * behavior of the spot tag.
26586      */
26587     function SpotTag(id, geometry, options) {
26588         var _this = _super.call(this, id, geometry) || this;
26589         _this._color = options.color == null ? 0xFFFFFF : options.color;
26590         _this._editable = options.editable == null ? false : options.editable;
26591         _this._icon = options.icon === undefined ? null : options.icon;
26592         _this._text = options.text === undefined ? null : options.text;
26593         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
26594         return _this;
26595     }
26596     Object.defineProperty(SpotTag.prototype, "color", {
26597         /**
26598          * Get color property.
26599          * @returns {number} The color of the spot as a hexagonal number;
26600          */
26601         get: function () {
26602             return this._color;
26603         },
26604         /**
26605          * Set color property.
26606          * @param {number}
26607          *
26608          * @fires Tag#changed
26609          */
26610         set: function (value) {
26611             this._color = value;
26612             this._notifyChanged$.next(this);
26613         },
26614         enumerable: true,
26615         configurable: true
26616     });
26617     Object.defineProperty(SpotTag.prototype, "editable", {
26618         /**
26619          * Get editable property.
26620          * @returns {boolean} Value indicating if tag is editable.
26621          */
26622         get: function () {
26623             return this._editable;
26624         },
26625         /**
26626          * Set editable property.
26627          * @param {boolean}
26628          *
26629          * @fires Tag#changed
26630          */
26631         set: function (value) {
26632             this._editable = value;
26633             this._notifyChanged$.next(this);
26634         },
26635         enumerable: true,
26636         configurable: true
26637     });
26638     Object.defineProperty(SpotTag.prototype, "icon", {
26639         /**
26640          * Get icon property.
26641          * @returns {string}
26642          */
26643         get: function () {
26644             return this._icon;
26645         },
26646         /**
26647          * Set icon property.
26648          * @param {string}
26649          *
26650          * @fires Tag#changed
26651          */
26652         set: function (value) {
26653             this._icon = value;
26654             this._notifyChanged$.next(this);
26655         },
26656         enumerable: true,
26657         configurable: true
26658     });
26659     Object.defineProperty(SpotTag.prototype, "text", {
26660         /**
26661          * Get text property.
26662          * @returns {string}
26663          */
26664         get: function () {
26665             return this._text;
26666         },
26667         /**
26668          * Set text property.
26669          * @param {string}
26670          *
26671          * @fires Tag#changed
26672          */
26673         set: function (value) {
26674             this._text = value;
26675             this._notifyChanged$.next(this);
26676         },
26677         enumerable: true,
26678         configurable: true
26679     });
26680     Object.defineProperty(SpotTag.prototype, "textColor", {
26681         /**
26682          * Get text color property.
26683          * @returns {number}
26684          */
26685         get: function () {
26686             return this._textColor;
26687         },
26688         /**
26689          * Set text color property.
26690          * @param {number}
26691          *
26692          * @fires Tag#changed
26693          */
26694         set: function (value) {
26695             this._textColor = value;
26696             this._notifyChanged$.next(this);
26697         },
26698         enumerable: true,
26699         configurable: true
26700     });
26701     /**
26702      * Set options for tag.
26703      *
26704      * @description Sets all the option properties provided and keps
26705      * the rest of the values as is.
26706      *
26707      * @param {ISpotTagOptions} options - Spot tag options
26708      *
26709      * @fires {Tag#changed}
26710      */
26711     SpotTag.prototype.setOptions = function (options) {
26712         this._color = options.color == null ? this._color : options.color;
26713         this._editable = options.editable == null ? this._editable : options.editable;
26714         this._icon = options.icon === undefined ? this._icon : options.icon;
26715         this._text = options.text === undefined ? this._text : options.text;
26716         this._textColor = options.textColor == null ? this._textColor : options.textColor;
26717         this._notifyChanged$.next(this);
26718     };
26719     return SpotTag;
26720 }(Component_1.Tag));
26721 exports.SpotTag = SpotTag;
26722 Object.defineProperty(exports, "__esModule", { value: true });
26723 exports.default = SpotTag;
26724
26725 },{"../../../Component":217}],280:[function(require,module,exports){
26726 "use strict";
26727 var __extends = (this && this.__extends) || function (d, b) {
26728     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26729     function __() { this.constructor = d; }
26730     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26731 };
26732 var Subject_1 = require("rxjs/Subject");
26733 require("rxjs/add/operator/map");
26734 require("rxjs/add/operator/share");
26735 var Utils_1 = require("../../../Utils");
26736 /**
26737  * @class Tag
26738  * @abstract
26739  * @classdesc Abstract class representing the basic functionality of for a tag.
26740  */
26741 var Tag = (function (_super) {
26742     __extends(Tag, _super);
26743     /**
26744      * Create a tag.
26745      *
26746      * @constructor
26747      * @param {string} id
26748      * @param {Geometry} geometry
26749      */
26750     function Tag(id, geometry) {
26751         var _this = _super.call(this) || this;
26752         _this._id = id;
26753         _this._geometry = geometry;
26754         _this._notifyChanged$ = new Subject_1.Subject();
26755         _this._notifyChanged$
26756             .subscribe(function (t) {
26757             _this.fire(Tag.changed, _this);
26758         });
26759         _this._geometry.changed$
26760             .subscribe(function (g) {
26761             _this.fire(Tag.geometrychanged, _this);
26762         });
26763         return _this;
26764     }
26765     Object.defineProperty(Tag.prototype, "id", {
26766         /**
26767          * Get id property.
26768          * @returns {string}
26769          */
26770         get: function () {
26771             return this._id;
26772         },
26773         enumerable: true,
26774         configurable: true
26775     });
26776     Object.defineProperty(Tag.prototype, "geometry", {
26777         /**
26778          * Get geometry property.
26779          * @returns {Geometry}
26780          */
26781         get: function () {
26782             return this._geometry;
26783         },
26784         enumerable: true,
26785         configurable: true
26786     });
26787     Object.defineProperty(Tag.prototype, "changed$", {
26788         /**
26789          * Get changed observable.
26790          * @returns {Observable<Tag>}
26791          */
26792         get: function () {
26793             return this._notifyChanged$;
26794         },
26795         enumerable: true,
26796         configurable: true
26797     });
26798     Object.defineProperty(Tag.prototype, "geometryChanged$", {
26799         /**
26800          * Get geometry changed observable.
26801          * @returns {Observable<Tag>}
26802          */
26803         get: function () {
26804             var _this = this;
26805             return this._geometry.changed$
26806                 .map(function (geometry) {
26807                 return _this;
26808             })
26809                 .share();
26810         },
26811         enumerable: true,
26812         configurable: true
26813     });
26814     return Tag;
26815 }(Utils_1.EventEmitter));
26816 /**
26817  * Event fired when a property related to the visual appearance of the
26818  * tag has changed.
26819  *
26820  * @event Tag#changed
26821  * @type {Tag} The tag instance that has changed.
26822  */
26823 Tag.changed = "changed";
26824 /**
26825  * Event fired when the geometry of the tag has changed.
26826  *
26827  * @event Tag#geometrychanged
26828  * @type {Tag} The tag instance whose geometry has changed.
26829  */
26830 Tag.geometrychanged = "geometrychanged";
26831 exports.Tag = Tag;
26832 Object.defineProperty(exports, "__esModule", { value: true });
26833 exports.default = Tag;
26834
26835 },{"../../../Utils":226,"rxjs/Subject":33,"rxjs/add/operator/map":62,"rxjs/add/operator/share":71}],281:[function(require,module,exports){
26836 "use strict";
26837 var __extends = (this && this.__extends) || function (d, b) {
26838     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26839     function __() { this.constructor = d; }
26840     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26841 };
26842 var MapillaryError_1 = require("./MapillaryError");
26843 var ArgumentMapillaryError = (function (_super) {
26844     __extends(ArgumentMapillaryError, _super);
26845     function ArgumentMapillaryError(message) {
26846         var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
26847         _this.name = "ArgumentMapillaryError";
26848         return _this;
26849     }
26850     return ArgumentMapillaryError;
26851 }(MapillaryError_1.MapillaryError));
26852 exports.ArgumentMapillaryError = ArgumentMapillaryError;
26853 Object.defineProperty(exports, "__esModule", { value: true });
26854 exports.default = ArgumentMapillaryError;
26855
26856 },{"./MapillaryError":283}],282:[function(require,module,exports){
26857 "use strict";
26858 var __extends = (this && this.__extends) || function (d, b) {
26859     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26860     function __() { this.constructor = d; }
26861     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26862 };
26863 var MapillaryError_1 = require("./MapillaryError");
26864 var GraphMapillaryError = (function (_super) {
26865     __extends(GraphMapillaryError, _super);
26866     function GraphMapillaryError(message) {
26867         var _this = _super.call(this, message) || this;
26868         _this.name = "GraphMapillaryError";
26869         return _this;
26870     }
26871     return GraphMapillaryError;
26872 }(MapillaryError_1.MapillaryError));
26873 exports.GraphMapillaryError = GraphMapillaryError;
26874 Object.defineProperty(exports, "__esModule", { value: true });
26875 exports.default = GraphMapillaryError;
26876
26877 },{"./MapillaryError":283}],283:[function(require,module,exports){
26878 "use strict";
26879 var __extends = (this && this.__extends) || function (d, b) {
26880     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26881     function __() { this.constructor = d; }
26882     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26883 };
26884 var MapillaryError = (function (_super) {
26885     __extends(MapillaryError, _super);
26886     function MapillaryError(message) {
26887         var _this = _super.call(this, message) || this;
26888         _this.name = "MapillaryError";
26889         return _this;
26890     }
26891     return MapillaryError;
26892 }(Error));
26893 exports.MapillaryError = MapillaryError;
26894 Object.defineProperty(exports, "__esModule", { value: true });
26895 exports.default = MapillaryError;
26896
26897 },{}],284:[function(require,module,exports){
26898 /// <reference path="../../typings/index.d.ts" />
26899 "use strict";
26900 var THREE = require("three");
26901 /**
26902  * @class Camera
26903  *
26904  * @classdesc Holds information about a camera.
26905  */
26906 var Camera = (function () {
26907     /**
26908      * Create a new camera instance.
26909      * @param {Transform} [transform] - Optional transform instance.
26910      */
26911     function Camera(transform) {
26912         if (transform != null) {
26913             this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
26914             this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
26915             this._up = transform.upVector();
26916             this._focal = this._getFocal(transform);
26917         }
26918         else {
26919             this._position = new THREE.Vector3(0, 0, 0);
26920             this._lookat = new THREE.Vector3(0, 0, 1);
26921             this._up = new THREE.Vector3(0, -1, 0);
26922             this._focal = 1;
26923         }
26924     }
26925     Object.defineProperty(Camera.prototype, "position", {
26926         /**
26927          * Get position.
26928          * @returns {THREE.Vector3} The position vector.
26929          */
26930         get: function () {
26931             return this._position;
26932         },
26933         enumerable: true,
26934         configurable: true
26935     });
26936     Object.defineProperty(Camera.prototype, "lookat", {
26937         /**
26938          * Get lookat.
26939          * @returns {THREE.Vector3} The lookat vector.
26940          */
26941         get: function () {
26942             return this._lookat;
26943         },
26944         enumerable: true,
26945         configurable: true
26946     });
26947     Object.defineProperty(Camera.prototype, "up", {
26948         /**
26949          * Get up.
26950          * @returns {THREE.Vector3} The up vector.
26951          */
26952         get: function () {
26953             return this._up;
26954         },
26955         enumerable: true,
26956         configurable: true
26957     });
26958     Object.defineProperty(Camera.prototype, "focal", {
26959         /**
26960          * Get focal.
26961          * @returns {number} The focal length.
26962          */
26963         get: function () {
26964             return this._focal;
26965         },
26966         /**
26967          * Set focal.
26968          */
26969         set: function (value) {
26970             this._focal = value;
26971         },
26972         enumerable: true,
26973         configurable: true
26974     });
26975     /**
26976      * Update this camera to the linearly interpolated value of two other cameras.
26977      *
26978      * @param {Camera} a - First camera.
26979      * @param {Camera} b - Second camera.
26980      * @param {number} alpha - Interpolation value on the interval [0, 1].
26981      */
26982     Camera.prototype.lerpCameras = function (a, b, alpha) {
26983         this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
26984         this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
26985         this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
26986         this._focal = (1 - alpha) * a.focal + alpha * b.focal;
26987     };
26988     /**
26989      * Copy the properties of another camera to this camera.
26990      *
26991      * @param {Camera} other - Another camera.
26992      */
26993     Camera.prototype.copy = function (other) {
26994         this._position.copy(other.position);
26995         this._lookat.copy(other.lookat);
26996         this._up.copy(other.up);
26997         this._focal = other.focal;
26998     };
26999     /**
27000      * Clone this camera.
27001      *
27002      * @returns {Camera} A camera with cloned properties equal to this camera.
27003      */
27004     Camera.prototype.clone = function () {
27005         var camera = new Camera();
27006         camera.position.copy(this._position);
27007         camera.lookat.copy(this._lookat);
27008         camera.up.copy(this._up);
27009         camera.focal = this._focal;
27010         return camera;
27011     };
27012     /**
27013      * Determine the distance between this camera and another camera.
27014      *
27015      * @param {Camera} other - Another camera.
27016      * @returns {number} The distance between the cameras.
27017      */
27018     Camera.prototype.diff = function (other) {
27019         var pd = this._position.distanceToSquared(other.position);
27020         var ld = this._lookat.distanceToSquared(other.lookat);
27021         var ud = this._up.distanceToSquared(other.up);
27022         var fd = 100 * Math.abs(this._focal - other.focal);
27023         return Math.max(pd, ld, ud, fd);
27024     };
27025     /**
27026      * Get the focal length based on the transform.
27027      *
27028      * @description Returns the focal length of the transform if gpano info is not available.
27029      * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
27030      * the gpano information if available.
27031      *
27032      * @returns {number} Focal length.
27033      */
27034     Camera.prototype._getFocal = function (transform) {
27035         if (transform.gpano == null) {
27036             return transform.focal;
27037         }
27038         var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
27039         var focal = 0.5 / Math.tan(vFov / 2);
27040         return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
27041     };
27042     return Camera;
27043 }());
27044 exports.Camera = Camera;
27045
27046 },{"three":167}],285:[function(require,module,exports){
27047 "use strict";
27048 /**
27049  * @class GeoCoords
27050  *
27051  * @classdesc Converts coordinates between the geodetic (WGS84),
27052  * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
27053  * East, North, Up (ENU) reference frames.
27054  *
27055  * The WGS84 has latitude (degrees), longitude (degrees) and
27056  * altitude (meters) values.
27057  *
27058  * The ECEF Z-axis pierces the north pole and the
27059  * XY-axis defines the equatorial plane. The X-axis extends
27060  * from the geocenter to the intersection of the Equator and
27061  * the Greenwich Meridian. All values in meters.
27062  *
27063  * The WGS84 parameters are:
27064  *
27065  * a = 6378137
27066  * b = a * (1 - f)
27067  * f = 1 / 298.257223563
27068  * e = Math.sqrt((a^2 - b^2) / a^2)
27069  * e' = Math.sqrt((a^2 - b^2) / b^2)
27070  *
27071  * The WGS84 to ECEF conversion is performed using the following:
27072  *
27073  * X = (N - h) * cos(phi) * cos(lambda)
27074  * Y = (N + h) * cos(phi) * sin(lambda)
27075  * Z = (b^2 * N / a^2 + h) * sin(phi)
27076  *
27077  * where
27078  *
27079  * phi = latitude
27080  * lambda = longitude
27081  * h = height above ellipsoid (altitude)
27082  * N = Radius of curvature (meters)
27083  *   = a / Math.sqrt(1 - e^2 * sin(phi)^2)
27084  *
27085  * The ECEF to WGS84 conversion is performed using the following:
27086  *
27087  * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
27088  * lambda = arctan(Y / X)
27089  * h = p / cos(phi) - N
27090  *
27091  * where
27092  *
27093  * p = Math.sqrt(X^2 + Y^2)
27094  * theta = arctan(Z * a / p * b)
27095  *
27096  * In the ENU reference frame the x-axis points to the
27097  * East, the y-axis to the North and the z-axis Up. All values
27098  * in meters.
27099  *
27100  * The ECEF to ENU conversion is performed using the following:
27101  *
27102  * | x |   |       -sin(lambda_r)                cos(lambda_r)             0      | | X - X_r |
27103  * | y | = | -sin(phi_r) * cos(lambda_r)  -sin(phi_r) * sin(lambda_r)  cos(phi_r) | | Y - Y_r |
27104  * | z |   |  cos(phi_r) * cos(lambda_r)   cos(phi_r) * sin(lambda_r)  sin(phi_r) | | Z - Z_r |
27105  *
27106  * where
27107  *
27108  * phi_r = latitude of reference
27109  * lambda_r = longitude of reference
27110  * X_r, Y_r, Z_r = ECEF coordinates of reference
27111  *
27112  * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
27113  *
27114  * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
27115  * the first step for both conversions.
27116  */
27117 var GeoCoords = (function () {
27118     function GeoCoords() {
27119         this._wgs84a = 6378137.0;
27120         this._wgs84b = 6356752.31424518;
27121     }
27122     /**
27123      * Convert coordinates from geodetic (WGS84) reference to local topocentric
27124      * (ENU) reference.
27125      *
27126      * @param {number} lat Latitude in degrees.
27127      * @param {number} lon Longitude in degrees.
27128      * @param {number} alt Altitude in meters.
27129      * @param {number} refLat Reference latitude in degrees.
27130      * @param {number} refLon Reference longitude in degrees.
27131      * @param {number} refAlt Reference altitude in meters.
27132      * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
27133      */
27134     GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
27135         var ecef = this.geodeticToEcef(lat, lon, alt);
27136         return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
27137     };
27138     /**
27139      * Convert coordinates from local topocentric (ENU) reference to
27140      * geodetic (WGS84) reference.
27141      *
27142      * @param {number} x Topocentric ENU coordinate in East direction.
27143      * @param {number} y Topocentric ENU coordinate in North direction.
27144      * @param {number} z Topocentric ENU coordinate in Up direction.
27145      * @param {number} refLat Reference latitude in degrees.
27146      * @param {number} refLon Reference longitude in degrees.
27147      * @param {number} refAlt Reference altitude in meters.
27148      * @returns {Array<number>} The latitude and longitude in degrees
27149      *                          as well as altitude in meters.
27150      */
27151     GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
27152         var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
27153         return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
27154     };
27155     /**
27156      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
27157      * to local topocentric (ENU) reference.
27158      *
27159      * @param {number} X ECEF X-value.
27160      * @param {number} Y ECEF Y-value.
27161      * @param {number} Z ECEF Z-value.
27162      * @param {number} refLat Reference latitude in degrees.
27163      * @param {number} refLon Reference longitude in degrees.
27164      * @param {number} refAlt Reference altitude in meters.
27165      * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
27166      * and Up directions respectively.
27167      */
27168     GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
27169         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
27170         var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
27171         refLat = refLat * Math.PI / 180.0;
27172         refLon = refLon * Math.PI / 180.0;
27173         var cosLat = Math.cos(refLat);
27174         var sinLat = Math.sin(refLat);
27175         var cosLon = Math.cos(refLon);
27176         var sinLon = Math.sin(refLon);
27177         var x = -sinLon * V[0] + cosLon * V[1];
27178         var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
27179         var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
27180         return [x, y, z];
27181     };
27182     /**
27183      * Convert coordinates from local topocentric (ENU) reference
27184      * to Earth-Centered, Earth-Fixed (ECEF) reference.
27185      *
27186      * @param {number} x Topocentric ENU coordinate in East direction.
27187      * @param {number} y Topocentric ENU coordinate in North direction.
27188      * @param {number} z Topocentric ENU coordinate in Up direction.
27189      * @param {number} refLat Reference latitude in degrees.
27190      * @param {number} refLon Reference longitude in degrees.
27191      * @param {number} refAlt Reference altitude in meters.
27192      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
27193      */
27194     GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
27195         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
27196         refLat = refLat * Math.PI / 180.0;
27197         refLon = refLon * Math.PI / 180.0;
27198         var cosLat = Math.cos(refLat);
27199         var sinLat = Math.sin(refLat);
27200         var cosLon = Math.cos(refLon);
27201         var sinLon = Math.sin(refLon);
27202         var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
27203         var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
27204         var Z = cosLat * y + sinLat * z + refEcef[2];
27205         return [X, Y, Z];
27206     };
27207     /**
27208      * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
27209      * Earth-Fixed (ECEF) reference.
27210      *
27211      * @param {number} lat Latitude in degrees.
27212      * @param {number} lon Longitude in degrees.
27213      * @param {number} alt Altitude in meters.
27214      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
27215      */
27216     GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
27217         var a = this._wgs84a;
27218         var b = this._wgs84b;
27219         lat = lat * Math.PI / 180.0;
27220         lon = lon * Math.PI / 180.0;
27221         var cosLat = Math.cos(lat);
27222         var sinLat = Math.sin(lat);
27223         var cosLon = Math.cos(lon);
27224         var sinLon = Math.sin(lon);
27225         var a2 = a * a;
27226         var b2 = b * b;
27227         var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
27228         var nhcl = (a2 * L + alt) * cosLat;
27229         var X = nhcl * cosLon;
27230         var Y = nhcl * sinLon;
27231         var Z = (b2 * L + alt) * sinLat;
27232         return [X, Y, Z];
27233     };
27234     /**
27235      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
27236      * to geodetic reference (WGS84).
27237      *
27238      * @param {number} X ECEF X-value.
27239      * @param {number} Y ECEF Y-value.
27240      * @param {number} Z ECEF Z-value.
27241      * @returns {Array<number>} The latitude and longitude in degrees
27242      *                          as well as altitude in meters.
27243      */
27244     GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
27245         var a = this._wgs84a;
27246         var b = this._wgs84b;
27247         var a2 = a * a;
27248         var b2 = b * b;
27249         var a2mb2 = a2 - b2;
27250         var ea = Math.sqrt(a2mb2 / a2);
27251         var eb = Math.sqrt(a2mb2 / b2);
27252         var p = Math.sqrt(X * X + Y * Y);
27253         var theta = Math.atan2(Z * a, p * b);
27254         var sinTheta = Math.sin(theta);
27255         var cosTheta = Math.cos(theta);
27256         var lon = Math.atan2(Y, X);
27257         var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
27258         var sinLat = Math.sin(lat);
27259         var cosLat = Math.cos(lat);
27260         var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
27261         var alt = p / cosLat - N;
27262         return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
27263     };
27264     return GeoCoords;
27265 }());
27266 exports.GeoCoords = GeoCoords;
27267 Object.defineProperty(exports, "__esModule", { value: true });
27268 exports.default = GeoCoords;
27269
27270 },{}],286:[function(require,module,exports){
27271 /// <reference path="../../typings/index.d.ts" />
27272 "use strict";
27273 var THREE = require("three");
27274 /**
27275  * @class Spatial
27276  *
27277  * @classdesc Provides methods for scalar, vector and matrix calculations.
27278  */
27279 var Spatial = (function () {
27280     function Spatial() {
27281         this._epsilon = 1e-9;
27282     }
27283     Spatial.prototype.azimuthalToBearing = function (phi) {
27284         return -phi + Math.PI / 2;
27285     };
27286     /**
27287      * Converts degrees to radians.
27288      *
27289      * @param {number} deg Degrees.
27290      */
27291     Spatial.prototype.degToRad = function (deg) {
27292         return Math.PI * deg / 180;
27293     };
27294     /**
27295      * Converts radians to degrees.
27296      *
27297      * @param {number} rad Radians.
27298      */
27299     Spatial.prototype.radToDeg = function (rad) {
27300         return 180 * rad / Math.PI;
27301     };
27302     /**
27303      * Creates a rotation matrix from an angle-axis vector.
27304      *
27305      * @param {Array<number>} angleAxis Angle-axis representation of a rotation.
27306      */
27307     Spatial.prototype.rotationMatrix = function (angleAxis) {
27308         var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
27309         var angle = axis.length();
27310         axis.normalize();
27311         return new THREE.Matrix4().makeRotationAxis(axis, angle);
27312     };
27313     /**
27314      * Rotates a vector according to a angle-axis rotation vector.
27315      *
27316      * @param {Array<number>} vector Vector to rotate.
27317      * @param {Array<number>} angleAxis Angle-axis representation of a rotation.
27318      */
27319     Spatial.prototype.rotate = function (vector, angleAxis) {
27320         var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
27321         var rotationMatrix = this.rotationMatrix(angleAxis);
27322         v.applyMatrix4(rotationMatrix);
27323         return v;
27324     };
27325     /**
27326      * Calculates the optical center from a rotation vector
27327      * on the angle-axis representation and a translation vector
27328      * according to C = -R^T t.
27329      *
27330      * @param {Array<number>} rotation Angle-axis representation of a rotation.
27331      * @param {Array<number>} translation Translation vector.
27332      */
27333     Spatial.prototype.opticalCenter = function (rotation, translation) {
27334         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
27335         var vector = [-translation[0], -translation[1], -translation[2]];
27336         return this.rotate(vector, angleAxis);
27337     };
27338     /**
27339      * Calculates the viewing direction from a rotation vector
27340      * on the angle-axis representation.
27341      *
27342      * @param {number[]} rotation Angle-axis representation of a rotation.
27343      */
27344     Spatial.prototype.viewingDirection = function (rotation) {
27345         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
27346         return this.rotate([0, 0, 1], angleAxis);
27347     };
27348     /**
27349      * Wrap a number on the interval [min, max].
27350      *
27351      * @param {number} value Value to wrap.
27352      * @param {number} min Lower endpoint of interval.
27353      * @param {number} max Upper endpoint of interval.
27354      *
27355      * @returs {number} The wrapped number.
27356      */
27357     Spatial.prototype.wrap = function (value, min, max) {
27358         if (max < min) {
27359             throw new Error("Invalid arguments: max must be larger than min.");
27360         }
27361         var interval = (max - min);
27362         while (value > max || value < min) {
27363             if (value > max) {
27364                 value = value - interval;
27365             }
27366             else if (value < min) {
27367                 value = value + interval;
27368             }
27369         }
27370         return value;
27371     };
27372     /**
27373      * Wrap an angle on the interval [-Pi, Pi].
27374      *
27375      * @param {number} angle Value to wrap.
27376      *
27377      * @returs {number} The wrapped angle.
27378      */
27379     Spatial.prototype.wrapAngle = function (angle) {
27380         return this.wrap(angle, -Math.PI, Math.PI);
27381     };
27382     /**
27383      * Limit the value to the interval [min, max] by changing the value to
27384      * the nearest available one when it is outside the interval.
27385      *
27386      * @param {number} value Value to clamp.
27387      * @param {number} min Minimum of the interval.
27388      * @param {number} max Maximum of the interval.
27389      *
27390      * @returns {number} The clamped value.
27391      */
27392     Spatial.prototype.clamp = function (value, min, max) {
27393         if (value < min) {
27394             return min;
27395         }
27396         if (value > max) {
27397             return max;
27398         }
27399         return value;
27400     };
27401     /**
27402      * Calculates the counter-clockwise angle from the first
27403      * vector (x1, y1)^T to the second (x2, y2)^T.
27404      *
27405      * @param {number} x1 X-value of first vector.
27406      * @param {number} y1 Y-value of first vector.
27407      * @param {number} x2 X-value of second vector.
27408      * @param {number} y2 Y-value of second vector.
27409      */
27410     Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
27411         var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
27412         return this.wrapAngle(angle);
27413     };
27414     /**
27415      * Calculates the minimum (absolute) angle change for rotation
27416      * from one angle to another on the [-Pi, Pi] interval.
27417      *
27418      * @param {number} angle1 The origin angle.
27419      * @param {number} angle2 The destination angle.
27420      */
27421     Spatial.prototype.angleDifference = function (angle1, angle2) {
27422         var angle = angle2 - angle1;
27423         return this.wrapAngle(angle);
27424     };
27425     /**
27426      * Calculates the relative rotation angle between two
27427      * angle-axis vectors.
27428      *
27429      * @param {number} rotation1 First angle-axis vector.
27430      * @param {number} rotation2 Second angle-axis vector.
27431      */
27432     Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
27433         var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
27434         var R2 = this.rotationMatrix(rotation2);
27435         var R = R1T.multiply(R2);
27436         var elements = R.elements;
27437         // from Tr(R) = 1 + 2*cos(theta)
27438         var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
27439         return theta;
27440     };
27441     /**
27442      * Calculates the angle from a vector to a plane.
27443      *
27444      * @param {Array<number>} vector The vector.
27445      * @param {Array<number>} planeNormal Normal of the plane.
27446      */
27447     Spatial.prototype.angleToPlane = function (vector, planeNormal) {
27448         var v = new THREE.Vector3().fromArray(vector);
27449         var norm = v.length();
27450         if (norm < this._epsilon) {
27451             return 0;
27452         }
27453         var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
27454         return Math.asin(projection / norm);
27455     };
27456     /**
27457      * Calculates the distance between two coordinates
27458      * (latitude longitude pairs) in meters according to
27459      * the haversine formula.
27460      *
27461      * @param {number} lat1 The latitude of the first coordinate.
27462      * @param {number} lon1 The longitude of the first coordinate.
27463      * @param {number} lat2 The latitude of the second coordinate.
27464      * @param {number} lon2 The longitude of the second coordinate.
27465      */
27466     Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
27467         var r = 6371000;
27468         var dLat = this.degToRad(lat2 - lat1);
27469         var dLon = this.degToRad(lon2 - lon1);
27470         var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
27471             Math.cos(lat1) * Math.cos(lat2) *
27472                 Math.sin(dLon / 2) * Math.sin(dLon / 2);
27473         var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
27474         return d;
27475     };
27476     return Spatial;
27477 }());
27478 exports.Spatial = Spatial;
27479 Object.defineProperty(exports, "__esModule", { value: true });
27480 exports.default = Spatial;
27481
27482 },{"three":167}],287:[function(require,module,exports){
27483 /// <reference path="../../typings/index.d.ts" />
27484 "use strict";
27485 var THREE = require("three");
27486 /**
27487  * @class Transform
27488  *
27489  * @classdesc Class used for calculating coordinate transformations
27490  * and projections.
27491  */
27492 var Transform = (function () {
27493     /**
27494      * Create a new transform instance.
27495      * @param {Node} apiNavImIm - Node properties.
27496      * @param {HTMLImageElement} image - Node image.
27497      * @param {Array<number>} translation - Node translation vector in three dimensions.
27498      */
27499     function Transform(node, image, translation) {
27500         this._orientation = this._getValue(node.orientation, 1);
27501         var imageWidth = image != null ? image.width : 4;
27502         var imageHeight = image != null ? image.height : 3;
27503         var keepOrientation = this._orientation < 5;
27504         this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
27505         this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
27506         this._basicAspect = keepOrientation ?
27507             this._width / this._height :
27508             this._height / this._width;
27509         this._basicWidth = keepOrientation ? node.width : node.height;
27510         this._basicHeight = keepOrientation ? node.height : node.width;
27511         this._focal = this._getValue(node.focal, 1);
27512         this._scale = this._getValue(node.scale, 0);
27513         this._gpano = node.gpano != null ? node.gpano : null;
27514         this._rt = this._getRt(node.rotation, translation);
27515         this._srt = this._getSrt(this._rt, this._scale);
27516     }
27517     Object.defineProperty(Transform.prototype, "basicAspect", {
27518         /**
27519          * Get basic aspect.
27520          * @returns {number} The orientation adjusted aspect ratio.
27521          */
27522         get: function () {
27523             return this._basicAspect;
27524         },
27525         enumerable: true,
27526         configurable: true
27527     });
27528     Object.defineProperty(Transform.prototype, "basicHeight", {
27529         /**
27530          * Get basic height.
27531          *
27532          * @description Does not fall back to node image height but
27533          * uses original value from API so can be faulty.
27534          *
27535          * @returns {number} The height of the basic version image
27536          * (adjusted for orientation).
27537          */
27538         get: function () {
27539             return this._basicHeight;
27540         },
27541         enumerable: true,
27542         configurable: true
27543     });
27544     Object.defineProperty(Transform.prototype, "basicWidth", {
27545         /**
27546          * Get basic width.
27547          *
27548          * @description Does not fall back to node image width but
27549          * uses original value from API so can be faulty.
27550          *
27551          * @returns {number} The width of the basic version image
27552          * (adjusted for orientation).
27553          */
27554         get: function () {
27555             return this._basicWidth;
27556         },
27557         enumerable: true,
27558         configurable: true
27559     });
27560     Object.defineProperty(Transform.prototype, "focal", {
27561         /**
27562          * Get focal.
27563          * @returns {number} The node focal length.
27564          */
27565         get: function () {
27566             return this._focal;
27567         },
27568         enumerable: true,
27569         configurable: true
27570     });
27571     Object.defineProperty(Transform.prototype, "fullPano", {
27572         /**
27573          * Get fullPano.
27574          *
27575          * @returns {boolean} Value indicating whether the node is a complete
27576          * 360 panorama.
27577          */
27578         get: function () {
27579             return this._gpano != null &&
27580                 this._gpano.CroppedAreaLeftPixels === 0 &&
27581                 this._gpano.CroppedAreaTopPixels === 0 &&
27582                 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
27583                 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
27584         },
27585         enumerable: true,
27586         configurable: true
27587     });
27588     Object.defineProperty(Transform.prototype, "gpano", {
27589         /**
27590          * Get gpano.
27591          * @returns {number} The node gpano information.
27592          */
27593         get: function () {
27594             return this._gpano;
27595         },
27596         enumerable: true,
27597         configurable: true
27598     });
27599     Object.defineProperty(Transform.prototype, "height", {
27600         /**
27601          * Get height.
27602          *
27603          * @description Falls back to the node image height if
27604          * the API data is faulty.
27605          *
27606          * @returns {number} The orientation adjusted image height.
27607          */
27608         get: function () {
27609             return this._height;
27610         },
27611         enumerable: true,
27612         configurable: true
27613     });
27614     Object.defineProperty(Transform.prototype, "orientation", {
27615         /**
27616          * Get orientation.
27617          * @returns {number} The image orientation.
27618          */
27619         get: function () {
27620             return this._orientation;
27621         },
27622         enumerable: true,
27623         configurable: true
27624     });
27625     Object.defineProperty(Transform.prototype, "rt", {
27626         /**
27627          * Get rt.
27628          * @returns {THREE.Matrix4} The extrinsic camera matrix.
27629          */
27630         get: function () {
27631             return this._rt;
27632         },
27633         enumerable: true,
27634         configurable: true
27635     });
27636     Object.defineProperty(Transform.prototype, "srt", {
27637         /**
27638          * Get srt.
27639          * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
27640          */
27641         get: function () {
27642             return this._srt;
27643         },
27644         enumerable: true,
27645         configurable: true
27646     });
27647     Object.defineProperty(Transform.prototype, "scale", {
27648         /**
27649          * Get scale.
27650          * @returns {number} The node atomic reconstruction scale.
27651          */
27652         get: function () {
27653             return this._scale;
27654         },
27655         enumerable: true,
27656         configurable: true
27657     });
27658     Object.defineProperty(Transform.prototype, "width", {
27659         /**
27660          * Get width.
27661          *
27662          * @description Falls back to the node image width if
27663          * the API data is faulty.
27664          *
27665          * @returns {number} The orientation adjusted image width.
27666          */
27667         get: function () {
27668             return this._width;
27669         },
27670         enumerable: true,
27671         configurable: true
27672     });
27673     /**
27674      * Calculate the up vector for the node transform.
27675      *
27676      * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
27677      */
27678     Transform.prototype.upVector = function () {
27679         var rte = this._rt.elements;
27680         switch (this._orientation) {
27681             case 1:
27682                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
27683             case 3:
27684                 return new THREE.Vector3(rte[1], rte[5], rte[9]);
27685             case 6:
27686                 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
27687             case 8:
27688                 return new THREE.Vector3(rte[0], rte[4], rte[8]);
27689             default:
27690                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
27691         }
27692     };
27693     /**
27694      * Calculate projector matrix for projecting 3D points to texture map
27695      * coordinates (u and v).
27696      *
27697      * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
27698      * map coordinate calculations.
27699      */
27700     Transform.prototype.projectorMatrix = function () {
27701         var projector = this._normalizedToTextureMatrix();
27702         var f = this._focal;
27703         var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
27704         projector.multiply(projection);
27705         projector.multiply(this._rt);
27706         return projector;
27707     };
27708     /**
27709      * Project 3D world coordinates to basic coordinates.
27710      *
27711      * @param {Array<number>} point3d - 3D world coordinates.
27712      * @return {Array<number>} 2D basic coordinates.
27713      */
27714     Transform.prototype.projectBasic = function (point3d) {
27715         var sfm = this.projectSfM(point3d);
27716         return this._sfmToBasic(sfm);
27717     };
27718     /**
27719      * Unproject basic coordinates to 3D world coordinates.
27720      *
27721      * @param {Array<number>} basic - 2D basic coordinates.
27722      * @param {Array<number>} distance - Depth to unproject from camera center.
27723      * @returns {Array<number>} Unprojected 3D world coordinates.
27724      */
27725     Transform.prototype.unprojectBasic = function (basic, distance) {
27726         var sfm = this._basicToSfm(basic);
27727         return this.unprojectSfM(sfm, distance);
27728     };
27729     /**
27730      * Project 3D world coordinates to SfM coordinates.
27731      *
27732      * @param {Array<number>} point3d - 3D world coordinates.
27733      * @return {Array<number>} 2D SfM coordinates.
27734      */
27735     Transform.prototype.projectSfM = function (point3d) {
27736         var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
27737         v.applyMatrix4(this._rt);
27738         return this._bearingToSfm([v.x, v.y, v.z]);
27739     };
27740     /**
27741      * Unproject SfM coordinates to a 3D world coordinates.
27742      *
27743      * @param {Array<number>} sfm - 2D SfM coordinates.
27744      * @param {Array<number>} distance - Depth to unproject from camera center.
27745      * @returns {Array<number>} Unprojected 3D world coordinates.
27746      */
27747     Transform.prototype.unprojectSfM = function (sfm, distance) {
27748         var bearing = this._sfmToBearing(sfm);
27749         var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
27750         v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
27751         return [v.x / v.w, v.y / v.w, v.z / v.w];
27752     };
27753     /**
27754      * Transform SfM coordinates to bearing vector (3D cartesian
27755      * coordinates on the unit sphere).
27756      *
27757      * @param {Array<number>} sfm - 2D SfM coordinates.
27758      * @returns {Array<number>} Bearing vector (3D cartesian coordinates
27759      * on the unit sphere).
27760      */
27761     Transform.prototype._sfmToBearing = function (sfm) {
27762         if (this._fullPano()) {
27763             var lon = sfm[0] * 2 * Math.PI;
27764             var lat = -sfm[1] * 2 * Math.PI;
27765             var x = Math.cos(lat) * Math.sin(lon);
27766             var y = -Math.sin(lat);
27767             var z = Math.cos(lat) * Math.cos(lon);
27768             return [x, y, z];
27769         }
27770         else if (this._gpano) {
27771             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
27772             var fullPanoPixel = [
27773                 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
27774                 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
27775             ];
27776             var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
27777             var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
27778             var x = Math.cos(lat) * Math.sin(lon);
27779             var y = -Math.sin(lat);
27780             var z = Math.cos(lat) * Math.cos(lon);
27781             return [x, y, z];
27782         }
27783         else {
27784             var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
27785             v.normalize();
27786             return [v.x, v.y, v.z];
27787         }
27788     };
27789     /**
27790      * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
27791      * SfM coordinates.
27792      *
27793      * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
27794      * unit sphere).
27795      * @returns {Array<number>} 2D SfM coordinates.
27796      */
27797     Transform.prototype._bearingToSfm = function (bearing) {
27798         if (this._fullPano()) {
27799             var x = bearing[0];
27800             var y = bearing[1];
27801             var z = bearing[2];
27802             var lon = Math.atan2(x, z);
27803             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
27804             return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
27805         }
27806         else if (this._gpano) {
27807             var x = bearing[0];
27808             var y = bearing[1];
27809             var z = bearing[2];
27810             var lon = Math.atan2(x, z);
27811             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
27812             var fullPanoPixel = [
27813                 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
27814                 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
27815             ];
27816             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
27817             return [
27818                 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
27819                 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
27820             ];
27821         }
27822         else {
27823             if (bearing[2] > 0) {
27824                 return [
27825                     bearing[0] * this._focal / bearing[2],
27826                     bearing[1] * this._focal / bearing[2],
27827                 ];
27828             }
27829             else {
27830                 return [
27831                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
27832                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
27833                 ];
27834             }
27835         }
27836     };
27837     /**
27838      * Convert basic coordinates to SfM coordinates.
27839      *
27840      * @param {Array<number>} basic - 2D basic coordinates.
27841      * @returns {Array<number>} 2D SfM coordinates.
27842      */
27843     Transform.prototype._basicToSfm = function (basic) {
27844         var rotatedX;
27845         var rotatedY;
27846         switch (this._orientation) {
27847             case 1:
27848                 rotatedX = basic[0];
27849                 rotatedY = basic[1];
27850                 break;
27851             case 3:
27852                 rotatedX = 1 - basic[0];
27853                 rotatedY = 1 - basic[1];
27854                 break;
27855             case 6:
27856                 rotatedX = basic[1];
27857                 rotatedY = 1 - basic[0];
27858                 break;
27859             case 8:
27860                 rotatedX = 1 - basic[1];
27861                 rotatedY = basic[0];
27862                 break;
27863             default:
27864                 rotatedX = basic[0];
27865                 rotatedY = basic[1];
27866                 break;
27867         }
27868         var w = this._width;
27869         var h = this._height;
27870         var s = Math.max(w, h);
27871         var sfmX = rotatedX * w / s - w / s / 2;
27872         var sfmY = rotatedY * h / s - h / s / 2;
27873         return [sfmX, sfmY];
27874     };
27875     /**
27876      * Convert SfM coordinates to basic coordinates.
27877      *
27878      * @param {Array<number>} sfm - 2D SfM coordinates.
27879      * @returns {Array<number>} 2D basic coordinates.
27880      */
27881     Transform.prototype._sfmToBasic = function (sfm) {
27882         var w = this._width;
27883         var h = this._height;
27884         var s = Math.max(w, h);
27885         var rotatedX = (sfm[0] + w / s / 2) / w * s;
27886         var rotatedY = (sfm[1] + h / s / 2) / h * s;
27887         var basicX;
27888         var basicY;
27889         switch (this._orientation) {
27890             case 1:
27891                 basicX = rotatedX;
27892                 basicY = rotatedY;
27893                 break;
27894             case 3:
27895                 basicX = 1 - rotatedX;
27896                 basicY = 1 - rotatedY;
27897                 break;
27898             case 6:
27899                 basicX = 1 - rotatedY;
27900                 basicY = rotatedX;
27901                 break;
27902             case 8:
27903                 basicX = rotatedY;
27904                 basicY = 1 - rotatedX;
27905                 break;
27906             default:
27907                 basicX = rotatedX;
27908                 basicY = rotatedY;
27909                 break;
27910         }
27911         return [basicX, basicY];
27912     };
27913     /**
27914      * Determines if the gpano information indicates a full panorama.
27915      *
27916      * @returns {boolean} Value determining if the gpano information indicates
27917      * a full panorama.
27918      */
27919     Transform.prototype._fullPano = function () {
27920         return this.gpano != null &&
27921             this.gpano.CroppedAreaLeftPixels === 0 &&
27922             this.gpano.CroppedAreaTopPixels === 0 &&
27923             this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
27924             this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
27925     };
27926     /**
27927      * Checks a value and returns it if it exists and is larger than 0.
27928      * Fallbacks if it is null.
27929      *
27930      * @param {number} value - Value to check.
27931      * @param {number} fallback - Value to fall back to.
27932      * @returns {number} The value or its fallback value if it is not defined or negative.
27933      */
27934     Transform.prototype._getValue = function (value, fallback) {
27935         return value != null && value > 0 ? value : fallback;
27936     };
27937     /**
27938      * Creates the extrinsic camera matrix [ R | t ].
27939      *
27940      * @param {Array<number>} rotation - Rotation vector in angle axis representation.
27941      * @param {Array<number>} translation - Translation vector.
27942      * @returns {THREE.Matrix4} Extrisic camera matrix.
27943      */
27944     Transform.prototype._getRt = function (rotation, translation) {
27945         var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
27946         var angle = axis.length();
27947         axis.normalize();
27948         var rt = new THREE.Matrix4();
27949         rt.makeRotationAxis(axis, angle);
27950         rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
27951         return rt;
27952     };
27953     /**
27954      * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
27955      *
27956      * @param {THREE.Matrix4} rt - Extrisic camera matrix.
27957      * @param {number} scale - Scale factor.
27958      * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
27959      */
27960     Transform.prototype._getSrt = function (rt, scale) {
27961         var srt = rt.clone();
27962         var elements = srt.elements;
27963         elements[12] = scale * elements[12];
27964         elements[13] = scale * elements[13];
27965         elements[14] = scale * elements[14];
27966         srt.scale(new THREE.Vector3(scale, scale, scale));
27967         return srt;
27968     };
27969     /**
27970      * Calculate a transformation matrix from normalized coordinates for
27971      * texture map coordinates.
27972      *
27973      * @returns {THREE.Matrix4} Normalized coordinates to texture map
27974      * coordinates transformation matrix.
27975      */
27976     Transform.prototype._normalizedToTextureMatrix = function () {
27977         var size = Math.max(this._width, this._height);
27978         var w = size / this._width;
27979         var h = size / this._height;
27980         switch (this._orientation) {
27981             case 1:
27982                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
27983             case 3:
27984                 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
27985             case 6:
27986                 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
27987             case 8:
27988                 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
27989             default:
27990                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
27991         }
27992     };
27993     return Transform;
27994 }());
27995 exports.Transform = Transform;
27996
27997 },{"three":167}],288:[function(require,module,exports){
27998 /// <reference path="../../typings/index.d.ts" />
27999 "use strict";
28000 var THREE = require("three");
28001 /**
28002  * @class ViewportCoords
28003  *
28004  * @classdesc Provides methods for calculating 2D coordinate conversions
28005  * as well as 3D projection and unprojection.
28006  *
28007  * Basic coordinates are 2D coordinates on the [0, 1] interval and
28008  * have the origin point, (0, 0), at the top left corner and the
28009  * maximum value, (1, 1), at the bottom right corner of the original
28010  * photo.
28011  *
28012  * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
28013  * have the origin point in the center. The bottom left corner point is
28014  * (-1, -1) and the top right corner point is (1, 1).
28015  *
28016  * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
28017  * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
28018  * corner and the maximum value is (canvasWidth, canvasHeight) is in the
28019  * bottom right corner.
28020  *
28021  * 3D coordinates are in the topocentric world reference frame.
28022  */
28023 var ViewportCoords = (function () {
28024     function ViewportCoords() {
28025         this._unprojectDepth = 200;
28026     }
28027     /**
28028      * Convert basic coordinates to canvas coordinates.
28029      *
28030      * @description Transform origin and perspective camera position needs to be the
28031      * equal for reliable return value.
28032      *
28033      * @param {number} basicX - Basic X coordinate.
28034      * @param {number} basicY - Basic Y coordinate.
28035      * @param {number} canvasWidth - Width of canvas.
28036      * @param {number} canvasHeight - Height of canvas.
28037      * @param {Transform} transform - Transform of the node to unproject from.
28038      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28039      * @returns {Array<number>} 2D canvas coordinates.
28040      */
28041     ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, canvasWidth, canvasHeight, transform, perspectiveCamera) {
28042         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
28043         var canvas = this.projectToCanvas(point3d, canvasWidth, canvasHeight, perspectiveCamera);
28044         return canvas;
28045     };
28046     /**
28047      * Convert basic coordinates to viewport coordinates.
28048      *
28049      * @description Transform origin and perspective camera position needs to be the
28050      * equal for reliable return value.
28051      *
28052      * @param {number} basicX - Basic X coordinate.
28053      * @param {number} basicY - Basic Y coordinate.
28054      * @param {number} canvasWidth - Width of canvas.
28055      * @param {number} canvasHeight - Height of canvas.
28056      * @param {Transform} transform - Transform of the node to unproject from.
28057      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28058      * @returns {Array<number>} 2D canvas coordinates.
28059      */
28060     ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, perspectiveCamera) {
28061         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
28062         var viewport = this.projectToViewport(point3d, perspectiveCamera);
28063         return viewport;
28064     };
28065     /**
28066      * Convert canvas coordinates to basic coordinates.
28067      *
28068      * @description Transform origin and perspective camera position needs to be the
28069      * equal for reliable return value.
28070      *
28071      * @param {number} canvasX - Canvas X coordinate.
28072      * @param {number} canvasY - Canvas Y coordinate.
28073      * @param {number} canvasWidth - Width of canvas.
28074      * @param {number} canvasHeight - Height of canvas.
28075      * @param {Transform} transform - Transform of the node to unproject from.
28076      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28077      * @returns {Array<number>} 2D basic coordinates.
28078      */
28079     ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, canvasWidth, canvasHeight, transform, perspectiveCamera) {
28080         var point3d = this.unprojectFromCanvas(canvasX, canvasY, canvasWidth, canvasHeight, perspectiveCamera)
28081             .toArray();
28082         var basic = transform.projectBasic(point3d);
28083         return basic;
28084     };
28085     /**
28086      * Convert canvas coordinates to viewport coordinates.
28087      *
28088      * @param {number} canvasX - Canvas X coordinate.
28089      * @param {number} canvasY - Canvas Y coordinate.
28090      * @param {number} canvasWidth - Width of canvas.
28091      * @param {number} canvasHeight - Height of canvas.
28092      * @returns {Array<number>} 2D viewport coordinates.
28093      */
28094     ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, canvasWidth, canvasHeight) {
28095         var viewportX = 2 * canvasX / canvasWidth - 1;
28096         var viewportY = 1 - 2 * canvasY / canvasHeight;
28097         return [viewportX, viewportY];
28098     };
28099     /**
28100      * Determine basic distances from image to canvas corners.
28101      *
28102      * @description Transform origin and perspective camera position needs to be the
28103      * equal for reliable return value.
28104      *
28105      * Determines the smallest basic distance for every side of the canvas.
28106      *
28107      * @param {Transform} transform - Transform of the node to unproject from.
28108      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28109      * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
28110      */
28111     ViewportCoords.prototype.getBasicDistances = function (transform, perspectiveCamera) {
28112         var topLeftBasic = this.viewportToBasic(-1, 1, transform, perspectiveCamera);
28113         var topRightBasic = this.viewportToBasic(1, 1, transform, perspectiveCamera);
28114         var bottomRightBasic = this.viewportToBasic(1, -1, transform, perspectiveCamera);
28115         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, perspectiveCamera);
28116         var topBasicDistance = 0;
28117         var rightBasicDistance = 0;
28118         var bottomBasicDistance = 0;
28119         var leftBasicDistance = 0;
28120         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
28121             topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
28122                 -topLeftBasic[1] :
28123                 -topRightBasic[1];
28124         }
28125         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
28126             rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
28127                 topRightBasic[0] - 1 :
28128                 bottomRightBasic[0] - 1;
28129         }
28130         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
28131             bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
28132                 bottomRightBasic[1] - 1 :
28133                 bottomLeftBasic[1] - 1;
28134         }
28135         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
28136             leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
28137                 -bottomLeftBasic[0] :
28138                 -topLeftBasic[0];
28139         }
28140         return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
28141     };
28142     /**
28143      * Determine pixel distances from image to canvas corners.
28144      *
28145      * @description Transform origin and perspective camera position needs to be the
28146      * equal for reliable return value.
28147      *
28148      * Determines the smallest pixel distance for every side of the canvas.
28149      *
28150      * @param {number} canvasWidth - Width of canvas.
28151      * @param {number} canvasHeight - Height of canvas.
28152      * @param {Transform} transform - Transform of the node to unproject from.
28153      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28154      * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
28155      */
28156     ViewportCoords.prototype.getPixelDistances = function (canvasWidth, canvasHeight, transform, perspectiveCamera) {
28157         var topLeftBasic = this.viewportToBasic(-1, 1, transform, perspectiveCamera);
28158         var topRightBasic = this.viewportToBasic(1, 1, transform, perspectiveCamera);
28159         var bottomRightBasic = this.viewportToBasic(1, -1, transform, perspectiveCamera);
28160         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, perspectiveCamera);
28161         var topPixelDistance = 0;
28162         var rightPixelDistance = 0;
28163         var bottomPixelDistance = 0;
28164         var leftPixelDistance = 0;
28165         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
28166             var basicX = topLeftBasic[1] > topRightBasic[1] ?
28167                 topLeftBasic[0] :
28168                 topRightBasic[0];
28169             var canvas = this.basicToCanvas(basicX, 0, canvasWidth, canvasHeight, transform, perspectiveCamera);
28170             topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
28171         }
28172         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
28173             var basicY = topRightBasic[0] < bottomRightBasic[0] ?
28174                 topRightBasic[1] :
28175                 bottomRightBasic[1];
28176             var canvas = this.basicToCanvas(1, basicY, canvasWidth, canvasHeight, transform, perspectiveCamera);
28177             rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
28178         }
28179         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
28180             var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
28181                 bottomRightBasic[0] :
28182                 bottomLeftBasic[0];
28183             var canvas = this.basicToCanvas(basicX, 1, canvasWidth, canvasHeight, transform, perspectiveCamera);
28184             bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
28185         }
28186         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
28187             var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
28188                 bottomLeftBasic[1] :
28189                 topLeftBasic[1];
28190             var canvas = this.basicToCanvas(0, basicY, canvasWidth, canvasHeight, transform, perspectiveCamera);
28191             leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
28192         }
28193         return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
28194     };
28195     /**
28196      * Project 3D world coordinates to canvas coordinates.
28197      *
28198      * @param {Array<number>} point3D - 3D world coordinates.
28199      * @param {number} canvasWidth - Width of canvas.
28200      * @param {number} canvasHeight - Height of canvas.
28201      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28202      * @returns {Array<number>} 3D world coordinates.
28203      */
28204     ViewportCoords.prototype.projectToCanvas = function (point3d, canvasWidth, canvasHeight, perspectiveCamera) {
28205         var viewport = this.projectToViewport(point3d, perspectiveCamera);
28206         var canvas = this.viewportToCanvas(viewport[0], viewport[1], canvasWidth, canvasHeight);
28207         return canvas;
28208     };
28209     /**
28210      * Project 3D world coordinates to viewport coordinates.
28211      *
28212      * @param {Array<number>} point3D - 3D world coordinates.
28213      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28214      * @returns {Array<number>} 3D world coordinates.
28215      */
28216     ViewportCoords.prototype.projectToViewport = function (point3d, perspectiveCamera) {
28217         var projected = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
28218             .project(perspectiveCamera);
28219         var z = Math.abs(projected.z) < 1e-9 ?
28220             projected.z < 0 ?
28221                 -1e-9 : 1e-9 :
28222             projected.z;
28223         var viewportX = projected.x / z;
28224         var viewportY = projected.y / z;
28225         return [viewportX, viewportY];
28226     };
28227     /**
28228      * Uproject canvas coordinates to 3D world coordinates.
28229      *
28230      * @param {number} canvasX - Canvas X coordinate.
28231      * @param {number} canvasY - Canvas Y coordinate.
28232      * @param {number} canvasWidth - Width of canvas.
28233      * @param {number} canvasHeight - Height of canvas.
28234      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28235      * @returns {Array<number>} 3D world coordinates.
28236      */
28237     ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, canvasWidth, canvasHeight, perspectiveCamera) {
28238         var viewport = this.canvasToViewport(canvasX, canvasY, canvasWidth, canvasHeight);
28239         var point3d = this.unprojectFromViewport(viewport[0], viewport[1], perspectiveCamera);
28240         return point3d;
28241     };
28242     /**
28243      * Unproject viewport coordinates to 3D world coordinates.
28244      *
28245      * @param {number} viewportX - Viewport X coordinate.
28246      * @param {number} viewportY - Viewport Y coordinate.
28247      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28248      * @returns {Array<number>} 3D world coordinates.
28249      */
28250     ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, perspectiveCamera) {
28251         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
28252             .unproject(perspectiveCamera);
28253         return point3d;
28254     };
28255     /**
28256      * Convert viewport coordinates to basic coordinates.
28257      *
28258      * @description Transform origin and perspective camera position needs to be the
28259      * equal for reliable return value.
28260      *
28261      * @param {number} viewportX - Viewport X coordinate.
28262      * @param {number} viewportY - Viewport Y coordinate.
28263      * @param {Transform} transform - Transform of the node to unproject from.
28264      * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
28265      * @returns {Array<number>} 2D basic coordinates.
28266      */
28267     ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, perspectiveCamera) {
28268         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
28269             .unproject(perspectiveCamera)
28270             .toArray();
28271         var basic = transform.projectBasic(point3d);
28272         return basic;
28273     };
28274     /**
28275      * Convert viewport coordinates to canvas coordinates.
28276      *
28277      * @param {number} viewportX - Viewport X coordinate.
28278      * @param {number} viewportY - Viewport Y coordinate.
28279      * @param {number} canvasWidth - Width of canvas.
28280      * @param {number} canvasHeight - Height of canvas.
28281      * @returns {Array<number>} 2D canvas coordinates.
28282      */
28283     ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, canvasWidth, canvasHeight) {
28284         var canvasX = canvasWidth * (viewportX + 1) / 2;
28285         var canvasY = -canvasHeight * (viewportY - 1) / 2;
28286         return [canvasX, canvasY];
28287     };
28288     return ViewportCoords;
28289 }());
28290 exports.ViewportCoords = ViewportCoords;
28291 Object.defineProperty(exports, "__esModule", { value: true });
28292 exports.default = ViewportCoords;
28293
28294 },{"three":167}],289:[function(require,module,exports){
28295 "use strict";
28296 /**
28297  * @class Filter
28298  *
28299  * @classdesc Represents a class for creating node filters. Implementation and
28300  * definitions based on https://github.com/mapbox/feature-filter.
28301  */
28302 var FilterCreator = (function () {
28303     function FilterCreator() {
28304     }
28305     /**
28306      * Create a filter from a filter expression.
28307      *
28308      * @description The following filters are supported:
28309      *
28310      * Comparison
28311      * `==`
28312      * `!=`
28313      * `<`
28314      * `<=`
28315      * `>`
28316      * `>=`
28317      *
28318      * Set membership
28319      * `in`
28320      * `!in`
28321      *
28322      * Combining
28323      * `all`
28324      *
28325      * @param {FilterExpression} filter - Comparison, set membership or combinding filter
28326      * expression.
28327      * @returns {FilterFunction} Function taking a node and returning a boolean that
28328      * indicates whether the node passed the test or not.
28329      */
28330     FilterCreator.prototype.createFilter = function (filter) {
28331         return new Function("node", "return " + this._compile(filter) + ";");
28332     };
28333     FilterCreator.prototype._compile = function (filter) {
28334         if (filter == null || filter.length <= 1) {
28335             return "true";
28336         }
28337         var operator = filter[0];
28338         var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
28339             operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
28340                 operator === ">" ||
28341                     operator === ">=" ||
28342                     operator === "<" ||
28343                     operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
28344                     operator === "in" ?
28345                         this._compileInOp(filter[1], filter.slice(2)) :
28346                         operator === "!in" ?
28347                             this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
28348                             operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
28349                                 "true";
28350         return "(" + operation + ")";
28351     };
28352     FilterCreator.prototype._compare = function (a, b) {
28353         return a < b ? -1 : a > b ? 1 : 0;
28354     };
28355     FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
28356         var left = this._compilePropertyReference(property);
28357         var right = JSON.stringify(value);
28358         return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
28359     };
28360     FilterCreator.prototype._compileInOp = function (property, values) {
28361         var compare = this._compare;
28362         var left = JSON.stringify(values.sort(compare));
28363         var right = this._compilePropertyReference(property);
28364         return left + ".indexOf(" + right + ")!==-1";
28365     };
28366     FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
28367         var compile = this._compile.bind(this);
28368         return filters.map(compile).join(operator);
28369     };
28370     FilterCreator.prototype._compileNegation = function (expression) {
28371         return "!(" + expression + ")";
28372     };
28373     FilterCreator.prototype._compilePropertyReference = function (property) {
28374         return "node[" + JSON.stringify(property) + "]";
28375     };
28376     return FilterCreator;
28377 }());
28378 exports.FilterCreator = FilterCreator;
28379 Object.defineProperty(exports, "__esModule", { value: true });
28380 exports.default = FilterCreator;
28381
28382 },{}],290:[function(require,module,exports){
28383 /// <reference path="../../typings/index.d.ts" />
28384 "use strict";
28385 var rbush = require("rbush");
28386 var Subject_1 = require("rxjs/Subject");
28387 require("rxjs/add/observable/from");
28388 require("rxjs/add/operator/catch");
28389 require("rxjs/add/operator/do");
28390 require("rxjs/add/operator/finally");
28391 require("rxjs/add/operator/map");
28392 require("rxjs/add/operator/publish");
28393 var Edge_1 = require("../Edge");
28394 var Error_1 = require("../Error");
28395 var Graph_1 = require("../Graph");
28396 /**
28397  * @class Graph
28398  *
28399  * @classdesc Represents a graph of nodes with edges.
28400  */
28401 var Graph = (function () {
28402     /**
28403      * Create a new graph instance.
28404      *
28405      * @param {APIv3} [apiV3] - API instance for retrieving data.
28406      * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
28407      * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
28408      * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
28409      * @param {FilterCreator} [filterCreator] - Instance for  filter creation.
28410      * @param {IGraphConfiguration} [configuration] - Configuration struct.
28411      */
28412     function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
28413         this._apiV3 = apiV3;
28414         this._cachedNodes = {};
28415         this._cachedNodeTiles = {};
28416         this._cachedSpatialEdges = {};
28417         this._cachedTiles = {};
28418         this._cachingFill$ = {};
28419         this._cachingFull$ = {};
28420         this._cachingSequences$ = {};
28421         this._cachingSpatialArea$ = {};
28422         this._cachingTiles$ = {};
28423         this._changed$ = new Subject_1.Subject();
28424         this._defaultAlt = 2;
28425         this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
28426         this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
28427         this._filter = this._filterCreator.createFilter(undefined);
28428         this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
28429         this._configuration = configuration != null ?
28430             configuration :
28431             {
28432                 maxSequences: 50,
28433                 maxUnusedNodes: 100,
28434                 maxUnusedTiles: 20,
28435             };
28436         this._nodes = {};
28437         this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
28438         this._nodeIndexTiles = {};
28439         this._nodeToTile = {};
28440         this._preStored = {};
28441         this._requiredNodeTiles = {};
28442         this._requiredSpatialArea = {};
28443         this._sequences = {};
28444         this._tilePrecision = 7;
28445         this._tileThreshold = 20;
28446     }
28447     Object.defineProperty(Graph.prototype, "changed$", {
28448         /**
28449          * Get changed$.
28450          *
28451          * @returns {Observable<Graph>} Observable emitting
28452          * the graph every time it has changed.
28453          */
28454         get: function () {
28455             return this._changed$;
28456         },
28457         enumerable: true,
28458         configurable: true
28459     });
28460     /**
28461      * Retrieve and cache node fill properties.
28462      *
28463      * @param {string} key - Key of node to fill.
28464      * @returns {Observable<Graph>} Observable emitting the graph
28465      * when the node has been updated.
28466      * @throws {GraphMapillaryError} When the operation is not valid on the
28467      * current graph.
28468      */
28469     Graph.prototype.cacheFill$ = function (key) {
28470         var _this = this;
28471         if (key in this._cachingFull$) {
28472             throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
28473         }
28474         if (!this.hasNode(key)) {
28475             throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
28476         }
28477         if (key in this._cachingFill$) {
28478             return this._cachingFill$[key];
28479         }
28480         var node = this.getNode(key);
28481         if (node.full) {
28482             throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
28483         }
28484         this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
28485             .do(function (imageByKeyFill) {
28486             if (!node.full) {
28487                 _this._makeFull(node, imageByKeyFill[key]);
28488             }
28489             delete _this._cachingFill$[key];
28490         })
28491             .map(function (imageByKeyFill) {
28492             return _this;
28493         })
28494             .finally(function () {
28495             if (key in _this._cachingFill$) {
28496                 delete _this._cachingFill$[key];
28497             }
28498             _this._changed$.next(_this);
28499         })
28500             .publish()
28501             .refCount();
28502         return this._cachingFill$[key];
28503     };
28504     /**
28505      * Retrieve and cache full node properties.
28506      *
28507      * @param {string} key - Key of node to fill.
28508      * @returns {Observable<Graph>} Observable emitting the graph
28509      * when the node has been updated.
28510      * @throws {GraphMapillaryError} When the operation is not valid on the
28511      * current graph.
28512      */
28513     Graph.prototype.cacheFull$ = function (key) {
28514         var _this = this;
28515         if (key in this._cachingFull$) {
28516             return this._cachingFull$[key];
28517         }
28518         if (this.hasNode(key)) {
28519             throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
28520         }
28521         this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
28522             .do(function (imageByKeyFull) {
28523             var fn = imageByKeyFull[key];
28524             if (_this.hasNode(key)) {
28525                 var node = _this.getNode(key);
28526                 if (!node.full) {
28527                     _this._makeFull(node, fn);
28528                 }
28529             }
28530             else {
28531                 if (fn.sequence == null || fn.sequence.key == null) {
28532                     throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
28533                 }
28534                 var node = new Graph_1.Node(fn);
28535                 _this._makeFull(node, fn);
28536                 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
28537                 _this._preStore(h, node);
28538                 _this._setNode(node);
28539                 delete _this._cachingFull$[key];
28540             }
28541         })
28542             .map(function (imageByKeyFull) {
28543             return _this;
28544         })
28545             .finally(function () {
28546             if (key in _this._cachingFull$) {
28547                 delete _this._cachingFull$[key];
28548             }
28549             _this._changed$.next(_this);
28550         })
28551             .publish()
28552             .refCount();
28553         return this._cachingFull$[key];
28554     };
28555     /**
28556      * Retrieve and cache a node sequence.
28557      *
28558      * @param {string} key - Key of node for which to retrieve sequence.
28559      * @returns {Observable<Graph>} Observable emitting the graph
28560      * when the sequence has been retrieved.
28561      * @throws {GraphMapillaryError} When the operation is not valid on the
28562      * current graph.
28563      */
28564     Graph.prototype.cacheNodeSequence$ = function (key) {
28565         if (!this.hasNode(key)) {
28566             throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
28567         }
28568         var node = this.getNode(key);
28569         if (node.sequenceKey in this._sequences) {
28570             throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
28571         }
28572         return this._cacheSequence$(node.sequenceKey);
28573     };
28574     /**
28575      * Retrieve and cache a sequence.
28576      *
28577      * @param {string} sequenceKey - Key of sequence to cache.
28578      * @returns {Observable<Graph>} Observable emitting the graph
28579      * when the sequence has been retrieved.
28580      * @throws {GraphMapillaryError} When the operation is not valid on the
28581      * current graph.
28582      */
28583     Graph.prototype.cacheSequence$ = function (sequenceKey) {
28584         if (sequenceKey in this._sequences) {
28585             throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
28586         }
28587         return this._cacheSequence$(sequenceKey);
28588     };
28589     /**
28590      * Cache sequence edges for a node.
28591      *
28592      * @param {string} key - Key of node.
28593      * @throws {GraphMapillaryError} When the operation is not valid on the
28594      * current graph.
28595      */
28596     Graph.prototype.cacheSequenceEdges = function (key) {
28597         var node = this.getNode(key);
28598         if (!(node.sequenceKey in this._sequences)) {
28599             throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
28600         }
28601         var sequence = this._sequences[node.sequenceKey].sequence;
28602         var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
28603         node.cacheSequenceEdges(edges);
28604     };
28605     /**
28606      * Retrieve and cache full nodes for a node spatial area.
28607      *
28608      * @param {string} key - Key of node for which to retrieve sequence.
28609      * @returns {Observable<Graph>} Observable emitting the graph
28610      * when the nodes in the spatial area has been made full.
28611      * @throws {GraphMapillaryError} When the operation is not valid on the
28612      * current graph.
28613      */
28614     Graph.prototype.cacheSpatialArea$ = function (key) {
28615         var _this = this;
28616         if (!this.hasNode(key)) {
28617             throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
28618         }
28619         if (key in this._cachedSpatialEdges) {
28620             throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
28621         }
28622         if (!(key in this._requiredSpatialArea)) {
28623             throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
28624         }
28625         var spatialArea = this._requiredSpatialArea[key];
28626         if (Object.keys(spatialArea.cacheNodes).length === 0) {
28627             throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
28628         }
28629         if (key in this._cachingSpatialArea$) {
28630             return this._cachingSpatialArea$[key];
28631         }
28632         var batches = [];
28633         while (spatialArea.cacheKeys.length > 0) {
28634             batches.push(spatialArea.cacheKeys.splice(0, 200));
28635         }
28636         var batchesToCache = batches.length;
28637         var spatialNodes$ = [];
28638         var _loop_1 = function (batch) {
28639             var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
28640                 .do(function (imageByKeyFill) {
28641                 for (var fillKey in imageByKeyFill) {
28642                     if (!imageByKeyFill.hasOwnProperty(fillKey)) {
28643                         continue;
28644                     }
28645                     var spatialNode = spatialArea.cacheNodes[fillKey];
28646                     if (spatialNode.full) {
28647                         delete spatialArea.cacheNodes[fillKey];
28648                         continue;
28649                     }
28650                     var fillNode = imageByKeyFill[fillKey];
28651                     _this._makeFull(spatialNode, fillNode);
28652                     delete spatialArea.cacheNodes[fillKey];
28653                 }
28654                 if (--batchesToCache === 0) {
28655                     delete _this._cachingSpatialArea$[key];
28656                 }
28657             })
28658                 .map(function (imageByKeyFill) {
28659                 return _this;
28660             })
28661                 .catch(function (error) {
28662                 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
28663                     var batchKey = batch_1[_i];
28664                     if (batchKey in spatialArea.all) {
28665                         delete spatialArea.all[batchKey];
28666                     }
28667                     if (batchKey in spatialArea.cacheNodes) {
28668                         delete spatialArea.cacheNodes[batchKey];
28669                     }
28670                 }
28671                 if (--batchesToCache === 0) {
28672                     delete _this._cachingSpatialArea$[key];
28673                 }
28674                 throw error;
28675             })
28676                 .finally(function () {
28677                 if (Object.keys(spatialArea.cacheNodes).length === 0) {
28678                     _this._changed$.next(_this);
28679                 }
28680             })
28681                 .publish()
28682                 .refCount();
28683             spatialNodes$.push(spatialNodeBatch$);
28684         };
28685         var this_1 = this;
28686         for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
28687             var batch = batches_1[_i];
28688             _loop_1(batch);
28689         }
28690         this._cachingSpatialArea$[key] = spatialNodes$;
28691         return spatialNodes$;
28692     };
28693     /**
28694      * Cache spatial edges for a node.
28695      *
28696      * @param {string} key - Key of node.
28697      * @throws {GraphMapillaryError} When the operation is not valid on the
28698      * current graph.
28699      */
28700     Graph.prototype.cacheSpatialEdges = function (key) {
28701         if (key in this._cachedSpatialEdges) {
28702             throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
28703         }
28704         var node = this.getNode(key);
28705         var sequence = this._sequences[node.sequenceKey].sequence;
28706         var fallbackKeys = [];
28707         var prevKey = sequence.findPrevKey(node.key);
28708         if (prevKey != null) {
28709             fallbackKeys.push(prevKey);
28710         }
28711         var nextKey = sequence.findNextKey(node.key);
28712         if (nextKey != null) {
28713             fallbackKeys.push(nextKey);
28714         }
28715         var allSpatialNodes = this._requiredSpatialArea[key].all;
28716         var potentialNodes = [];
28717         var filter = this._filter;
28718         for (var spatialNodeKey in allSpatialNodes) {
28719             if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
28720                 continue;
28721             }
28722             var spatialNode = allSpatialNodes[spatialNodeKey];
28723             if (filter(spatialNode)) {
28724                 potentialNodes.push(spatialNode);
28725             }
28726         }
28727         var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
28728         var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
28729         edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
28730         edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
28731         edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
28732         edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
28733         node.cacheSpatialEdges(edges);
28734         this._cachedSpatialEdges[key] = node;
28735         delete this._requiredSpatialArea[key];
28736         delete this._cachedNodeTiles[key];
28737     };
28738     /**
28739      * Retrieve and cache geohash tiles for a node.
28740      *
28741      * @param {string} key - Key of node for which to retrieve tiles.
28742      * @returns {Observable<Graph>} Observable emitting the graph
28743      * when the tiles required for the node has been cached.
28744      * @throws {GraphMapillaryError} When the operation is not valid on the
28745      * current graph.
28746      */
28747     Graph.prototype.cacheTiles$ = function (key) {
28748         var _this = this;
28749         if (key in this._cachedNodeTiles) {
28750             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
28751         }
28752         if (key in this._cachedSpatialEdges) {
28753             throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
28754         }
28755         if (!(key in this._requiredNodeTiles)) {
28756             throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
28757         }
28758         var nodeTiles = this._requiredNodeTiles[key];
28759         if (nodeTiles.cache.length === 0 &&
28760             nodeTiles.caching.length === 0) {
28761             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
28762         }
28763         if (!this.hasNode(key)) {
28764             throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
28765         }
28766         var hs = nodeTiles.cache.slice();
28767         nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
28768         nodeTiles.cache = [];
28769         var cacheTiles$ = [];
28770         var _loop_2 = function (h) {
28771             var cacheTile$ = null;
28772             if (h in this_2._cachingTiles$) {
28773                 cacheTile$ = this_2._cachingTiles$[h];
28774             }
28775             else {
28776                 cacheTile$ = this_2._apiV3.imagesByH$([h])
28777                     .do(function (imagesByH) {
28778                     var coreNodes = imagesByH[h];
28779                     if (h in _this._cachedTiles) {
28780                         return;
28781                     }
28782                     _this._nodeIndexTiles[h] = [];
28783                     _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
28784                     var hCache = _this._cachedTiles[h].nodes;
28785                     var preStored = _this._removeFromPreStore(h);
28786                     for (var index in coreNodes) {
28787                         if (!coreNodes.hasOwnProperty(index)) {
28788                             continue;
28789                         }
28790                         var coreNode = coreNodes[index];
28791                         if (coreNode == null) {
28792                             break;
28793                         }
28794                         if (coreNode.sequence == null ||
28795                             coreNode.sequence.key == null) {
28796                             console.warn("Sequence missing, discarding (" + coreNode.key + ")");
28797                             continue;
28798                         }
28799                         if (preStored != null && coreNode.key in preStored) {
28800                             var node_1 = preStored[coreNode.key];
28801                             delete preStored[coreNode.key];
28802                             hCache.push(node_1);
28803                             var nodeIndexItem_1 = {
28804                                 lat: node_1.latLon.lat,
28805                                 lon: node_1.latLon.lon,
28806                                 node: node_1,
28807                             };
28808                             _this._nodeIndex.insert(nodeIndexItem_1);
28809                             _this._nodeIndexTiles[h].push(nodeIndexItem_1);
28810                             _this._nodeToTile[node_1.key] = h;
28811                             continue;
28812                         }
28813                         var node = new Graph_1.Node(coreNode);
28814                         hCache.push(node);
28815                         var nodeIndexItem = {
28816                             lat: node.latLon.lat,
28817                             lon: node.latLon.lon,
28818                             node: node,
28819                         };
28820                         _this._nodeIndex.insert(nodeIndexItem);
28821                         _this._nodeIndexTiles[h].push(nodeIndexItem);
28822                         _this._nodeToTile[node.key] = h;
28823                         _this._setNode(node);
28824                     }
28825                     delete _this._cachingTiles$[h];
28826                 })
28827                     .map(function (imagesByH) {
28828                     return _this;
28829                 })
28830                     .catch(function (error) {
28831                     delete _this._cachingTiles$[h];
28832                     throw error;
28833                 })
28834                     .publish()
28835                     .refCount();
28836                 this_2._cachingTiles$[h] = cacheTile$;
28837             }
28838             cacheTiles$.push(cacheTile$
28839                 .do(function (graph) {
28840                 var index = nodeTiles.caching.indexOf(h);
28841                 if (index > -1) {
28842                     nodeTiles.caching.splice(index, 1);
28843                 }
28844                 if (nodeTiles.caching.length === 0 &&
28845                     nodeTiles.cache.length === 0) {
28846                     delete _this._requiredNodeTiles[key];
28847                     _this._cachedNodeTiles[key] = true;
28848                 }
28849             })
28850                 .catch(function (error) {
28851                 var index = nodeTiles.caching.indexOf(h);
28852                 if (index > -1) {
28853                     nodeTiles.caching.splice(index, 1);
28854                 }
28855                 if (nodeTiles.caching.length === 0 &&
28856                     nodeTiles.cache.length === 0) {
28857                     delete _this._requiredNodeTiles[key];
28858                     _this._cachedNodeTiles[key] = true;
28859                 }
28860                 throw error;
28861             })
28862                 .finally(function () {
28863                 _this._changed$.next(_this);
28864             })
28865                 .publish()
28866                 .refCount());
28867         };
28868         var this_2 = this;
28869         for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
28870             var h = _a[_i];
28871             _loop_2(h);
28872         }
28873         return cacheTiles$;
28874     };
28875     /**
28876      * Initialize the cache for a node.
28877      *
28878      * @param {string} key - Key of node.
28879      * @throws {GraphMapillaryError} When the operation is not valid on the
28880      * current graph.
28881      */
28882     Graph.prototype.initializeCache = function (key) {
28883         if (key in this._cachedNodes) {
28884             throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
28885         }
28886         var node = this.getNode(key);
28887         node.initializeCache(new Graph_1.NodeCache());
28888         var accessed = new Date().getTime();
28889         this._cachedNodes[key] = { accessed: accessed, node: node };
28890         this._updateCachedTileAccess(key, accessed);
28891     };
28892     /**
28893      * Get a value indicating if the graph is fill caching a node.
28894      *
28895      * @param {string} key - Key of node.
28896      * @returns {boolean} Value indicating if the node is being fill cached.
28897      */
28898     Graph.prototype.isCachingFill = function (key) {
28899         return key in this._cachingFill$;
28900     };
28901     /**
28902      * Get a value indicating if the graph is fully caching a node.
28903      *
28904      * @param {string} key - Key of node.
28905      * @returns {boolean} Value indicating if the node is being fully cached.
28906      */
28907     Graph.prototype.isCachingFull = function (key) {
28908         return key in this._cachingFull$;
28909     };
28910     /**
28911      * Get a value indicating if the graph is caching a sequence of a node.
28912      *
28913      * @param {string} key - Key of node.
28914      * @returns {boolean} Value indicating if the sequence of a node is
28915      * being cached.
28916      */
28917     Graph.prototype.isCachingNodeSequence = function (key) {
28918         var node = this.getNode(key);
28919         return node.sequenceKey in this._cachingSequences$;
28920     };
28921     /**
28922      * Get a value indicating if the graph is caching a sequence.
28923      *
28924      * @param {string} sequenceKey - Key of sequence.
28925      * @returns {boolean} Value indicating if the sequence is
28926      * being cached.
28927      */
28928     Graph.prototype.isCachingSequence = function (sequenceKey) {
28929         return sequenceKey in this._cachingSequences$;
28930     };
28931     /**
28932      * Get a value indicating if the graph is caching the tiles
28933      * required for calculating spatial edges of a node.
28934      *
28935      * @param {string} key - Key of node.
28936      * @returns {boolean} Value indicating if the tiles of
28937      * a node are being cached.
28938      */
28939     Graph.prototype.isCachingTiles = function (key) {
28940         return key in this._requiredNodeTiles &&
28941             this._requiredNodeTiles[key].cache.length === 0 &&
28942             this._requiredNodeTiles[key].caching.length > 0;
28943     };
28944     /**
28945      * Get a value indicating if the cache has been initialized
28946      * for a node.
28947      *
28948      * @param {string} key - Key of node.
28949      * @returns {boolean} Value indicating if the cache has been
28950      * initialized for a node.
28951      */
28952     Graph.prototype.hasInitializedCache = function (key) {
28953         return key in this._cachedNodes;
28954     };
28955     /**
28956      * Get a value indicating if a node exist in the graph.
28957      *
28958      * @param {string} key - Key of node.
28959      * @returns {boolean} Value indicating if a node exist in the graph.
28960      */
28961     Graph.prototype.hasNode = function (key) {
28962         var accessed = new Date().getTime();
28963         this._updateCachedNodeAccess(key, accessed);
28964         this._updateCachedTileAccess(key, accessed);
28965         return key in this._nodes;
28966     };
28967     /**
28968      * Get a value indicating if a node sequence exist in the graph.
28969      *
28970      * @param {string} key - Key of node.
28971      * @returns {boolean} Value indicating if a node sequence exist
28972      * in the graph.
28973      */
28974     Graph.prototype.hasNodeSequence = function (key) {
28975         var node = this.getNode(key);
28976         var sequenceKey = node.sequenceKey;
28977         var hasNodeSequence = sequenceKey in this._sequences;
28978         if (hasNodeSequence) {
28979             this._sequences[sequenceKey].accessed = new Date().getTime();
28980         }
28981         return hasNodeSequence;
28982     };
28983     /**
28984      * Get a value indicating if a sequence exist in the graph.
28985      *
28986      * @param {string} sequenceKey - Key of sequence.
28987      * @returns {boolean} Value indicating if a sequence exist
28988      * in the graph.
28989      */
28990     Graph.prototype.hasSequence = function (sequenceKey) {
28991         var hasSequence = sequenceKey in this._sequences;
28992         if (hasSequence) {
28993             this._sequences[sequenceKey].accessed = new Date().getTime();
28994         }
28995         return hasSequence;
28996     };
28997     /**
28998      * Get a value indicating if the graph has fully cached
28999      * all nodes in the spatial area of a node.
29000      *
29001      * @param {string} key - Key of node.
29002      * @returns {boolean} Value indicating if the spatial area
29003      * of a node has been cached.
29004      */
29005     Graph.prototype.hasSpatialArea = function (key) {
29006         if (!this.hasNode(key)) {
29007             throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
29008         }
29009         if (key in this._cachedSpatialEdges) {
29010             return true;
29011         }
29012         if (key in this._requiredSpatialArea) {
29013             return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
29014         }
29015         var node = this.getNode(key);
29016         var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
29017         var spatialItems = this._nodeIndex.search({
29018             maxX: bbox[1].lat,
29019             maxY: bbox[1].lon,
29020             minX: bbox[0].lat,
29021             minY: bbox[0].lon,
29022         });
29023         var spatialNodes = {
29024             all: {},
29025             cacheKeys: [],
29026             cacheNodes: {},
29027         };
29028         for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
29029             var spatialItem = spatialItems_1[_i];
29030             spatialNodes.all[spatialItem.node.key] = spatialItem.node;
29031             if (!spatialItem.node.full) {
29032                 spatialNodes.cacheKeys.push(spatialItem.node.key);
29033                 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
29034             }
29035         }
29036         this._requiredSpatialArea[key] = spatialNodes;
29037         return spatialNodes.cacheKeys.length === 0;
29038     };
29039     /**
29040      * Get a value indicating if the graph has a tiles required
29041      * for a node.
29042      *
29043      * @param {string} key - Key of node.
29044      * @returns {boolean} Value indicating if the the tiles required
29045      * by a node has been cached.
29046      */
29047     Graph.prototype.hasTiles = function (key) {
29048         var _this = this;
29049         if (key in this._cachedNodeTiles) {
29050             return true;
29051         }
29052         if (key in this._cachedSpatialEdges) {
29053             return true;
29054         }
29055         if (!this.hasNode(key)) {
29056             throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
29057         }
29058         var nodeTiles = { cache: [], caching: [] };
29059         if (!(key in this._requiredNodeTiles)) {
29060             var node = this.getNode(key);
29061             nodeTiles.cache = this._graphCalculator
29062                 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
29063                 .filter(function (h) {
29064                 return !(h in _this._cachedTiles);
29065             });
29066             if (nodeTiles.cache.length > 0) {
29067                 this._requiredNodeTiles[key] = nodeTiles;
29068             }
29069         }
29070         else {
29071             nodeTiles = this._requiredNodeTiles[key];
29072         }
29073         return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
29074     };
29075     /**
29076      * Get a node.
29077      *
29078      * @param {string} key - Key of node.
29079      * @returns {Node} Retrieved node.
29080      */
29081     Graph.prototype.getNode = function (key) {
29082         var accessed = new Date().getTime();
29083         this._updateCachedNodeAccess(key, accessed);
29084         this._updateCachedTileAccess(key, accessed);
29085         return this._nodes[key];
29086     };
29087     /**
29088      * Get a sequence.
29089      *
29090      * @param {string} sequenceKey - Key of sequence.
29091      * @returns {Node} Retrieved sequence.
29092      */
29093     Graph.prototype.getSequence = function (sequenceKey) {
29094         var sequenceAccess = this._sequences[sequenceKey];
29095         sequenceAccess.accessed = new Date().getTime();
29096         return sequenceAccess.sequence;
29097     };
29098     /**
29099      * Reset all spatial edges of the graph nodes.
29100      */
29101     Graph.prototype.resetSpatialEdges = function () {
29102         var cachedKeys = Object.keys(this._cachedSpatialEdges);
29103         for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
29104             var cachedKey = cachedKeys_1[_i];
29105             var node = this._cachedSpatialEdges[cachedKey];
29106             node.resetSpatialEdges();
29107             delete this._cachedSpatialEdges[cachedKey];
29108         }
29109     };
29110     /**
29111      * Reset the complete graph but keep the nodes corresponding
29112      * to the supplied keys. All other nodes will be disposed.
29113      *
29114      * @param {Array<string>} keepKeys - Keys for nodes to keep
29115      * in graph after reset.
29116      */
29117     Graph.prototype.reset = function (keepKeys) {
29118         var nodes = [];
29119         for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
29120             var key = keepKeys_1[_i];
29121             if (!this.hasNode(key)) {
29122                 throw new Error("Node does not exist " + key);
29123             }
29124             var node = this.getNode(key);
29125             node.resetSequenceEdges();
29126             node.resetSpatialEdges();
29127             nodes.push(node);
29128         }
29129         for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
29130             var cachedKey = _b[_a];
29131             if (keepKeys.indexOf(cachedKey) !== -1) {
29132                 continue;
29133             }
29134             this._cachedNodes[cachedKey].node.dispose();
29135             delete this._cachedNodes[cachedKey];
29136         }
29137         this._cachedNodeTiles = {};
29138         this._cachedSpatialEdges = {};
29139         this._cachedTiles = {};
29140         this._cachingFill$ = {};
29141         this._cachingFull$ = {};
29142         this._cachingSequences$ = {};
29143         this._cachingSpatialArea$ = {};
29144         this._cachingTiles$ = {};
29145         this._nodes = {};
29146         this._nodeToTile = {};
29147         this._preStored = {};
29148         for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
29149             var node = nodes_1[_c];
29150             this._nodes[node.key] = node;
29151             var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
29152             this._preStore(h, node);
29153         }
29154         this._requiredNodeTiles = {};
29155         this._requiredSpatialArea = {};
29156         this._sequences = {};
29157         this._nodeIndexTiles = {};
29158         this._nodeIndex.clear();
29159     };
29160     /**
29161      * Set the spatial node filter.
29162      *
29163      * @param {FilterExpression} filter - Filter expression to be applied
29164      * when calculating spatial edges.
29165      */
29166     Graph.prototype.setFilter = function (filter) {
29167         this._filter = this._filterCreator.createFilter(filter);
29168     };
29169     /**
29170      * Uncache the graph according to the graph configuration.
29171      *
29172      * @description Uncaches unused tiles, unused nodes and
29173      * sequences according to the numbers specified in the
29174      * graph configuration. Sequences does not have a direct
29175      * reference to either tiles or nodes and may be uncached
29176      * even if they are related to the nodes that should be kept.
29177      *
29178      * @param {Array<string>} keepKeys - Keys of nodes to keep in
29179      * graph unrelated to last access. Tiles related to those keys
29180      * will also be kept in graph.
29181      */
29182     Graph.prototype.uncache = function (keepKeys) {
29183         var keysInUse = {};
29184         this._addNewKeys(keysInUse, this._cachingFull$);
29185         this._addNewKeys(keysInUse, this._cachingFill$);
29186         this._addNewKeys(keysInUse, this._cachingTiles$);
29187         this._addNewKeys(keysInUse, this._cachingSpatialArea$);
29188         this._addNewKeys(keysInUse, this._requiredNodeTiles);
29189         this._addNewKeys(keysInUse, this._requiredSpatialArea);
29190         for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
29191             var key = keepKeys_2[_i];
29192             if (key in keysInUse) {
29193                 continue;
29194             }
29195             keysInUse[key] = true;
29196         }
29197         var keepHs = {};
29198         for (var key in keysInUse) {
29199             if (!keysInUse.hasOwnProperty(key)) {
29200                 continue;
29201             }
29202             var node = this._nodes[key];
29203             var nodeHs = this._graphCalculator.encodeHs(node.latLon);
29204             for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
29205                 var nodeH = nodeHs_1[_a];
29206                 if (!(nodeH in keepHs)) {
29207                     keepHs[nodeH] = true;
29208                 }
29209             }
29210         }
29211         var potentialHs = [];
29212         for (var h in this._cachedTiles) {
29213             if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
29214                 continue;
29215             }
29216             potentialHs.push([h, this._cachedTiles[h]]);
29217         }
29218         var uncacheHs = potentialHs
29219             .sort(function (h1, h2) {
29220             return h2[1].accessed - h1[1].accessed;
29221         })
29222             .slice(this._configuration.maxUnusedTiles)
29223             .map(function (h) {
29224             return h[0];
29225         });
29226         for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
29227             var uncacheH = uncacheHs_1[_b];
29228             this._uncacheTile(uncacheH);
29229         }
29230         var potentialNodes = [];
29231         for (var key in this._cachedNodes) {
29232             if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
29233                 continue;
29234             }
29235             potentialNodes.push(this._cachedNodes[key]);
29236         }
29237         var uncacheNodes = potentialNodes
29238             .sort(function (n1, n2) {
29239             return n2.accessed - n1.accessed;
29240         })
29241             .slice(this._configuration.maxUnusedNodes);
29242         for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
29243             var nodeAccess = uncacheNodes_1[_c];
29244             nodeAccess.node.uncache();
29245             var key = nodeAccess.node.key;
29246             delete this._cachedNodes[key];
29247             if (key in this._cachedNodeTiles) {
29248                 delete this._cachedNodeTiles[key];
29249             }
29250             if (key in this._cachedSpatialEdges) {
29251                 delete this._cachedSpatialEdges[key];
29252             }
29253         }
29254         var potentialSequences = [];
29255         for (var sequenceKey in this._sequences) {
29256             if (!this._sequences.hasOwnProperty(sequenceKey) ||
29257                 sequenceKey in this._cachingSequences$) {
29258                 continue;
29259             }
29260             potentialSequences.push(this._sequences[sequenceKey]);
29261         }
29262         var uncacheSequences = potentialSequences
29263             .sort(function (s1, s2) {
29264             return s2.accessed - s1.accessed;
29265         })
29266             .slice(this._configuration.maxSequences);
29267         for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
29268             var sequenceAccess = uncacheSequences_1[_d];
29269             var sequenceKey = sequenceAccess.sequence.key;
29270             delete this._sequences[sequenceKey];
29271             sequenceAccess.sequence.dispose();
29272         }
29273     };
29274     Graph.prototype._addNewKeys = function (keys, dict) {
29275         for (var key in dict) {
29276             if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
29277                 continue;
29278             }
29279             if (!(key in keys)) {
29280                 keys[key] = true;
29281             }
29282         }
29283     };
29284     Graph.prototype._cacheSequence$ = function (sequenceKey) {
29285         var _this = this;
29286         if (sequenceKey in this._cachingSequences$) {
29287             return this._cachingSequences$[sequenceKey];
29288         }
29289         this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
29290             .do(function (sequenceByKey) {
29291             if (!(sequenceKey in _this._sequences)) {
29292                 _this._sequences[sequenceKey] = {
29293                     accessed: new Date().getTime(),
29294                     sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
29295                 };
29296             }
29297             delete _this._cachingSequences$[sequenceKey];
29298         })
29299             .map(function (sequenceByKey) {
29300             return _this;
29301         })
29302             .finally(function () {
29303             if (sequenceKey in _this._cachingSequences$) {
29304                 delete _this._cachingSequences$[sequenceKey];
29305             }
29306             _this._changed$.next(_this);
29307         })
29308             .publish()
29309             .refCount();
29310         return this._cachingSequences$[sequenceKey];
29311     };
29312     Graph.prototype._makeFull = function (node, fillNode) {
29313         if (fillNode.calt == null) {
29314             fillNode.calt = this._defaultAlt;
29315         }
29316         if (fillNode.c_rotation == null) {
29317             fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
29318         }
29319         node.makeFull(fillNode);
29320     };
29321     Graph.prototype._preStore = function (h, node) {
29322         if (!(h in this._preStored)) {
29323             this._preStored[h] = {};
29324         }
29325         this._preStored[h][node.key] = node;
29326     };
29327     Graph.prototype._removeFromPreStore = function (h) {
29328         var preStored = null;
29329         if (h in this._preStored) {
29330             preStored = this._preStored[h];
29331             delete this._preStored[h];
29332         }
29333         return preStored;
29334     };
29335     Graph.prototype._setNode = function (node) {
29336         var key = node.key;
29337         if (this.hasNode(key)) {
29338             throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
29339         }
29340         this._nodes[key] = node;
29341     };
29342     Graph.prototype._uncacheTile = function (h) {
29343         for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
29344             var node = _a[_i];
29345             var key = node.key;
29346             delete this._nodes[key];
29347             delete this._nodeToTile[key];
29348             if (key in this._cachedNodes) {
29349                 delete this._cachedNodes[key];
29350             }
29351             if (key in this._cachedNodeTiles) {
29352                 delete this._cachedNodeTiles[key];
29353             }
29354             if (key in this._cachedSpatialEdges) {
29355                 delete this._cachedSpatialEdges[key];
29356             }
29357             node.dispose();
29358         }
29359         for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
29360             var nodeIndexItem = _c[_b];
29361             this._nodeIndex.remove(nodeIndexItem);
29362         }
29363         delete this._nodeIndexTiles[h];
29364         delete this._cachedTiles[h];
29365     };
29366     Graph.prototype._updateCachedTileAccess = function (key, accessed) {
29367         if (key in this._nodeToTile) {
29368             this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
29369         }
29370     };
29371     Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
29372         if (key in this._cachedNodes) {
29373             this._cachedNodes[key].accessed = accessed;
29374         }
29375     };
29376     return Graph;
29377 }());
29378 exports.Graph = Graph;
29379 Object.defineProperty(exports, "__esModule", { value: true });
29380 exports.default = Graph;
29381
29382 },{"../Edge":218,"../Error":219,"../Graph":221,"rbush":24,"rxjs/Subject":33,"rxjs/add/observable/from":40,"rxjs/add/operator/catch":49,"rxjs/add/operator/do":56,"rxjs/add/operator/finally":59,"rxjs/add/operator/map":62,"rxjs/add/operator/publish":68}],291:[function(require,module,exports){
29383 /// <reference path="../../typings/index.d.ts" />
29384 "use strict";
29385 var geohash = require("latlon-geohash");
29386 var THREE = require("three");
29387 var Geo_1 = require("../Geo");
29388 var GeoHashDirections = (function () {
29389     function GeoHashDirections() {
29390     }
29391     return GeoHashDirections;
29392 }());
29393 GeoHashDirections.n = "n";
29394 GeoHashDirections.nw = "nw";
29395 GeoHashDirections.w = "w";
29396 GeoHashDirections.sw = "sw";
29397 GeoHashDirections.s = "s";
29398 GeoHashDirections.se = "se";
29399 GeoHashDirections.e = "e";
29400 GeoHashDirections.ne = "ne";
29401 /**
29402  * @class GraphCalculator
29403  *
29404  * @classdesc Represents a calculator for graph entities.
29405  */
29406 var GraphCalculator = (function () {
29407     /**
29408      * Create a new graph calculator instance.
29409      *
29410      * @param {GeoCoords} geoCoords - Geo coords instance.
29411      */
29412     function GraphCalculator(geoCoords) {
29413         this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
29414     }
29415     /**
29416      * Encode the geohash tile for geodetic coordinates.
29417      *
29418      * @param {ILatLon} latlon - Latitude and longitude to encode.
29419      * @param {number} precision - Precision of the encoding.
29420      *
29421      * @returns {string} The geohash tile for the lat, lon and precision.
29422      */
29423     GraphCalculator.prototype.encodeH = function (latLon, precision) {
29424         if (precision === void 0) { precision = 7; }
29425         return geohash.encode(latLon.lat, latLon.lon, precision);
29426     };
29427     /**
29428      * Encode the geohash tiles within a threshold from a position
29429      * using Manhattan distance.
29430      *
29431      * @param {ILatLon} latlon - Latitude and longitude to encode.
29432      * @param {number} precision - Precision of the encoding.
29433      * @param {number} threshold - Threshold of the encoding in meters.
29434      *
29435      * @returns {string} The geohash tiles reachable within the threshold.
29436      */
29437     GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
29438         if (precision === void 0) { precision = 7; }
29439         if (threshold === void 0) { threshold = 20; }
29440         var h = geohash.encode(latLon.lat, latLon.lon, precision);
29441         var bounds = geohash.bounds(h);
29442         var ne = bounds.ne;
29443         var sw = bounds.sw;
29444         var neighbours = geohash.neighbours(h);
29445         var bl = [0, 0, 0];
29446         var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
29447         var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
29448         var left = position[0] - bl[0];
29449         var right = tr[0] - position[0];
29450         var bottom = position[1] - bl[1];
29451         var top = tr[1] - position[1];
29452         var l = left < threshold;
29453         var r = right < threshold;
29454         var b = bottom < threshold;
29455         var t = top < threshold;
29456         var hs = [h];
29457         if (t) {
29458             hs.push(neighbours[GeoHashDirections.n]);
29459         }
29460         if (t && l) {
29461             hs.push(neighbours[GeoHashDirections.nw]);
29462         }
29463         if (l) {
29464             hs.push(neighbours[GeoHashDirections.w]);
29465         }
29466         if (l && b) {
29467             hs.push(neighbours[GeoHashDirections.sw]);
29468         }
29469         if (b) {
29470             hs.push(neighbours[GeoHashDirections.s]);
29471         }
29472         if (b && r) {
29473             hs.push(neighbours[GeoHashDirections.se]);
29474         }
29475         if (r) {
29476             hs.push(neighbours[GeoHashDirections.e]);
29477         }
29478         if (r && t) {
29479             hs.push(neighbours[GeoHashDirections.ne]);
29480         }
29481         return hs;
29482     };
29483     /**
29484      * Get the bounding box corners for a circle with radius of a threshold
29485      * with center in a geodetic position.
29486      *
29487      * @param {ILatLon} latlon - Latitude and longitude to encode.
29488      * @param {number} threshold - Threshold distance from the position in meters.
29489      *
29490      * @returns {Array<ILatLon>} The south west and north east corners of the
29491      * bounding box.
29492      */
29493     GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
29494         var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
29495         var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
29496         return [
29497             { lat: bl[0], lon: bl[1] },
29498             { lat: tr[0], lon: tr[1] },
29499         ];
29500     };
29501     /**
29502      * Convert a compass angle to an angle axis rotation vector.
29503      *
29504      * @param {number} compassAngle - The compass angle in degrees.
29505      * @param {number} orientation - The orientation of the original image.
29506      *
29507      * @returns {Array<number>} Angle axis rotation vector.
29508      */
29509     GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
29510         var x = 0;
29511         var y = 0;
29512         var z = 0;
29513         switch (orientation) {
29514             case 1:
29515                 x = Math.PI / 2;
29516                 break;
29517             case 3:
29518                 x = -Math.PI / 2;
29519                 z = Math.PI;
29520                 break;
29521             case 6:
29522                 y = -Math.PI / 2;
29523                 z = -Math.PI / 2;
29524                 break;
29525             case 8:
29526                 y = Math.PI / 2;
29527                 z = Math.PI / 2;
29528                 break;
29529             default:
29530                 break;
29531         }
29532         var rz = new THREE.Matrix4().makeRotationZ(z);
29533         var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
29534         var re = new THREE.Matrix4().makeRotationFromEuler(euler);
29535         var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
29536         return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
29537     };
29538     return GraphCalculator;
29539 }());
29540 exports.GraphCalculator = GraphCalculator;
29541 Object.defineProperty(exports, "__esModule", { value: true });
29542 exports.default = GraphCalculator;
29543
29544 },{"../Geo":220,"latlon-geohash":20,"three":167}],292:[function(require,module,exports){
29545 "use strict";
29546 var Observable_1 = require("rxjs/Observable");
29547 var Subject_1 = require("rxjs/Subject");
29548 require("rxjs/add/operator/catch");
29549 require("rxjs/add/operator/concat");
29550 require("rxjs/add/operator/do");
29551 require("rxjs/add/operator/expand");
29552 require("rxjs/add/operator/finally");
29553 require("rxjs/add/operator/first");
29554 require("rxjs/add/operator/last");
29555 require("rxjs/add/operator/map");
29556 require("rxjs/add/operator/mergeMap");
29557 require("rxjs/add/operator/publishReplay");
29558 /**
29559  * @class GraphService
29560  *
29561  * @classdesc Represents a service for graph operations.
29562  */
29563 var GraphService = (function () {
29564     /**
29565      * Create a new graph service instance.
29566      *
29567      * @param {Graph} graph - Graph instance to be operated on.
29568      */
29569     function GraphService(graph, imageLoadingService) {
29570         this._graph$ = Observable_1.Observable
29571             .of(graph)
29572             .concat(graph.changed$)
29573             .publishReplay(1)
29574             .refCount();
29575         this._graph$.subscribe(function () { });
29576         this._imageLoadingService = imageLoadingService;
29577         this._firstGraphSubjects$ = [];
29578         this._initializeCacheSubscriptions = [];
29579         this._sequenceSubscriptions = [];
29580         this._spatialSubscriptions = [];
29581     }
29582     /**
29583      * Cache a node in the graph and retrieve it.
29584      *
29585      * @description When called, the full properties of
29586      * the node are retrieved and the node cache is initialized.
29587      * After that the node assets are cached and the node
29588      * is emitted to the observable when.
29589      * In parallel to caching the node assets, the sequence and
29590      * spatial edges of the node are cached. For this, the sequence
29591      * of the node and the required tiles and spatial nodes are
29592      * retrieved. The sequence and spatial edges may be set before
29593      * or after the node is returned.
29594      *
29595      * @param {string} key - Key of the node to cache.
29596      * @return {Observable<Node>} Observable emitting a single item,
29597      * the node, when it has been retrieved and its assets are cached.
29598      * @throws {Error} Propagates any IO node caching errors to the caller.
29599      */
29600     GraphService.prototype.cacheNode$ = function (key) {
29601         var _this = this;
29602         var firstGraphSubject$ = new Subject_1.Subject();
29603         this._firstGraphSubjects$.push(firstGraphSubject$);
29604         var firstGraph$ = firstGraphSubject$
29605             .publishReplay(1)
29606             .refCount();
29607         var node$ = firstGraph$
29608             .map(function (graph) {
29609             return graph.getNode(key);
29610         })
29611             .mergeMap(function (node) {
29612             return node.assetsCached ?
29613                 Observable_1.Observable.of(node) :
29614                 node.cacheAssets$();
29615         })
29616             .publishReplay(1)
29617             .refCount();
29618         node$.subscribe(function (node) {
29619             _this._imageLoadingService.loadnode$.next(node);
29620         }, function (error) {
29621             console.error("Failed to cache node (" + key + ")", error);
29622         });
29623         var initializeCacheSubscription = this._graph$
29624             .first()
29625             .mergeMap(function (graph) {
29626             if (graph.isCachingFull(key) || !graph.hasNode(key)) {
29627                 return graph.cacheFull$(key);
29628             }
29629             if (graph.isCachingFill(key) || !graph.getNode(key).full) {
29630                 return graph.cacheFill$(key);
29631             }
29632             return Observable_1.Observable.of(graph);
29633         })
29634             .do(function (graph) {
29635             if (!graph.hasInitializedCache(key)) {
29636                 graph.initializeCache(key);
29637             }
29638         })
29639             .finally(function () {
29640             if (initializeCacheSubscription == null) {
29641                 return;
29642             }
29643             _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
29644             _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
29645         })
29646             .subscribe(function (graph) {
29647             firstGraphSubject$.next(graph);
29648             firstGraphSubject$.complete();
29649         }, function (error) {
29650             firstGraphSubject$.error(error);
29651         });
29652         if (!initializeCacheSubscription.closed) {
29653             this._initializeCacheSubscriptions.push(initializeCacheSubscription);
29654         }
29655         var sequenceSubscription = firstGraph$
29656             .mergeMap(function (graph) {
29657             if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
29658                 return graph.cacheNodeSequence$(key);
29659             }
29660             return Observable_1.Observable.of(graph);
29661         })
29662             .do(function (graph) {
29663             if (!graph.getNode(key).sequenceEdges.cached) {
29664                 graph.cacheSequenceEdges(key);
29665             }
29666         })
29667             .finally(function () {
29668             if (sequenceSubscription == null) {
29669                 return;
29670             }
29671             _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
29672         })
29673             .subscribe(function (graph) { return; }, function (error) {
29674             console.error("Failed to cache sequence edges (" + key + ").", error);
29675         });
29676         if (!sequenceSubscription.closed) {
29677             this._sequenceSubscriptions.push(sequenceSubscription);
29678         }
29679         var spatialSubscription = firstGraph$
29680             .expand(function (graph) {
29681             if (graph.hasTiles(key)) {
29682                 return Observable_1.Observable.empty();
29683             }
29684             return Observable_1.Observable
29685                 .from(graph.cacheTiles$(key))
29686                 .mergeMap(function (graph$) {
29687                 return graph$
29688                     .mergeMap(function (g) {
29689                     if (g.isCachingTiles(key)) {
29690                         return Observable_1.Observable.empty();
29691                     }
29692                     return Observable_1.Observable.of(g);
29693                 })
29694                     .catch(function (error, caught$) {
29695                     console.error("Failed to cache tile data (" + key + ").", error);
29696                     return Observable_1.Observable.empty();
29697                 });
29698             });
29699         })
29700             .last()
29701             .mergeMap(function (graph) {
29702             if (graph.hasSpatialArea(key)) {
29703                 return Observable_1.Observable.of(graph);
29704             }
29705             return Observable_1.Observable
29706                 .from(graph.cacheSpatialArea$(key))
29707                 .mergeMap(function (graph$) {
29708                 return graph$
29709                     .catch(function (error, caught$) {
29710                     console.error("Failed to cache spatial nodes (" + key + ").", error);
29711                     return Observable_1.Observable.empty();
29712                 });
29713             });
29714         })
29715             .last()
29716             .mergeMap(function (graph) {
29717             return graph.hasNodeSequence(key) ?
29718                 Observable_1.Observable.of(graph) :
29719                 graph.cacheNodeSequence$(key);
29720         })
29721             .do(function (graph) {
29722             if (!graph.getNode(key).spatialEdges.cached) {
29723                 graph.cacheSpatialEdges(key);
29724             }
29725         })
29726             .finally(function () {
29727             if (spatialSubscription == null) {
29728                 return;
29729             }
29730             _this._removeFromArray(spatialSubscription, _this._spatialSubscriptions);
29731         })
29732             .subscribe(function (graph) { return; }, function (error) {
29733             console.error("Failed to cache spatial edges (" + key + ").", error);
29734         });
29735         if (!spatialSubscription.closed) {
29736             this._spatialSubscriptions.push(spatialSubscription);
29737         }
29738         return node$
29739             .first(function (node) {
29740             return node.assetsCached;
29741         });
29742     };
29743     /**
29744      * Cache a sequence in the graph and retrieve it.
29745      *
29746      * @param {string} sequenceKey - Sequence key.
29747      * @returns {Observable<Sequence>} Observable emitting a single item,
29748      * the sequence, when it has been retrieved and its assets are cached.
29749      * @throws {Error} Propagates any IO node caching errors to the caller.
29750      */
29751     GraphService.prototype.cacheSequence$ = function (sequenceKey) {
29752         return this._graph$
29753             .first()
29754             .mergeMap(function (graph) {
29755             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
29756                 return graph.cacheSequence$(sequenceKey);
29757             }
29758             return Observable_1.Observable.of(graph);
29759         })
29760             .map(function (graph) {
29761             return graph.getSequence(sequenceKey);
29762         });
29763     };
29764     /**
29765      * Set a spatial edge filter on the graph.
29766      *
29767      * @description Resets the spatial edges of all cached nodes.
29768      *
29769      * @param {FilterExpression} filter - Filter expression to be applied.
29770      * @return {Observable<Graph>} Observable emitting a single item,
29771      * the graph, when the spatial edges have been reset.
29772      */
29773     GraphService.prototype.setFilter$ = function (filter) {
29774         this._resetSubscriptions(this._spatialSubscriptions);
29775         return this._graph$
29776             .first()
29777             .do(function (graph) {
29778             graph.resetSpatialEdges();
29779             graph.setFilter(filter);
29780         });
29781     };
29782     /**
29783      * Reset the graph.
29784      *
29785      * @description Resets the graph but keeps the nodes of the
29786      * supplied keys.
29787      *
29788      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
29789      * @return {Observable<Node>} Observable emitting a single item,
29790      * the graph, when it has been reset.
29791      */
29792     GraphService.prototype.reset$ = function (keepKeys) {
29793         this._abortSubjects(this._firstGraphSubjects$);
29794         this._resetSubscriptions(this._initializeCacheSubscriptions);
29795         this._resetSubscriptions(this._sequenceSubscriptions);
29796         this._resetSubscriptions(this._spatialSubscriptions);
29797         return this._graph$
29798             .first()
29799             .do(function (graph) {
29800             graph.reset(keepKeys);
29801         });
29802     };
29803     /**
29804      * Uncache the graph.
29805      *
29806      * @description Uncaches the graph by removing tiles, nodes and
29807      * sequences. Keeps the nodes of the supplied keys and the tiles
29808      * related to those nodes.
29809      *
29810      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
29811      * @return {Observable<Graph>} Observable emitting a single item,
29812      * the graph, when the graph has been uncached.
29813      */
29814     GraphService.prototype.uncache$ = function (keepKeys) {
29815         return this._graph$
29816             .first()
29817             .do(function (graph) {
29818             graph.uncache(keepKeys);
29819         });
29820     };
29821     GraphService.prototype._abortSubjects = function (subjects) {
29822         for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
29823             var subject = _a[_i];
29824             this._removeFromArray(subject, subjects);
29825             subject.error(new Error("Cache node request was aborted."));
29826         }
29827     };
29828     GraphService.prototype._removeFromArray = function (object, objects) {
29829         var index = objects.indexOf(object);
29830         if (index !== -1) {
29831             objects.splice(index, 1);
29832         }
29833     };
29834     GraphService.prototype._resetSubscriptions = function (subscriptions) {
29835         for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
29836             var subscription = _a[_i];
29837             this._removeFromArray(subscription, subscriptions);
29838             if (!subscription.closed) {
29839                 subscription.unsubscribe();
29840             }
29841         }
29842     };
29843     return GraphService;
29844 }());
29845 exports.GraphService = GraphService;
29846 Object.defineProperty(exports, "__esModule", { value: true });
29847 exports.default = GraphService;
29848
29849 },{"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/catch":49,"rxjs/add/operator/concat":51,"rxjs/add/operator/do":56,"rxjs/add/operator/expand":57,"rxjs/add/operator/finally":59,"rxjs/add/operator/first":60,"rxjs/add/operator/last":61,"rxjs/add/operator/map":62,"rxjs/add/operator/mergeMap":65,"rxjs/add/operator/publishReplay":69}],293:[function(require,module,exports){
29850 /// <reference path="../../typings/index.d.ts" />
29851 "use strict";
29852 var Subject_1 = require("rxjs/Subject");
29853 var ImageLoadingService = (function () {
29854     function ImageLoadingService() {
29855         this._loadnode$ = new Subject_1.Subject();
29856         this._loadstatus$ = this._loadnode$
29857             .scan(function (nodes, node) {
29858             nodes[node.key] = node.loadStatus;
29859             return nodes;
29860         }, {})
29861             .publishReplay(1)
29862             .refCount();
29863         this._loadstatus$.subscribe(function () { });
29864     }
29865     Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
29866         get: function () {
29867             return this._loadnode$;
29868         },
29869         enumerable: true,
29870         configurable: true
29871     });
29872     Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
29873         get: function () {
29874             return this._loadstatus$;
29875         },
29876         enumerable: true,
29877         configurable: true
29878     });
29879     return ImageLoadingService;
29880 }());
29881 exports.ImageLoadingService = ImageLoadingService;
29882
29883 },{"rxjs/Subject":33}],294:[function(require,module,exports){
29884 /// <reference path="../../typings/index.d.ts" />
29885 "use strict";
29886 var Pbf = require("pbf");
29887 var MeshReader = (function () {
29888     function MeshReader() {
29889     }
29890     MeshReader.read = function (buffer) {
29891         var pbf = new Pbf(buffer);
29892         return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
29893     };
29894     MeshReader._readMeshField = function (tag, mesh, pbf) {
29895         if (tag === 1) {
29896             mesh.vertices.push(pbf.readFloat());
29897         }
29898         else if (tag === 2) {
29899             mesh.faces.push(pbf.readVarint());
29900         }
29901     };
29902     return MeshReader;
29903 }());
29904 exports.MeshReader = MeshReader;
29905
29906 },{"pbf":22}],295:[function(require,module,exports){
29907 "use strict";
29908 require("rxjs/add/observable/combineLatest");
29909 require("rxjs/add/operator/map");
29910 /**
29911  * @class Node
29912  *
29913  * @classdesc Represents a node in the navigation graph.
29914  */
29915 var Node = (function () {
29916     /**
29917      * Create a new node instance.
29918      *
29919      * @param {ICoreNode} coreNode - Raw core node data.
29920      */
29921     function Node(core) {
29922         this._cache = null;
29923         this._core = core;
29924         this._fill = null;
29925     }
29926     Object.defineProperty(Node.prototype, "assetsCached", {
29927         /**
29928          * Get assets cached.
29929          *
29930          * @description The assets that need to be cached for this property
29931          * to report true are the following: fill properties, image and mesh.
29932          * The library ensures that the current node will always have the
29933          * assets cached.
29934          *
29935          * @returns {boolean} Value indicating whether all assets have been
29936          * cached.
29937          */
29938         get: function () {
29939             return this._core != null &&
29940                 this._fill != null &&
29941                 this._cache != null &&
29942                 this._cache.image != null &&
29943                 this._cache.mesh != null;
29944         },
29945         enumerable: true,
29946         configurable: true
29947     });
29948     Object.defineProperty(Node.prototype, "alt", {
29949         /**
29950          * Get alt.
29951          *
29952          * @description If SfM has not been run the computed altitude is
29953          * set to a default value of two meters.
29954          *
29955          * @returns {number} Altitude, in meters.
29956          */
29957         get: function () {
29958             return this._fill.calt;
29959         },
29960         enumerable: true,
29961         configurable: true
29962     });
29963     Object.defineProperty(Node.prototype, "ca", {
29964         /**
29965          * Get ca.
29966          *
29967          * @description If the SfM computed compass angle exists it will
29968          * be returned, otherwise the original EXIF compass angle.
29969          *
29970          * @returns {number} Compass angle, measured in degrees.
29971          */
29972         get: function () {
29973             return this._fill.cca != null ? this._fill.cca : this._fill.ca;
29974         },
29975         enumerable: true,
29976         configurable: true
29977     });
29978     Object.defineProperty(Node.prototype, "capturedAt", {
29979         /**
29980          * Get capturedAt.
29981          *
29982          * @returns {number} Timestamp when the image was captured.
29983          */
29984         get: function () {
29985             return this._fill.captured_at;
29986         },
29987         enumerable: true,
29988         configurable: true
29989     });
29990     Object.defineProperty(Node.prototype, "computedCA", {
29991         /**
29992          * Get computedCA.
29993          *
29994          * @description Will not be set if SfM has not been run.
29995          *
29996          * @returns {number} SfM computed compass angle, measured in degrees.
29997          */
29998         get: function () {
29999             return this._fill.cca;
30000         },
30001         enumerable: true,
30002         configurable: true
30003     });
30004     Object.defineProperty(Node.prototype, "computedLatLon", {
30005         /**
30006          * Get computedLatLon.
30007          *
30008          * @description Will not be set if SfM has not been run.
30009          *
30010          * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
30011          * measured in degrees.
30012          */
30013         get: function () {
30014             return this._core.cl;
30015         },
30016         enumerable: true,
30017         configurable: true
30018     });
30019     Object.defineProperty(Node.prototype, "focal", {
30020         /**
30021          * Get focal.
30022          *
30023          * @description Will not be set if SfM has not been run.
30024          *
30025          * @returns {number} SfM computed focal length.
30026          */
30027         get: function () {
30028             return this._fill.cfocal;
30029         },
30030         enumerable: true,
30031         configurable: true
30032     });
30033     Object.defineProperty(Node.prototype, "full", {
30034         /**
30035          * Get full.
30036          *
30037          * @description The library ensures that the current node will
30038          * always be full.
30039          *
30040          * @returns {boolean} Value indicating whether the node has all
30041          * properties filled.
30042          */
30043         get: function () {
30044             return this._fill != null;
30045         },
30046         enumerable: true,
30047         configurable: true
30048     });
30049     Object.defineProperty(Node.prototype, "fullPano", {
30050         /**
30051          * Get fullPano.
30052          *
30053          * @returns {boolean} Value indicating whether the node is a complete
30054          * 360 panorama.
30055          */
30056         get: function () {
30057             return this._fill.gpano != null &&
30058                 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
30059                 this._fill.gpano.CroppedAreaTopPixels === 0 &&
30060                 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
30061                 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
30062         },
30063         enumerable: true,
30064         configurable: true
30065     });
30066     Object.defineProperty(Node.prototype, "gpano", {
30067         /**
30068          * Get gpano.
30069          *
30070          * @description Will not be set for non panoramic images.
30071          *
30072          * @returns {IGPano} Panorama information for panorama images.
30073          */
30074         get: function () {
30075             return this._fill.gpano;
30076         },
30077         enumerable: true,
30078         configurable: true
30079     });
30080     Object.defineProperty(Node.prototype, "height", {
30081         /**
30082          * Get height.
30083          *
30084          * @returns {number} Height of original image, not adjusted
30085          * for orientation.
30086          */
30087         get: function () {
30088             return this._fill.height;
30089         },
30090         enumerable: true,
30091         configurable: true
30092     });
30093     Object.defineProperty(Node.prototype, "image", {
30094         /**
30095          * Get image.
30096          *
30097          * @description The image will always be set on the current node.
30098          *
30099          * @returns {HTMLImageElement} Cached image element of the node.
30100          */
30101         get: function () {
30102             return this._cache.image;
30103         },
30104         enumerable: true,
30105         configurable: true
30106     });
30107     Object.defineProperty(Node.prototype, "key", {
30108         /**
30109          * Get key.
30110          *
30111          * @returns {string} Unique key of the node.
30112          */
30113         get: function () {
30114             return this._core.key;
30115         },
30116         enumerable: true,
30117         configurable: true
30118     });
30119     Object.defineProperty(Node.prototype, "latLon", {
30120         /**
30121          * Get latLon.
30122          *
30123          * @description If the SfM computed latitude longitude exist
30124          * it will be returned, otherwise the original EXIF latitude
30125          * longitude.
30126          *
30127          * @returns {ILatLon} Latitude longitude in WGS84 datum,
30128          * measured in degrees.
30129          */
30130         get: function () {
30131             return this._core.cl != null ? this._core.cl : this._core.l;
30132         },
30133         enumerable: true,
30134         configurable: true
30135     });
30136     Object.defineProperty(Node.prototype, "loadStatus", {
30137         /**
30138          * Get loadStatus.
30139          *
30140          * @returns {ILoadStatus} Value indicating the load status
30141          * of the mesh and image.
30142          */
30143         get: function () {
30144             return this._cache.loadStatus;
30145         },
30146         enumerable: true,
30147         configurable: true
30148     });
30149     Object.defineProperty(Node.prototype, "merged", {
30150         /**
30151          * Get merged.
30152          *
30153          * @returns {boolean} Value indicating whether SfM has been
30154          * run on the node and the node has been merged into a
30155          * connected component.
30156          */
30157         get: function () {
30158             return this._fill != null &&
30159                 this._fill.merge_version != null &&
30160                 this._fill.merge_version > 0;
30161         },
30162         enumerable: true,
30163         configurable: true
30164     });
30165     Object.defineProperty(Node.prototype, "mergeCC", {
30166         /**
30167          * Get mergeCC.
30168          *
30169          * @description Will not be set if SfM has not yet been run on
30170          * node.
30171          *
30172          * @returns {number} SfM connected component key to which
30173          * image belongs.
30174          */
30175         get: function () {
30176             return this._fill.merge_cc;
30177         },
30178         enumerable: true,
30179         configurable: true
30180     });
30181     Object.defineProperty(Node.prototype, "mergeVersion", {
30182         /**
30183          * Get mergeVersion.
30184          *
30185          * @returns {number} Version for which SfM was run and image was merged.
30186          */
30187         get: function () {
30188             return this._fill.merge_version;
30189         },
30190         enumerable: true,
30191         configurable: true
30192     });
30193     Object.defineProperty(Node.prototype, "mesh", {
30194         /**
30195          * Get mesh.
30196          *
30197          * @description The mesh will always be set on the current node.
30198          *
30199          * @returns {IMesh} SfM triangulated mesh of reconstructed
30200          * atomic 3D points.
30201          */
30202         get: function () {
30203             return this._cache.mesh;
30204         },
30205         enumerable: true,
30206         configurable: true
30207     });
30208     Object.defineProperty(Node.prototype, "orientation", {
30209         /**
30210          * Get orientation.
30211          *
30212          * @returns {number} EXIF orientation of original image.
30213          */
30214         get: function () {
30215             return this._fill.orientation;
30216         },
30217         enumerable: true,
30218         configurable: true
30219     });
30220     Object.defineProperty(Node.prototype, "originalCA", {
30221         /**
30222          * Get originalCA.
30223          *
30224          * @returns {number} Original EXIF compass angle, measured in
30225          * degrees.
30226          */
30227         get: function () {
30228             return this._fill.ca;
30229         },
30230         enumerable: true,
30231         configurable: true
30232     });
30233     Object.defineProperty(Node.prototype, "originalLatLon", {
30234         /**
30235          * Get originalLatLon.
30236          *
30237          * @returns {ILatLon} Original EXIF latitude longitude in
30238          * WGS84 datum, measured in degrees.
30239          */
30240         get: function () {
30241             return this._core.l;
30242         },
30243         enumerable: true,
30244         configurable: true
30245     });
30246     Object.defineProperty(Node.prototype, "pano", {
30247         /**
30248          * Get pano.
30249          *
30250          * @returns {boolean} Value indicating whether the node is a panorama.
30251          * It could be a cropped or full panorama.
30252          */
30253         get: function () {
30254             return this._fill.gpano != null &&
30255                 this._fill.gpano.FullPanoWidthPixels != null;
30256         },
30257         enumerable: true,
30258         configurable: true
30259     });
30260     Object.defineProperty(Node.prototype, "projectKey", {
30261         /**
30262          * Get projectKey.
30263          *
30264          * @returns {string} Unique key of the project to which
30265          * the node belongs.
30266          */
30267         get: function () {
30268             return this._fill.project != null ?
30269                 this._fill.project.key :
30270                 null;
30271         },
30272         enumerable: true,
30273         configurable: true
30274     });
30275     Object.defineProperty(Node.prototype, "rotation", {
30276         /**
30277          * Get rotation.
30278          *
30279          * @description Will not be set if SfM has not been run.
30280          *
30281          * @returns {Array<number>} Rotation vector in angle axis representation.
30282          */
30283         get: function () {
30284             return this._fill.c_rotation;
30285         },
30286         enumerable: true,
30287         configurable: true
30288     });
30289     Object.defineProperty(Node.prototype, "scale", {
30290         /**
30291          * Get scale.
30292          *
30293          * @description Will not be set if SfM has not been run.
30294          *
30295          * @returns {number} Scale of atomic reconstruction.
30296          */
30297         get: function () {
30298             return this._fill.atomic_scale;
30299         },
30300         enumerable: true,
30301         configurable: true
30302     });
30303     Object.defineProperty(Node.prototype, "sequenceKey", {
30304         /**
30305          * Get sequenceKey.
30306          *
30307          * @returns {string} Unique key of the sequence to which
30308          * the node belongs.
30309          */
30310         get: function () {
30311             return this._core.sequence.key;
30312         },
30313         enumerable: true,
30314         configurable: true
30315     });
30316     Object.defineProperty(Node.prototype, "sequenceEdges", {
30317         /**
30318          * Get sequenceEdges.
30319          *
30320          * @returns {IEdgeStatus} Value describing the status of the
30321          * sequence edges.
30322          */
30323         get: function () {
30324             return this._cache.sequenceEdges;
30325         },
30326         enumerable: true,
30327         configurable: true
30328     });
30329     Object.defineProperty(Node.prototype, "sequenceEdges$", {
30330         /**
30331          * Get sequenceEdges$.
30332          *
30333          * @returns {Observable<IEdgeStatus>} Observable emitting
30334          * values describing the status of the sequence edges.
30335          */
30336         get: function () {
30337             return this._cache.sequenceEdges$;
30338         },
30339         enumerable: true,
30340         configurable: true
30341     });
30342     Object.defineProperty(Node.prototype, "spatialEdges", {
30343         /**
30344          * Get spatialEdges.
30345          *
30346          * @returns {IEdgeStatus} Value describing the status of the
30347          * spatial edges.
30348          */
30349         get: function () {
30350             return this._cache.spatialEdges;
30351         },
30352         enumerable: true,
30353         configurable: true
30354     });
30355     Object.defineProperty(Node.prototype, "spatialEdges$", {
30356         /**
30357          * Get spatialEdges$.
30358          *
30359          * @returns {Observable<IEdgeStatus>} Observable emitting
30360          * values describing the status of the spatial edges.
30361          */
30362         get: function () {
30363             return this._cache.spatialEdges$;
30364         },
30365         enumerable: true,
30366         configurable: true
30367     });
30368     Object.defineProperty(Node.prototype, "userKey", {
30369         /**
30370          * Get userKey.
30371          *
30372          * @returns {string} Unique key of the user who uploaded
30373          * the image.
30374          */
30375         get: function () {
30376             return this._fill.user.key;
30377         },
30378         enumerable: true,
30379         configurable: true
30380     });
30381     Object.defineProperty(Node.prototype, "username", {
30382         /**
30383          * Get username.
30384          *
30385          * @returns {string} Username of the user who uploaded
30386          * the image.
30387          */
30388         get: function () {
30389             return this._fill.user.username;
30390         },
30391         enumerable: true,
30392         configurable: true
30393     });
30394     Object.defineProperty(Node.prototype, "width", {
30395         /**
30396          * Get width.
30397          *
30398          * @returns {number} Width of original image, not
30399          * adjusted for orientation.
30400          */
30401         get: function () {
30402             return this._fill.width;
30403         },
30404         enumerable: true,
30405         configurable: true
30406     });
30407     /**
30408      * Cache the image and mesh assets.
30409      *
30410      * @description The assets are always cached internally by the
30411      * library prior to setting a node as the current node.
30412      *
30413      * @returns {Observable<Node>} Observable emitting this node whenever the
30414      * load status has changed and when the mesh or image has been fully loaded.
30415      */
30416     Node.prototype.cacheAssets$ = function () {
30417         var _this = this;
30418         return this._cache.cacheAssets$(this.key, this.pano, this.merged)
30419             .map(function (cache) {
30420             return _this;
30421         });
30422     };
30423     Node.prototype.cacheImage$ = function (imageSize) {
30424         var _this = this;
30425         return this._cache.cacheImage$(this.key, imageSize)
30426             .map(function (cache) {
30427             return _this;
30428         });
30429     };
30430     /**
30431      * Cache the sequence edges.
30432      *
30433      * @description The sequence edges are cached asynchronously
30434      * internally by the library.
30435      *
30436      * @param {Array<IEdge>} edges - Sequence edges to cache.
30437      */
30438     Node.prototype.cacheSequenceEdges = function (edges) {
30439         this._cache.cacheSequenceEdges(edges);
30440     };
30441     /**
30442      * Cache the spatial edges.
30443      *
30444      * @description The spatial edges are cached asynchronously
30445      * internally by the library.
30446      *
30447      * @param {Array<IEdge>} edges - Spatial edges to cache.
30448      */
30449     Node.prototype.cacheSpatialEdges = function (edges) {
30450         this._cache.cacheSpatialEdges(edges);
30451     };
30452     /**
30453      * Dispose the node.
30454      *
30455      * @description Disposes all cached assets.
30456      */
30457     Node.prototype.dispose = function () {
30458         if (this._cache != null) {
30459             this._cache.dispose();
30460             this._cache = null;
30461         }
30462         this._core = null;
30463         this._fill = null;
30464     };
30465     /**
30466      * Initialize the node cache.
30467      *
30468      * @description The node cache is initialized internally by
30469      * the library.
30470      *
30471      * @param {NodeCache} cache - The node cache to set as cache.
30472      */
30473     Node.prototype.initializeCache = function (cache) {
30474         if (this._cache != null) {
30475             throw new Error("Node cache already initialized (" + this.key + ").");
30476         }
30477         this._cache = cache;
30478     };
30479     /**
30480      * Fill the node with all properties.
30481      *
30482      * @description The node is filled internally by
30483      * the library.
30484      *
30485      * @param {IFillNode} fill - The fill node struct.
30486      */
30487     Node.prototype.makeFull = function (fill) {
30488         if (fill == null) {
30489             throw new Error("Fill can not be null.");
30490         }
30491         this._fill = fill;
30492     };
30493     /**
30494      * Reset the sequence edges.
30495      */
30496     Node.prototype.resetSequenceEdges = function () {
30497         this._cache.resetSequenceEdges();
30498     };
30499     /**
30500      * Reset the spatial edges.
30501      */
30502     Node.prototype.resetSpatialEdges = function () {
30503         this._cache.resetSpatialEdges();
30504     };
30505     /**
30506      * Clears the image and mesh assets, aborts
30507      * any outstanding requests and resets edges.
30508      */
30509     Node.prototype.uncache = function () {
30510         if (this._cache == null) {
30511             return;
30512         }
30513         this._cache.dispose();
30514         this._cache = null;
30515     };
30516     return Node;
30517 }());
30518 exports.Node = Node;
30519 Object.defineProperty(exports, "__esModule", { value: true });
30520 exports.default = Node;
30521
30522 },{"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/map":62}],296:[function(require,module,exports){
30523 (function (Buffer){
30524 "use strict";
30525 var Subject_1 = require("rxjs/Subject");
30526 var Observable_1 = require("rxjs/Observable");
30527 require("rxjs/add/observable/combineLatest");
30528 require("rxjs/add/operator/publishReplay");
30529 var Graph_1 = require("../Graph");
30530 var Utils_1 = require("../Utils");
30531 /**
30532  * @class NodeCache
30533  *
30534  * @classdesc Represents the cached properties of a node.
30535  */
30536 var NodeCache = (function () {
30537     /**
30538      * Create a new node cache instance.
30539      */
30540     function NodeCache() {
30541         this._disposed = false;
30542         this._image = null;
30543         this._loadStatus = { loaded: 0, total: 0 };
30544         this._mesh = null;
30545         this._sequenceEdges = { cached: false, edges: [] };
30546         this._spatialEdges = { cached: false, edges: [] };
30547         this._sequenceEdgesChanged$ = new Subject_1.Subject();
30548         this._sequenceEdges$ = this._sequenceEdgesChanged$
30549             .startWith(this._sequenceEdges)
30550             .publishReplay(1)
30551             .refCount();
30552         this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
30553         this._spatialEdgesChanged$ = new Subject_1.Subject();
30554         this._spatialEdges$ = this._spatialEdgesChanged$
30555             .startWith(this._spatialEdges)
30556             .publishReplay(1)
30557             .refCount();
30558         this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
30559         this._cachingAssets$ = null;
30560     }
30561     Object.defineProperty(NodeCache.prototype, "image", {
30562         /**
30563          * Get image.
30564          *
30565          * @description Will not be set when assets have not been cached
30566          * or when the object has been disposed.
30567          *
30568          * @returns {HTMLImageElement} Cached image element of the node.
30569          */
30570         get: function () {
30571             return this._image;
30572         },
30573         enumerable: true,
30574         configurable: true
30575     });
30576     Object.defineProperty(NodeCache.prototype, "loadStatus", {
30577         /**
30578          * Get loadStatus.
30579          *
30580          * @returns {ILoadStatus} Value indicating the load status
30581          * of the mesh and image.
30582          */
30583         get: function () {
30584             return this._loadStatus;
30585         },
30586         enumerable: true,
30587         configurable: true
30588     });
30589     Object.defineProperty(NodeCache.prototype, "mesh", {
30590         /**
30591          * Get mesh.
30592          *
30593          * @description Will not be set when assets have not been cached
30594          * or when the object has been disposed.
30595          *
30596          * @returns {IMesh} SfM triangulated mesh of reconstructed
30597          * atomic 3D points.
30598          */
30599         get: function () {
30600             return this._mesh;
30601         },
30602         enumerable: true,
30603         configurable: true
30604     });
30605     Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
30606         /**
30607          * Get sequenceEdges.
30608          *
30609          * @returns {IEdgeStatus} Value describing the status of the
30610          * sequence edges.
30611          */
30612         get: function () {
30613             return this._sequenceEdges;
30614         },
30615         enumerable: true,
30616         configurable: true
30617     });
30618     Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
30619         /**
30620          * Get sequenceEdges$.
30621          *
30622          * @returns {Observable<IEdgeStatus>} Observable emitting
30623          * values describing the status of the sequence edges.
30624          */
30625         get: function () {
30626             return this._sequenceEdges$;
30627         },
30628         enumerable: true,
30629         configurable: true
30630     });
30631     Object.defineProperty(NodeCache.prototype, "spatialEdges", {
30632         /**
30633          * Get spatialEdges.
30634          *
30635          * @returns {IEdgeStatus} Value describing the status of the
30636          * spatial edges.
30637          */
30638         get: function () {
30639             return this._spatialEdges;
30640         },
30641         enumerable: true,
30642         configurable: true
30643     });
30644     Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
30645         /**
30646          * Get spatialEdges$.
30647          *
30648          * @returns {Observable<IEdgeStatus>} Observable emitting
30649          * values describing the status of the spatial edges.
30650          */
30651         get: function () {
30652             return this._spatialEdges$;
30653         },
30654         enumerable: true,
30655         configurable: true
30656     });
30657     /**
30658      * Cache the image and mesh assets.
30659      *
30660      * @param {string} key - Key of the node to cache.
30661      * @param {boolean} pano - Value indicating whether node is a panorama.
30662      * @param {boolean} merged - Value indicating whether node is merged.
30663      * @returns {Observable<NodeCache>} Observable emitting this node
30664      * cache whenever the load status has changed and when the mesh or image
30665      * has been fully loaded.
30666      */
30667     NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
30668         var _this = this;
30669         if (this._cachingAssets$ != null) {
30670             return this._cachingAssets$;
30671         }
30672         var imageSize = pano ?
30673             Utils_1.Settings.basePanoramaSize :
30674             Utils_1.Settings.baseImageSize;
30675         this._cachingAssets$ = Observable_1.Observable
30676             .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
30677             _this._loadStatus.loaded = 0;
30678             _this._loadStatus.total = 0;
30679             if (meshStatus) {
30680                 _this._mesh = meshStatus.object;
30681                 _this._loadStatus.loaded += meshStatus.loaded.loaded;
30682                 _this._loadStatus.total += meshStatus.loaded.total;
30683             }
30684             if (imageStatus) {
30685                 _this._image = imageStatus.object;
30686                 _this._loadStatus.loaded += imageStatus.loaded.loaded;
30687                 _this._loadStatus.total += imageStatus.loaded.total;
30688             }
30689             return _this;
30690         })
30691             .finally(function () {
30692             _this._cachingAssets$ = null;
30693         })
30694             .publishReplay(1)
30695             .refCount();
30696         return this._cachingAssets$;
30697     };
30698     /**
30699      * Cache an image with a higher resolution than the current one.
30700      *
30701      * @param {string} key - Key of the node to cache.
30702      * @param {ImageSize} imageSize - The size to cache.
30703      * @returns {Observable<NodeCache>} Observable emitting a single item,
30704      * the node cache, when the image has been cached. If supplied image
30705      * size is not larger than the current image size the node cache is
30706      * returned immediately.
30707      */
30708     NodeCache.prototype.cacheImage$ = function (key, imageSize) {
30709         var _this = this;
30710         if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
30711             return Observable_1.Observable.of(this);
30712         }
30713         return this._cacheImage$(key, imageSize)
30714             .first(function (status) {
30715             return status.object != null;
30716         })
30717             .do(function (status) {
30718             _this._disposeImage();
30719             _this._image = status.object;
30720         })
30721             .map(function (imageStatus) {
30722             return _this;
30723         });
30724     };
30725     /**
30726      * Cache the sequence edges.
30727      *
30728      * @param {Array<IEdge>} edges - Sequence edges to cache.
30729      */
30730     NodeCache.prototype.cacheSequenceEdges = function (edges) {
30731         this._sequenceEdges = { cached: true, edges: edges };
30732         this._sequenceEdgesChanged$.next(this._sequenceEdges);
30733     };
30734     /**
30735      * Cache the spatial edges.
30736      *
30737      * @param {Array<IEdge>} edges - Spatial edges to cache.
30738      */
30739     NodeCache.prototype.cacheSpatialEdges = function (edges) {
30740         this._spatialEdges = { cached: true, edges: edges };
30741         this._spatialEdgesChanged$.next(this._spatialEdges);
30742     };
30743     /**
30744      * Dispose the node cache.
30745      *
30746      * @description Disposes all cached assets and unsubscribes to
30747      * all streams.
30748      */
30749     NodeCache.prototype.dispose = function () {
30750         this._sequenceEdgesSubscription.unsubscribe();
30751         this._spatialEdgesSubscription.unsubscribe();
30752         this._disposeImage();
30753         this._mesh = null;
30754         this._loadStatus.loaded = 0;
30755         this._loadStatus.total = 0;
30756         this._sequenceEdges = { cached: false, edges: [] };
30757         this._spatialEdges = { cached: false, edges: [] };
30758         this._sequenceEdgesChanged$.next(this._sequenceEdges);
30759         this._spatialEdgesChanged$.next(this._spatialEdges);
30760         this._disposed = true;
30761         if (this._imageRequest != null) {
30762             this._imageRequest.abort();
30763         }
30764         if (this._meshRequest != null) {
30765             this._meshRequest.abort();
30766         }
30767     };
30768     /**
30769      * Reset the sequence edges.
30770      */
30771     NodeCache.prototype.resetSequenceEdges = function () {
30772         this._sequenceEdges = { cached: false, edges: [] };
30773         this._sequenceEdgesChanged$.next(this._sequenceEdges);
30774     };
30775     /**
30776      * Reset the spatial edges.
30777      */
30778     NodeCache.prototype.resetSpatialEdges = function () {
30779         this._spatialEdges = { cached: false, edges: [] };
30780         this._spatialEdgesChanged$.next(this._spatialEdges);
30781     };
30782     /**
30783      * Cache the image.
30784      *
30785      * @param {string} key - Key of the node to cache.
30786      * @param {boolean} pano - Value indicating whether node is a panorama.
30787      * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
30788      * emitting a load status object every time the load status changes
30789      * and completes when the image is fully loaded.
30790      */
30791     NodeCache.prototype._cacheImage$ = function (key, imageSize) {
30792         var _this = this;
30793         return Observable_1.Observable.create(function (subscriber) {
30794             var xmlHTTP = new XMLHttpRequest();
30795             xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
30796             xmlHTTP.responseType = "arraybuffer";
30797             xmlHTTP.timeout = 15000;
30798             xmlHTTP.onload = function (pe) {
30799                 if (xmlHTTP.status !== 200) {
30800                     _this._imageRequest = null;
30801                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
30802                     return;
30803                 }
30804                 var image = new Image();
30805                 image.crossOrigin = "Anonymous";
30806                 image.onload = function (e) {
30807                     _this._imageRequest = null;
30808                     if (_this._disposed) {
30809                         window.URL.revokeObjectURL(image.src);
30810                         subscriber.error(new Error("Image load was aborted (" + key + ")"));
30811                         return;
30812                     }
30813                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
30814                     subscriber.complete();
30815                 };
30816                 image.onerror = function (error) {
30817                     _this._imageRequest = null;
30818                     subscriber.error(new Error("Failed to load image (" + key + ")"));
30819                 };
30820                 var blob = new Blob([xmlHTTP.response]);
30821                 image.src = window.URL.createObjectURL(blob);
30822             };
30823             xmlHTTP.onprogress = function (pe) {
30824                 if (_this._disposed) {
30825                     return;
30826                 }
30827                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
30828             };
30829             xmlHTTP.onerror = function (error) {
30830                 _this._imageRequest = null;
30831                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
30832             };
30833             xmlHTTP.ontimeout = function (e) {
30834                 _this._imageRequest = null;
30835                 subscriber.error(new Error("Image request timed out (" + key + ")"));
30836             };
30837             xmlHTTP.onabort = function (event) {
30838                 _this._imageRequest = null;
30839                 subscriber.error(new Error("Image request was aborted (" + key + ")"));
30840             };
30841             _this._imageRequest = xmlHTTP;
30842             xmlHTTP.send(null);
30843         });
30844     };
30845     /**
30846      * Cache the mesh.
30847      *
30848      * @param {string} key - Key of the node to cache.
30849      * @param {boolean} merged - Value indicating whether node is merged.
30850      * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
30851      * a load status object every time the load status changes and completes
30852      * when the mesh is fully loaded.
30853      */
30854     NodeCache.prototype._cacheMesh$ = function (key, merged) {
30855         var _this = this;
30856         return Observable_1.Observable.create(function (subscriber) {
30857             if (!merged) {
30858                 subscriber.next(_this._createEmptyMeshLoadStatus());
30859                 subscriber.complete();
30860                 return;
30861             }
30862             var xmlHTTP = new XMLHttpRequest();
30863             xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
30864             xmlHTTP.responseType = "arraybuffer";
30865             xmlHTTP.timeout = 15000;
30866             xmlHTTP.onload = function (pe) {
30867                 _this._meshRequest = null;
30868                 if (_this._disposed) {
30869                     return;
30870                 }
30871                 var mesh = xmlHTTP.status === 200 ?
30872                     Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
30873                     { faces: [], vertices: [] };
30874                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
30875                 subscriber.complete();
30876             };
30877             xmlHTTP.onprogress = function (pe) {
30878                 if (_this._disposed) {
30879                     return;
30880                 }
30881                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
30882             };
30883             xmlHTTP.onerror = function (e) {
30884                 _this._meshRequest = null;
30885                 console.error("Failed to cache mesh (" + key + ")");
30886                 subscriber.next(_this._createEmptyMeshLoadStatus());
30887                 subscriber.complete();
30888             };
30889             xmlHTTP.ontimeout = function (e) {
30890                 _this._meshRequest = null;
30891                 console.error("Mesh request timed out (" + key + ")");
30892                 subscriber.next(_this._createEmptyMeshLoadStatus());
30893                 subscriber.complete();
30894             };
30895             xmlHTTP.onabort = function (e) {
30896                 _this._meshRequest = null;
30897                 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
30898             };
30899             _this._meshRequest = xmlHTTP;
30900             xmlHTTP.send(null);
30901         });
30902     };
30903     /**
30904      * Create a load status object with an empty mesh.
30905      *
30906      * @returns {ILoadStatusObject<IMesh>} Load status object
30907      * with empty mesh.
30908      */
30909     NodeCache.prototype._createEmptyMeshLoadStatus = function () {
30910         return {
30911             loaded: { loaded: 0, total: 0 },
30912             object: { faces: [], vertices: [] },
30913         };
30914     };
30915     NodeCache.prototype._disposeImage = function () {
30916         if (this._image != null) {
30917             window.URL.revokeObjectURL(this._image.src);
30918         }
30919         this._image = null;
30920     };
30921     return NodeCache;
30922 }());
30923 exports.NodeCache = NodeCache;
30924 Object.defineProperty(exports, "__esModule", { value: true });
30925 exports.default = NodeCache;
30926
30927 }).call(this,require("buffer").Buffer)
30928
30929 },{"../Graph":221,"../Utils":226,"buffer":5,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/publishReplay":69}],297:[function(require,module,exports){
30930 /// <reference path="../../typings/index.d.ts" />
30931 "use strict";
30932 var _ = require("underscore");
30933 /**
30934  * @class Sequence
30935  *
30936  * @classdesc Represents a sequence of ordered nodes.
30937  */
30938 var Sequence = (function () {
30939     /**
30940      * Create a new sequene instance.
30941      *
30942      * @param {ISequence} sequence - Raw sequence data.
30943      */
30944     function Sequence(sequence) {
30945         this._key = sequence.key;
30946         this._keys = sequence.keys;
30947     }
30948     Object.defineProperty(Sequence.prototype, "key", {
30949         /**
30950          * Get key.
30951          *
30952          * @returns {string} Unique sequence key.
30953          */
30954         get: function () {
30955             return this._key;
30956         },
30957         enumerable: true,
30958         configurable: true
30959     });
30960     Object.defineProperty(Sequence.prototype, "keys", {
30961         /**
30962          * Get keys.
30963          *
30964          * @returns {Array<string>} Array of ordered node keys in the sequence.
30965          */
30966         get: function () {
30967             return this._keys;
30968         },
30969         enumerable: true,
30970         configurable: true
30971     });
30972     /**
30973      * Dispose the sequence.
30974      *
30975      * @description Disposes all cached assets.
30976      */
30977     Sequence.prototype.dispose = function () {
30978         this._key = null;
30979         this._keys = null;
30980     };
30981     /**
30982      * Find the next node key in the sequence with respect to
30983      * the provided node key.
30984      *
30985      * @param {string} key - Reference node key.
30986      * @returns {string} Next key in sequence if it exists, null otherwise.
30987      */
30988     Sequence.prototype.findNextKey = function (key) {
30989         var i = _.indexOf(this._keys, key);
30990         if ((i + 1) >= this._keys.length || i === -1) {
30991             return null;
30992         }
30993         else {
30994             return this._keys[i + 1];
30995         }
30996     };
30997     /**
30998      * Find the previous node key in the sequence with respect to
30999      * the provided node key.
31000      *
31001      * @param {string} key - Reference node key.
31002      * @returns {string} Previous key in sequence if it exists, null otherwise.
31003      */
31004     Sequence.prototype.findPrevKey = function (key) {
31005         var i = _.indexOf(this._keys, key);
31006         if (i === 0 || i === -1) {
31007             return null;
31008         }
31009         else {
31010             return this._keys[i - 1];
31011         }
31012     };
31013     return Sequence;
31014 }());
31015 exports.Sequence = Sequence;
31016 Object.defineProperty(exports, "__esModule", { value: true });
31017 exports.default = Sequence;
31018
31019 },{"underscore":168}],298:[function(require,module,exports){
31020 /// <reference path="../../../typings/index.d.ts" />
31021 "use strict";
31022 var THREE = require("three");
31023 var Edge_1 = require("../../Edge");
31024 var Error_1 = require("../../Error");
31025 var Geo_1 = require("../../Geo");
31026 /**
31027  * @class EdgeCalculator
31028  *
31029  * @classdesc Represents a class for calculating node edges.
31030  */
31031 var EdgeCalculator = (function () {
31032     /**
31033      * Create a new edge calculator instance.
31034      *
31035      * @param {EdgeCalculatorSettings} settings - Settings struct.
31036      * @param {EdgeCalculatorDirections} directions - Directions struct.
31037      * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
31038      */
31039     function EdgeCalculator(settings, directions, coefficients) {
31040         this._spatial = new Geo_1.Spatial();
31041         this._geoCoords = new Geo_1.GeoCoords();
31042         this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
31043         this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
31044         this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
31045     }
31046     /**
31047      * Returns the potential edges to destination nodes for a set
31048      * of nodes with respect to a source node.
31049      *
31050      * @param {Node} node - Source node.
31051      * @param {Array<Node>} nodes - Potential destination nodes.
31052      * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
31053      * be returned even if they do not meet the criteria for a potential edge.
31054      * @throws {ArgumentMapillaryError} If node is not full.
31055      */
31056     EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
31057         if (!node.full) {
31058             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
31059         }
31060         if (!node.merged) {
31061             return [];
31062         }
31063         var currentDirection = this._spatial.viewingDirection(node.rotation);
31064         var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
31065         var potentialEdges = [];
31066         for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
31067             var potential = potentialNodes_1[_i];
31068             if (!potential.merged ||
31069                 potential.key === node.key) {
31070                 continue;
31071             }
31072             var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
31073             var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
31074             var distance = motion.length();
31075             if (distance > this._settings.maxDistance &&
31076                 fallbackKeys.indexOf(potential.key) < 0) {
31077                 continue;
31078             }
31079             var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
31080             var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
31081             var direction = this._spatial.viewingDirection(potential.rotation);
31082             var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
31083             var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
31084             var verticalDirectionChange = verticalDirection - currentVerticalDirection;
31085             var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
31086             var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
31087             var sameSequence = potential.sequenceKey != null &&
31088                 node.sequenceKey != null &&
31089                 potential.sequenceKey === node.sequenceKey;
31090             var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
31091                 potential.mergeCC === node.mergeCC;
31092             var sameUser = potential.userKey === node.userKey;
31093             var potentialEdge = {
31094                 capturedAt: potential.capturedAt,
31095                 directionChange: directionChange,
31096                 distance: distance,
31097                 fullPano: potential.fullPano,
31098                 key: potential.key,
31099                 motionChange: motionChange,
31100                 rotation: rotation,
31101                 sameMergeCC: sameMergeCC,
31102                 sameSequence: sameSequence,
31103                 sameUser: sameUser,
31104                 sequenceKey: potential.sequenceKey,
31105                 verticalDirectionChange: verticalDirectionChange,
31106                 verticalMotion: verticalMotion,
31107                 worldMotionAzimuth: worldMotionAzimuth,
31108             };
31109             potentialEdges.push(potentialEdge);
31110         }
31111         return potentialEdges;
31112     };
31113     /**
31114      * Computes the sequence edges for a node.
31115      *
31116      * @param {Node} node - Source node.
31117      * @throws {ArgumentMapillaryError} If node is not full.
31118      */
31119     EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
31120         if (!node.full) {
31121             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
31122         }
31123         if (node.sequenceKey !== sequence.key) {
31124             throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
31125         }
31126         var edges = [];
31127         var nextKey = sequence.findNextKey(node.key);
31128         if (nextKey != null) {
31129             edges.push({
31130                 data: {
31131                     direction: Edge_1.EdgeDirection.Next,
31132                     worldMotionAzimuth: Number.NaN,
31133                 },
31134                 from: node.key,
31135                 to: nextKey,
31136             });
31137         }
31138         var prevKey = sequence.findPrevKey(node.key);
31139         if (prevKey != null) {
31140             edges.push({
31141                 data: {
31142                     direction: Edge_1.EdgeDirection.Prev,
31143                     worldMotionAzimuth: Number.NaN,
31144                 },
31145                 from: node.key,
31146                 to: prevKey,
31147             });
31148         }
31149         return edges;
31150     };
31151     /**
31152      * Computes the similar edges for a node.
31153      *
31154      * @description Similar edges for perspective images and cropped panoramas
31155      * look roughly in the same direction and are positioned closed to the node.
31156      * Similar edges for full panoramas only target other full panoramas.
31157      *
31158      * @param {Node} node - Source node.
31159      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
31160      * @throws {ArgumentMapillaryError} If node is not full.
31161      */
31162     EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
31163         var _this = this;
31164         if (!node.full) {
31165             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
31166         }
31167         var nodeFullPano = node.fullPano;
31168         var sequenceGroups = {};
31169         for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
31170             var potentialEdge = potentialEdges_1[_i];
31171             if (potentialEdge.sequenceKey == null) {
31172                 continue;
31173             }
31174             if (potentialEdge.sameSequence ||
31175                 !potentialEdge.sameMergeCC) {
31176                 continue;
31177             }
31178             if (nodeFullPano) {
31179                 if (!potentialEdge.fullPano) {
31180                     continue;
31181                 }
31182             }
31183             else {
31184                 if (!potentialEdge.fullPano &&
31185                     Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
31186                     continue;
31187                 }
31188             }
31189             if (potentialEdge.distance > this._settings.similarMaxDistance) {
31190                 continue;
31191             }
31192             if (potentialEdge.sameUser &&
31193                 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
31194                     this._settings.similarMinTimeDifference) {
31195                 continue;
31196             }
31197             if (sequenceGroups[potentialEdge.sequenceKey] == null) {
31198                 sequenceGroups[potentialEdge.sequenceKey] = [];
31199             }
31200             sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
31201         }
31202         var similarEdges = [];
31203         var calculateScore = node.fullPano ?
31204             function (potentialEdge) {
31205                 return potentialEdge.distance;
31206             } :
31207             function (potentialEdge) {
31208                 return _this._coefficients.similarDistance * potentialEdge.distance +
31209                     _this._coefficients.similarRotation * potentialEdge.rotation;
31210             };
31211         for (var sequenceKey in sequenceGroups) {
31212             if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
31213                 continue;
31214             }
31215             var lowestScore = Number.MAX_VALUE;
31216             var similarEdge = null;
31217             for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
31218                 var potentialEdge = _b[_a];
31219                 var score = calculateScore(potentialEdge);
31220                 if (score < lowestScore) {
31221                     lowestScore = score;
31222                     similarEdge = potentialEdge;
31223                 }
31224             }
31225             if (similarEdge == null) {
31226                 continue;
31227             }
31228             similarEdges.push(similarEdge);
31229         }
31230         return similarEdges
31231             .map(function (potentialEdge) {
31232             return {
31233                 data: {
31234                     direction: Edge_1.EdgeDirection.Similar,
31235                     worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
31236                 },
31237                 from: node.key,
31238                 to: potentialEdge.key,
31239             };
31240         });
31241     };
31242     /**
31243      * Computes the step edges for a perspective node.
31244      *
31245      * @param {Node} node - Source node.
31246      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
31247      * @param {string} prevKey - Key of previous node in sequence.
31248      * @param {string} prevKey - Key of next node in sequence.
31249      * @throws {ArgumentMapillaryError} If node is not full.
31250      */
31251     EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
31252         if (!node.full) {
31253             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
31254         }
31255         var edges = [];
31256         if (node.fullPano) {
31257             return edges;
31258         }
31259         for (var k in this._directions.steps) {
31260             if (!this._directions.steps.hasOwnProperty(k)) {
31261                 continue;
31262             }
31263             var step = this._directions.steps[k];
31264             var lowestScore = Number.MAX_VALUE;
31265             var edge = null;
31266             var fallback = null;
31267             for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
31268                 var potential = potentialEdges_2[_i];
31269                 if (potential.fullPano) {
31270                     continue;
31271                 }
31272                 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
31273                     continue;
31274                 }
31275                 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
31276                 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
31277                 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
31278                 if (Math.abs(drift) > this._settings.stepMaxDrift) {
31279                     continue;
31280                 }
31281                 var potentialKey = potential.key;
31282                 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
31283                     fallback = potential;
31284                 }
31285                 if (potential.distance > this._settings.stepMaxDistance) {
31286                     continue;
31287                 }
31288                 motionDifference = Math.sqrt(motionDifference * motionDifference +
31289                     potential.verticalMotion * potential.verticalMotion);
31290                 var score = this._coefficients.stepPreferredDistance *
31291                     Math.abs(potential.distance - this._settings.stepPreferredDistance) /
31292                     this._settings.stepMaxDistance +
31293                     this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
31294                     this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
31295                     this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
31296                     this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
31297                 if (score < lowestScore) {
31298                     lowestScore = score;
31299                     edge = potential;
31300                 }
31301             }
31302             edge = edge == null ? fallback : edge;
31303             if (edge != null) {
31304                 edges.push({
31305                     data: {
31306                         direction: step.direction,
31307                         worldMotionAzimuth: edge.worldMotionAzimuth,
31308                     },
31309                     from: node.key,
31310                     to: edge.key,
31311                 });
31312             }
31313         }
31314         return edges;
31315     };
31316     /**
31317      * Computes the turn edges for a perspective node.
31318      *
31319      * @param {Node} node - Source node.
31320      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
31321      * @throws {ArgumentMapillaryError} If node is not full.
31322      */
31323     EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
31324         if (!node.full) {
31325             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
31326         }
31327         var edges = [];
31328         if (node.fullPano) {
31329             return edges;
31330         }
31331         for (var k in this._directions.turns) {
31332             if (!this._directions.turns.hasOwnProperty(k)) {
31333                 continue;
31334             }
31335             var turn = this._directions.turns[k];
31336             var lowestScore = Number.MAX_VALUE;
31337             var edge = null;
31338             for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
31339                 var potential = potentialEdges_3[_i];
31340                 if (potential.fullPano) {
31341                     continue;
31342                 }
31343                 if (potential.distance > this._settings.turnMaxDistance) {
31344                     continue;
31345                 }
31346                 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
31347                     potential.distance < this._settings.turnMaxRigDistance &&
31348                     Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
31349                 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
31350                 var score = void 0;
31351                 if (rig &&
31352                     potential.directionChange * turn.directionChange > 0 &&
31353                     Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
31354                     score = -Math.PI / 2 + Math.abs(potential.directionChange);
31355                 }
31356                 else {
31357                     if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
31358                         continue;
31359                     }
31360                     var motionDifference = turn.motionChange ?
31361                         this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
31362                     motionDifference = Math.sqrt(motionDifference * motionDifference +
31363                         potential.verticalMotion * potential.verticalMotion);
31364                     score =
31365                         this._coefficients.turnDistance * potential.distance /
31366                             this._settings.turnMaxDistance +
31367                             this._coefficients.turnMotion * motionDifference / Math.PI +
31368                             this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
31369                             this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
31370                 }
31371                 if (score < lowestScore) {
31372                     lowestScore = score;
31373                     edge = potential;
31374                 }
31375             }
31376             if (edge != null) {
31377                 edges.push({
31378                     data: {
31379                         direction: turn.direction,
31380                         worldMotionAzimuth: edge.worldMotionAzimuth,
31381                     },
31382                     from: node.key,
31383                     to: edge.key,
31384                 });
31385             }
31386         }
31387         return edges;
31388     };
31389     /**
31390      * Computes the pano edges for a perspective node.
31391      *
31392      * @param {Node} node - Source node.
31393      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
31394      * @throws {ArgumentMapillaryError} If node is not full.
31395      */
31396     EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
31397         if (!node.full) {
31398             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
31399         }
31400         if (node.fullPano) {
31401             return [];
31402         }
31403         var lowestScore = Number.MAX_VALUE;
31404         var edge = null;
31405         for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
31406             var potential = potentialEdges_4[_i];
31407             if (!potential.fullPano) {
31408                 continue;
31409             }
31410             var score = this._coefficients.panoPreferredDistance *
31411                 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
31412                 this._settings.panoMaxDistance +
31413                 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
31414                 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
31415             if (score < lowestScore) {
31416                 lowestScore = score;
31417                 edge = potential;
31418             }
31419         }
31420         if (edge == null) {
31421             return [];
31422         }
31423         return [
31424             {
31425                 data: {
31426                     direction: Edge_1.EdgeDirection.Pano,
31427                     worldMotionAzimuth: edge.worldMotionAzimuth,
31428                 },
31429                 from: node.key,
31430                 to: edge.key,
31431             },
31432         ];
31433     };
31434     /**
31435      * Computes the pano and step edges for a pano node.
31436      *
31437      * @param {Node} node - Source node.
31438      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
31439      * @throws {ArgumentMapillaryError} If node is not full.
31440      */
31441     EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
31442         if (!node.full) {
31443             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
31444         }
31445         if (!node.fullPano) {
31446             return [];
31447         }
31448         var panoEdges = [];
31449         var potentialPanos = [];
31450         var potentialSteps = [];
31451         for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
31452             var potential = potentialEdges_5[_i];
31453             if (potential.distance > this._settings.panoMaxDistance) {
31454                 continue;
31455             }
31456             if (potential.fullPano) {
31457                 if (potential.distance < this._settings.panoMinDistance) {
31458                     continue;
31459                 }
31460                 potentialPanos.push(potential);
31461             }
31462             else {
31463                 for (var k in this._directions.panos) {
31464                     if (!this._directions.panos.hasOwnProperty(k)) {
31465                         continue;
31466                     }
31467                     var pano = this._directions.panos[k];
31468                     var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
31469                     var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
31470                     if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
31471                         continue;
31472                     }
31473                     potentialSteps.push([pano.direction, potential]);
31474                     // break if step direction found
31475                     break;
31476                 }
31477             }
31478         }
31479         var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
31480         var occupiedAngles = [];
31481         var stepAngles = [];
31482         for (var index = 0; index < this._settings.panoMaxItems; index++) {
31483             var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
31484             var lowestScore = Number.MAX_VALUE;
31485             var edge = null;
31486             for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
31487                 var potential = potentialPanos_1[_a];
31488                 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
31489                 if (Math.abs(motionDifference) > maxRotationDifference) {
31490                     continue;
31491                 }
31492                 var occupiedDifference = Number.MAX_VALUE;
31493                 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
31494                     var occupiedAngle = occupiedAngles_1[_b];
31495                     var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
31496                     if (difference < occupiedDifference) {
31497                         occupiedDifference = difference;
31498                     }
31499                 }
31500                 if (occupiedDifference <= maxRotationDifference) {
31501                     continue;
31502                 }
31503                 var score = this._coefficients.panoPreferredDistance *
31504                     Math.abs(potential.distance - this._settings.panoPreferredDistance) /
31505                     this._settings.panoMaxDistance +
31506                     this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
31507                     this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
31508                     this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
31509                 if (score < lowestScore) {
31510                     lowestScore = score;
31511                     edge = potential;
31512                 }
31513             }
31514             if (edge != null) {
31515                 occupiedAngles.push(edge.motionChange);
31516                 panoEdges.push({
31517                     data: {
31518                         direction: Edge_1.EdgeDirection.Pano,
31519                         worldMotionAzimuth: edge.worldMotionAzimuth,
31520                     },
31521                     from: node.key,
31522                     to: edge.key,
31523                 });
31524             }
31525             else {
31526                 stepAngles.push(rotation);
31527             }
31528         }
31529         var occupiedStepAngles = {};
31530         occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
31531         occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
31532         occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
31533         occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
31534         occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
31535         for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
31536             var stepAngle = stepAngles_1[_c];
31537             var occupations = [];
31538             for (var k in this._directions.panos) {
31539                 if (!this._directions.panos.hasOwnProperty(k)) {
31540                     continue;
31541                 }
31542                 var pano = this._directions.panos[k];
31543                 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
31544                     .concat(occupiedStepAngles[pano.direction])
31545                     .concat(occupiedStepAngles[pano.prev])
31546                     .concat(occupiedStepAngles[pano.next]);
31547                 var lowestScore = Number.MAX_VALUE;
31548                 var edge = null;
31549                 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
31550                     var potential = potentialSteps_1[_d];
31551                     if (potential[0] !== pano.direction) {
31552                         continue;
31553                     }
31554                     var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
31555                     if (Math.abs(motionChange) > maxRotationDifference) {
31556                         continue;
31557                     }
31558                     var minOccupiedDifference = Number.MAX_VALUE;
31559                     for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
31560                         var occupiedAngle = allOccupiedAngles_1[_e];
31561                         var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
31562                         if (occupiedDifference < minOccupiedDifference) {
31563                             minOccupiedDifference = occupiedDifference;
31564                         }
31565                     }
31566                     if (minOccupiedDifference <= maxRotationDifference) {
31567                         continue;
31568                     }
31569                     var score = this._coefficients.panoPreferredDistance *
31570                         Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
31571                         this._settings.panoMaxDistance +
31572                         this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
31573                         this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
31574                     if (score < lowestScore) {
31575                         lowestScore = score;
31576                         edge = potential;
31577                     }
31578                 }
31579                 if (edge != null) {
31580                     occupations.push(edge);
31581                     panoEdges.push({
31582                         data: {
31583                             direction: edge[0],
31584                             worldMotionAzimuth: edge[1].worldMotionAzimuth,
31585                         },
31586                         from: node.key,
31587                         to: edge[1].key,
31588                     });
31589                 }
31590             }
31591             for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
31592                 var occupation = occupations_1[_f];
31593                 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
31594             }
31595         }
31596         return panoEdges;
31597     };
31598     return EdgeCalculator;
31599 }());
31600 exports.EdgeCalculator = EdgeCalculator;
31601 Object.defineProperty(exports, "__esModule", { value: true });
31602 exports.default = EdgeCalculator;
31603
31604 },{"../../Edge":218,"../../Error":219,"../../Geo":220,"three":167}],299:[function(require,module,exports){
31605 "use strict";
31606 var EdgeCalculatorCoefficients = (function () {
31607     function EdgeCalculatorCoefficients() {
31608         this.panoPreferredDistance = 2;
31609         this.panoMotion = 2;
31610         this.panoSequencePenalty = 1;
31611         this.panoMergeCCPenalty = 4;
31612         this.stepPreferredDistance = 4;
31613         this.stepMotion = 3;
31614         this.stepRotation = 4;
31615         this.stepSequencePenalty = 2;
31616         this.stepMergeCCPenalty = 6;
31617         this.similarDistance = 2;
31618         this.similarRotation = 3;
31619         this.turnDistance = 4;
31620         this.turnMotion = 2;
31621         this.turnSequencePenalty = 1;
31622         this.turnMergeCCPenalty = 4;
31623     }
31624     return EdgeCalculatorCoefficients;
31625 }());
31626 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
31627 Object.defineProperty(exports, "__esModule", { value: true });
31628 exports.default = EdgeCalculatorCoefficients;
31629
31630 },{}],300:[function(require,module,exports){
31631 "use strict";
31632 var Edge_1 = require("../../Edge");
31633 var EdgeCalculatorDirections = (function () {
31634     function EdgeCalculatorDirections() {
31635         this.steps = {};
31636         this.turns = {};
31637         this.panos = {};
31638         this.steps[Edge_1.EdgeDirection.StepForward] = {
31639             direction: Edge_1.EdgeDirection.StepForward,
31640             motionChange: 0,
31641             useFallback: true,
31642         };
31643         this.steps[Edge_1.EdgeDirection.StepBackward] = {
31644             direction: Edge_1.EdgeDirection.StepBackward,
31645             motionChange: Math.PI,
31646             useFallback: true,
31647         };
31648         this.steps[Edge_1.EdgeDirection.StepLeft] = {
31649             direction: Edge_1.EdgeDirection.StepLeft,
31650             motionChange: Math.PI / 2,
31651             useFallback: false,
31652         };
31653         this.steps[Edge_1.EdgeDirection.StepRight] = {
31654             direction: Edge_1.EdgeDirection.StepRight,
31655             motionChange: -Math.PI / 2,
31656             useFallback: false,
31657         };
31658         this.turns[Edge_1.EdgeDirection.TurnLeft] = {
31659             direction: Edge_1.EdgeDirection.TurnLeft,
31660             directionChange: Math.PI / 2,
31661             motionChange: Math.PI / 4,
31662         };
31663         this.turns[Edge_1.EdgeDirection.TurnRight] = {
31664             direction: Edge_1.EdgeDirection.TurnRight,
31665             directionChange: -Math.PI / 2,
31666             motionChange: -Math.PI / 4,
31667         };
31668         this.turns[Edge_1.EdgeDirection.TurnU] = {
31669             direction: Edge_1.EdgeDirection.TurnU,
31670             directionChange: Math.PI,
31671             motionChange: null,
31672         };
31673         this.panos[Edge_1.EdgeDirection.StepForward] = {
31674             direction: Edge_1.EdgeDirection.StepForward,
31675             directionChange: 0,
31676             next: Edge_1.EdgeDirection.StepLeft,
31677             prev: Edge_1.EdgeDirection.StepRight,
31678         };
31679         this.panos[Edge_1.EdgeDirection.StepBackward] = {
31680             direction: Edge_1.EdgeDirection.StepBackward,
31681             directionChange: Math.PI,
31682             next: Edge_1.EdgeDirection.StepRight,
31683             prev: Edge_1.EdgeDirection.StepLeft,
31684         };
31685         this.panos[Edge_1.EdgeDirection.StepLeft] = {
31686             direction: Edge_1.EdgeDirection.StepLeft,
31687             directionChange: Math.PI / 2,
31688             next: Edge_1.EdgeDirection.StepBackward,
31689             prev: Edge_1.EdgeDirection.StepForward,
31690         };
31691         this.panos[Edge_1.EdgeDirection.StepRight] = {
31692             direction: Edge_1.EdgeDirection.StepRight,
31693             directionChange: -Math.PI / 2,
31694             next: Edge_1.EdgeDirection.StepForward,
31695             prev: Edge_1.EdgeDirection.StepBackward,
31696         };
31697     }
31698     return EdgeCalculatorDirections;
31699 }());
31700 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
31701
31702 },{"../../Edge":218}],301:[function(require,module,exports){
31703 "use strict";
31704 var EdgeCalculatorSettings = (function () {
31705     function EdgeCalculatorSettings() {
31706         this.panoMinDistance = 0.1;
31707         this.panoMaxDistance = 20;
31708         this.panoPreferredDistance = 5;
31709         this.panoMaxItems = 4;
31710         this.panoMaxStepTurnChange = Math.PI / 8;
31711         this.rotationMaxDistance = this.turnMaxRigDistance;
31712         this.rotationMaxDirectionChange = Math.PI / 6;
31713         this.rotationMaxVerticalDirectionChange = Math.PI / 8;
31714         this.similarMaxDirectionChange = Math.PI / 8;
31715         this.similarMaxDistance = 12;
31716         this.similarMinTimeDifference = 12 * 3600 * 1000;
31717         this.stepMaxDistance = 20;
31718         this.stepMaxDirectionChange = Math.PI / 6;
31719         this.stepMaxDrift = Math.PI / 6;
31720         this.stepPreferredDistance = 4;
31721         this.turnMaxDistance = 15;
31722         this.turnMaxDirectionChange = 2 * Math.PI / 9;
31723         this.turnMaxRigDistance = 0.65;
31724         this.turnMinRigDirectionChange = Math.PI / 6;
31725     }
31726     Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
31727         get: function () {
31728             return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
31729         },
31730         enumerable: true,
31731         configurable: true
31732     });
31733     return EdgeCalculatorSettings;
31734 }());
31735 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
31736 Object.defineProperty(exports, "__esModule", { value: true });
31737 exports.default = EdgeCalculatorSettings;
31738
31739 },{}],302:[function(require,module,exports){
31740 "use strict";
31741 /**
31742  * Enumeration for edge directions
31743  * @enum {number}
31744  * @readonly
31745  * @description Directions for edges in node graph describing
31746  * sequence, spatial and node type relations between nodes.
31747  */
31748 var EdgeDirection;
31749 (function (EdgeDirection) {
31750     /**
31751      * Next node in the sequence.
31752      */
31753     EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
31754     /**
31755      * Previous node in the sequence.
31756      */
31757     EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
31758     /**
31759      * Step to the left keeping viewing direction.
31760      */
31761     EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
31762     /**
31763      * Step to the right keeping viewing direction.
31764      */
31765     EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
31766     /**
31767      * Step forward keeping viewing direction.
31768      */
31769     EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
31770     /**
31771      * Step backward keeping viewing direction.
31772      */
31773     EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
31774     /**
31775      * Turn 90 degrees counter clockwise.
31776      */
31777     EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
31778     /**
31779      * Turn 90 degrees clockwise.
31780      */
31781     EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
31782     /**
31783      * Turn 180 degrees.
31784      */
31785     EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
31786     /**
31787      * Panorama in general direction.
31788      */
31789     EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
31790     /**
31791      * Looking in roughly the same direction at rougly the same position.
31792      */
31793     EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
31794 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
31795 ;
31796
31797 },{}],303:[function(require,module,exports){
31798 /// <reference path="../../typings/index.d.ts" />
31799 "use strict";
31800 var _ = require("underscore");
31801 var vd = require("virtual-dom");
31802 var Subject_1 = require("rxjs/Subject");
31803 require("rxjs/add/operator/combineLatest");
31804 require("rxjs/add/operator/distinctUntilChanged");
31805 require("rxjs/add/operator/filter");
31806 require("rxjs/add/operator/map");
31807 require("rxjs/add/operator/pluck");
31808 require("rxjs/add/operator/scan");
31809 var Render_1 = require("../Render");
31810 var DOMRenderer = (function () {
31811     function DOMRenderer(element, renderService, currentFrame$) {
31812         this._adaptiveOperation$ = new Subject_1.Subject();
31813         this._render$ = new Subject_1.Subject();
31814         this._renderAdaptive$ = new Subject_1.Subject();
31815         this._renderService = renderService;
31816         this._currentFrame$ = currentFrame$;
31817         var rootNode = vd.create(vd.h("div.domRenderer", []));
31818         element.appendChild(rootNode);
31819         this._offset$ = this._adaptiveOperation$
31820             .scan(function (adaptive, operation) {
31821             return operation(adaptive);
31822         }, {
31823             elementHeight: element.offsetHeight,
31824             elementWidth: element.offsetWidth,
31825             imageAspect: 0,
31826             renderMode: Render_1.RenderMode.Fill,
31827         })
31828             .filter(function (adaptive) {
31829             return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
31830         })
31831             .map(function (adaptive) {
31832             var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
31833             var ratio = adaptive.imageAspect / elementAspect;
31834             var verticalOffset = 0;
31835             var horizontalOffset = 0;
31836             if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
31837                 if (adaptive.imageAspect > elementAspect) {
31838                     verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
31839                 }
31840                 else {
31841                     horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
31842                 }
31843             }
31844             else {
31845                 if (adaptive.imageAspect > elementAspect) {
31846                     horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
31847                 }
31848                 else {
31849                     verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
31850                 }
31851             }
31852             return {
31853                 bottom: verticalOffset,
31854                 left: horizontalOffset,
31855                 right: horizontalOffset,
31856                 top: verticalOffset,
31857             };
31858         });
31859         this._currentFrame$
31860             .filter(function (frame) {
31861             return frame.state.currentNode != null;
31862         })
31863             .distinctUntilChanged(function (k1, k2) {
31864             return k1 === k2;
31865         }, function (frame) {
31866             return frame.state.currentNode.key;
31867         })
31868             .map(function (frame) {
31869             return frame.state.currentTransform.basicAspect;
31870         })
31871             .map(function (aspect) {
31872             return function (adaptive) {
31873                 adaptive.imageAspect = aspect;
31874                 return adaptive;
31875             };
31876         })
31877             .subscribe(this._adaptiveOperation$);
31878         this._renderAdaptive$
31879             .scan(function (vNodeHashes, vNodeHash) {
31880             if (vNodeHash.vnode == null) {
31881                 delete vNodeHashes[vNodeHash.name];
31882             }
31883             else {
31884                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
31885             }
31886             return vNodeHashes;
31887         }, {})
31888             .combineLatest(this._offset$)
31889             .map(function (vo) {
31890             var vNodes = _.values(vo[0]);
31891             var offset = vo[1];
31892             var properties = {
31893                 style: {
31894                     bottom: offset.bottom + "px",
31895                     left: offset.left + "px",
31896                     position: "absolute",
31897                     right: offset.right + "px",
31898                     top: offset.top + "px",
31899                     zIndex: -1,
31900                 },
31901             };
31902             return {
31903                 name: "adaptiveDomRenderer",
31904                 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
31905             };
31906         })
31907             .subscribe(this._render$);
31908         this._vNode$ = this._render$
31909             .scan(function (vNodeHashes, vNodeHash) {
31910             if (vNodeHash.vnode == null) {
31911                 delete vNodeHashes[vNodeHash.name];
31912             }
31913             else {
31914                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
31915             }
31916             return vNodeHashes;
31917         }, {})
31918             .map(function (vNodeHashes) {
31919             var vNodes = _.values(vNodeHashes);
31920             return vd.h("div.domRenderer", vNodes);
31921         });
31922         this._vPatch$ = this._vNode$
31923             .scan(function (nodePatch, vNode) {
31924             nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
31925             nodePatch.vnode = vNode;
31926             return nodePatch;
31927         }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
31928             .pluck("vpatch");
31929         this._element$ = this._vPatch$
31930             .scan(function (oldElement, vPatch) {
31931             return vd.patch(oldElement, vPatch);
31932         }, rootNode)
31933             .publishReplay(1)
31934             .refCount();
31935         this._element$.subscribe(function () { });
31936         this._renderService.size$
31937             .map(function (size) {
31938             return function (adaptive) {
31939                 adaptive.elementWidth = size.width;
31940                 adaptive.elementHeight = size.height;
31941                 return adaptive;
31942             };
31943         })
31944             .subscribe(this._adaptiveOperation$);
31945         this._renderService.renderMode$
31946             .map(function (renderMode) {
31947             return function (adaptive) {
31948                 adaptive.renderMode = renderMode;
31949                 return adaptive;
31950             };
31951         })
31952             .subscribe(this._adaptiveOperation$);
31953     }
31954     Object.defineProperty(DOMRenderer.prototype, "element$", {
31955         get: function () {
31956             return this._element$;
31957         },
31958         enumerable: true,
31959         configurable: true
31960     });
31961     Object.defineProperty(DOMRenderer.prototype, "render$", {
31962         get: function () {
31963             return this._render$;
31964         },
31965         enumerable: true,
31966         configurable: true
31967     });
31968     Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
31969         get: function () {
31970             return this._renderAdaptive$;
31971         },
31972         enumerable: true,
31973         configurable: true
31974     });
31975     DOMRenderer.prototype.clear = function (name) {
31976         this._renderAdaptive$.next({ name: name, vnode: null });
31977         this._render$.next({ name: name, vnode: null });
31978     };
31979     return DOMRenderer;
31980 }());
31981 exports.DOMRenderer = DOMRenderer;
31982 Object.defineProperty(exports, "__esModule", { value: true });
31983 exports.default = DOMRenderer;
31984
31985 },{"../Render":223,"rxjs/Subject":33,"rxjs/add/operator/combineLatest":50,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/pluck":67,"rxjs/add/operator/scan":70,"underscore":168,"virtual-dom":173}],304:[function(require,module,exports){
31986 "use strict";
31987 var GLRenderStage;
31988 (function (GLRenderStage) {
31989     GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
31990     GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
31991 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
31992 Object.defineProperty(exports, "__esModule", { value: true });
31993 exports.default = GLRenderStage;
31994
31995 },{}],305:[function(require,module,exports){
31996 /// <reference path="../../typings/index.d.ts" />
31997 "use strict";
31998 var THREE = require("three");
31999 var Observable_1 = require("rxjs/Observable");
32000 var Subject_1 = require("rxjs/Subject");
32001 require("rxjs/add/observable/combineLatest");
32002 require("rxjs/add/operator/distinctUntilChanged");
32003 require("rxjs/add/operator/filter");
32004 require("rxjs/add/operator/first");
32005 require("rxjs/add/operator/map");
32006 require("rxjs/add/operator/merge");
32007 require("rxjs/add/operator/mergeMap");
32008 require("rxjs/add/operator/scan");
32009 require("rxjs/add/operator/share");
32010 require("rxjs/add/operator/startWith");
32011 var Render_1 = require("../Render");
32012 var GLRenderer = (function () {
32013     function GLRenderer(renderService) {
32014         var _this = this;
32015         this._renderFrame$ = new Subject_1.Subject();
32016         this._renderCameraOperation$ = new Subject_1.Subject();
32017         this._render$ = new Subject_1.Subject();
32018         this._clear$ = new Subject_1.Subject();
32019         this._renderOperation$ = new Subject_1.Subject();
32020         this._rendererOperation$ = new Subject_1.Subject();
32021         this._eraserOperation$ = new Subject_1.Subject();
32022         this._renderService = renderService;
32023         this._renderer$ = this._rendererOperation$
32024             .scan(function (renderer, operation) {
32025             return operation(renderer);
32026         }, { needsRender: false, renderer: null });
32027         this._renderCollection$ = this._renderOperation$
32028             .scan(function (hashes, operation) {
32029             return operation(hashes);
32030         }, {})
32031             .share();
32032         this._renderCamera$ = this._renderCameraOperation$
32033             .scan(function (rc, operation) {
32034             return operation(rc);
32035         }, { frameId: -1, needsRender: false, perspective: null });
32036         this._eraser$ = this._eraserOperation$
32037             .startWith(function (eraser) {
32038             return eraser;
32039         })
32040             .scan(function (eraser, operation) {
32041             return operation(eraser);
32042         }, { needsRender: false });
32043         Observable_1.Observable
32044             .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
32045             var renders = Object.keys(hashes)
32046                 .map(function (key) {
32047                 return hashes[key];
32048             });
32049             return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
32050         })
32051             .filter(function (co) {
32052             var needsRender = co.renderer.needsRender ||
32053                 co.camera.needsRender ||
32054                 co.eraser.needsRender;
32055             var frameId = co.camera.frameId;
32056             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
32057                 var render = _a[_i];
32058                 if (render.frameId !== frameId) {
32059                     return false;
32060                 }
32061                 needsRender = needsRender || render.needsRender;
32062             }
32063             return needsRender;
32064         })
32065             .distinctUntilChanged(function (n1, n2) {
32066             return n1 === n2;
32067         }, function (co) {
32068             return co.eraser.needsRender ? -1 : co.camera.frameId;
32069         })
32070             .subscribe(function (co) {
32071             co.renderer.needsRender = false;
32072             co.camera.needsRender = false;
32073             co.eraser.needsRender = false;
32074             var perspectiveCamera = co.camera.perspective;
32075             var backgroundRenders = [];
32076             var foregroundRenders = [];
32077             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
32078                 var render = _a[_i];
32079                 if (render.stage === Render_1.GLRenderStage.Background) {
32080                     backgroundRenders.push(render.render);
32081                 }
32082                 else if (render.stage === Render_1.GLRenderStage.Foreground) {
32083                     foregroundRenders.push(render.render);
32084                 }
32085             }
32086             var renderer = co.renderer.renderer;
32087             renderer.clear();
32088             for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
32089                 var render = backgroundRenders_1[_b];
32090                 render(perspectiveCamera, renderer);
32091             }
32092             renderer.clearDepth();
32093             for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
32094                 var render = foregroundRenders_1[_c];
32095                 render(perspectiveCamera, renderer);
32096             }
32097         });
32098         this._renderFrame$
32099             .map(function (rc) {
32100             return function (irc) {
32101                 irc.frameId = rc.frameId;
32102                 irc.perspective = rc.perspective;
32103                 if (rc.changed === true) {
32104                     irc.needsRender = true;
32105                 }
32106                 return irc;
32107             };
32108         })
32109             .subscribe(this._renderCameraOperation$);
32110         this._renderFrameSubscribe();
32111         var renderHash$ = this._render$
32112             .map(function (hash) {
32113             return function (hashes) {
32114                 hashes[hash.name] = hash.render;
32115                 return hashes;
32116             };
32117         });
32118         var clearHash$ = this._clear$
32119             .map(function (name) {
32120             return function (hashes) {
32121                 delete hashes[name];
32122                 return hashes;
32123             };
32124         });
32125         Observable_1.Observable
32126             .merge(renderHash$, clearHash$)
32127             .subscribe(this._renderOperation$);
32128         this._webGLRenderer$ = this._render$
32129             .first()
32130             .map(function (hash) {
32131             var element = renderService.element;
32132             var webGLRenderer = new THREE.WebGLRenderer();
32133             webGLRenderer.setPixelRatio(window.devicePixelRatio);
32134             webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
32135             webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
32136             webGLRenderer.autoClear = false;
32137             webGLRenderer.sortObjects = false;
32138             element.appendChild(webGLRenderer.domElement);
32139             return webGLRenderer;
32140         })
32141             .publishReplay(1)
32142             .refCount();
32143         this._webGLRenderer$.subscribe(function () { });
32144         var createRenderer$ = this._webGLRenderer$
32145             .first()
32146             .map(function (webGLRenderer) {
32147             return function (renderer) {
32148                 renderer.needsRender = true;
32149                 renderer.renderer = webGLRenderer;
32150                 return renderer;
32151             };
32152         });
32153         var resizeRenderer$ = this._renderService.size$
32154             .map(function (size) {
32155             return function (renderer) {
32156                 if (renderer.renderer == null) {
32157                     return renderer;
32158                 }
32159                 renderer.renderer.setSize(size.width, size.height);
32160                 renderer.needsRender = true;
32161                 return renderer;
32162             };
32163         });
32164         var clearRenderer$ = this._clear$
32165             .map(function (name) {
32166             return function (renderer) {
32167                 if (renderer.renderer == null) {
32168                     return renderer;
32169                 }
32170                 renderer.needsRender = true;
32171                 return renderer;
32172             };
32173         });
32174         Observable_1.Observable
32175             .merge(createRenderer$, resizeRenderer$, clearRenderer$)
32176             .subscribe(this._rendererOperation$);
32177         var renderCollectionEmpty$ = this._renderCollection$
32178             .filter(function (hashes) {
32179             return Object.keys(hashes).length === 0;
32180         })
32181             .share();
32182         renderCollectionEmpty$
32183             .subscribe(function (hashes) {
32184             if (_this._renderFrameSubscription == null) {
32185                 return;
32186             }
32187             _this._renderFrameSubscription.unsubscribe();
32188             _this._renderFrameSubscription = null;
32189             _this._renderFrameSubscribe();
32190         });
32191         renderCollectionEmpty$
32192             .map(function (hashes) {
32193             return function (eraser) {
32194                 eraser.needsRender = true;
32195                 return eraser;
32196             };
32197         })
32198             .subscribe(this._eraserOperation$);
32199     }
32200     Object.defineProperty(GLRenderer.prototype, "render$", {
32201         get: function () {
32202             return this._render$;
32203         },
32204         enumerable: true,
32205         configurable: true
32206     });
32207     Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
32208         get: function () {
32209             return this._webGLRenderer$;
32210         },
32211         enumerable: true,
32212         configurable: true
32213     });
32214     GLRenderer.prototype.clear = function (name) {
32215         this._clear$.next(name);
32216     };
32217     GLRenderer.prototype._renderFrameSubscribe = function () {
32218         var _this = this;
32219         this._render$
32220             .first()
32221             .map(function (renderHash) {
32222             return function (irc) {
32223                 irc.needsRender = true;
32224                 return irc;
32225             };
32226         })
32227             .subscribe(function (operation) {
32228             _this._renderCameraOperation$.next(operation);
32229         });
32230         this._renderFrameSubscription = this._render$
32231             .first()
32232             .mergeMap(function (hash) {
32233             return _this._renderService.renderCameraFrame$;
32234         })
32235             .subscribe(this._renderFrame$);
32236     };
32237     return GLRenderer;
32238 }());
32239 exports.GLRenderer = GLRenderer;
32240 Object.defineProperty(exports, "__esModule", { value: true });
32241 exports.default = GLRenderer;
32242
32243 },{"../Render":223,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/filter":58,"rxjs/add/operator/first":60,"rxjs/add/operator/map":62,"rxjs/add/operator/merge":63,"rxjs/add/operator/mergeMap":65,"rxjs/add/operator/scan":70,"rxjs/add/operator/share":71,"rxjs/add/operator/startWith":75,"three":167}],306:[function(require,module,exports){
32244 /// <reference path="../../typings/index.d.ts" />
32245 "use strict";
32246 var THREE = require("three");
32247 var Geo_1 = require("../Geo");
32248 var Render_1 = require("../Render");
32249 var RenderCamera = (function () {
32250     function RenderCamera(perspectiveCameraAspect, renderMode) {
32251         this.alpha = -1;
32252         this.zoom = 0;
32253         this._frameId = -1;
32254         this._changed = false;
32255         this._changedForFrame = -1;
32256         this.currentAspect = 1;
32257         this.currentPano = false;
32258         this.previousAspect = 1;
32259         this.previousPano = false;
32260         this.renderMode = renderMode;
32261         this._spatial = new Geo_1.Spatial();
32262         this._camera = new Geo_1.Camera();
32263         this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
32264         this._perspective.matrixAutoUpdate = false;
32265         this._rotation = { phi: 0, theta: 0 };
32266     }
32267     Object.defineProperty(RenderCamera.prototype, "camera", {
32268         get: function () {
32269             return this._camera;
32270         },
32271         enumerable: true,
32272         configurable: true
32273     });
32274     Object.defineProperty(RenderCamera.prototype, "changed", {
32275         get: function () {
32276             return this.frameId === this._changedForFrame;
32277         },
32278         enumerable: true,
32279         configurable: true
32280     });
32281     Object.defineProperty(RenderCamera.prototype, "frameId", {
32282         get: function () {
32283             return this._frameId;
32284         },
32285         set: function (value) {
32286             this._frameId = value;
32287             if (this._changed) {
32288                 this._changed = false;
32289                 this._changedForFrame = value;
32290             }
32291         },
32292         enumerable: true,
32293         configurable: true
32294     });
32295     Object.defineProperty(RenderCamera.prototype, "perspective", {
32296         get: function () {
32297             return this._perspective;
32298         },
32299         enumerable: true,
32300         configurable: true
32301     });
32302     Object.defineProperty(RenderCamera.prototype, "rotation", {
32303         get: function () {
32304             return this._rotation;
32305         },
32306         enumerable: true,
32307         configurable: true
32308     });
32309     RenderCamera.prototype.updateProjection = function () {
32310         var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
32311         var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
32312         var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
32313         var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
32314         this._perspective.fov = verticalFov;
32315         this._perspective.updateProjectionMatrix();
32316         this._changed = true;
32317     };
32318     RenderCamera.prototype.updatePerspective = function (camera) {
32319         this._perspective.up.copy(camera.up);
32320         this._perspective.position.copy(camera.position);
32321         this._perspective.lookAt(camera.lookat);
32322         this._perspective.updateMatrix();
32323         this._perspective.updateMatrixWorld(false);
32324         this._changed = true;
32325     };
32326     RenderCamera.prototype.updateRotation = function (camera) {
32327         this._rotation = this._getRotation(camera);
32328     };
32329     RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
32330         return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
32331     };
32332     RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
32333         if (pano) {
32334             return 1;
32335         }
32336         var coeff = Math.max(1, 1 / nodeAspect);
32337         var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
32338             nodeAspect > perspectiveCameraAspect :
32339             nodeAspect < perspectiveCameraAspect;
32340         var aspect = usePerspective ?
32341             coeff * perspectiveCameraAspect :
32342             coeff * nodeAspect;
32343         return aspect;
32344     };
32345     RenderCamera.prototype._getRotation = function (camera) {
32346         var direction = camera.lookat.clone().sub(camera.position);
32347         var up = camera.up.clone();
32348         var upProjection = direction.clone().dot(up);
32349         var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
32350         var phi = Math.atan2(planeProjection.y, planeProjection.x);
32351         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
32352         return { phi: phi, theta: theta };
32353     };
32354     return RenderCamera;
32355 }());
32356 exports.RenderCamera = RenderCamera;
32357 Object.defineProperty(exports, "__esModule", { value: true });
32358 exports.default = RenderCamera;
32359
32360 },{"../Geo":220,"../Render":223,"three":167}],307:[function(require,module,exports){
32361 "use strict";
32362 /**
32363  * Enumeration for render mode
32364  * @enum {number}
32365  * @readonly
32366  * @description Modes for specifying how rendering is done
32367  * in the viewer. All modes preserves the original aspect
32368  * ratio of the images.
32369  */
32370 var RenderMode;
32371 (function (RenderMode) {
32372     /**
32373      * Displays all content within the viewer.
32374      *
32375      * @description Black bars shown on both
32376      * sides of the content. Bars are shown
32377      * either below and above or to the left
32378      * and right of the content depending on
32379      * the aspect ratio relation between the
32380      * image and the viewer.
32381      */
32382     RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
32383     /**
32384      * Fills the viewer by cropping content.
32385      *
32386      * @description Cropping is done either
32387      * in horizontal or vertical direction
32388      * depending on the aspect ratio relation
32389      * between the image and the viewer.
32390      */
32391     RenderMode[RenderMode["Fill"] = 1] = "Fill";
32392 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
32393 Object.defineProperty(exports, "__esModule", { value: true });
32394 exports.default = RenderMode;
32395
32396 },{}],308:[function(require,module,exports){
32397 /// <reference path="../../typings/index.d.ts" />
32398 "use strict";
32399 var Subject_1 = require("rxjs/Subject");
32400 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
32401 require("rxjs/add/observable/combineLatest");
32402 require("rxjs/add/operator/do");
32403 require("rxjs/add/operator/filter");
32404 require("rxjs/add/operator/map");
32405 require("rxjs/add/operator/publishReplay");
32406 require("rxjs/add/operator/scan");
32407 require("rxjs/add/operator/skip");
32408 require("rxjs/add/operator/startWith");
32409 require("rxjs/add/operator/withLatestFrom");
32410 var Geo_1 = require("../Geo");
32411 var Render_1 = require("../Render");
32412 var RenderService = (function () {
32413     function RenderService(element, currentFrame$, renderMode) {
32414         var _this = this;
32415         this._element = element;
32416         this._currentFrame$ = currentFrame$;
32417         this._spatial = new Geo_1.Spatial();
32418         renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
32419         this._resize$ = new Subject_1.Subject();
32420         this._renderCameraOperation$ = new Subject_1.Subject();
32421         this._size$ =
32422             new BehaviorSubject_1.BehaviorSubject({
32423                 height: this._element.offsetHeight,
32424                 width: this._element.offsetWidth,
32425             });
32426         this._resize$
32427             .map(function () {
32428             return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
32429         })
32430             .subscribe(this._size$);
32431         this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
32432         this._renderCameraHolder$ = this._renderCameraOperation$
32433             .startWith(function (rc) {
32434             return rc;
32435         })
32436             .scan(function (rc, operation) {
32437             return operation(rc);
32438         }, new Render_1.RenderCamera(this._element.offsetWidth / this._element.offsetHeight, renderMode))
32439             .publishReplay(1)
32440             .refCount();
32441         this._renderCameraFrame$ = this._currentFrame$
32442             .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
32443             return [frame, renderCamera];
32444         })
32445             .do(function (args) {
32446             var frame = args[0];
32447             var rc = args[1];
32448             var camera = frame.state.camera;
32449             if (rc.alpha !== frame.state.alpha ||
32450                 rc.zoom !== frame.state.zoom ||
32451                 rc.camera.diff(camera) > 1e-9) {
32452                 var currentTransform = frame.state.currentTransform;
32453                 var previousTransform = frame.state.previousTransform != null ?
32454                     frame.state.previousTransform :
32455                     frame.state.currentTransform;
32456                 var previousNode = frame.state.previousNode != null ?
32457                     frame.state.previousNode :
32458                     frame.state.currentNode;
32459                 rc.currentAspect = currentTransform.basicAspect;
32460                 rc.currentPano = frame.state.currentNode.pano;
32461                 rc.previousAspect = previousTransform.basicAspect;
32462                 rc.previousPano = previousNode.pano;
32463                 rc.alpha = frame.state.alpha;
32464                 rc.zoom = frame.state.zoom;
32465                 rc.camera.copy(camera);
32466                 rc.updatePerspective(camera);
32467                 rc.updateRotation(camera);
32468                 rc.updateProjection();
32469             }
32470             rc.frameId = frame.id;
32471         })
32472             .map(function (args) {
32473             return args[1];
32474         })
32475             .publishReplay(1)
32476             .refCount();
32477         this._renderCamera$ = this._renderCameraFrame$
32478             .filter(function (rc) {
32479             return rc.changed;
32480         })
32481             .publishReplay(1)
32482             .refCount();
32483         this._bearing$ = this._renderCamera$
32484             .map(function (renderCamera) {
32485             var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
32486             return _this._spatial.wrap(bearing, 0, 360);
32487         })
32488             .publishReplay(1)
32489             .refCount();
32490         this._size$
32491             .skip(1)
32492             .map(function (size) {
32493             return function (rc) {
32494                 rc.perspective.aspect = size.width / size.height;
32495                 rc.updateProjection();
32496                 return rc;
32497             };
32498         })
32499             .subscribe(this._renderCameraOperation$);
32500         this._renderMode$
32501             .skip(1)
32502             .map(function (rm) {
32503             return function (rc) {
32504                 rc.renderMode = rm;
32505                 rc.updateProjection();
32506                 return rc;
32507             };
32508         })
32509             .subscribe(this._renderCameraOperation$);
32510         this._bearing$.subscribe(function () { });
32511         this._renderCameraHolder$.subscribe(function () { });
32512         this._size$.subscribe(function () { });
32513         this._renderMode$.subscribe(function () { });
32514         this._renderCamera$.subscribe(function () { });
32515         this._renderCameraFrame$.subscribe(function () { });
32516     }
32517     Object.defineProperty(RenderService.prototype, "bearing$", {
32518         get: function () {
32519             return this._bearing$;
32520         },
32521         enumerable: true,
32522         configurable: true
32523     });
32524     Object.defineProperty(RenderService.prototype, "element", {
32525         get: function () {
32526             return this._element;
32527         },
32528         enumerable: true,
32529         configurable: true
32530     });
32531     Object.defineProperty(RenderService.prototype, "resize$", {
32532         get: function () {
32533             return this._resize$;
32534         },
32535         enumerable: true,
32536         configurable: true
32537     });
32538     Object.defineProperty(RenderService.prototype, "size$", {
32539         get: function () {
32540             return this._size$;
32541         },
32542         enumerable: true,
32543         configurable: true
32544     });
32545     Object.defineProperty(RenderService.prototype, "renderMode$", {
32546         get: function () {
32547             return this._renderMode$;
32548         },
32549         enumerable: true,
32550         configurable: true
32551     });
32552     Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
32553         get: function () {
32554             return this._renderCameraFrame$;
32555         },
32556         enumerable: true,
32557         configurable: true
32558     });
32559     Object.defineProperty(RenderService.prototype, "renderCamera$", {
32560         get: function () {
32561             return this._renderCamera$;
32562         },
32563         enumerable: true,
32564         configurable: true
32565     });
32566     return RenderService;
32567 }());
32568 exports.RenderService = RenderService;
32569 Object.defineProperty(exports, "__esModule", { value: true });
32570 exports.default = RenderService;
32571
32572 },{"../Geo":220,"../Render":223,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/do":56,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/skip":72,"rxjs/add/operator/startWith":75,"rxjs/add/operator/withLatestFrom":80}],309:[function(require,module,exports){
32573 "use strict";
32574 var State;
32575 (function (State) {
32576     State[State["Traversing"] = 0] = "Traversing";
32577     State[State["Waiting"] = 1] = "Waiting";
32578 })(State = exports.State || (exports.State = {}));
32579 Object.defineProperty(exports, "__esModule", { value: true });
32580 exports.default = State;
32581
32582 },{}],310:[function(require,module,exports){
32583 "use strict";
32584 var State_1 = require("../State");
32585 var Geo_1 = require("../Geo");
32586 var StateContext = (function () {
32587     function StateContext() {
32588         this._state = new State_1.TraversingState({
32589             alpha: 1,
32590             camera: new Geo_1.Camera(),
32591             currentIndex: -1,
32592             reference: { alt: 0, lat: 0, lon: 0 },
32593             trajectory: [],
32594             zoom: 0,
32595         });
32596     }
32597     StateContext.prototype.traverse = function () {
32598         this._state = this._state.traverse();
32599     };
32600     StateContext.prototype.wait = function () {
32601         this._state = this._state.wait();
32602     };
32603     Object.defineProperty(StateContext.prototype, "state", {
32604         get: function () {
32605             if (this._state instanceof State_1.TraversingState) {
32606                 return State_1.State.Traversing;
32607             }
32608             else if (this._state instanceof State_1.WaitingState) {
32609                 return State_1.State.Waiting;
32610             }
32611             throw new Error("Invalid state");
32612         },
32613         enumerable: true,
32614         configurable: true
32615     });
32616     Object.defineProperty(StateContext.prototype, "reference", {
32617         get: function () {
32618             return this._state.reference;
32619         },
32620         enumerable: true,
32621         configurable: true
32622     });
32623     Object.defineProperty(StateContext.prototype, "alpha", {
32624         get: function () {
32625             return this._state.alpha;
32626         },
32627         enumerable: true,
32628         configurable: true
32629     });
32630     Object.defineProperty(StateContext.prototype, "camera", {
32631         get: function () {
32632             return this._state.camera;
32633         },
32634         enumerable: true,
32635         configurable: true
32636     });
32637     Object.defineProperty(StateContext.prototype, "zoom", {
32638         get: function () {
32639             return this._state.zoom;
32640         },
32641         enumerable: true,
32642         configurable: true
32643     });
32644     Object.defineProperty(StateContext.prototype, "currentNode", {
32645         get: function () {
32646             return this._state.currentNode;
32647         },
32648         enumerable: true,
32649         configurable: true
32650     });
32651     Object.defineProperty(StateContext.prototype, "previousNode", {
32652         get: function () {
32653             return this._state.previousNode;
32654         },
32655         enumerable: true,
32656         configurable: true
32657     });
32658     Object.defineProperty(StateContext.prototype, "currentCamera", {
32659         get: function () {
32660             return this._state.currentCamera;
32661         },
32662         enumerable: true,
32663         configurable: true
32664     });
32665     Object.defineProperty(StateContext.prototype, "currentTransform", {
32666         get: function () {
32667             return this._state.currentTransform;
32668         },
32669         enumerable: true,
32670         configurable: true
32671     });
32672     Object.defineProperty(StateContext.prototype, "previousTransform", {
32673         get: function () {
32674             return this._state.previousTransform;
32675         },
32676         enumerable: true,
32677         configurable: true
32678     });
32679     Object.defineProperty(StateContext.prototype, "trajectory", {
32680         get: function () {
32681             return this._state.trajectory;
32682         },
32683         enumerable: true,
32684         configurable: true
32685     });
32686     Object.defineProperty(StateContext.prototype, "currentIndex", {
32687         get: function () {
32688             return this._state.currentIndex;
32689         },
32690         enumerable: true,
32691         configurable: true
32692     });
32693     Object.defineProperty(StateContext.prototype, "lastNode", {
32694         get: function () {
32695             return this._state.trajectory[this._state.trajectory.length - 1];
32696         },
32697         enumerable: true,
32698         configurable: true
32699     });
32700     Object.defineProperty(StateContext.prototype, "nodesAhead", {
32701         get: function () {
32702             return this._state.trajectory.length - 1 - this._state.currentIndex;
32703         },
32704         enumerable: true,
32705         configurable: true
32706     });
32707     Object.defineProperty(StateContext.prototype, "motionless", {
32708         get: function () {
32709             return this._state.motionless;
32710         },
32711         enumerable: true,
32712         configurable: true
32713     });
32714     StateContext.prototype.getCenter = function () {
32715         return this._state.getCenter();
32716     };
32717     StateContext.prototype.setCenter = function (center) {
32718         this._state.setCenter(center);
32719     };
32720     StateContext.prototype.setZoom = function (zoom) {
32721         this._state.setZoom(zoom);
32722     };
32723     StateContext.prototype.update = function (fps) {
32724         this._state.update(fps);
32725     };
32726     StateContext.prototype.append = function (nodes) {
32727         this._state.append(nodes);
32728     };
32729     StateContext.prototype.prepend = function (nodes) {
32730         this._state.prepend(nodes);
32731     };
32732     StateContext.prototype.remove = function (n) {
32733         this._state.remove(n);
32734     };
32735     StateContext.prototype.clear = function () {
32736         this._state.clear();
32737     };
32738     StateContext.prototype.clearPrior = function () {
32739         this._state.clearPrior();
32740     };
32741     StateContext.prototype.cut = function () {
32742         this._state.cut();
32743     };
32744     StateContext.prototype.set = function (nodes) {
32745         this._state.set(nodes);
32746     };
32747     StateContext.prototype.rotate = function (delta) {
32748         this._state.rotate(delta);
32749     };
32750     StateContext.prototype.rotateBasic = function (basicRotation) {
32751         this._state.rotateBasic(basicRotation);
32752     };
32753     StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
32754         this._state.rotateBasicUnbounded(basicRotation);
32755     };
32756     StateContext.prototype.rotateToBasic = function (basic) {
32757         this._state.rotateToBasic(basic);
32758     };
32759     StateContext.prototype.move = function (delta) {
32760         this._state.move(delta);
32761     };
32762     StateContext.prototype.moveTo = function (delta) {
32763         this._state.moveTo(delta);
32764     };
32765     StateContext.prototype.zoomIn = function (delta, reference) {
32766         this._state.zoomIn(delta, reference);
32767     };
32768     return StateContext;
32769 }());
32770 exports.StateContext = StateContext;
32771
32772 },{"../Geo":220,"../State":224}],311:[function(require,module,exports){
32773 "use strict";
32774 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
32775 var Subject_1 = require("rxjs/Subject");
32776 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
32777 require("rxjs/add/operator/bufferCount");
32778 require("rxjs/add/operator/distinctUntilChanged");
32779 require("rxjs/add/operator/do");
32780 require("rxjs/add/operator/filter");
32781 require("rxjs/add/operator/first");
32782 require("rxjs/add/operator/map");
32783 require("rxjs/add/operator/pairwise");
32784 require("rxjs/add/operator/publishReplay");
32785 require("rxjs/add/operator/scan");
32786 require("rxjs/add/operator/startWith");
32787 require("rxjs/add/operator/switchMap");
32788 require("rxjs/add/operator/withLatestFrom");
32789 var State_1 = require("../State");
32790 var StateService = (function () {
32791     function StateService() {
32792         var _this = this;
32793         this._appendNode$ = new Subject_1.Subject();
32794         this._start$ = new Subject_1.Subject();
32795         this._frame$ = new Subject_1.Subject();
32796         this._fpsSampleRate = 30;
32797         this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
32798             return context;
32799         });
32800         this._context$ = this._contextOperation$
32801             .scan(function (context, operation) {
32802             return operation(context);
32803         }, new State_1.StateContext())
32804             .publishReplay(1)
32805             .refCount();
32806         this._state$ = this._context$
32807             .map(function (context) {
32808             return context.state;
32809         })
32810             .distinctUntilChanged()
32811             .publishReplay(1)
32812             .refCount();
32813         this._fps$ = this._start$
32814             .switchMap(function () {
32815             return _this._frame$
32816                 .bufferCount(1, _this._fpsSampleRate)
32817                 .map(function (frameIds) {
32818                 return new Date().getTime();
32819             })
32820                 .pairwise()
32821                 .map(function (times) {
32822                 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
32823             })
32824                 .startWith(60);
32825         })
32826             .share();
32827         this._currentState$ = this._frame$
32828             .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
32829             return [frameId, fps, context];
32830         })
32831             .filter(function (fc) {
32832             return fc[2].currentNode != null;
32833         })
32834             .do(function (fc) {
32835             fc[2].update(fc[1]);
32836         })
32837             .map(function (fc) {
32838             return { fps: fc[1], id: fc[0], state: fc[2] };
32839         })
32840             .share();
32841         this._lastState$ = this._currentState$
32842             .publishReplay(1)
32843             .refCount();
32844         var nodeChanged$ = this._currentState$
32845             .distinctUntilChanged(undefined, function (f) {
32846             return f.state.currentNode.key;
32847         })
32848             .publishReplay(1)
32849             .refCount();
32850         var nodeChangedSubject$ = new Subject_1.Subject();
32851         nodeChanged$
32852             .subscribe(nodeChangedSubject$);
32853         this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
32854         nodeChangedSubject$
32855             .map(function (f) {
32856             return f.state.currentNode.key;
32857         })
32858             .subscribe(this._currentKey$);
32859         this._currentNode$ = nodeChangedSubject$
32860             .map(function (f) {
32861             return f.state.currentNode;
32862         })
32863             .publishReplay(1)
32864             .refCount();
32865         this._currentCamera$ = nodeChangedSubject$
32866             .map(function (f) {
32867             return f.state.currentCamera;
32868         })
32869             .publishReplay(1)
32870             .refCount();
32871         this._currentTransform$ = nodeChangedSubject$
32872             .map(function (f) {
32873             return f.state.currentTransform;
32874         })
32875             .publishReplay(1)
32876             .refCount();
32877         this._reference$ = nodeChangedSubject$
32878             .map(function (f) {
32879             return f.state.reference;
32880         })
32881             .distinctUntilChanged(function (r1, r2) {
32882             return r1.lat === r2.lat && r1.lon === r2.lon;
32883         }, function (reference) {
32884             return { lat: reference.lat, lon: reference.lon };
32885         })
32886             .publishReplay(1)
32887             .refCount();
32888         this._currentNodeExternal$ = nodeChanged$
32889             .map(function (f) {
32890             return f.state.currentNode;
32891         })
32892             .publishReplay(1)
32893             .refCount();
32894         this._appendNode$
32895             .map(function (node) {
32896             return function (context) {
32897                 context.append([node]);
32898                 return context;
32899             };
32900         })
32901             .subscribe(this._contextOperation$);
32902         this._inMotionOperation$ = new Subject_1.Subject();
32903         nodeChanged$
32904             .map(function (frame) {
32905             return true;
32906         })
32907             .subscribe(this._inMotionOperation$);
32908         this._inMotionOperation$
32909             .distinctUntilChanged()
32910             .filter(function (moving) {
32911             return moving;
32912         })
32913             .switchMap(function (moving) {
32914             return _this._currentState$
32915                 .filter(function (frame) {
32916                 return frame.state.nodesAhead === 0;
32917             })
32918                 .map(function (frame) {
32919                 return [frame.state.camera.clone(), frame.state.zoom];
32920             })
32921                 .pairwise()
32922                 .map(function (pair) {
32923                 var c1 = pair[0][0];
32924                 var c2 = pair[1][0];
32925                 var z1 = pair[0][1];
32926                 var z2 = pair[1][1];
32927                 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
32928             })
32929                 .first(function (changed) {
32930                 return !changed;
32931             });
32932         })
32933             .subscribe(this._inMotionOperation$);
32934         this._inMotion$ = this._inMotionOperation$
32935             .distinctUntilChanged()
32936             .publishReplay(1)
32937             .refCount();
32938         this._inTranslationOperation$ = new Subject_1.Subject();
32939         nodeChanged$
32940             .map(function (frame) {
32941             return true;
32942         })
32943             .subscribe(this._inTranslationOperation$);
32944         this._inTranslationOperation$
32945             .distinctUntilChanged()
32946             .filter(function (inTranslation) {
32947             return inTranslation;
32948         })
32949             .switchMap(function (inTranslation) {
32950             return _this._currentState$
32951                 .filter(function (frame) {
32952                 return frame.state.nodesAhead === 0;
32953             })
32954                 .map(function (frame) {
32955                 return frame.state.camera.position.clone();
32956             })
32957                 .pairwise()
32958                 .map(function (pair) {
32959                 return pair[0].distanceToSquared(pair[1]) !== 0;
32960             })
32961                 .first(function (changed) {
32962                 return !changed;
32963             });
32964         })
32965             .subscribe(this._inTranslationOperation$);
32966         this._inTranslation$ = this._inTranslationOperation$
32967             .distinctUntilChanged()
32968             .publishReplay(1)
32969             .refCount();
32970         this._state$.subscribe(function () { });
32971         this._currentNode$.subscribe(function () { });
32972         this._currentCamera$.subscribe(function () { });
32973         this._currentTransform$.subscribe(function () { });
32974         this._reference$.subscribe(function () { });
32975         this._currentNodeExternal$.subscribe(function () { });
32976         this._lastState$.subscribe(function () { });
32977         this._inMotion$.subscribe(function () { });
32978         this._inTranslation$.subscribe(function () { });
32979         this._frameId = null;
32980         this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
32981     }
32982     Object.defineProperty(StateService.prototype, "currentState$", {
32983         get: function () {
32984             return this._currentState$;
32985         },
32986         enumerable: true,
32987         configurable: true
32988     });
32989     Object.defineProperty(StateService.prototype, "currentNode$", {
32990         get: function () {
32991             return this._currentNode$;
32992         },
32993         enumerable: true,
32994         configurable: true
32995     });
32996     Object.defineProperty(StateService.prototype, "currentKey$", {
32997         get: function () {
32998             return this._currentKey$;
32999         },
33000         enumerable: true,
33001         configurable: true
33002     });
33003     Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
33004         get: function () {
33005             return this._currentNodeExternal$;
33006         },
33007         enumerable: true,
33008         configurable: true
33009     });
33010     Object.defineProperty(StateService.prototype, "currentCamera$", {
33011         get: function () {
33012             return this._currentCamera$;
33013         },
33014         enumerable: true,
33015         configurable: true
33016     });
33017     Object.defineProperty(StateService.prototype, "currentTransform$", {
33018         get: function () {
33019             return this._currentTransform$;
33020         },
33021         enumerable: true,
33022         configurable: true
33023     });
33024     Object.defineProperty(StateService.prototype, "state$", {
33025         get: function () {
33026             return this._state$;
33027         },
33028         enumerable: true,
33029         configurable: true
33030     });
33031     Object.defineProperty(StateService.prototype, "reference$", {
33032         get: function () {
33033             return this._reference$;
33034         },
33035         enumerable: true,
33036         configurable: true
33037     });
33038     Object.defineProperty(StateService.prototype, "inMotion$", {
33039         get: function () {
33040             return this._inMotion$;
33041         },
33042         enumerable: true,
33043         configurable: true
33044     });
33045     Object.defineProperty(StateService.prototype, "inTranslation$", {
33046         get: function () {
33047             return this._inTranslation$;
33048         },
33049         enumerable: true,
33050         configurable: true
33051     });
33052     Object.defineProperty(StateService.prototype, "appendNode$", {
33053         get: function () {
33054             return this._appendNode$;
33055         },
33056         enumerable: true,
33057         configurable: true
33058     });
33059     StateService.prototype.traverse = function () {
33060         this._inMotionOperation$.next(true);
33061         this._invokeContextOperation(function (context) { context.traverse(); });
33062     };
33063     StateService.prototype.wait = function () {
33064         this._invokeContextOperation(function (context) { context.wait(); });
33065     };
33066     StateService.prototype.appendNodes = function (nodes) {
33067         this._invokeContextOperation(function (context) { context.append(nodes); });
33068     };
33069     StateService.prototype.prependNodes = function (nodes) {
33070         this._invokeContextOperation(function (context) { context.prepend(nodes); });
33071     };
33072     StateService.prototype.removeNodes = function (n) {
33073         this._invokeContextOperation(function (context) { context.remove(n); });
33074     };
33075     StateService.prototype.clearNodes = function () {
33076         this._invokeContextOperation(function (context) { context.clear(); });
33077     };
33078     StateService.prototype.clearPriorNodes = function () {
33079         this._invokeContextOperation(function (context) { context.clearPrior(); });
33080     };
33081     StateService.prototype.cutNodes = function () {
33082         this._invokeContextOperation(function (context) { context.cut(); });
33083     };
33084     StateService.prototype.setNodes = function (nodes) {
33085         this._invokeContextOperation(function (context) { context.set(nodes); });
33086     };
33087     StateService.prototype.rotate = function (delta) {
33088         this._inMotionOperation$.next(true);
33089         this._invokeContextOperation(function (context) { context.rotate(delta); });
33090     };
33091     StateService.prototype.rotateBasic = function (basicRotation) {
33092         this._inMotionOperation$.next(true);
33093         this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
33094     };
33095     StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
33096         this._inMotionOperation$.next(true);
33097         this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
33098     };
33099     StateService.prototype.rotateToBasic = function (basic) {
33100         this._inMotionOperation$.next(true);
33101         this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
33102     };
33103     StateService.prototype.move = function (delta) {
33104         this._inMotionOperation$.next(true);
33105         this._invokeContextOperation(function (context) { context.move(delta); });
33106     };
33107     StateService.prototype.moveTo = function (position) {
33108         this._inMotionOperation$.next(true);
33109         this._invokeContextOperation(function (context) { context.moveTo(position); });
33110     };
33111     /**
33112      * Change zoom level while keeping the reference point position approximately static.
33113      *
33114      * @parameter {number} delta - Change in zoom level.
33115      * @parameter {Array<number>} reference - Reference point in basic coordinates.
33116      */
33117     StateService.prototype.zoomIn = function (delta, reference) {
33118         this._inMotionOperation$.next(true);
33119         this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
33120     };
33121     StateService.prototype.getCenter = function () {
33122         return this._lastState$
33123             .first()
33124             .map(function (frame) {
33125             return frame.state.getCenter();
33126         });
33127     };
33128     StateService.prototype.getZoom = function () {
33129         return this._lastState$
33130             .first()
33131             .map(function (frame) {
33132             return frame.state.zoom;
33133         });
33134     };
33135     StateService.prototype.setCenter = function (center) {
33136         this._inMotionOperation$.next(true);
33137         this._invokeContextOperation(function (context) { context.setCenter(center); });
33138     };
33139     StateService.prototype.setZoom = function (zoom) {
33140         this._inMotionOperation$.next(true);
33141         this._invokeContextOperation(function (context) { context.setZoom(zoom); });
33142     };
33143     StateService.prototype.start = function () {
33144         if (this._frameId == null) {
33145             this._start$.next(null);
33146             this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
33147             this._frame$.next(this._frameId);
33148         }
33149     };
33150     StateService.prototype.stop = function () {
33151         if (this._frameId != null) {
33152             this._frameGenerator.cancelAnimationFrame(this._frameId);
33153             this._frameId = null;
33154         }
33155     };
33156     StateService.prototype._invokeContextOperation = function (action) {
33157         this._contextOperation$
33158             .next(function (context) {
33159             action(context);
33160             return context;
33161         });
33162     };
33163     StateService.prototype._frame = function (time) {
33164         this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
33165         this._frame$.next(this._frameId);
33166     };
33167     return StateService;
33168 }());
33169 exports.StateService = StateService;
33170
33171 },{"../State":224,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/bufferCount":48,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/do":56,"rxjs/add/operator/filter":58,"rxjs/add/operator/first":60,"rxjs/add/operator/map":62,"rxjs/add/operator/pairwise":66,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/startWith":75,"rxjs/add/operator/switchMap":76,"rxjs/add/operator/withLatestFrom":80,"rxjs/util/AnimationFrame":150}],312:[function(require,module,exports){
33172 /// <reference path="../../../typings/index.d.ts" />
33173 "use strict";
33174 var Error_1 = require("../../Error");
33175 var Geo_1 = require("../../Geo");
33176 var StateBase = (function () {
33177     function StateBase(state) {
33178         this._spatial = new Geo_1.Spatial();
33179         this._geoCoords = new Geo_1.GeoCoords();
33180         this._referenceThreshold = 0.01;
33181         this._reference = state.reference;
33182         this._alpha = state.alpha;
33183         this._camera = state.camera.clone();
33184         this._zoom = state.zoom;
33185         this._currentIndex = state.currentIndex;
33186         this._trajectory = state.trajectory.slice();
33187         this._trajectoryTransforms = [];
33188         this._trajectoryCameras = [];
33189         for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
33190             var node = _a[_i];
33191             var translation = this._nodeToTranslation(node);
33192             var transform = new Geo_1.Transform(node, node.image, translation);
33193             this._trajectoryTransforms.push(transform);
33194             this._trajectoryCameras.push(new Geo_1.Camera(transform));
33195         }
33196         this._currentNode = this._trajectory.length > 0 ?
33197             this._trajectory[this._currentIndex] :
33198             null;
33199         this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
33200             this._trajectory[this._currentIndex - 1] :
33201             null;
33202         this._currentCamera = this._trajectoryCameras.length > 0 ?
33203             this._trajectoryCameras[this._currentIndex].clone() :
33204             new Geo_1.Camera();
33205         this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
33206             this._trajectoryCameras[this._currentIndex - 1].clone() :
33207             this._currentCamera.clone();
33208     }
33209     Object.defineProperty(StateBase.prototype, "reference", {
33210         get: function () {
33211             return this._reference;
33212         },
33213         enumerable: true,
33214         configurable: true
33215     });
33216     Object.defineProperty(StateBase.prototype, "alpha", {
33217         get: function () {
33218             return this._getAlpha();
33219         },
33220         enumerable: true,
33221         configurable: true
33222     });
33223     Object.defineProperty(StateBase.prototype, "camera", {
33224         get: function () {
33225             return this._camera;
33226         },
33227         enumerable: true,
33228         configurable: true
33229     });
33230     Object.defineProperty(StateBase.prototype, "zoom", {
33231         get: function () {
33232             return this._zoom;
33233         },
33234         enumerable: true,
33235         configurable: true
33236     });
33237     Object.defineProperty(StateBase.prototype, "trajectory", {
33238         get: function () {
33239             return this._trajectory;
33240         },
33241         enumerable: true,
33242         configurable: true
33243     });
33244     Object.defineProperty(StateBase.prototype, "currentIndex", {
33245         get: function () {
33246             return this._currentIndex;
33247         },
33248         enumerable: true,
33249         configurable: true
33250     });
33251     Object.defineProperty(StateBase.prototype, "currentNode", {
33252         get: function () {
33253             return this._currentNode;
33254         },
33255         enumerable: true,
33256         configurable: true
33257     });
33258     Object.defineProperty(StateBase.prototype, "previousNode", {
33259         get: function () {
33260             return this._previousNode;
33261         },
33262         enumerable: true,
33263         configurable: true
33264     });
33265     Object.defineProperty(StateBase.prototype, "currentCamera", {
33266         get: function () {
33267             return this._currentCamera;
33268         },
33269         enumerable: true,
33270         configurable: true
33271     });
33272     Object.defineProperty(StateBase.prototype, "currentTransform", {
33273         get: function () {
33274             return this._trajectoryTransforms.length > 0 ?
33275                 this._trajectoryTransforms[this.currentIndex] : null;
33276         },
33277         enumerable: true,
33278         configurable: true
33279     });
33280     Object.defineProperty(StateBase.prototype, "previousTransform", {
33281         get: function () {
33282             return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
33283                 this._trajectoryTransforms[this.currentIndex - 1] : null;
33284         },
33285         enumerable: true,
33286         configurable: true
33287     });
33288     Object.defineProperty(StateBase.prototype, "motionless", {
33289         get: function () {
33290             return this._motionless;
33291         },
33292         enumerable: true,
33293         configurable: true
33294     });
33295     StateBase.prototype.append = function (nodes) {
33296         if (nodes.length < 1) {
33297             throw Error("Trajectory can not be empty");
33298         }
33299         if (this._currentIndex < 0) {
33300             this.set(nodes);
33301         }
33302         else {
33303             this._trajectory = this._trajectory.concat(nodes);
33304             this._appendToTrajectories(nodes);
33305         }
33306     };
33307     StateBase.prototype.prepend = function (nodes) {
33308         if (nodes.length < 1) {
33309             throw Error("Trajectory can not be empty");
33310         }
33311         this._trajectory = nodes.slice().concat(this._trajectory);
33312         this._currentIndex += nodes.length;
33313         this._setCurrentNode();
33314         var referenceReset = this._setReference(this._currentNode);
33315         if (referenceReset) {
33316             this._setTrajectories();
33317         }
33318         else {
33319             this._prependToTrajectories(nodes);
33320         }
33321         this._setCurrentCamera();
33322     };
33323     StateBase.prototype.remove = function (n) {
33324         if (n < 0) {
33325             throw Error("n must be a positive integer");
33326         }
33327         if (this._currentIndex - 1 < n) {
33328             throw Error("Current and previous nodes can not be removed");
33329         }
33330         for (var i = 0; i < n; i++) {
33331             this._trajectory.shift();
33332             this._trajectoryTransforms.shift();
33333             this._trajectoryCameras.shift();
33334             this._currentIndex--;
33335         }
33336         this._setCurrentNode();
33337     };
33338     StateBase.prototype.clearPrior = function () {
33339         if (this._currentIndex > 0) {
33340             this.remove(this._currentIndex - 1);
33341         }
33342     };
33343     StateBase.prototype.clear = function () {
33344         this.cut();
33345         if (this._currentIndex > 0) {
33346             this.remove(this._currentIndex - 1);
33347         }
33348     };
33349     StateBase.prototype.cut = function () {
33350         while (this._trajectory.length - 1 > this._currentIndex) {
33351             this._trajectory.pop();
33352             this._trajectoryTransforms.pop();
33353             this._trajectoryCameras.pop();
33354         }
33355     };
33356     StateBase.prototype.set = function (nodes) {
33357         this._setTrajectory(nodes);
33358         this._setCurrentNode();
33359         this._setReference(this._currentNode);
33360         this._setTrajectories();
33361         this._setCurrentCamera();
33362     };
33363     StateBase.prototype.getCenter = function () {
33364         return this._currentNode != null ?
33365             this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
33366             [0.5, 0.5];
33367     };
33368     StateBase.prototype._setCurrent = function () {
33369         this._setCurrentNode();
33370         var referenceReset = this._setReference(this._currentNode);
33371         if (referenceReset) {
33372             this._setTrajectories();
33373         }
33374         this._setCurrentCamera();
33375     };
33376     StateBase.prototype._setCurrentCamera = function () {
33377         this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
33378         this._previousCamera = this._currentIndex > 0 ?
33379             this._trajectoryCameras[this._currentIndex - 1].clone() :
33380             this._currentCamera.clone();
33381     };
33382     StateBase.prototype._motionlessTransition = function () {
33383         var nodesSet = this._currentNode != null && this._previousNode != null;
33384         return nodesSet && !(this._currentNode.merged &&
33385             this._previousNode.merged &&
33386             this._withinOriginalDistance() &&
33387             this._sameConnectedComponent());
33388     };
33389     StateBase.prototype._setReference = function (node) {
33390         // do not reset reference if node is within threshold distance
33391         if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
33392             Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
33393             return false;
33394         }
33395         // do not reset reference if previous node exist and transition is with motion
33396         if (this._previousNode != null && !this._motionlessTransition()) {
33397             return false;
33398         }
33399         this._reference.lat = node.latLon.lat;
33400         this._reference.lon = node.latLon.lon;
33401         this._reference.alt = node.alt;
33402         return true;
33403     };
33404     StateBase.prototype._setCurrentNode = function () {
33405         this._currentNode = this._trajectory.length > 0 ?
33406             this._trajectory[this._currentIndex] :
33407             null;
33408         this._previousNode = this._currentIndex > 0 ?
33409             this._trajectory[this._currentIndex - 1] :
33410             null;
33411     };
33412     StateBase.prototype._setTrajectory = function (nodes) {
33413         if (nodes.length < 1) {
33414             throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
33415         }
33416         if (this._currentNode != null) {
33417             this._trajectory = [this._currentNode].concat(nodes);
33418             this._currentIndex = 1;
33419         }
33420         else {
33421             this._trajectory = nodes.slice();
33422             this._currentIndex = 0;
33423         }
33424     };
33425     StateBase.prototype._setTrajectories = function () {
33426         this._trajectoryTransforms.length = 0;
33427         this._trajectoryCameras.length = 0;
33428         this._appendToTrajectories(this._trajectory);
33429     };
33430     StateBase.prototype._appendToTrajectories = function (nodes) {
33431         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
33432             var node = nodes_1[_i];
33433             if (!node.assetsCached) {
33434                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
33435             }
33436             var translation = this._nodeToTranslation(node);
33437             var transform = new Geo_1.Transform(node, node.image, translation);
33438             this._trajectoryTransforms.push(transform);
33439             this._trajectoryCameras.push(new Geo_1.Camera(transform));
33440         }
33441     };
33442     StateBase.prototype._prependToTrajectories = function (nodes) {
33443         for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
33444             var node = _a[_i];
33445             if (!node.assetsCached) {
33446                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
33447             }
33448             var translation = this._nodeToTranslation(node);
33449             var transform = new Geo_1.Transform(node, node.image, translation);
33450             this._trajectoryTransforms.unshift(transform);
33451             this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
33452         }
33453     };
33454     StateBase.prototype._nodeToTranslation = function (node) {
33455         var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
33456         var RC = this._spatial.rotate(C, node.rotation);
33457         return [-RC.x, -RC.y, -RC.z];
33458     };
33459     StateBase.prototype._sameConnectedComponent = function () {
33460         var current = this._currentNode;
33461         var previous = this._previousNode;
33462         if (!current ||
33463             !current.mergeCC ||
33464             !previous ||
33465             !previous.mergeCC) {
33466             return true;
33467         }
33468         return current.mergeCC === previous.mergeCC;
33469     };
33470     StateBase.prototype._withinOriginalDistance = function () {
33471         var current = this._currentNode;
33472         var previous = this._previousNode;
33473         if (!current || !previous) {
33474             return true;
33475         }
33476         // 50 km/h moves 28m in 2s
33477         var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
33478         return distance < 25;
33479     };
33480     return StateBase;
33481 }());
33482 exports.StateBase = StateBase;
33483
33484 },{"../../Error":219,"../../Geo":220}],313:[function(require,module,exports){
33485 /// <reference path="../../../typings/index.d.ts" />
33486 "use strict";
33487 var __extends = (this && this.__extends) || function (d, b) {
33488     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
33489     function __() { this.constructor = d; }
33490     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33491 };
33492 var THREE = require("three");
33493 var UnitBezier = require("unitbezier");
33494 var State_1 = require("../../State");
33495 var RotationDelta = (function () {
33496     function RotationDelta(phi, theta) {
33497         this._phi = phi;
33498         this._theta = theta;
33499     }
33500     Object.defineProperty(RotationDelta.prototype, "phi", {
33501         get: function () {
33502             return this._phi;
33503         },
33504         set: function (value) {
33505             this._phi = value;
33506         },
33507         enumerable: true,
33508         configurable: true
33509     });
33510     Object.defineProperty(RotationDelta.prototype, "theta", {
33511         get: function () {
33512             return this._theta;
33513         },
33514         set: function (value) {
33515             this._theta = value;
33516         },
33517         enumerable: true,
33518         configurable: true
33519     });
33520     Object.defineProperty(RotationDelta.prototype, "isZero", {
33521         get: function () {
33522             return this._phi === 0 && this._theta === 0;
33523         },
33524         enumerable: true,
33525         configurable: true
33526     });
33527     RotationDelta.prototype.copy = function (delta) {
33528         this._phi = delta.phi;
33529         this._theta = delta.theta;
33530     };
33531     RotationDelta.prototype.lerp = function (other, alpha) {
33532         this._phi = (1 - alpha) * this._phi + alpha * other.phi;
33533         this._theta = (1 - alpha) * this._theta + alpha * other.theta;
33534     };
33535     RotationDelta.prototype.multiply = function (value) {
33536         this._phi *= value;
33537         this._theta *= value;
33538     };
33539     RotationDelta.prototype.threshold = function (value) {
33540         this._phi = Math.abs(this._phi) > value ? this._phi : 0;
33541         this._theta = Math.abs(this._theta) > value ? this._theta : 0;
33542     };
33543     RotationDelta.prototype.lengthSquared = function () {
33544         return this._phi * this._phi + this._theta * this._theta;
33545     };
33546     RotationDelta.prototype.reset = function () {
33547         this._phi = 0;
33548         this._theta = 0;
33549     };
33550     return RotationDelta;
33551 }());
33552 var TraversingState = (function (_super) {
33553     __extends(TraversingState, _super);
33554     function TraversingState(state) {
33555         var _this = _super.call(this, state) || this;
33556         _this._adjustCameras();
33557         _this._motionless = _this._motionlessTransition();
33558         _this._baseAlpha = _this._alpha;
33559         _this._animationSpeed = 0.025;
33560         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
33561         _this._useBezier = false;
33562         _this._rotationDelta = new RotationDelta(0, 0);
33563         _this._requestedRotationDelta = null;
33564         _this._basicRotation = [0, 0];
33565         _this._requestedBasicRotation = null;
33566         _this._requestedBasicRotationUnbounded = null;
33567         _this._rotationAcceleration = 0.86;
33568         _this._rotationIncreaseAlpha = 0.97;
33569         _this._rotationDecreaseAlpha = 0.9;
33570         _this._rotationThreshold = 1e-3;
33571         _this._unboundedRotationAlpha = 0.8;
33572         _this._desiredZoom = state.zoom;
33573         _this._minZoom = 0;
33574         _this._maxZoom = 3;
33575         _this._lookatDepth = 10;
33576         _this._desiredLookat = null;
33577         _this._desiredCenter = null;
33578         return _this;
33579     }
33580     TraversingState.prototype.traverse = function () {
33581         throw new Error("Not implemented");
33582     };
33583     TraversingState.prototype.wait = function () {
33584         return new State_1.WaitingState(this);
33585     };
33586     TraversingState.prototype.append = function (nodes) {
33587         var emptyTrajectory = this._trajectory.length === 0;
33588         if (emptyTrajectory) {
33589             this._resetTransition();
33590         }
33591         _super.prototype.append.call(this, nodes);
33592         if (emptyTrajectory) {
33593             this._setDesiredCenter();
33594             this._setDesiredZoom();
33595         }
33596     };
33597     TraversingState.prototype.prepend = function (nodes) {
33598         var emptyTrajectory = this._trajectory.length === 0;
33599         if (emptyTrajectory) {
33600             this._resetTransition();
33601         }
33602         _super.prototype.prepend.call(this, nodes);
33603         if (emptyTrajectory) {
33604             this._setDesiredCenter();
33605             this._setDesiredZoom();
33606         }
33607     };
33608     TraversingState.prototype.set = function (nodes) {
33609         _super.prototype.set.call(this, nodes);
33610         this._desiredLookat = null;
33611         this._resetTransition();
33612         this._clearRotation();
33613         this._setDesiredCenter();
33614         this._setDesiredZoom();
33615         if (this._trajectory.length < 3) {
33616             this._useBezier = true;
33617         }
33618     };
33619     TraversingState.prototype.move = function (delta) {
33620         throw new Error("Not implemented");
33621     };
33622     TraversingState.prototype.moveTo = function (delta) {
33623         throw new Error("Not implemented");
33624     };
33625     TraversingState.prototype.rotate = function (rotationDelta) {
33626         if (this._currentNode == null) {
33627             return;
33628         }
33629         this._desiredZoom = this._zoom;
33630         this._desiredLookat = null;
33631         this._requestedBasicRotation = null;
33632         if (this._requestedRotationDelta != null) {
33633             this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
33634             this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
33635         }
33636         else {
33637             this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
33638         }
33639     };
33640     TraversingState.prototype.rotateBasic = function (basicRotation) {
33641         if (this._currentNode == null) {
33642             return;
33643         }
33644         this._desiredZoom = this._zoom;
33645         this._desiredLookat = null;
33646         this._requestedRotationDelta = null;
33647         if (this._requestedBasicRotation != null) {
33648             this._requestedBasicRotation[0] += basicRotation[0];
33649             this._requestedBasicRotation[1] += basicRotation[1];
33650             var threshold = 0.05 / Math.pow(2, this._zoom);
33651             this._requestedBasicRotation[0] =
33652                 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
33653             this._requestedBasicRotation[1] =
33654                 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
33655         }
33656         else {
33657             this._requestedBasicRotation = basicRotation.slice();
33658         }
33659     };
33660     TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
33661         if (this._currentNode == null) {
33662             return;
33663         }
33664         if (this._requestedBasicRotationUnbounded != null) {
33665             this._requestedBasicRotationUnbounded[0] += basicRotation[0];
33666             this._requestedBasicRotationUnbounded[1] += basicRotation[1];
33667         }
33668         else {
33669             this._requestedBasicRotationUnbounded = basicRotation.slice();
33670         }
33671     };
33672     TraversingState.prototype.rotateToBasic = function (basic) {
33673         if (this._currentNode == null) {
33674             return;
33675         }
33676         this._desiredZoom = this._zoom;
33677         this._desiredLookat = null;
33678         basic[0] = this._spatial.clamp(basic[0], 0, 1);
33679         basic[1] = this._spatial.clamp(basic[1], 0, 1);
33680         var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
33681         this._currentCamera.lookat.fromArray(lookat);
33682     };
33683     TraversingState.prototype.zoomIn = function (delta, reference) {
33684         if (this._currentNode == null) {
33685             return;
33686         }
33687         this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
33688         var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
33689         var currentCenterX = currentCenter[0];
33690         var currentCenterY = currentCenter[1];
33691         var zoom0 = Math.pow(2, this._zoom);
33692         var zoom1 = Math.pow(2, this._desiredZoom);
33693         var refX = reference[0];
33694         var refY = reference[1];
33695         if (this.currentTransform.gpano != null &&
33696             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
33697             if (refX - currentCenterX > 0.5) {
33698                 refX = refX - 1;
33699             }
33700             else if (currentCenterX - refX > 0.5) {
33701                 refX = 1 + refX;
33702             }
33703         }
33704         var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
33705         var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
33706         var gpano = this.currentTransform.gpano;
33707         if (this._currentNode.fullPano) {
33708             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
33709             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
33710         }
33711         else if (gpano != null &&
33712             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
33713             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
33714             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
33715         }
33716         else {
33717             newCenterX = this._spatial.clamp(newCenterX, 0, 1);
33718             newCenterY = this._spatial.clamp(newCenterY, 0, 1);
33719         }
33720         this._desiredLookat = new THREE.Vector3()
33721             .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
33722     };
33723     TraversingState.prototype.setCenter = function (center) {
33724         this._desiredLookat = null;
33725         this._requestedRotationDelta = null;
33726         this._requestedBasicRotation = null;
33727         this._desiredZoom = this._zoom;
33728         var clamped = [
33729             this._spatial.clamp(center[0], 0, 1),
33730             this._spatial.clamp(center[1], 0, 1),
33731         ];
33732         if (this._currentNode == null) {
33733             this._desiredCenter = clamped;
33734             return;
33735         }
33736         this._desiredCenter = null;
33737         var currentLookat = new THREE.Vector3()
33738             .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
33739         var previousTransform = this.previousTransform != null ?
33740             this.previousTransform :
33741             this.currentTransform;
33742         var previousLookat = new THREE.Vector3()
33743             .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
33744         this._currentCamera.lookat.copy(currentLookat);
33745         this._previousCamera.lookat.copy(previousLookat);
33746     };
33747     TraversingState.prototype.setZoom = function (zoom) {
33748         this._desiredLookat = null;
33749         this._requestedRotationDelta = null;
33750         this._requestedBasicRotation = null;
33751         this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
33752         this._desiredZoom = this._zoom;
33753     };
33754     TraversingState.prototype.update = function (fps) {
33755         if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
33756             this._currentIndex += 1;
33757             this._useBezier = this._trajectory.length < 3 &&
33758                 this._currentIndex + 1 === this._trajectory.length;
33759             this._setCurrent();
33760             this._resetTransition();
33761             this._clearRotation();
33762             this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
33763             this._desiredLookat = null;
33764         }
33765         var animationSpeed = this._animationSpeed * (60 / fps);
33766         this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed);
33767         if (this._useBezier) {
33768             this._alpha = this._unitBezier.solve(this._baseAlpha);
33769         }
33770         else {
33771             this._alpha = this._baseAlpha;
33772         }
33773         this._updateRotation();
33774         if (!this._rotationDelta.isZero) {
33775             this._applyRotation(this._previousCamera);
33776             this._applyRotation(this._currentCamera);
33777         }
33778         this._updateRotationBasic();
33779         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
33780             this._applyRotationBasic();
33781         }
33782         this._updateZoom(animationSpeed);
33783         this._updateLookat(animationSpeed);
33784         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
33785     };
33786     TraversingState.prototype._getAlpha = function () {
33787         return this._motionless ? Math.ceil(this._alpha) : this._alpha;
33788     };
33789     TraversingState.prototype._setCurrentCamera = function () {
33790         _super.prototype._setCurrentCamera.call(this);
33791         this._adjustCameras();
33792     };
33793     TraversingState.prototype._adjustCameras = function () {
33794         if (this._previousNode == null) {
33795             return;
33796         }
33797         var lookat = this._camera.lookat.clone().sub(this._camera.position);
33798         this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
33799         if (this._currentNode.fullPano) {
33800             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
33801         }
33802     };
33803     TraversingState.prototype._resetTransition = function () {
33804         this._alpha = 0;
33805         this._baseAlpha = 0;
33806         this._motionless = this._motionlessTransition();
33807     };
33808     TraversingState.prototype._applyRotation = function (camera) {
33809         if (camera == null) {
33810             return;
33811         }
33812         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
33813         var qInverse = q.clone().inverse();
33814         var offset = new THREE.Vector3();
33815         offset.copy(camera.lookat).sub(camera.position);
33816         offset.applyQuaternion(q);
33817         var length = offset.length();
33818         var phi = Math.atan2(offset.y, offset.x);
33819         phi += this._rotationDelta.phi;
33820         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
33821         theta += this._rotationDelta.theta;
33822         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
33823         offset.x = Math.sin(theta) * Math.cos(phi);
33824         offset.y = Math.sin(theta) * Math.sin(phi);
33825         offset.z = Math.cos(theta);
33826         offset.applyQuaternion(qInverse);
33827         camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
33828     };
33829     TraversingState.prototype._applyRotationBasic = function () {
33830         var currentNode = this._currentNode;
33831         var previousNode = this._previousNode != null ?
33832             this.previousNode :
33833             this.currentNode;
33834         var currentCamera = this._currentCamera;
33835         var previousCamera = this._previousCamera;
33836         var currentTransform = this.currentTransform;
33837         var previousTransform = this.previousTransform != null ?
33838             this.previousTransform :
33839             this.currentTransform;
33840         var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
33841         var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
33842         var currentGPano = currentTransform.gpano;
33843         var previousGPano = previousTransform.gpano;
33844         if (currentNode.fullPano) {
33845             currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
33846             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0.05, 0.95);
33847         }
33848         else if (currentGPano != null &&
33849             currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
33850             currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
33851             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
33852         }
33853         else {
33854             currentBasic[0] = this._spatial.clamp(currentBasic[0] + this._basicRotation[0], 0, 1);
33855             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
33856         }
33857         if (previousNode.fullPano) {
33858             previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
33859             previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0.05, 0.95);
33860         }
33861         else if (previousGPano != null &&
33862             previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
33863             previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
33864             previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0, 1);
33865         }
33866         else {
33867             previousBasic[0] = this._spatial.clamp(previousBasic[0] + this._basicRotation[0], 0, 1);
33868             previousBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
33869         }
33870         var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
33871         currentCamera.lookat.fromArray(currentLookat);
33872         var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
33873         previousCamera.lookat.fromArray(previousLookat);
33874     };
33875     TraversingState.prototype._updateZoom = function (animationSpeed) {
33876         var diff = this._desiredZoom - this._zoom;
33877         var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
33878         if (diff === 0) {
33879             return;
33880         }
33881         else if (Math.abs(diff) < 2e-3) {
33882             this._zoom = this._desiredZoom;
33883             if (this._desiredLookat != null) {
33884                 this._desiredLookat = null;
33885             }
33886         }
33887         else {
33888             this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
33889         }
33890     };
33891     TraversingState.prototype._updateLookat = function (animationSpeed) {
33892         if (this._desiredLookat === null) {
33893             return;
33894         }
33895         var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
33896         if (Math.abs(diff) < 1e-6) {
33897             this._currentCamera.lookat.copy(this._desiredLookat);
33898             this._desiredLookat = null;
33899         }
33900         else {
33901             this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
33902         }
33903     };
33904     TraversingState.prototype._updateRotation = function () {
33905         if (this._requestedRotationDelta != null) {
33906             var length_1 = this._rotationDelta.lengthSquared();
33907             var requestedLength = this._requestedRotationDelta.lengthSquared();
33908             if (requestedLength > length_1) {
33909                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
33910             }
33911             else {
33912                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
33913             }
33914             this._requestedRotationDelta = null;
33915             return;
33916         }
33917         if (this._rotationDelta.isZero) {
33918             return;
33919         }
33920         this._rotationDelta.multiply(this._rotationAcceleration);
33921         this._rotationDelta.threshold(this._rotationThreshold);
33922     };
33923     TraversingState.prototype._updateRotationBasic = function () {
33924         if (this._requestedBasicRotation != null) {
33925             var x = this._basicRotation[0];
33926             var y = this._basicRotation[1];
33927             var reqX = this._requestedBasicRotation[0];
33928             var reqY = this._requestedBasicRotation[1];
33929             if (Math.abs(reqX) > Math.abs(x)) {
33930                 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
33931             }
33932             else {
33933                 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
33934             }
33935             if (Math.abs(reqY) > Math.abs(y)) {
33936                 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
33937             }
33938             else {
33939                 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
33940             }
33941             this._requestedBasicRotation = null;
33942             return;
33943         }
33944         if (this._requestedBasicRotationUnbounded != null) {
33945             var reqX = this._requestedBasicRotationUnbounded[0];
33946             var reqY = this._requestedBasicRotationUnbounded[1];
33947             if (Math.abs(reqX) > 0) {
33948                 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
33949             }
33950             if (Math.abs(reqY) > 0) {
33951                 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
33952             }
33953             if (this._desiredLookat != null) {
33954                 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
33955                 desiredBasicLookat[0] += reqX;
33956                 desiredBasicLookat[1] += reqY;
33957                 this._desiredLookat = new THREE.Vector3()
33958                     .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
33959             }
33960             this._requestedBasicRotationUnbounded = null;
33961         }
33962         if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
33963             return;
33964         }
33965         this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
33966         this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
33967         if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
33968             Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
33969             this._basicRotation = [0, 0];
33970         }
33971     };
33972     TraversingState.prototype._clearRotation = function () {
33973         if (this._currentNode.fullPano) {
33974             return;
33975         }
33976         if (this._requestedRotationDelta != null) {
33977             this._requestedRotationDelta = null;
33978         }
33979         if (!this._rotationDelta.isZero) {
33980             this._rotationDelta.reset();
33981         }
33982         if (this._requestedBasicRotation != null) {
33983             this._requestedBasicRotation = null;
33984         }
33985         if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
33986             this._basicRotation = [0, 0];
33987         }
33988     };
33989     TraversingState.prototype._setDesiredCenter = function () {
33990         if (this._desiredCenter == null) {
33991             return;
33992         }
33993         var lookatDirection = new THREE.Vector3()
33994             .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
33995             .sub(this._currentCamera.position);
33996         this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
33997         this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
33998         this._desiredCenter = null;
33999     };
34000     TraversingState.prototype._setDesiredZoom = function () {
34001         this._desiredZoom =
34002             this._currentNode.fullPano || this._previousNode == null ?
34003                 this._zoom : 0;
34004     };
34005     return TraversingState;
34006 }(State_1.StateBase));
34007 exports.TraversingState = TraversingState;
34008
34009 },{"../../State":224,"three":167,"unitbezier":169}],314:[function(require,module,exports){
34010 "use strict";
34011 var __extends = (this && this.__extends) || function (d, b) {
34012     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
34013     function __() { this.constructor = d; }
34014     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34015 };
34016 var State_1 = require("../../State");
34017 var WaitingState = (function (_super) {
34018     __extends(WaitingState, _super);
34019     function WaitingState(state) {
34020         var _this = _super.call(this, state) || this;
34021         _this._adjustCameras();
34022         _this._motionless = _this._motionlessTransition();
34023         return _this;
34024     }
34025     WaitingState.prototype.traverse = function () {
34026         return new State_1.TraversingState(this);
34027     };
34028     WaitingState.prototype.wait = function () {
34029         throw new Error("Not implemented");
34030     };
34031     WaitingState.prototype.prepend = function (nodes) {
34032         _super.prototype.prepend.call(this, nodes);
34033         this._motionless = this._motionlessTransition();
34034     };
34035     WaitingState.prototype.set = function (nodes) {
34036         _super.prototype.set.call(this, nodes);
34037         this._motionless = this._motionlessTransition();
34038     };
34039     WaitingState.prototype.rotate = function (delta) { return; };
34040     WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
34041     WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
34042     WaitingState.prototype.rotateToBasic = function (basic) { return; };
34043     WaitingState.prototype.zoomIn = function (delta, reference) { return; };
34044     WaitingState.prototype.move = function (delta) {
34045         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
34046     };
34047     WaitingState.prototype.moveTo = function (position) {
34048         this._alpha = Math.max(0, Math.min(1, position));
34049     };
34050     WaitingState.prototype.update = function (fps) {
34051         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
34052     };
34053     WaitingState.prototype.setCenter = function (center) { return; };
34054     WaitingState.prototype.setZoom = function (zoom) { return; };
34055     WaitingState.prototype._getAlpha = function () {
34056         return this._motionless ? Math.round(this._alpha) : this._alpha;
34057     };
34058     ;
34059     WaitingState.prototype._setCurrentCamera = function () {
34060         _super.prototype._setCurrentCamera.call(this);
34061         this._adjustCameras();
34062     };
34063     WaitingState.prototype._adjustCameras = function () {
34064         if (this._previousNode == null) {
34065             return;
34066         }
34067         if (this._currentNode.fullPano) {
34068             var lookat = this._camera.lookat.clone().sub(this._camera.position);
34069             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
34070         }
34071         if (this._previousNode.fullPano) {
34072             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
34073             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
34074         }
34075     };
34076     return WaitingState;
34077 }(State_1.StateBase));
34078 exports.WaitingState = WaitingState;
34079
34080 },{"../../State":224}],315:[function(require,module,exports){
34081 "use strict";
34082 var Observable_1 = require("rxjs/Observable");
34083 /**
34084  * @class ImageTileLoader
34085  *
34086  * @classdesc Represents a loader of image tiles.
34087  */
34088 var ImageTileLoader = (function () {
34089     /**
34090      * Create a new node image tile loader instance.
34091      *
34092      * @param {string} scheme - The URI scheme.
34093      * @param {string} host - The URI host.
34094      * @param {string} [origin] - The origin query param.
34095      */
34096     function ImageTileLoader(scheme, host, origin) {
34097         this._scheme = scheme;
34098         this._host = host;
34099         this._origin = origin != null ? "?origin=" + origin : "";
34100     }
34101     /**
34102      * Retrieve an image tile.
34103      *
34104      * @description Retrieve an image tile by specifying the area
34105      * as well as the scaled size.
34106      *
34107      * @param {string} identifier - The identifier of the image.
34108      * @param {number} x - The top left x pixel coordinate for the tile
34109      * in the original image.
34110      * @param {number} y - The top left y pixel coordinate for the tile
34111      * in the original image.
34112      * @param {number} w - The pixel width of the tile in the original image.
34113      * @param {number} h - The pixel height of the tile in the original image.
34114      * @param {number} scaledW - The scaled width of the returned tile.
34115      * @param {number} scaledH - The scaled height of the returned tile.
34116      */
34117     ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
34118         var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
34119         var url = this._scheme +
34120             "://" +
34121             this._host +
34122             characteristics +
34123             this._origin;
34124         var xmlHTTP = null;
34125         return [Observable_1.Observable.create(function (subscriber) {
34126                 xmlHTTP = new XMLHttpRequest();
34127                 xmlHTTP.open("GET", url, true);
34128                 xmlHTTP.responseType = "arraybuffer";
34129                 xmlHTTP.timeout = 15000;
34130                 xmlHTTP.onload = function (event) {
34131                     if (xmlHTTP.status !== 200) {
34132                         subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
34133                             ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
34134                         return;
34135                     }
34136                     var image = new Image();
34137                     image.crossOrigin = "Anonymous";
34138                     image.onload = function (e) {
34139                         subscriber.next(image);
34140                         subscriber.complete();
34141                     };
34142                     image.onerror = function (error) {
34143                         subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
34144                     };
34145                     var blob = new Blob([xmlHTTP.response]);
34146                     image.src = window.URL.createObjectURL(blob);
34147                 };
34148                 xmlHTTP.onerror = function (error) {
34149                     subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
34150                 };
34151                 xmlHTTP.ontimeout = function (error) {
34152                     subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
34153                 };
34154                 xmlHTTP.onabort = function (event) {
34155                     subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
34156                 };
34157                 xmlHTTP.send(null);
34158             }),
34159             function () {
34160                 if (xmlHTTP != null) {
34161                     xmlHTTP.abort();
34162                 }
34163             },
34164         ];
34165     };
34166     return ImageTileLoader;
34167 }());
34168 exports.ImageTileLoader = ImageTileLoader;
34169 Object.defineProperty(exports, "__esModule", { value: true });
34170 exports.default = ImageTileLoader;
34171
34172 },{"rxjs/Observable":28}],316:[function(require,module,exports){
34173 "use strict";
34174 /**
34175  * @class ImageTileStore
34176  *
34177  * @classdesc Represents a store for image tiles.
34178  */
34179 var ImageTileStore = (function () {
34180     /**
34181      * Create a new node image tile store instance.
34182      */
34183     function ImageTileStore() {
34184         this._images = {};
34185     }
34186     /**
34187      * Add an image tile to the store.
34188      *
34189      * @param {HTMLImageElement} image - The image tile.
34190      * @param {string} key - The identifier for the tile.
34191      * @param {number} level - The level of the tile.
34192      */
34193     ImageTileStore.prototype.addImage = function (image, key, level) {
34194         if (!(level in this._images)) {
34195             this._images[level] = {};
34196         }
34197         this._images[level][key] = image;
34198     };
34199     /**
34200      * Dispose the store.
34201      *
34202      * @description Disposes all cached assets.
34203      */
34204     ImageTileStore.prototype.dispose = function () {
34205         for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
34206             var level = _a[_i];
34207             var levelImages = this._images[level];
34208             for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
34209                 var key = _c[_b];
34210                 window.URL.revokeObjectURL(levelImages[key].src);
34211                 delete levelImages[key];
34212             }
34213             delete this._images[level];
34214         }
34215     };
34216     /**
34217      * Get an image tile from the store.
34218      *
34219      * @param {string} key - The identifier for the tile.
34220      * @param {number} level - The level of the tile.
34221      */
34222     ImageTileStore.prototype.getImage = function (key, level) {
34223         return this._images[level][key];
34224     };
34225     /**
34226      * Check if an image tile exist in the store.
34227      *
34228      * @param {string} key - The identifier for the tile.
34229      * @param {number} level - The level of the tile.
34230      */
34231     ImageTileStore.prototype.hasImage = function (key, level) {
34232         return level in this._images && key in this._images[level];
34233     };
34234     return ImageTileStore;
34235 }());
34236 exports.ImageTileStore = ImageTileStore;
34237 Object.defineProperty(exports, "__esModule", { value: true });
34238 exports.default = ImageTileStore;
34239
34240 },{}],317:[function(require,module,exports){
34241 /// <reference path="../../typings/index.d.ts" />
34242 "use strict";
34243 var Geo_1 = require("../Geo");
34244 /**
34245  * @class RegionOfInterestCalculator
34246  *
34247  * @classdesc Represents a calculator for regions of interest.
34248  */
34249 var RegionOfInterestCalculator = (function () {
34250     function RegionOfInterestCalculator() {
34251         this._viewportCoords = new Geo_1.ViewportCoords();
34252     }
34253     /**
34254      * Compute a region of interest based on the current render camera
34255      * and the viewport size.
34256      *
34257      * @param {RenderCamera} renderCamera - Render camera used for unprojections.
34258      * @param {ISize} size - Viewport size in pixels.
34259      * @param {Transform} transform - Transform used for projections.
34260      *
34261      * @returns {IRegionOfInterest} A region of interest.
34262      */
34263     RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
34264         var canvasPoints = this._canvasBoundaryPoints(4);
34265         var bbox = this._canvasPointsBoundingBox(canvasPoints, renderCamera, transform);
34266         this._clipBoundingBox(bbox);
34267         var centralPixel = [
34268             [0.5 - 0.5 / size.width, 0.5 - 0.5 / size.height],
34269             [0.5 + 0.5 / size.width, 0.5 - 0.5 / size.height],
34270             [0.5 + 0.5 / size.width, 0.5 + 0.5 / size.height],
34271             [0.5 - 0.5 / size.width, 0.5 + 0.5 / size.height],
34272         ];
34273         var cpbox = this._canvasPointsBoundingBox(centralPixel, renderCamera, transform);
34274         return {
34275             bbox: bbox,
34276             pixelHeight: cpbox.maxY - cpbox.minY,
34277             pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
34278         };
34279     };
34280     RegionOfInterestCalculator.prototype._canvasBoundaryPoints = function (pointsPerSide) {
34281         var points = [];
34282         var os = [[0, 0], [1, 0], [1, 1], [0, 1]];
34283         var ds = [[1, 0], [0, 1], [-1, 0], [0, -1]];
34284         for (var side = 0; side < 4; ++side) {
34285             var o = os[side];
34286             var d = ds[side];
34287             for (var i = 0; i < pointsPerSide; ++i) {
34288                 points.push([o[0] + d[0] * i / pointsPerSide,
34289                     o[1] + d[1] * i / pointsPerSide]);
34290             }
34291         }
34292         return points;
34293     };
34294     RegionOfInterestCalculator.prototype._canvasPointsBoundingBox = function (canvasPoints, renderCamera, transform) {
34295         var _this = this;
34296         var basicPoints = canvasPoints.map(function (point) {
34297             return _this._viewportCoords
34298                 .canvasToBasic(point[0], point[1], 1, 1, transform, renderCamera.perspective);
34299         });
34300         if (transform.gpano != null) {
34301             return this._boundingBoxPano(basicPoints);
34302         }
34303         else {
34304             return this._boundingBox(basicPoints);
34305         }
34306     };
34307     RegionOfInterestCalculator.prototype._boundingBox = function (points) {
34308         var bbox = {
34309             maxX: Number.NEGATIVE_INFINITY,
34310             maxY: Number.NEGATIVE_INFINITY,
34311             minX: Number.POSITIVE_INFINITY,
34312             minY: Number.POSITIVE_INFINITY,
34313         };
34314         for (var i = 0; i < points.length; ++i) {
34315             bbox.minX = Math.min(bbox.minX, points[i][0]);
34316             bbox.maxX = Math.max(bbox.maxX, points[i][0]);
34317             bbox.minY = Math.min(bbox.minY, points[i][1]);
34318             bbox.maxY = Math.max(bbox.maxY, points[i][1]);
34319         }
34320         return bbox;
34321     };
34322     RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
34323         var _this = this;
34324         var xs = [];
34325         var ys = [];
34326         for (var i = 0; i < points.length; ++i) {
34327             xs.push(points[i][0]);
34328             ys.push(points[i][1]);
34329         }
34330         xs.sort(function (a, b) { return _this._sign(a - b); });
34331         ys.sort(function (a, b) { return _this._sign(a - b); });
34332         var intervalX = this._intervalPano(xs);
34333         return {
34334             maxX: intervalX[1],
34335             maxY: ys[ys.length - 1],
34336             minX: intervalX[0],
34337             minY: ys[0],
34338         };
34339     };
34340     /**
34341      * Find the max interval between consecutive numbers.
34342      * Assumes numbers are between 0 and 1, sorted and that
34343      * x is equivalent to x + 1.
34344      */
34345     RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
34346         var maxdx = 0;
34347         var maxi = -1;
34348         for (var i = 0; i < xs.length - 1; ++i) {
34349             var dx = xs[i + 1] - xs[i];
34350             if (dx > maxdx) {
34351                 maxdx = dx;
34352                 maxi = i;
34353             }
34354         }
34355         var loopdx = xs[0] + 1 - xs[xs.length - 1];
34356         if (loopdx > maxdx) {
34357             return [xs[0], xs[xs.length - 1]];
34358         }
34359         else {
34360             return [xs[maxi + 1], xs[maxi]];
34361         }
34362     };
34363     RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
34364         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
34365         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
34366         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
34367         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
34368     };
34369     RegionOfInterestCalculator.prototype._sign = function (n) {
34370         return n > 0 ? 1 : n < 0 ? -1 : 0;
34371     };
34372     return RegionOfInterestCalculator;
34373 }());
34374 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
34375 Object.defineProperty(exports, "__esModule", { value: true });
34376 exports.default = RegionOfInterestCalculator;
34377
34378 },{"../Geo":220}],318:[function(require,module,exports){
34379 /// <reference path="../../typings/index.d.ts" />
34380 "use strict";
34381 var THREE = require("three");
34382 var Subject_1 = require("rxjs/Subject");
34383 /**
34384  * @class TextureProvider
34385  *
34386  * @classdesc Represents a provider of textures.
34387  */
34388 var TextureProvider = (function () {
34389     /**
34390      * Create a new node texture provider instance.
34391      *
34392      * @param {string} key - The identifier of the image for which to request tiles.
34393      * @param {number} width - The full width of the original image.
34394      * @param {number} height - The full height of the original image.
34395      * @param {number} tileSize - The size used when requesting tiles.
34396      * @param {HTMLImageElement} background - Image to use as background.
34397      * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
34398      * @param {ImageTileStore} imageTileStore - Store for saving tiles.
34399      * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
34400      */
34401     function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
34402         this._disposed = false;
34403         this._key = key;
34404         if (width <= 0 || height <= 0) {
34405             console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
34406         }
34407         this._width = width;
34408         this._height = height;
34409         this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
34410         this._currentLevel = -1;
34411         this._tileSize = tileSize;
34412         this._updated$ = new Subject_1.Subject();
34413         this._createdSubject$ = new Subject_1.Subject();
34414         this._created$ = this._createdSubject$
34415             .publishReplay(1)
34416             .refCount();
34417         this._createdSubscription = this._created$.subscribe(function () { });
34418         this._hasSubject$ = new Subject_1.Subject();
34419         this._has$ = this._hasSubject$
34420             .startWith(false)
34421             .publishReplay(1)
34422             .refCount();
34423         this._hasSubscription = this._has$.subscribe(function () { });
34424         this._abortFunctions = [];
34425         this._tileSubscriptions = {};
34426         this._renderedCurrentLevelTiles = {};
34427         this._renderedTiles = {};
34428         this._background = background;
34429         this._camera = null;
34430         this._imageTileLoader = imageTileLoader;
34431         this._imageTileStore = imageTileStore;
34432         this._renderer = renderer;
34433         this._renderTarget = null;
34434         this._roi = null;
34435     }
34436     Object.defineProperty(TextureProvider.prototype, "disposed", {
34437         /**
34438          * Get disposed.
34439          *
34440          * @returns {boolean} Value indicating whether provider has
34441          * been disposed.
34442          */
34443         get: function () {
34444             return this._disposed;
34445         },
34446         enumerable: true,
34447         configurable: true
34448     });
34449     Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
34450         /**
34451          * Get hasTexture$.
34452          *
34453          * @returns {Observable<boolean>} Observable emitting
34454          * values indicating when the existance of a texture
34455          * changes.
34456          */
34457         get: function () {
34458             return this._has$;
34459         },
34460         enumerable: true,
34461         configurable: true
34462     });
34463     Object.defineProperty(TextureProvider.prototype, "key", {
34464         /**
34465          * Get key.
34466          *
34467          * @returns {boolean} The identifier of the image for
34468          * which to render textures.
34469          */
34470         get: function () {
34471             return this._key;
34472         },
34473         enumerable: true,
34474         configurable: true
34475     });
34476     Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
34477         /**
34478          * Get textureUpdated$.
34479          *
34480          * @returns {Observable<boolean>} Observable emitting
34481          * values when an existing texture has been updated.
34482          */
34483         get: function () {
34484             return this._updated$;
34485         },
34486         enumerable: true,
34487         configurable: true
34488     });
34489     Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
34490         /**
34491          * Get textureCreated$.
34492          *
34493          * @returns {Observable<boolean>} Observable emitting
34494          * values when a new texture has been created.
34495          */
34496         get: function () {
34497             return this._created$;
34498         },
34499         enumerable: true,
34500         configurable: true
34501     });
34502     /**
34503      * Abort all outstanding image tile requests.
34504      */
34505     TextureProvider.prototype.abort = function () {
34506         for (var key in this._tileSubscriptions) {
34507             if (!this._tileSubscriptions.hasOwnProperty(key)) {
34508                 continue;
34509             }
34510             this._tileSubscriptions[key].unsubscribe();
34511         }
34512         this._tileSubscriptions = {};
34513         for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
34514             var abort = _a[_i];
34515             abort();
34516         }
34517         this._abortFunctions = [];
34518     };
34519     /**
34520      * Dispose the provider.
34521      *
34522      * @description Disposes all cached assets and
34523      * aborts all outstanding image tile requests.
34524      */
34525     TextureProvider.prototype.dispose = function () {
34526         this.abort();
34527         if (this._renderTarget != null) {
34528             this._renderTarget.dispose();
34529             this._renderTarget = null;
34530         }
34531         this._imageTileStore.dispose();
34532         this._imageTileStore = null;
34533         this._background = null;
34534         this._camera = null;
34535         this._imageTileLoader = null;
34536         this._renderer = null;
34537         this._roi = null;
34538         this._createdSubscription.unsubscribe();
34539         this._hasSubscription.unsubscribe();
34540         this._disposed = true;
34541     };
34542     /**
34543      * Set the region of interest.
34544      *
34545      * @description When the region of interest is set the
34546      * the tile level is determined and tiles for the region
34547      * are fetched from the store or the loader and renderedLevel
34548      * to the texture.
34549      *
34550      * @param {IRegionOfInterest} roi - Spatial edges to cache.
34551      */
34552     TextureProvider.prototype.setRegionOfInterest = function (roi) {
34553         if (this._width <= 0 || this._height <= 0) {
34554             return;
34555         }
34556         this._roi = roi;
34557         var width = 1 / this._roi.pixelWidth;
34558         var height = 1 / this._roi.pixelHeight;
34559         var size = Math.max(height, width);
34560         var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.round(Math.log(size) / Math.log(2))));
34561         if (currentLevel !== this._currentLevel) {
34562             this.abort();
34563             this._currentLevel = currentLevel;
34564             if (!(this._currentLevel in this._renderedTiles)) {
34565                 this._renderedTiles[this._currentLevel] = [];
34566             }
34567             this._renderedCurrentLevelTiles = {};
34568             for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
34569                 var tile = _a[_i];
34570                 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
34571             }
34572         }
34573         var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
34574         var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
34575         var tiles = this._getTiles(topLeft, bottomRight);
34576         if (this._camera == null) {
34577             this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
34578             this._camera.position.z = 1;
34579             var gl = this._renderer.getContext();
34580             var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
34581             var backgroundSize = Math.max(this._width, this._height);
34582             var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
34583             var targetWidth = Math.floor(scale * this._width);
34584             var targetHeight = Math.floor(scale * this._height);
34585             this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
34586                 depthBuffer: false,
34587                 format: THREE.RGBFormat,
34588                 magFilter: THREE.LinearFilter,
34589                 minFilter: THREE.LinearFilter,
34590                 stencilBuffer: false,
34591             });
34592             this._renderToTarget(0, 0, this._width, this._height, this._background);
34593             this._createdSubject$.next(this._renderTarget.texture);
34594             this._hasSubject$.next(true);
34595         }
34596         this._fetchTiles(tiles);
34597     };
34598     /**
34599      * Update the image used as background for the texture.
34600      *
34601      * @param {HTMLImageElement} background - The background image.
34602      */
34603     TextureProvider.prototype.updateBackground = function (background) {
34604         this._background = background;
34605     };
34606     /**
34607      * Retrieve an image tile.
34608      *
34609      * @description Retrieve an image tile and render it to the
34610      * texture. Add the tile to the store and emit to the updated
34611      * observable.
34612      *
34613      * @param {Array<number>} tile - The tile coordinates.
34614      * @param {number} level - The tile level.
34615      * @param {number} x - The top left x pixel coordinate of the tile.
34616      * @param {number} y - The top left y pixel coordinate of the tile.
34617      * @param {number} w - The pixel width of the tile.
34618      * @param {number} h - The pixel height of the tile.
34619      * @param {number} scaledW - The scaled width of the returned tile.
34620      * @param {number} scaledH - The scaled height of the returned tile.
34621      */
34622     TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
34623         var _this = this;
34624         var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
34625         var tile$ = getTile[0];
34626         var abort = getTile[1];
34627         this._abortFunctions.push(abort);
34628         var tileKey = this._tileKey(tile);
34629         var subscription = tile$
34630             .subscribe(function (image) {
34631             _this._renderToTarget(x, y, w, h, image);
34632             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
34633             _this._removeFromArray(abort, _this._abortFunctions);
34634             _this._setTileRendered(tile, _this._currentLevel);
34635             _this._imageTileStore.addImage(image, tileKey, level);
34636             _this._updated$.next(true);
34637         }, function (error) {
34638             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
34639             _this._removeFromArray(abort, _this._abortFunctions);
34640             console.error(error);
34641         });
34642         if (!subscription.closed) {
34643             this._tileSubscriptions[tileKey] = subscription;
34644         }
34645     };
34646     /**
34647      * Retrieve image tiles.
34648      *
34649      * @description Retrieve a image tiles and render them to the
34650      * texture. Retrieve from store if it exists, otherwise Retrieve
34651      * from loader.
34652      *
34653      * @param {Array<Array<number>>} tiles - Array of tile coordinates to
34654      * retrieve.
34655      */
34656     TextureProvider.prototype._fetchTiles = function (tiles) {
34657         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
34658         for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
34659             var tile = tiles_1[_i];
34660             var tileKey = this._tileKey(tile);
34661             if (tileKey in this._renderedCurrentLevelTiles ||
34662                 tileKey in this._tileSubscriptions) {
34663                 continue;
34664             }
34665             var tileX = tileSize * tile[0];
34666             var tileY = tileSize * tile[1];
34667             var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
34668             var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
34669             if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
34670                 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
34671                 this._setTileRendered(tile, this._currentLevel);
34672                 this._updated$.next(true);
34673                 continue;
34674             }
34675             var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
34676             var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
34677             this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
34678         }
34679     };
34680     /**
34681      * Get tile coordinates for a point using the current level.
34682      *
34683      * @param {Array<number>} point - Point in basic coordinates.
34684      *
34685      * @returns {Array<number>} x and y tile coodinates.
34686      */
34687     TextureProvider.prototype._getTileCoords = function (point) {
34688         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
34689         var maxX = Math.ceil(this._width / tileSize) - 1;
34690         var maxY = Math.ceil(this._height / tileSize) - 1;
34691         return [
34692             Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
34693             Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
34694         ];
34695     };
34696     /**
34697      * Get tile coordinates for all tiles contained in a bounding
34698      * box.
34699      *
34700      * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
34701      * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
34702      *
34703      * @returns {Array<Array<number>>} Array of x, y tile coodinates.
34704      */
34705     TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
34706         var xs = [];
34707         if (topLeft[0] > bottomRight[0]) {
34708             var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
34709             var maxX = Math.ceil(this._width / tileSize) - 1;
34710             for (var x = topLeft[0]; x <= maxX; x++) {
34711                 xs.push(x);
34712             }
34713             for (var x = 0; x <= bottomRight[0]; x++) {
34714                 xs.push(x);
34715             }
34716         }
34717         else {
34718             for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
34719                 xs.push(x);
34720             }
34721         }
34722         var tiles = [];
34723         for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
34724             var x = xs_1[_i];
34725             for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
34726                 tiles.push([x, y]);
34727             }
34728         }
34729         return tiles;
34730     };
34731     /**
34732      * Remove an item from an array if it exists in array.
34733      *
34734      * @param {T} item - Item to remove.
34735      * @param {Array<T>} array - Array from which item should be removed.
34736      */
34737     TextureProvider.prototype._removeFromArray = function (item, array) {
34738         var index = array.indexOf(item);
34739         if (index !== -1) {
34740             array.splice(index, 1);
34741         }
34742     };
34743     /**
34744      * Remove an item from a dictionary.
34745      *
34746      * @param {string} key - Key of the item to remove.
34747      * @param {Object} dict - Dictionary from which item should be removed.
34748      */
34749     TextureProvider.prototype._removeFromDictionary = function (key, dict) {
34750         if (key in dict) {
34751             delete dict[key];
34752         }
34753     };
34754     /**
34755      * Render an image tile to the target texture.
34756      *
34757      * @param {number} x - The top left x pixel coordinate of the tile.
34758      * @param {number} y - The top left y pixel coordinate of the tile.
34759      * @param {number} w - The pixel width of the tile.
34760      * @param {number} h - The pixel height of the tile.
34761      * @param {HTMLImageElement} background - The image tile to render.
34762      */
34763     TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
34764         var texture = new THREE.Texture(image);
34765         texture.minFilter = THREE.LinearFilter;
34766         texture.needsUpdate = true;
34767         var geometry = new THREE.PlaneGeometry(w, h);
34768         var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
34769         var mesh = new THREE.Mesh(geometry, material);
34770         mesh.position.x = -this._width / 2 + x + w / 2;
34771         mesh.position.y = this._height / 2 - y - h / 2;
34772         var scene = new THREE.Scene();
34773         scene.add(mesh);
34774         this._renderer.render(scene, this._camera, this._renderTarget);
34775         this._renderer.setRenderTarget(undefined);
34776         scene.remove(mesh);
34777         geometry.dispose();
34778         material.dispose();
34779         texture.dispose();
34780     };
34781     /**
34782      * Mark a tile as rendered.
34783      *
34784      * @description Clears tiles marked as rendered in other
34785      * levels of the tile pyramid  if they were rendered on
34786      * top of or below the tile.
34787      *
34788      * @param {Arrary<number>} tile - The tile coordinates.
34789      * @param {number} level - Tile level of the tile coordinates.
34790      */
34791     TextureProvider.prototype._setTileRendered = function (tile, level) {
34792         var otherLevels = Object.keys(this._renderedTiles)
34793             .map(function (key) {
34794             return parseInt(key, 10);
34795         })
34796             .filter(function (renderedLevel) {
34797             return renderedLevel !== level;
34798         });
34799         for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
34800             var otherLevel = otherLevels_1[_i];
34801             var scale = Math.pow(2, otherLevel - level);
34802             if (otherLevel < level) {
34803                 var x = Math.floor(scale * tile[0]);
34804                 var y = Math.floor(scale * tile[1]);
34805                 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
34806                     var otherTile = _b[_a];
34807                     if (otherTile[0] === x && otherTile[1] === y) {
34808                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
34809                         this._renderedTiles[otherLevel].splice(index, 1);
34810                     }
34811                 }
34812             }
34813             else {
34814                 var startX = scale * tile[0];
34815                 var endX = startX + scale - 1;
34816                 var startY = scale * tile[1];
34817                 var endY = startY + scale - 1;
34818                 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
34819                     var otherTile = _d[_c];
34820                     if (otherTile[0] >= startX && otherTile[0] <= endX &&
34821                         otherTile[1] >= startY && otherTile[1] <= endY) {
34822                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
34823                         this._renderedTiles[otherLevel].splice(index, 1);
34824                     }
34825                 }
34826             }
34827             if (this._renderedTiles[otherLevel].length === 0) {
34828                 delete this._renderedTiles[otherLevel];
34829             }
34830         }
34831         this._renderedTiles[level].push(tile);
34832         this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
34833     };
34834     /**
34835      * Create a tile key from a tile coordinates.
34836      *
34837      * @description Tile keys are used as a hash for
34838      * storing the tile in a dictionary.
34839      *
34840      * @param {Arrary<number>} tile - The tile coordinates.
34841      */
34842     TextureProvider.prototype._tileKey = function (tile) {
34843         return tile[0] + "-" + tile[1];
34844     };
34845     return TextureProvider;
34846 }());
34847 exports.TextureProvider = TextureProvider;
34848 Object.defineProperty(exports, "__esModule", { value: true });
34849 exports.default = TextureProvider;
34850
34851 },{"rxjs/Subject":33,"three":167}],319:[function(require,module,exports){
34852 "use strict";
34853 var EventEmitter = (function () {
34854     function EventEmitter() {
34855         this._events = {};
34856     }
34857     /**
34858      * Subscribe to an event by its name.
34859      * @param {string }eventType - The name of the event to subscribe to.
34860      * @param {any} fn - The handler called when the event occurs.
34861      */
34862     EventEmitter.prototype.on = function (eventType, fn) {
34863         this._events[eventType] = this._events[eventType] || [];
34864         this._events[eventType].push(fn);
34865         return;
34866     };
34867     /**
34868      * Unsubscribe from an event by its name.
34869      * @param {string} eventType - The name of the event to subscribe to.
34870      * @param {any} fn - The handler to remove.
34871      */
34872     EventEmitter.prototype.off = function (eventType, fn) {
34873         if (!eventType) {
34874             this._events = {};
34875             return;
34876         }
34877         if (!this._listens(eventType)) {
34878             var idx = this._events[eventType].indexOf(fn);
34879             if (idx >= 0) {
34880                 this._events[eventType].splice(idx, 1);
34881             }
34882             if (this._events[eventType].length) {
34883                 delete this._events[eventType];
34884             }
34885         }
34886         else {
34887             delete this._events[eventType];
34888         }
34889         return;
34890     };
34891     EventEmitter.prototype.fire = function (eventType, data) {
34892         if (!this._listens(eventType)) {
34893             return;
34894         }
34895         for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
34896             var fn = _a[_i];
34897             fn.call(this, data);
34898         }
34899         return;
34900     };
34901     EventEmitter.prototype._listens = function (eventType) {
34902         return !!(this._events && this._events[eventType]);
34903     };
34904     return EventEmitter;
34905 }());
34906 exports.EventEmitter = EventEmitter;
34907 Object.defineProperty(exports, "__esModule", { value: true });
34908 exports.default = EventEmitter;
34909
34910 },{}],320:[function(require,module,exports){
34911 "use strict";
34912 var Viewer_1 = require("../Viewer");
34913 var Settings = (function () {
34914     function Settings() {
34915     }
34916     Settings.setOptions = function (options) {
34917         Settings._baseImageSize = options.baseImageSize != null ?
34918             options.baseImageSize :
34919             Viewer_1.ImageSize.Size640;
34920         Settings._basePanoramaSize = options.basePanoramaSize != null ?
34921             options.basePanoramaSize :
34922             Viewer_1.ImageSize.Size2048;
34923         Settings._maxImageSize = options.maxImageSize != null ?
34924             options.maxImageSize :
34925             Viewer_1.ImageSize.Size2048;
34926     };
34927     Object.defineProperty(Settings, "baseImageSize", {
34928         get: function () {
34929             return Settings._baseImageSize;
34930         },
34931         enumerable: true,
34932         configurable: true
34933     });
34934     Object.defineProperty(Settings, "basePanoramaSize", {
34935         get: function () {
34936             return Settings._basePanoramaSize;
34937         },
34938         enumerable: true,
34939         configurable: true
34940     });
34941     Object.defineProperty(Settings, "maxImageSize", {
34942         get: function () {
34943             return Settings._maxImageSize;
34944         },
34945         enumerable: true,
34946         configurable: true
34947     });
34948     return Settings;
34949 }());
34950 exports.Settings = Settings;
34951 Object.defineProperty(exports, "__esModule", { value: true });
34952 exports.default = Settings;
34953
34954 },{"../Viewer":227}],321:[function(require,module,exports){
34955 "use strict";
34956 var Urls = (function () {
34957     function Urls() {
34958     }
34959     Object.defineProperty(Urls, "tileScheme", {
34960         get: function () {
34961             return "https";
34962         },
34963         enumerable: true,
34964         configurable: true
34965     });
34966     Object.defineProperty(Urls, "tileDomain", {
34967         get: function () {
34968             return "d2qb1440i7l50o.cloudfront.net";
34969         },
34970         enumerable: true,
34971         configurable: true
34972     });
34973     Object.defineProperty(Urls, "origin", {
34974         get: function () {
34975             return "mapillary.webgl";
34976         },
34977         enumerable: true,
34978         configurable: true
34979     });
34980     Urls.thumbnail = function (key, size) {
34981         return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=" + this.origin;
34982     };
34983     Urls.falcorModel = function (clientId) {
34984         return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
34985     };
34986     Urls.protoMesh = function (key) {
34987         return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
34988     };
34989     return Urls;
34990 }());
34991 exports.Urls = Urls;
34992 Object.defineProperty(exports, "__esModule", { value: true });
34993 exports.default = Urls;
34994
34995 },{}],322:[function(require,module,exports){
34996 "use strict";
34997 require("rxjs/add/operator/bufferCount");
34998 require("rxjs/add/operator/delay");
34999 require("rxjs/add/operator/distinctUntilChanged");
35000 require("rxjs/add/operator/map");
35001 require("rxjs/add/operator/switchMap");
35002 var CacheService = (function () {
35003     function CacheService(graphService, stateService) {
35004         this._graphService = graphService;
35005         this._stateService = stateService;
35006         this._started = false;
35007     }
35008     Object.defineProperty(CacheService.prototype, "started", {
35009         get: function () {
35010             return this._started;
35011         },
35012         enumerable: true,
35013         configurable: true
35014     });
35015     CacheService.prototype.start = function () {
35016         var _this = this;
35017         if (this._started) {
35018             return;
35019         }
35020         this._uncacheSubscription = this._stateService.currentState$
35021             .distinctUntilChanged(undefined, function (frame) {
35022             return frame.state.currentNode.key;
35023         })
35024             .map(function (frame) {
35025             return frame.state.trajectory
35026                 .map(function (n) {
35027                 return n.key;
35028             });
35029         })
35030             .bufferCount(1, 5)
35031             .switchMap(function (keepKeysBuffer) {
35032             var keepKeys = keepKeysBuffer[0];
35033             return _this._graphService.uncache$(keepKeys);
35034         })
35035             .subscribe(function () { });
35036         this._started = true;
35037     };
35038     CacheService.prototype.stop = function () {
35039         if (!this._started) {
35040             return;
35041         }
35042         this._uncacheSubscription.unsubscribe();
35043         this._uncacheSubscription = null;
35044         this._started = false;
35045     };
35046     return CacheService;
35047 }());
35048 exports.CacheService = CacheService;
35049 Object.defineProperty(exports, "__esModule", { value: true });
35050 exports.default = CacheService;
35051
35052 },{"rxjs/add/operator/bufferCount":48,"rxjs/add/operator/delay":53,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/map":62,"rxjs/add/operator/switchMap":76}],323:[function(require,module,exports){
35053 "use strict";
35054 var Component_1 = require("../Component");
35055 var ComponentController = (function () {
35056     function ComponentController(container, navigator, key, options) {
35057         var _this = this;
35058         this._container = container;
35059         this._navigator = navigator;
35060         this._options = options != null ? options : {};
35061         this._key = key;
35062         this._componentService = new Component_1.ComponentService(this._container, this._navigator);
35063         this._coverComponent = this._componentService.getCover();
35064         this._initializeComponents();
35065         if (key) {
35066             this._initilizeCoverComponent();
35067             this._subscribeCoverComponent();
35068         }
35069         else {
35070             this._navigator.movedToKey$
35071                 .first(function (k) {
35072                 return k != null;
35073             })
35074                 .subscribe(function (k) {
35075                 _this._key = k;
35076                 _this._componentService.deactivateCover();
35077                 _this._coverComponent.configure({ key: _this._key, loading: false, visible: false });
35078                 _this._subscribeCoverComponent();
35079                 _this._navigator.stateService.start();
35080             });
35081         }
35082     }
35083     ComponentController.prototype.get = function (name) {
35084         return this._componentService.get(name);
35085     };
35086     ComponentController.prototype.activate = function (name) {
35087         this._componentService.activate(name);
35088     };
35089     ComponentController.prototype.activateCover = function () {
35090         this._coverComponent.configure({ loading: false, visible: true });
35091     };
35092     ComponentController.prototype.deactivate = function (name) {
35093         this._componentService.deactivate(name);
35094     };
35095     ComponentController.prototype.deactivateCover = function () {
35096         this._coverComponent.configure({ loading: true, visible: true });
35097     };
35098     ComponentController.prototype.resize = function () {
35099         this._componentService.resize();
35100     };
35101     ComponentController.prototype._initializeComponents = function () {
35102         var options = this._options;
35103         this._uFalse(options.background, "background");
35104         this._uFalse(options.debug, "debug");
35105         this._uFalse(options.image, "image");
35106         this._uFalse(options.marker, "marker");
35107         this._uFalse(options.navigation, "navigation");
35108         this._uFalse(options.route, "route");
35109         this._uFalse(options.slider, "slider");
35110         this._uFalse(options.stats, "stats");
35111         this._uFalse(options.tag, "tag");
35112         this._uTrue(options.attribution, "attribution");
35113         this._uTrue(options.bearing, "bearing");
35114         this._uTrue(options.cache, "cache");
35115         this._uTrue(options.direction, "direction");
35116         this._uTrue(options.imagePlane, "imagePlane");
35117         this._uTrue(options.keyboard, "keyboard");
35118         this._uTrue(options.loading, "loading");
35119         this._uTrue(options.mouse, "mouse");
35120         this._uTrue(options.sequence, "sequence");
35121     };
35122     ComponentController.prototype._initilizeCoverComponent = function () {
35123         var options = this._options;
35124         this._coverComponent.configure({ key: this._key });
35125         if (options.cover === undefined || options.cover) {
35126             this.activateCover();
35127         }
35128         else {
35129             this.deactivateCover();
35130         }
35131     };
35132     ComponentController.prototype._subscribeCoverComponent = function () {
35133         var _this = this;
35134         this._coverComponent.configuration$.subscribe(function (conf) {
35135             if (conf.loading) {
35136                 _this._navigator.stateService.currentKey$
35137                     .first()
35138                     .switchMap(function (key) {
35139                     return key == null || key !== conf.key ?
35140                         _this._navigator.moveToKey$(conf.key) :
35141                         _this._navigator.stateService.currentNode$
35142                             .first();
35143                 })
35144                     .subscribe(function (node) {
35145                     _this._navigator.stateService.start();
35146                     _this._coverComponent.configure({ loading: false, visible: false });
35147                     _this._componentService.deactivateCover();
35148                 }, function (error) {
35149                     console.error("Failed to deactivate cover.", error);
35150                     _this._coverComponent.configure({ loading: false, visible: true });
35151                 });
35152             }
35153             else if (conf.visible) {
35154                 _this._navigator.stateService.stop();
35155                 _this._componentService.activateCover();
35156             }
35157         });
35158     };
35159     ComponentController.prototype._uFalse = function (option, name) {
35160         if (option === undefined) {
35161             this._componentService.deactivate(name);
35162             return;
35163         }
35164         if (typeof option === "boolean") {
35165             if (option) {
35166                 this._componentService.activate(name);
35167             }
35168             else {
35169                 this._componentService.deactivate(name);
35170             }
35171             return;
35172         }
35173         this._componentService.configure(name, option);
35174         this._componentService.activate(name);
35175     };
35176     ComponentController.prototype._uTrue = function (option, name) {
35177         if (option === undefined) {
35178             this._componentService.activate(name);
35179             return;
35180         }
35181         if (typeof option === "boolean") {
35182             if (option) {
35183                 this._componentService.activate(name);
35184             }
35185             else {
35186                 this._componentService.deactivate(name);
35187             }
35188             return;
35189         }
35190         this._componentService.configure(name, option);
35191         this._componentService.activate(name);
35192     };
35193     return ComponentController;
35194 }());
35195 exports.ComponentController = ComponentController;
35196
35197 },{"../Component":217}],324:[function(require,module,exports){
35198 "use strict";
35199 var Render_1 = require("../Render");
35200 var Viewer_1 = require("../Viewer");
35201 var Container = (function () {
35202     function Container(id, stateService, options) {
35203         this.id = id;
35204         this.element = document.getElementById(id);
35205         this.element.classList.add("mapillary-js");
35206         this.renderService = new Render_1.RenderService(this.element, stateService.currentState$, options.renderMode);
35207         this.glRenderer = new Render_1.GLRenderer(this.renderService);
35208         this.domRenderer = new Render_1.DOMRenderer(this.element, this.renderService, stateService.currentState$);
35209         this.mouseService = new Viewer_1.MouseService(this.element);
35210         this.touchService = new Viewer_1.TouchService(this.element);
35211         this.spriteService = new Viewer_1.SpriteService(options.sprite);
35212     }
35213     return Container;
35214 }());
35215 exports.Container = Container;
35216 Object.defineProperty(exports, "__esModule", { value: true });
35217 exports.default = Container;
35218
35219 },{"../Render":223,"../Viewer":227}],325:[function(require,module,exports){
35220 "use strict";
35221 var Observable_1 = require("rxjs/Observable");
35222 require("rxjs/add/observable/combineLatest");
35223 require("rxjs/add/operator/distinctUntilChanged");
35224 require("rxjs/add/operator/map");
35225 require("rxjs/add/operator/throttleTime");
35226 var Viewer_1 = require("../Viewer");
35227 var EventLauncher = (function () {
35228     function EventLauncher(eventEmitter, navigator, container) {
35229         var _this = this;
35230         this._container = container;
35231         this._eventEmitter = eventEmitter;
35232         this._navigator = navigator;
35233         this._loadingSubscription = this._navigator.loadingService.loading$
35234             .subscribe(function (loading) {
35235             _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
35236         });
35237         this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
35238             .subscribe(function (node) {
35239             _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
35240         });
35241         this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
35242             .switchMap(function (node) {
35243             return node.sequenceEdges$;
35244         })
35245             .subscribe(function (status) {
35246             _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
35247         });
35248         this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
35249             .switchMap(function (node) {
35250             return node.spatialEdges$;
35251         })
35252             .subscribe(function (status) {
35253             _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
35254         });
35255         this._moveSubscription = Observable_1.Observable
35256             .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
35257             .map(function (values) {
35258             return values[0] || values[1] || values[2];
35259         })
35260             .distinctUntilChanged()
35261             .subscribe(function (started) {
35262             if (started) {
35263                 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
35264             }
35265             else {
35266                 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
35267             }
35268         });
35269         this._bearingSubscription = this._container.renderService.bearing$
35270             .throttleTime(100)
35271             .distinctUntilChanged(function (b1, b2) {
35272             return Math.abs(b2 - b1) < 1;
35273         })
35274             .subscribe(function (bearing) {
35275             _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
35276         });
35277     }
35278     EventLauncher.prototype.dispose = function () {
35279         this._bearingSubscription.unsubscribe();
35280         this._loadingSubscription.unsubscribe();
35281         this._currentNodeSubscription.unsubscribe();
35282         this._moveSubscription.unsubscribe();
35283         this._sequenceEdgesSubscription.unsubscribe();
35284         this._spatialEdgesSubscription.unsubscribe();
35285     };
35286     return EventLauncher;
35287 }());
35288 exports.EventLauncher = EventLauncher;
35289 Object.defineProperty(exports, "__esModule", { value: true });
35290 exports.default = EventLauncher;
35291
35292 },{"../Viewer":227,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/map":62,"rxjs/add/operator/throttleTime":79}],326:[function(require,module,exports){
35293 "use strict";
35294 /**
35295  * Enumeration for image sizes
35296  * @enum {number}
35297  * @readonly
35298  * @description Image sizes in pixels for the long side of the image.
35299  */
35300 var ImageSize;
35301 (function (ImageSize) {
35302     /**
35303      * 320 pixels image size
35304      */
35305     ImageSize[ImageSize["Size320"] = 320] = "Size320";
35306     /**
35307      * 640 pixels image size
35308      */
35309     ImageSize[ImageSize["Size640"] = 640] = "Size640";
35310     /**
35311      * 1024 pixels image size
35312      */
35313     ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
35314     /**
35315      * 2048 pixels image size
35316      */
35317     ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
35318 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
35319
35320 },{}],327:[function(require,module,exports){
35321 /// <reference path="../../typings/index.d.ts" />
35322 "use strict";
35323 var _ = require("underscore");
35324 var Subject_1 = require("rxjs/Subject");
35325 require("rxjs/add/operator/debounceTime");
35326 require("rxjs/add/operator/distinctUntilChanged");
35327 require("rxjs/add/operator/map");
35328 require("rxjs/add/operator/publishReplay");
35329 require("rxjs/add/operator/scan");
35330 require("rxjs/add/operator/startWith");
35331 var LoadingService = (function () {
35332     function LoadingService() {
35333         this._loadersSubject$ = new Subject_1.Subject();
35334         this._loaders$ = this._loadersSubject$
35335             .scan(function (loaders, loader) {
35336             if (loader.task !== undefined) {
35337                 loaders[loader.task] = loader.loading;
35338             }
35339             return loaders;
35340         }, {})
35341             .startWith({})
35342             .publishReplay(1)
35343             .refCount();
35344     }
35345     Object.defineProperty(LoadingService.prototype, "loading$", {
35346         get: function () {
35347             return this._loaders$
35348                 .map(function (loaders) {
35349                 return _.reduce(loaders, function (loader, acc) {
35350                     return (loader || acc);
35351                 }, false);
35352             })
35353                 .debounceTime(100)
35354                 .distinctUntilChanged();
35355         },
35356         enumerable: true,
35357         configurable: true
35358     });
35359     LoadingService.prototype.taskLoading$ = function (task) {
35360         return this._loaders$
35361             .map(function (loaders) {
35362             return !!loaders[task];
35363         })
35364             .debounceTime(100)
35365             .distinctUntilChanged();
35366     };
35367     LoadingService.prototype.startLoading = function (task) {
35368         this._loadersSubject$.next({ loading: true, task: task });
35369     };
35370     LoadingService.prototype.stopLoading = function (task) {
35371         this._loadersSubject$.next({ loading: false, task: task });
35372     };
35373     return LoadingService;
35374 }());
35375 exports.LoadingService = LoadingService;
35376 Object.defineProperty(exports, "__esModule", { value: true });
35377 exports.default = LoadingService;
35378
35379 },{"rxjs/Subject":33,"rxjs/add/operator/debounceTime":52,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/map":62,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/startWith":75,"underscore":168}],328:[function(require,module,exports){
35380 "use strict";
35381 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
35382 var Observable_1 = require("rxjs/Observable");
35383 var Subject_1 = require("rxjs/Subject");
35384 require("rxjs/add/observable/fromEvent");
35385 require("rxjs/add/operator/distinctUntilChanged");
35386 require("rxjs/add/operator/filter");
35387 require("rxjs/add/operator/map");
35388 require("rxjs/add/operator/merge");
35389 require("rxjs/add/operator/mergeMap");
35390 require("rxjs/add/operator/publishReplay");
35391 require("rxjs/add/operator/scan");
35392 require("rxjs/add/operator/switchMap");
35393 require("rxjs/add/operator/withLatestFrom");
35394 var MouseService = (function () {
35395     function MouseService(element) {
35396         var _this = this;
35397         this._element = element;
35398         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
35399         this._active$ = this._activeSubject$
35400             .distinctUntilChanged()
35401             .publishReplay(1)
35402             .refCount();
35403         this._preventMouseDownOperation$ = new Subject_1.Subject();
35404         this._preventMouseDown$ = new Subject_1.Subject();
35405         this._mouseMoveOperation$ = new Subject_1.Subject();
35406         this._claimMouse$ = new Subject_1.Subject();
35407         this._mouseDown$ = Observable_1.Observable.fromEvent(element, "mousedown");
35408         this._mouseLeave$ = Observable_1.Observable.fromEvent(element, "mouseleave");
35409         this._mouseUp$ = Observable_1.Observable.fromEvent(element, "mouseup");
35410         this._mouseOver$ = Observable_1.Observable.fromEvent(element, "mouseover");
35411         this._click$ = Observable_1.Observable.fromEvent(element, "click");
35412         this._mouseWheel$ = Observable_1.Observable.fromEvent(element, "wheel");
35413         this._mouseWheel$
35414             .subscribe(function (event) {
35415             event.preventDefault();
35416         });
35417         this._preventMouseDownOperation$
35418             .scan(function (prevent, operation) {
35419             return operation(prevent);
35420         }, true)
35421             .subscribe(function () { });
35422         this._preventMouseDown$
35423             .map(function (prevent) {
35424             return function (previous) {
35425                 return prevent;
35426             };
35427         })
35428             .subscribe(this._preventMouseDownOperation$);
35429         this._mouseDown$
35430             .map(function (e) {
35431             return function (prevent) {
35432                 if (prevent) {
35433                     e.preventDefault();
35434                 }
35435                 return prevent;
35436             };
35437         })
35438             .subscribe(this._preventMouseDownOperation$);
35439         this._mouseMove$ = this._mouseMoveOperation$
35440             .scan(function (e, operation) {
35441             return operation(e);
35442         }, null);
35443         Observable_1.Observable
35444             .fromEvent(element, "mousemove")
35445             .map(function (e) {
35446             return function (previous) {
35447                 if (previous == null) {
35448                     previous = e;
35449                 }
35450                 if (e.movementX == null) {
35451                     Object.defineProperty(e, "movementX", {
35452                         configurable: false,
35453                         enumerable: false,
35454                         value: e.clientX - previous.clientX,
35455                         writable: false,
35456                     });
35457                 }
35458                 if (e.movementY == null) {
35459                     Object.defineProperty(e, "movementY", {
35460                         configurable: false,
35461                         enumerable: false,
35462                         value: e.clientY - previous.clientY,
35463                         writable: false,
35464                     });
35465                 }
35466                 return e;
35467             };
35468         })
35469             .subscribe(this._mouseMoveOperation$);
35470         var dragStop$ = Observable_1.Observable
35471             .merge(this._mouseLeave$, this._mouseUp$);
35472         this._mouseDragStart$ = this._mouseDown$
35473             .mergeMap(function (e) {
35474             return _this._mouseMove$
35475                 .takeUntil(dragStop$)
35476                 .take(1);
35477         });
35478         this._mouseDrag$ = this._mouseDown$
35479             .mergeMap(function (e) {
35480             return _this._mouseMove$
35481                 .skip(1)
35482                 .takeUntil(dragStop$);
35483         });
35484         this._mouseDragEnd$ = this._mouseDragStart$
35485             .mergeMap(function (e) {
35486             return dragStop$.first();
35487         });
35488         this._staticClick$ = this._mouseDown$
35489             .switchMap(function (e) {
35490             return _this._click$
35491                 .takeUntil(_this._mouseMove$)
35492                 .take(1);
35493         });
35494         this._mouseOwner$ = this._claimMouse$
35495             .scan(function (claims, mouseClaim) {
35496             if (mouseClaim.zindex == null) {
35497                 delete claims[mouseClaim.name];
35498             }
35499             else {
35500                 claims[mouseClaim.name] = mouseClaim.zindex;
35501             }
35502             return claims;
35503         }, {})
35504             .map(function (claims) {
35505             var owner = null;
35506             var curZ = -1;
35507             for (var name_1 in claims) {
35508                 if (claims.hasOwnProperty(name_1)) {
35509                     if (claims[name_1] > curZ) {
35510                         curZ = claims[name_1];
35511                         owner = name_1;
35512                     }
35513                 }
35514             }
35515             return owner;
35516         })
35517             .publishReplay(1)
35518             .refCount();
35519     }
35520     Object.defineProperty(MouseService.prototype, "active$", {
35521         get: function () {
35522             return this._active$;
35523         },
35524         enumerable: true,
35525         configurable: true
35526     });
35527     Object.defineProperty(MouseService.prototype, "activate$", {
35528         get: function () {
35529             return this._activeSubject$;
35530         },
35531         enumerable: true,
35532         configurable: true
35533     });
35534     Object.defineProperty(MouseService.prototype, "mouseOwner$", {
35535         get: function () {
35536             return this._mouseOwner$;
35537         },
35538         enumerable: true,
35539         configurable: true
35540     });
35541     Object.defineProperty(MouseService.prototype, "mouseDown$", {
35542         get: function () {
35543             return this._mouseDown$;
35544         },
35545         enumerable: true,
35546         configurable: true
35547     });
35548     Object.defineProperty(MouseService.prototype, "mouseMove$", {
35549         get: function () {
35550             return this._mouseMove$;
35551         },
35552         enumerable: true,
35553         configurable: true
35554     });
35555     Object.defineProperty(MouseService.prototype, "mouseLeave$", {
35556         get: function () {
35557             return this._mouseLeave$;
35558         },
35559         enumerable: true,
35560         configurable: true
35561     });
35562     Object.defineProperty(MouseService.prototype, "mouseUp$", {
35563         get: function () {
35564             return this._mouseUp$;
35565         },
35566         enumerable: true,
35567         configurable: true
35568     });
35569     Object.defineProperty(MouseService.prototype, "click$", {
35570         get: function () {
35571             return this._click$;
35572         },
35573         enumerable: true,
35574         configurable: true
35575     });
35576     Object.defineProperty(MouseService.prototype, "mouseWheel$", {
35577         get: function () {
35578             return this._mouseWheel$;
35579         },
35580         enumerable: true,
35581         configurable: true
35582     });
35583     Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
35584         get: function () {
35585             return this._mouseDragStart$;
35586         },
35587         enumerable: true,
35588         configurable: true
35589     });
35590     Object.defineProperty(MouseService.prototype, "mouseDrag$", {
35591         get: function () {
35592             return this._mouseDrag$;
35593         },
35594         enumerable: true,
35595         configurable: true
35596     });
35597     Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
35598         get: function () {
35599             return this._mouseDragEnd$;
35600         },
35601         enumerable: true,
35602         configurable: true
35603     });
35604     Object.defineProperty(MouseService.prototype, "staticClick$", {
35605         get: function () {
35606             return this._staticClick$;
35607         },
35608         enumerable: true,
35609         configurable: true
35610     });
35611     Object.defineProperty(MouseService.prototype, "preventDefaultMouseDown$", {
35612         get: function () {
35613             return this._preventMouseDown$;
35614         },
35615         enumerable: true,
35616         configurable: true
35617     });
35618     MouseService.prototype.claimMouse = function (name, zindex) {
35619         this._claimMouse$.next({ name: name, zindex: zindex });
35620     };
35621     MouseService.prototype.unclaimMouse = function (name) {
35622         this._claimMouse$.next({ name: name, zindex: null });
35623     };
35624     MouseService.prototype.filtered$ = function (name, observable$) {
35625         return observable$
35626             .withLatestFrom(this.mouseOwner$, function (event, owner) {
35627             return [event, owner];
35628         })
35629             .filter(function (eo) {
35630             return eo[1] === name;
35631         })
35632             .map(function (eo) {
35633             return eo[0];
35634         });
35635     };
35636     return MouseService;
35637 }());
35638 exports.MouseService = MouseService;
35639 Object.defineProperty(exports, "__esModule", { value: true });
35640 exports.default = MouseService;
35641
35642 },{"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/distinctUntilChanged":55,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/merge":63,"rxjs/add/operator/mergeMap":65,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/switchMap":76,"rxjs/add/operator/withLatestFrom":80}],329:[function(require,module,exports){
35643 /// <reference path="../../typings/index.d.ts" />
35644 "use strict";
35645 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
35646 var Observable_1 = require("rxjs/Observable");
35647 require("rxjs/add/observable/throw");
35648 require("rxjs/add/operator/do");
35649 require("rxjs/add/operator/finally");
35650 require("rxjs/add/operator/first");
35651 require("rxjs/add/operator/map");
35652 require("rxjs/add/operator/mergeMap");
35653 var API_1 = require("../API");
35654 var Graph_1 = require("../Graph");
35655 var Edge_1 = require("../Edge");
35656 var State_1 = require("../State");
35657 var Viewer_1 = require("../Viewer");
35658 var Navigator = (function () {
35659     function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService) {
35660         this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
35661         this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
35662         this._graphService = graphService != null ?
35663             graphService :
35664             new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
35665         this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
35666         this._loadingName = "navigator";
35667         this._stateService = stateService != null ? stateService : new State_1.StateService();
35668         this._cacheService = cacheService != null ?
35669             cacheService :
35670             new Viewer_1.CacheService(this._graphService, this._stateService);
35671         this._cacheService.start();
35672         this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
35673         this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
35674         this._dirRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
35675         this._latLonRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
35676     }
35677     Object.defineProperty(Navigator.prototype, "apiV3", {
35678         get: function () {
35679             return this._apiV3;
35680         },
35681         enumerable: true,
35682         configurable: true
35683     });
35684     Object.defineProperty(Navigator.prototype, "graphService", {
35685         get: function () {
35686             return this._graphService;
35687         },
35688         enumerable: true,
35689         configurable: true
35690     });
35691     Object.defineProperty(Navigator.prototype, "imageLoadingService", {
35692         get: function () {
35693             return this._imageLoadingService;
35694         },
35695         enumerable: true,
35696         configurable: true
35697     });
35698     Object.defineProperty(Navigator.prototype, "keyRequested$", {
35699         get: function () {
35700             return this._keyRequested$;
35701         },
35702         enumerable: true,
35703         configurable: true
35704     });
35705     Object.defineProperty(Navigator.prototype, "loadingService", {
35706         get: function () {
35707             return this._loadingService;
35708         },
35709         enumerable: true,
35710         configurable: true
35711     });
35712     Object.defineProperty(Navigator.prototype, "movedToKey$", {
35713         get: function () {
35714             return this._movedToKey$;
35715         },
35716         enumerable: true,
35717         configurable: true
35718     });
35719     Object.defineProperty(Navigator.prototype, "stateService", {
35720         get: function () {
35721             return this._stateService;
35722         },
35723         enumerable: true,
35724         configurable: true
35725     });
35726     Navigator.prototype.moveToKey$ = function (key) {
35727         var _this = this;
35728         this.loadingService.startLoading(this._loadingName);
35729         this._keyRequested$.next(key);
35730         return this._graphService.cacheNode$(key)
35731             .do(function (node) {
35732             _this.stateService.setNodes([node]);
35733             _this._movedToKey$.next(node.key);
35734         })
35735             .finally(function () {
35736             _this.loadingService.stopLoading(_this._loadingName);
35737         });
35738     };
35739     Navigator.prototype.moveDir$ = function (direction) {
35740         var _this = this;
35741         this.loadingService.startLoading(this._loadingName);
35742         this._dirRequested$.next(direction);
35743         return this.stateService.currentNode$
35744             .first()
35745             .mergeMap(function (node) {
35746             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
35747                 node.sequenceEdges$ :
35748                 node.spatialEdges$)
35749                 .first()
35750                 .map(function (status) {
35751                 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
35752                     var edge = _a[_i];
35753                     if (edge.data.direction === direction) {
35754                         return edge.to;
35755                     }
35756                 }
35757                 return null;
35758             });
35759         })
35760             .mergeMap(function (directionKey) {
35761             if (directionKey == null) {
35762                 _this.loadingService.stopLoading(_this._loadingName);
35763                 return Observable_1.Observable
35764                     .throw(new Error("Direction (" + direction + ") does not exist for current node."));
35765             }
35766             return _this.moveToKey$(directionKey);
35767         });
35768     };
35769     Navigator.prototype.moveCloseTo$ = function (lat, lon) {
35770         var _this = this;
35771         this.loadingService.startLoading(this._loadingName);
35772         this._latLonRequested$.next({ lat: lat, lon: lon });
35773         return this.apiV3.imageCloseTo$(lat, lon)
35774             .mergeMap(function (fullNode) {
35775             if (fullNode == null) {
35776                 _this.loadingService.stopLoading(_this._loadingName);
35777                 return Observable_1.Observable
35778                     .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
35779             }
35780             return _this.moveToKey$(fullNode.key);
35781         });
35782     };
35783     Navigator.prototype.setFilter$ = function (filter) {
35784         var _this = this;
35785         this._stateService.clearNodes();
35786         return this._movedToKey$
35787             .first()
35788             .mergeMap(function (key) {
35789             if (key != null) {
35790                 return _this._trajectoryKeys$()
35791                     .mergeMap(function (keys) {
35792                     return _this._graphService.setFilter$(filter)
35793                         .mergeMap(function (graph) {
35794                         return _this._cacheKeys$(keys);
35795                     });
35796                 })
35797                     .last();
35798             }
35799             return _this._keyRequested$
35800                 .mergeMap(function (requestedKey) {
35801                 if (requestedKey != null) {
35802                     return _this._graphService.setFilter$(filter)
35803                         .mergeMap(function (graph) {
35804                         return _this._graphService.cacheNode$(requestedKey);
35805                     });
35806                 }
35807                 return _this._graphService.setFilter$(filter)
35808                     .map(function (graph) {
35809                     return undefined;
35810                 });
35811             });
35812         })
35813             .map(function (node) {
35814             return undefined;
35815         });
35816     };
35817     Navigator.prototype.setToken$ = function (token) {
35818         var _this = this;
35819         this._stateService.clearNodes();
35820         return this._movedToKey$
35821             .first()
35822             .do(function (key) {
35823             _this._apiV3.setToken(token);
35824         })
35825             .mergeMap(function (key) {
35826             return key == null ?
35827                 _this._graphService.reset$([])
35828                     .map(function (graph) {
35829                     return undefined;
35830                 }) :
35831                 _this._trajectoryKeys$()
35832                     .mergeMap(function (keys) {
35833                     return _this._graphService.reset$(keys)
35834                         .mergeMap(function (graph) {
35835                         return _this._cacheKeys$(keys);
35836                     });
35837                 })
35838                     .last()
35839                     .map(function (node) {
35840                     return undefined;
35841                 });
35842         });
35843     };
35844     Navigator.prototype._cacheKeys$ = function (keys) {
35845         var _this = this;
35846         var cacheNodes$ = keys
35847             .map(function (key) {
35848             return _this._graphService.cacheNode$(key);
35849         });
35850         return Observable_1.Observable
35851             .from(cacheNodes$)
35852             .mergeAll();
35853     };
35854     Navigator.prototype._trajectoryKeys$ = function () {
35855         return this._stateService.currentState$
35856             .first()
35857             .map(function (frame) {
35858             return frame.state.trajectory
35859                 .map(function (node) {
35860                 return node.key;
35861             });
35862         });
35863     };
35864     return Navigator;
35865 }());
35866 exports.Navigator = Navigator;
35867 Object.defineProperty(exports, "__esModule", { value: true });
35868 exports.default = Navigator;
35869
35870 },{"../API":216,"../Edge":218,"../Graph":221,"../State":224,"../Viewer":227,"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/add/observable/throw":45,"rxjs/add/operator/do":56,"rxjs/add/operator/finally":59,"rxjs/add/operator/first":60,"rxjs/add/operator/map":62,"rxjs/add/operator/mergeMap":65}],330:[function(require,module,exports){
35871 "use strict";
35872 var SpriteAlignment;
35873 (function (SpriteAlignment) {
35874     SpriteAlignment[SpriteAlignment["Center"] = 0] = "Center";
35875     SpriteAlignment[SpriteAlignment["Start"] = 1] = "Start";
35876     SpriteAlignment[SpriteAlignment["End"] = 2] = "End";
35877 })(SpriteAlignment = exports.SpriteAlignment || (exports.SpriteAlignment = {}));
35878 Object.defineProperty(exports, "__esModule", { value: true });
35879 exports.default = SpriteAlignment;
35880
35881 },{}],331:[function(require,module,exports){
35882 /// <reference path="../../typings/index.d.ts" />
35883 "use strict";
35884 var THREE = require("three");
35885 var vd = require("virtual-dom");
35886 var Subject_1 = require("rxjs/Subject");
35887 require("rxjs/add/operator/publishReplay");
35888 require("rxjs/add/operator/scan");
35889 require("rxjs/add/operator/startWith");
35890 var Viewer_1 = require("../Viewer");
35891 var SpriteAtlas = (function () {
35892     function SpriteAtlas() {
35893     }
35894     Object.defineProperty(SpriteAtlas.prototype, "json", {
35895         set: function (value) {
35896             this._json = value;
35897         },
35898         enumerable: true,
35899         configurable: true
35900     });
35901     Object.defineProperty(SpriteAtlas.prototype, "image", {
35902         set: function (value) {
35903             this._image = value;
35904             this._texture = new THREE.Texture(this._image);
35905             this._texture.minFilter = THREE.NearestFilter;
35906         },
35907         enumerable: true,
35908         configurable: true
35909     });
35910     Object.defineProperty(SpriteAtlas.prototype, "loaded", {
35911         get: function () {
35912             return !!(this._image && this._json);
35913         },
35914         enumerable: true,
35915         configurable: true
35916     });
35917     SpriteAtlas.prototype.getGLSprite = function (name) {
35918         if (!this.loaded) {
35919             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
35920         }
35921         var definition = this._json[name];
35922         if (!definition) {
35923             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
35924             return new THREE.Object3D();
35925         }
35926         var texture = this._texture.clone();
35927         texture.needsUpdate = true;
35928         var width = this._image.width;
35929         var height = this._image.height;
35930         texture.offset.x = definition.x / width;
35931         texture.offset.y = (height - definition.y - definition.height) / height;
35932         texture.repeat.x = definition.width / width;
35933         texture.repeat.y = definition.height / height;
35934         var material = new THREE.SpriteMaterial({ map: texture });
35935         return new THREE.Sprite(material);
35936     };
35937     SpriteAtlas.prototype.getDOMSprite = function (name, horizontalAlign, verticalAlign) {
35938         if (!this.loaded) {
35939             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
35940         }
35941         if (horizontalAlign == null) {
35942             horizontalAlign = Viewer_1.SpriteAlignment.Start;
35943         }
35944         if (verticalAlign == null) {
35945             verticalAlign = Viewer_1.SpriteAlignment.Start;
35946         }
35947         var definition = this._json[name];
35948         if (!definition) {
35949             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
35950             return vd.h("div", {}, []);
35951         }
35952         var clipTop = definition.y;
35953         var clipRigth = definition.x + definition.width;
35954         var clipBottom = definition.y + definition.height;
35955         var clipLeft = definition.x;
35956         var left = -definition.x;
35957         var top = -definition.y;
35958         var height = this._image.height;
35959         var width = this._image.width;
35960         switch (horizontalAlign) {
35961             case Viewer_1.SpriteAlignment.Center:
35962                 left -= definition.width / 2;
35963                 break;
35964             case Viewer_1.SpriteAlignment.End:
35965                 left -= definition.width;
35966                 break;
35967             case Viewer_1.SpriteAlignment.Start:
35968                 break;
35969             default:
35970                 break;
35971         }
35972         switch (verticalAlign) {
35973             case Viewer_1.SpriteAlignment.Center:
35974                 top -= definition.height / 2;
35975                 break;
35976             case Viewer_1.SpriteAlignment.End:
35977                 top -= definition.height;
35978                 break;
35979             case Viewer_1.SpriteAlignment.Start:
35980                 break;
35981             default:
35982                 break;
35983         }
35984         var pixelRatioInverse = 1 / definition.pixelRatio;
35985         clipTop *= pixelRatioInverse;
35986         clipRigth *= pixelRatioInverse;
35987         clipBottom *= pixelRatioInverse;
35988         clipLeft *= pixelRatioInverse;
35989         left *= pixelRatioInverse;
35990         top *= pixelRatioInverse;
35991         height *= pixelRatioInverse;
35992         width *= pixelRatioInverse;
35993         var properties = {
35994             src: this._image.src,
35995             style: {
35996                 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
35997                 height: height + "px",
35998                 left: left + "px",
35999                 position: "absolute",
36000                 top: top + "px",
36001                 width: width + "px",
36002             },
36003         };
36004         return vd.h("img", properties, []);
36005     };
36006     return SpriteAtlas;
36007 }());
36008 var SpriteService = (function () {
36009     function SpriteService(sprite) {
36010         var _this = this;
36011         this._retina = window.devicePixelRatio > 1;
36012         this._spriteAtlasOperation$ = new Subject_1.Subject();
36013         this._spriteAtlas$ = this._spriteAtlasOperation$
36014             .startWith(function (atlas) {
36015             return atlas;
36016         })
36017             .scan(function (atlas, operation) {
36018             return operation(atlas);
36019         }, new SpriteAtlas())
36020             .publishReplay(1)
36021             .refCount();
36022         this._spriteAtlas$.subscribe(function () { });
36023         if (sprite == null) {
36024             return;
36025         }
36026         var format = this._retina ? "@2x" : "";
36027         var imageXmlHTTP = new XMLHttpRequest();
36028         imageXmlHTTP.open("GET", sprite + format + ".png", true);
36029         imageXmlHTTP.responseType = "arraybuffer";
36030         imageXmlHTTP.onload = function () {
36031             var image = new Image();
36032             image.onload = function () {
36033                 _this._spriteAtlasOperation$.next(function (atlas) {
36034                     atlas.image = image;
36035                     return atlas;
36036                 });
36037             };
36038             var blob = new Blob([imageXmlHTTP.response]);
36039             image.src = window.URL.createObjectURL(blob);
36040         };
36041         imageXmlHTTP.onerror = function (error) {
36042             console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
36043         };
36044         imageXmlHTTP.send();
36045         var jsonXmlHTTP = new XMLHttpRequest();
36046         jsonXmlHTTP.open("GET", sprite + format + ".json", true);
36047         jsonXmlHTTP.responseType = "text";
36048         jsonXmlHTTP.onload = function () {
36049             var json = JSON.parse(jsonXmlHTTP.response);
36050             _this._spriteAtlasOperation$.next(function (atlas) {
36051                 atlas.json = json;
36052                 return atlas;
36053             });
36054         };
36055         jsonXmlHTTP.onerror = function (error) {
36056             console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
36057         };
36058         jsonXmlHTTP.send();
36059     }
36060     Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
36061         get: function () {
36062             return this._spriteAtlas$;
36063         },
36064         enumerable: true,
36065         configurable: true
36066     });
36067     return SpriteService;
36068 }());
36069 exports.SpriteService = SpriteService;
36070 Object.defineProperty(exports, "__esModule", { value: true });
36071 exports.default = SpriteService;
36072
36073 },{"../Viewer":227,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":69,"rxjs/add/operator/scan":70,"rxjs/add/operator/startWith":75,"three":167,"virtual-dom":173}],332:[function(require,module,exports){
36074 "use strict";
36075 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
36076 var Observable_1 = require("rxjs/Observable");
36077 var Subject_1 = require("rxjs/Subject");
36078 require("rxjs/add/operator/filter");
36079 require("rxjs/add/operator/map");
36080 require("rxjs/add/operator/merge");
36081 require("rxjs/add/operator/scan");
36082 require("rxjs/add/operator/switchMap");
36083 var TouchMove = (function () {
36084     function TouchMove(touch) {
36085         this.movementX = 0;
36086         this.movementY = 0;
36087         if (touch == null) {
36088             return;
36089         }
36090         this.identifier = touch.identifier;
36091         this.clientX = touch.clientX;
36092         this.clientY = touch.clientY;
36093         this.pageX = touch.pageX;
36094         this.pageY = touch.pageY;
36095         this.screenX = touch.screenX;
36096         this.screenY = touch.screenY;
36097         this.target = touch.target;
36098     }
36099     return TouchMove;
36100 }());
36101 exports.TouchMove = TouchMove;
36102 var TouchService = (function () {
36103     function TouchService(element) {
36104         var _this = this;
36105         this._element = element;
36106         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
36107         this._active$ = this._activeSubject$
36108             .distinctUntilChanged()
36109             .publishReplay(1)
36110             .refCount();
36111         this._touchStart$ = Observable_1.Observable.fromEvent(element, "touchstart");
36112         this._touchMove$ = Observable_1.Observable.fromEvent(element, "touchmove");
36113         this._touchEnd$ = Observable_1.Observable.fromEvent(element, "touchend");
36114         this._touchCancel$ = Observable_1.Observable.fromEvent(element, "touchcancel");
36115         this._preventTouchMoveOperation$ = new Subject_1.Subject();
36116         this._preventTouchMove$ = new Subject_1.Subject();
36117         this._preventTouchMoveOperation$
36118             .scan(function (prevent, operation) {
36119             return operation(prevent);
36120         }, true)
36121             .subscribe(function () { });
36122         this._preventTouchMove$
36123             .map(function (prevent) {
36124             return function (previous) {
36125                 return prevent;
36126             };
36127         })
36128             .subscribe(this._preventTouchMoveOperation$);
36129         this._touchMove$
36130             .map(function (te) {
36131             return function (prevent) {
36132                 if (prevent) {
36133                     te.preventDefault();
36134                 }
36135                 return prevent;
36136             };
36137         })
36138             .subscribe(this._preventTouchMoveOperation$);
36139         this._singleTouchMoveOperation$ = new Subject_1.Subject();
36140         this._singleTouchMove$ = this._singleTouchMoveOperation$
36141             .scan(function (touch, operation) {
36142             return operation(touch);
36143         }, new TouchMove());
36144         this._touchMove$
36145             .filter(function (te) {
36146             return te.touches.length === 1 && te.targetTouches.length === 1;
36147         })
36148             .map(function (te) {
36149             return function (previous) {
36150                 var touch = te.touches[0];
36151                 var current = new TouchMove(touch);
36152                 current.movementX = touch.pageX - previous.pageX;
36153                 current.movementY = touch.pageY - previous.pageY;
36154                 return current;
36155             };
36156         })
36157             .subscribe(this._singleTouchMoveOperation$);
36158         var singleTouchStart$ = Observable_1.Observable
36159             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
36160             .filter(function (te) {
36161             return te.touches.length === 1 && te.targetTouches.length === 1;
36162         });
36163         var multipleTouchStart$ = Observable_1.Observable
36164             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
36165             .filter(function (te) {
36166             return te.touches.length >= 1;
36167         });
36168         var touchStop$ = Observable_1.Observable
36169             .merge(this._touchEnd$, this._touchCancel$)
36170             .filter(function (te) {
36171             return te.touches.length === 0;
36172         });
36173         this._singleTouchMoveStart$ = singleTouchStart$
36174             .mergeMap(function (e) {
36175             return _this._singleTouchMove$
36176                 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
36177                 .take(1);
36178         });
36179         this._singleTouchMoveEnd$ = singleTouchStart$
36180             .mergeMap(function (e) {
36181             return Observable_1.Observable
36182                 .merge(touchStop$, multipleTouchStart$)
36183                 .first();
36184         });
36185         this._singleTouch$ = singleTouchStart$
36186             .switchMap(function (te) {
36187             return _this._singleTouchMove$
36188                 .skip(1)
36189                 .takeUntil(Observable_1.Observable
36190                 .merge(multipleTouchStart$, touchStop$));
36191         });
36192         var touchesChanged$ = Observable_1.Observable
36193             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
36194         var pinchStart$ = touchesChanged$
36195             .filter(function (te) {
36196             return te.touches.length === 2 && te.targetTouches.length === 2;
36197         });
36198         var pinchStop$ = touchesChanged$
36199             .filter(function (te) {
36200             return te.touches.length !== 2 || te.targetTouches.length !== 2;
36201         });
36202         this._pinchOperation$ = new Subject_1.Subject();
36203         this._pinch$ = this._pinchOperation$
36204             .scan(function (pinch, operation) {
36205             return operation(pinch);
36206         }, {
36207             centerClientX: 0,
36208             centerClientY: 0,
36209             centerPageX: 0,
36210             centerPageY: 0,
36211             centerScreenX: 0,
36212             centerScreenY: 0,
36213             changeX: 0,
36214             changeY: 0,
36215             distance: 0,
36216             distanceChange: 0,
36217             distanceX: 0,
36218             distanceY: 0,
36219             touch1: null,
36220             touch2: null,
36221         });
36222         this._touchMove$
36223             .filter(function (te) {
36224             return te.touches.length === 2 && te.targetTouches.length === 2;
36225         })
36226             .map(function (te) {
36227             return function (previous) {
36228                 var touch1 = te.touches[0];
36229                 var touch2 = te.touches[1];
36230                 var minX = Math.min(touch1.clientX, touch2.clientX);
36231                 var maxX = Math.max(touch1.clientX, touch2.clientX);
36232                 var minY = Math.min(touch1.clientY, touch2.clientY);
36233                 var maxY = Math.max(touch1.clientY, touch2.clientY);
36234                 var centerClientX = minX + (maxX - minX) / 2;
36235                 var centerClientY = minY + (maxY - minY) / 2;
36236                 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
36237                 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
36238                 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
36239                 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
36240                 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
36241                 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
36242                 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
36243                 var distanceChange = distance - previous.distance;
36244                 var changeX = distanceX - previous.distanceX;
36245                 var changeY = distanceY - previous.distanceY;
36246                 var current = {
36247                     centerClientX: centerClientX,
36248                     centerClientY: centerClientY,
36249                     centerPageX: centerPageX,
36250                     centerPageY: centerPageY,
36251                     centerScreenX: centerScreenX,
36252                     centerScreenY: centerScreenY,
36253                     changeX: changeX,
36254                     changeY: changeY,
36255                     distance: distance,
36256                     distanceChange: distanceChange,
36257                     distanceX: distanceX,
36258                     distanceY: distanceY,
36259                     touch1: touch1,
36260                     touch2: touch2,
36261                 };
36262                 return current;
36263             };
36264         })
36265             .subscribe(this._pinchOperation$);
36266         this._pinchChange$ = pinchStart$
36267             .switchMap(function (te) {
36268             return _this._pinch$
36269                 .skip(1)
36270                 .takeUntil(pinchStop$);
36271         });
36272     }
36273     Object.defineProperty(TouchService.prototype, "active$", {
36274         get: function () {
36275             return this._active$;
36276         },
36277         enumerable: true,
36278         configurable: true
36279     });
36280     Object.defineProperty(TouchService.prototype, "activate$", {
36281         get: function () {
36282             return this._activeSubject$;
36283         },
36284         enumerable: true,
36285         configurable: true
36286     });
36287     Object.defineProperty(TouchService.prototype, "touchStart$", {
36288         get: function () {
36289             return this._touchStart$;
36290         },
36291         enumerable: true,
36292         configurable: true
36293     });
36294     Object.defineProperty(TouchService.prototype, "touchMove$", {
36295         get: function () {
36296             return this._touchMove$;
36297         },
36298         enumerable: true,
36299         configurable: true
36300     });
36301     Object.defineProperty(TouchService.prototype, "touchEnd$", {
36302         get: function () {
36303             return this._touchEnd$;
36304         },
36305         enumerable: true,
36306         configurable: true
36307     });
36308     Object.defineProperty(TouchService.prototype, "touchCancel$", {
36309         get: function () {
36310             return this._touchCancel$;
36311         },
36312         enumerable: true,
36313         configurable: true
36314     });
36315     Object.defineProperty(TouchService.prototype, "singleTouchMoveStart$", {
36316         get: function () {
36317             return this._singleTouchMoveStart$;
36318         },
36319         enumerable: true,
36320         configurable: true
36321     });
36322     Object.defineProperty(TouchService.prototype, "singleTouchMove$", {
36323         get: function () {
36324             return this._singleTouch$;
36325         },
36326         enumerable: true,
36327         configurable: true
36328     });
36329     Object.defineProperty(TouchService.prototype, "singleTouchMoveEnd$", {
36330         get: function () {
36331             return this._singleTouchMoveEnd$;
36332         },
36333         enumerable: true,
36334         configurable: true
36335     });
36336     Object.defineProperty(TouchService.prototype, "pinch$", {
36337         get: function () {
36338             return this._pinchChange$;
36339         },
36340         enumerable: true,
36341         configurable: true
36342     });
36343     Object.defineProperty(TouchService.prototype, "preventDefaultTouchMove$", {
36344         get: function () {
36345             return this._preventTouchMove$;
36346         },
36347         enumerable: true,
36348         configurable: true
36349     });
36350     return TouchService;
36351 }());
36352 exports.TouchService = TouchService;
36353
36354 },{"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/filter":58,"rxjs/add/operator/map":62,"rxjs/add/operator/merge":63,"rxjs/add/operator/scan":70,"rxjs/add/operator/switchMap":76}],333:[function(require,module,exports){
36355 /// <reference path="../../typings/index.d.ts" />
36356 "use strict";
36357 var __extends = (this && this.__extends) || function (d, b) {
36358     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
36359     function __() { this.constructor = d; }
36360     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36361 };
36362 var when = require("when");
36363 var Viewer_1 = require("../Viewer");
36364 var Utils_1 = require("../Utils");
36365 /**
36366  * @class Viewer
36367  *
36368  * @classdesc The Viewer object represents the navigable photo viewer.
36369  * Create a Viewer by specifying a container, client ID, photo key and
36370  * other options. The viewer exposes methods and events for programmatic
36371  * interaction.
36372  */
36373 var Viewer = (function (_super) {
36374     __extends(Viewer, _super);
36375     /**
36376      * Create a new viewer instance.
36377      *
36378      * @param {string} id - Required `id` of a DOM element which will
36379      * be transformed into the viewer.
36380      * @param {string} clientId - Required `Mapillary API ClientID`. Can
36381      * be obtained from https://www.mapillary.com/app/settings/developers.
36382      * @param {string} [key] - Optional `photoId` to start from, can be any
36383      * Mapillary photo, if null no image is loaded.
36384      * @param {IViewerOptions} [options] - Optional configuration object
36385      * specifing Viewer's initial setup.
36386      * @param {string} [token] - Optional bearer token for API requests of
36387      * protected resources.
36388      */
36389     function Viewer(id, clientId, key, options, token) {
36390         var _this = _super.call(this) || this;
36391         options = options != null ? options : {};
36392         Utils_1.Settings.setOptions(options);
36393         _this._navigator = new Viewer_1.Navigator(clientId, token);
36394         _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
36395         _this._eventLauncher = new Viewer_1.EventLauncher(_this, _this._navigator, _this._container);
36396         _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, key, options.component);
36397         return _this;
36398     }
36399     /**
36400      * Activate a component.
36401      *
36402      * @param {string} name - Name of the component which will become active.
36403      */
36404     Viewer.prototype.activateComponent = function (name) {
36405         this._componentController.activate(name);
36406     };
36407     /**
36408      * Activate the cover (deactivates all other components).
36409      */
36410     Viewer.prototype.activateCover = function () {
36411         this._componentController.activateCover();
36412     };
36413     /**
36414      * Deactivate a component.
36415      *
36416      * @param {string} name - Name of component which become inactive.
36417      */
36418     Viewer.prototype.deactivateComponent = function (name) {
36419         this._componentController.deactivate(name);
36420     };
36421     /**
36422      * Deactivate the cover (activates all components marked as active).
36423      */
36424     Viewer.prototype.deactivateCover = function () {
36425         this._componentController.deactivateCover();
36426     };
36427     /**
36428      * Get the bearing of the current viewer camera.
36429      *
36430      * @description The bearing depends on how the camera
36431      * is currently rotated and does not correspond
36432      * to the compass angle of the current node if the view
36433      * has been panned.
36434      *
36435      * Bearing is measured in degrees clockwise with respect to
36436      * north.
36437      *
36438      * @returns {Promise<number>} Promise to the bearing
36439      * of the current viewer camera.
36440      */
36441     Viewer.prototype.getBearing = function () {
36442         var _this = this;
36443         return when.promise(function (resolve, reject) {
36444             _this._container.renderService.bearing$
36445                 .first()
36446                 .subscribe(function (bearing) {
36447                 resolve(bearing);
36448             }, function (error) {
36449                 reject(error);
36450             });
36451         });
36452     };
36453     /**
36454      * Get the basic coordinates of the current photo that is
36455      * at the center of the viewport.
36456      *
36457      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
36458      * and have the origin point, (0, 0), at the top left corner and the
36459      * maximum value, (1, 1), at the bottom right corner of the original
36460      * photo.
36461      *
36462      * @returns {Promise<number[]>} Promise to the basic coordinates
36463      * of the current photo at the center for the viewport.
36464      */
36465     Viewer.prototype.getCenter = function () {
36466         var _this = this;
36467         return when.promise(function (resolve, reject) {
36468             _this._navigator.stateService.getCenter()
36469                 .subscribe(function (center) {
36470                 resolve(center);
36471             }, function (error) {
36472                 reject(error);
36473             });
36474         });
36475     };
36476     /**
36477      * Get a component.
36478      *
36479      * @param {string} name - Name of component.
36480      * @returns {Component} The requested component.
36481      */
36482     Viewer.prototype.getComponent = function (name) {
36483         return this._componentController.get(name);
36484     };
36485     /**
36486      * Get the photo's current zoom level.
36487      *
36488      * @returns {Promise<number>} Promise to the viewers's current
36489      * zoom level.
36490      */
36491     Viewer.prototype.getZoom = function () {
36492         var _this = this;
36493         return when.promise(function (resolve, reject) {
36494             _this._navigator.stateService.getZoom()
36495                 .subscribe(function (zoom) {
36496                 resolve(zoom);
36497             }, function (error) {
36498                 reject(error);
36499             });
36500         });
36501     };
36502     /**
36503      * Move close to given latitude and longitude.
36504      *
36505      * @param {Number} lat - Latitude, in degrees.
36506      * @param {Number} lon - Longitude, in degrees.
36507      * @returns {Promise<Node>} Promise to the node that was navigated to.
36508      * @throws {Error} If no nodes exist close to provided latitude
36509      * longitude.
36510      * @throws {Error} Propagates any IO errors to the caller.
36511      */
36512     Viewer.prototype.moveCloseTo = function (lat, lon) {
36513         var _this = this;
36514         return when.promise(function (resolve, reject) {
36515             _this._navigator.moveCloseTo$(lat, lon).subscribe(function (node) {
36516                 resolve(node);
36517             }, function (error) {
36518                 reject(error);
36519             });
36520         });
36521     };
36522     /**
36523      * Navigate in a given direction.
36524      *
36525      * @description This method has to be called through EdgeDirection enumeration as in the example.
36526      *
36527      * @param {EdgeDirection} dir - Direction in which which to move.
36528      * @returns {Promise<Node>} Promise to the node that was navigated to.
36529      * @throws {Error} If the current node does not have the edge direction
36530      * or the edges has not yet been cached.
36531      * @throws {Error} Propagates any IO errors to the caller.
36532      *
36533      * @example `viewer.moveDir(Mapillary.EdgeDirection.Next);`
36534      */
36535     Viewer.prototype.moveDir = function (dir) {
36536         var _this = this;
36537         return when.promise(function (resolve, reject) {
36538             _this._navigator.moveDir$(dir).subscribe(function (node) {
36539                 resolve(node);
36540             }, function (error) {
36541                 reject(error);
36542             });
36543         });
36544     };
36545     /**
36546      * Navigate to a given photo key.
36547      *
36548      * @param {string} key - A valid Mapillary photo key.
36549      * @returns {Promise<Node>} Promise to the node that was navigated to.
36550      * @throws {Error} Propagates any IO errors to the caller.
36551      */
36552     Viewer.prototype.moveToKey = function (key) {
36553         var _this = this;
36554         return when.promise(function (resolve, reject) {
36555             _this._navigator.moveToKey$(key).subscribe(function (node) {
36556                 resolve(node);
36557             }, function (error) {
36558                 reject(error);
36559             });
36560         });
36561     };
36562     /**
36563      * Detect the viewer's new width and height and resize it.
36564      *
36565      * @description The components will also detect the viewer's
36566      * new size and resize their rendered elements if needed.
36567      */
36568     Viewer.prototype.resize = function () {
36569         this._container.renderService.resize$.next(null);
36570         this._componentController.resize();
36571     };
36572     /**
36573      * Set a bearer token for authenticated API requests of
36574      * protected resources.
36575      *
36576      * @description When the supplied token is null or undefined,
36577      * any previously set bearer token will be cleared and the
36578      * viewer will make unauthenticated requests.
36579      *
36580      * Calling setAuthToken aborts all outstanding move requests.
36581      * The promises of those move requests will be rejected and
36582      * the rejections need to be caught.
36583      *
36584      * @param {string} [token] token - Bearer token.
36585      * @returns {Promise<void>} Promise that resolves after token
36586      * is set.
36587      */
36588     Viewer.prototype.setAuthToken = function (token) {
36589         var _this = this;
36590         return when.promise(function (resolve, reject) {
36591             _this._navigator.setToken$(token)
36592                 .subscribe(function () {
36593                 resolve(undefined);
36594             }, function (error) {
36595                 reject(error);
36596             });
36597         });
36598     };
36599     /**
36600      * Set the basic coordinates of the current photo to be in the
36601      * center of the viewport.
36602      *
36603      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
36604      * and has the origin point, (0, 0), at the top left corner and the
36605      * maximum value, (1, 1), at the bottom right corner of the original
36606      * photo.
36607      *
36608      * @param {number[]} The basic coordinates of the current
36609      * photo to be at the center for the viewport.
36610      */
36611     Viewer.prototype.setCenter = function (center) {
36612         this._navigator.stateService.setCenter(center);
36613     };
36614     /**
36615      * Set the filter selecting nodes to use when calculating
36616      * the spatial edges.
36617      *
36618      * @description The following filter types are supported:
36619      *
36620      * Comparison
36621      *
36622      * `["==", key, value]` equality: `node[key] = value`
36623      *
36624      * `["!=", key, value]` inequality: `node[key] ≠ value`
36625      *
36626      * `["<", key, value]` less than: `node[key] < value`
36627      *
36628      * `["<=", key, value]` less than or equal: `node[key] ≤ value`
36629      *
36630      * `[">", key, value]` greater than: `node[key] > value`
36631      *
36632      * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
36633      *
36634      * Set membership
36635      *
36636      * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
36637      *
36638      * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
36639      *
36640      * Combining
36641      *
36642      * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
36643      *
36644      * A key must be a string that identifies a node property name. A value must be
36645      * a string, number, or boolean. Strictly-typed comparisons are used. The values
36646      * `f0, ..., fn` of the combining filter must be filter expressions.
36647      *
36648      * Clear the filter by setting it to null or empty array.
36649      *
36650      * @param {FilterExpression} filter - The filter expression.
36651      * @returns {Promise<void>} Promise that resolves after filter is applied.
36652      *
36653      * @example `viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);`
36654      */
36655     Viewer.prototype.setFilter = function (filter) {
36656         var _this = this;
36657         return when.promise(function (resolve, reject) {
36658             _this._navigator.setFilter$(filter)
36659                 .subscribe(function () {
36660                 resolve(undefined);
36661             }, function (error) {
36662                 reject(error);
36663             });
36664         });
36665     };
36666     /**
36667      * Set the viewer's render mode.
36668      *
36669      * @param {RenderMode} renderMode - Render mode.
36670      *
36671      * @example `viewer.setRenderMode(Mapillary.RenderMode.Letterbox);`
36672      */
36673     Viewer.prototype.setRenderMode = function (renderMode) {
36674         this._container.renderService.renderMode$.next(renderMode);
36675     };
36676     /**
36677      * Set the photo's current zoom level.
36678      *
36679      * @description Possible zoom level values are on the [0, 3] interval.
36680      * Zero means zooming out to fit the photo to the view whereas three
36681      * shows the highest level of detail.
36682      *
36683      * @param {number} The photo's current zoom level.
36684      */
36685     Viewer.prototype.setZoom = function (zoom) {
36686         this._navigator.stateService.setZoom(zoom);
36687     };
36688     return Viewer;
36689 }(Utils_1.EventEmitter));
36690 /**
36691  * Fired when the viewing direction of the camera changes.
36692  * @event
36693  * @type {boolean} bearing - Value indicating the current bearing
36694  * measured in degrees clockwise with respect to north.
36695  */
36696 Viewer.bearingchanged = "bearingchanged";
36697 /**
36698  * Fired when the viewer is loading more data.
36699  * @event
36700  * @type {boolean} loading - Value indicating whether the viewer is loading.
36701  */
36702 Viewer.loadingchanged = "loadingchanged";
36703 /**
36704  * Fired when the viewer finishes transitioning and is in a fixed
36705  * position with a fixed point of view.
36706  * @event
36707  */
36708 Viewer.moveend = "moveend";
36709 /**
36710  * Fired when the viewer starts transitioning from one view to another,
36711  * either by changing the node or by interaction such as pan and zoom.
36712  * @event
36713  */
36714 Viewer.movestart = "movestart";
36715 /**
36716  * Fired every time the viewer navigates to a new node.
36717  * @event
36718  * @type {Node} node - Current node.
36719  */
36720 Viewer.nodechanged = "nodechanged";
36721 /**
36722  * Fired every time the sequence edges of the current node changes.
36723  * @event
36724  * @type {IEdgeStatus} status - The edge status object.
36725  */
36726 Viewer.sequenceedgeschanged = "sequenceedgeschanged";
36727 /**
36728  * Fired every time the spatial edges of the current node changes.
36729  * @event
36730  * @type {IEdgeStatus} status - The edge status object.
36731  */
36732 Viewer.spatialedgeschanged = "spatialedgeschanged";
36733 exports.Viewer = Viewer;
36734
36735 },{"../Utils":226,"../Viewer":227,"when":214}]},{},[222])(222)
36736 });
36737 //# sourceMappingURL=mapillary.js.map