]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/iD/iD/mapillary-js/mapillary.js
Merge remote-tracking branch 'upstream/pull/2413'
[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 var Queue = require('tinyqueue');
5
6 module.exports = polylabel;
7 module.exports.default = polylabel;
8
9 function polylabel(polygon, precision, debug) {
10     precision = precision || 1.0;
11
12     // find the bounding box of the outer ring
13     var minX, minY, maxX, maxY;
14     for (var i = 0; i < polygon[0].length; i++) {
15         var p = polygon[0][i];
16         if (!i || p[0] < minX) minX = p[0];
17         if (!i || p[1] < minY) minY = p[1];
18         if (!i || p[0] > maxX) maxX = p[0];
19         if (!i || p[1] > maxY) maxY = p[1];
20     }
21
22     var width = maxX - minX;
23     var height = maxY - minY;
24     var cellSize = Math.min(width, height);
25     var h = cellSize / 2;
26
27     // a priority queue of cells in order of their "potential" (max distance to polygon)
28     var cellQueue = new Queue(null, compareMax);
29
30     if (cellSize === 0) return [minX, minY];
31
32     // cover polygon with initial cells
33     for (var x = minX; x < maxX; x += cellSize) {
34         for (var y = minY; y < maxY; y += cellSize) {
35             cellQueue.push(new Cell(x + h, y + h, h, polygon));
36         }
37     }
38
39     // take centroid as the first best guess
40     var bestCell = getCentroidCell(polygon);
41
42     // special case for rectangular polygons
43     var bboxCell = new Cell(minX + width / 2, minY + height / 2, 0, polygon);
44     if (bboxCell.d > bestCell.d) bestCell = bboxCell;
45
46     var numProbes = cellQueue.length;
47
48     while (cellQueue.length) {
49         // pick the most promising cell from the queue
50         var cell = cellQueue.pop();
51
52         // update the best cell if we found a better one
53         if (cell.d > bestCell.d) {
54             bestCell = cell;
55             if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes);
56         }
57
58         // do not drill down further if there's no chance of a better solution
59         if (cell.max - bestCell.d <= precision) continue;
60
61         // split the cell into four cells
62         h = cell.h / 2;
63         cellQueue.push(new Cell(cell.x - h, cell.y - h, h, polygon));
64         cellQueue.push(new Cell(cell.x + h, cell.y - h, h, polygon));
65         cellQueue.push(new Cell(cell.x - h, cell.y + h, h, polygon));
66         cellQueue.push(new Cell(cell.x + h, cell.y + h, h, polygon));
67         numProbes += 4;
68     }
69
70     if (debug) {
71         console.log('num probes: ' + numProbes);
72         console.log('best distance: ' + bestCell.d);
73     }
74
75     return [bestCell.x, bestCell.y];
76 }
77
78 function compareMax(a, b) {
79     return b.max - a.max;
80 }
81
82 function Cell(x, y, h, polygon) {
83     this.x = x; // cell center x
84     this.y = y; // cell center y
85     this.h = h; // half the cell size
86     this.d = pointToPolygonDist(x, y, polygon); // distance from cell center to polygon
87     this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell
88 }
89
90 // signed distance from point to polygon outline (negative if point is outside)
91 function pointToPolygonDist(x, y, polygon) {
92     var inside = false;
93     var minDistSq = Infinity;
94
95     for (var k = 0; k < polygon.length; k++) {
96         var ring = polygon[k];
97
98         for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {
99             var a = ring[i];
100             var b = ring[j];
101
102             if ((a[1] > y !== b[1] > y) &&
103                 (x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0])) inside = !inside;
104
105             minDistSq = Math.min(minDistSq, getSegDistSq(x, y, a, b));
106         }
107     }
108
109     return (inside ? 1 : -1) * Math.sqrt(minDistSq);
110 }
111
112 // get polygon centroid
113 function getCentroidCell(polygon) {
114     var area = 0;
115     var x = 0;
116     var y = 0;
117     var points = polygon[0];
118
119     for (var i = 0, len = points.length, j = len - 1; i < len; j = i++) {
120         var a = points[i];
121         var b = points[j];
122         var f = a[0] * b[1] - b[0] * a[1];
123         x += (a[0] + b[0]) * f;
124         y += (a[1] + b[1]) * f;
125         area += f * 3;
126     }
127     if (area === 0) return new Cell(points[0][0], points[0][1], 0, polygon);
128     return new Cell(x / area, y / area, 0, polygon);
129 }
130
131 // get squared distance from a point to a segment
132 function getSegDistSq(px, py, a, b) {
133
134     var x = a[0];
135     var y = a[1];
136     var dx = b[0] - x;
137     var dy = b[1] - y;
138
139     if (dx !== 0 || dy !== 0) {
140
141         var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
142
143         if (t > 1) {
144             x = b[0];
145             y = b[1];
146
147         } else if (t > 0) {
148             x += dx * t;
149             y += dy * t;
150         }
151     }
152
153     dx = px - x;
154     dy = py - y;
155
156     return dx * dx + dy * dy;
157 }
158
159 },{"tinyqueue":227}],2:[function(require,module,exports){
160 /*
161  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
162  *
163  * Redistribution and use in source and binary forms, with or without
164  * modification, are permitted provided that the following conditions
165  * are met:
166  * 1. Redistributions of source code must retain the above copyright
167  *    notice, this list of conditions and the following disclaimer.
168  * 2. Redistributions in binary form must reproduce the above copyright
169  *    notice, this list of conditions and the following disclaimer in the
170  *    documentation and/or other materials provided with the distribution.
171  *
172  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
173  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
174  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
175  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
176  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
177  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
178  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
179  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
180  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
181  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
182  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
183  *
184  * Ported from Webkit
185  * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
186  */
187
188 module.exports = UnitBezier;
189
190 function UnitBezier(p1x, p1y, p2x, p2y) {
191     // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
192     this.cx = 3.0 * p1x;
193     this.bx = 3.0 * (p2x - p1x) - this.cx;
194     this.ax = 1.0 - this.cx - this.bx;
195
196     this.cy = 3.0 * p1y;
197     this.by = 3.0 * (p2y - p1y) - this.cy;
198     this.ay = 1.0 - this.cy - this.by;
199
200     this.p1x = p1x;
201     this.p1y = p2y;
202     this.p2x = p2x;
203     this.p2y = p2y;
204 }
205
206 UnitBezier.prototype.sampleCurveX = function(t) {
207     // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
208     return ((this.ax * t + this.bx) * t + this.cx) * t;
209 };
210
211 UnitBezier.prototype.sampleCurveY = function(t) {
212     return ((this.ay * t + this.by) * t + this.cy) * t;
213 };
214
215 UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
216     return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
217 };
218
219 UnitBezier.prototype.solveCurveX = function(x, epsilon) {
220     if (typeof epsilon === 'undefined') epsilon = 1e-6;
221
222     var t0, t1, t2, x2, i;
223
224     // First try a few iterations of Newton's method -- normally very fast.
225     for (t2 = x, i = 0; i < 8; i++) {
226
227         x2 = this.sampleCurveX(t2) - x;
228         if (Math.abs(x2) < epsilon) return t2;
229
230         var d2 = this.sampleCurveDerivativeX(t2);
231         if (Math.abs(d2) < 1e-6) break;
232
233         t2 = t2 - x2 / d2;
234     }
235
236     // Fall back to the bisection method for reliability.
237     t0 = 0.0;
238     t1 = 1.0;
239     t2 = x;
240
241     if (t2 < t0) return t0;
242     if (t2 > t1) return t1;
243
244     while (t0 < t1) {
245
246         x2 = this.sampleCurveX(t2);
247         if (Math.abs(x2 - x) < epsilon) return t2;
248
249         if (x > x2) {
250             t0 = t2;
251         } else {
252             t1 = t2;
253         }
254
255         t2 = (t1 - t0) * 0.5 + t0;
256     }
257
258     // Failure.
259     return t2;
260 };
261
262 UnitBezier.prototype.solve = function(x, epsilon) {
263     return this.sampleCurveY(this.solveCurveX(x, epsilon));
264 };
265
266 },{}],3:[function(require,module,exports){
267 'use strict'
268
269 exports.byteLength = byteLength
270 exports.toByteArray = toByteArray
271 exports.fromByteArray = fromByteArray
272
273 var lookup = []
274 var revLookup = []
275 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
276
277 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
278 for (var i = 0, len = code.length; i < len; ++i) {
279   lookup[i] = code[i]
280   revLookup[code.charCodeAt(i)] = i
281 }
282
283 revLookup['-'.charCodeAt(0)] = 62
284 revLookup['_'.charCodeAt(0)] = 63
285
286 function placeHoldersCount (b64) {
287   var len = b64.length
288   if (len % 4 > 0) {
289     throw new Error('Invalid string. Length must be a multiple of 4')
290   }
291
292   // the number of equal signs (place holders)
293   // if there are two placeholders, than the two characters before it
294   // represent one byte
295   // if there is only one, then the three characters before it represent 2 bytes
296   // this is just a cheap hack to not do indexOf twice
297   return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
298 }
299
300 function byteLength (b64) {
301   // base64 is 4/3 + up to two characters of the original data
302   return (b64.length * 3 / 4) - placeHoldersCount(b64)
303 }
304
305 function toByteArray (b64) {
306   var i, l, tmp, placeHolders, arr
307   var len = b64.length
308   placeHolders = placeHoldersCount(b64)
309
310   arr = new Arr((len * 3 / 4) - placeHolders)
311
312   // if there are placeholders, only get up to the last complete 4 chars
313   l = placeHolders > 0 ? len - 4 : len
314
315   var L = 0
316
317   for (i = 0; i < l; i += 4) {
318     tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
319     arr[L++] = (tmp >> 16) & 0xFF
320     arr[L++] = (tmp >> 8) & 0xFF
321     arr[L++] = tmp & 0xFF
322   }
323
324   if (placeHolders === 2) {
325     tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
326     arr[L++] = tmp & 0xFF
327   } else if (placeHolders === 1) {
328     tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
329     arr[L++] = (tmp >> 8) & 0xFF
330     arr[L++] = tmp & 0xFF
331   }
332
333   return arr
334 }
335
336 function tripletToBase64 (num) {
337   return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
338 }
339
340 function encodeChunk (uint8, start, end) {
341   var tmp
342   var output = []
343   for (var i = start; i < end; i += 3) {
344     tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
345     output.push(tripletToBase64(tmp))
346   }
347   return output.join('')
348 }
349
350 function fromByteArray (uint8) {
351   var tmp
352   var len = uint8.length
353   var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
354   var output = ''
355   var parts = []
356   var maxChunkLength = 16383 // must be multiple of 3
357
358   // go through the array every three bytes, we'll deal with trailing stuff later
359   for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
360     parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
361   }
362
363   // pad the end with zeros, but make sure to not forget the extra bytes
364   if (extraBytes === 1) {
365     tmp = uint8[len - 1]
366     output += lookup[tmp >> 2]
367     output += lookup[(tmp << 4) & 0x3F]
368     output += '=='
369   } else if (extraBytes === 2) {
370     tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
371     output += lookup[tmp >> 10]
372     output += lookup[(tmp >> 4) & 0x3F]
373     output += lookup[(tmp << 2) & 0x3F]
374     output += '='
375   }
376
377   parts.push(output)
378
379   return parts.join('')
380 }
381
382 },{}],4:[function(require,module,exports){
383
384 },{}],5:[function(require,module,exports){
385 /*!
386  * Cross-Browser Split 1.1.1
387  * Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
388  * Available under the MIT License
389  * ECMAScript compliant, uniform cross-browser split method
390  */
391
392 /**
393  * Splits a string into an array of strings using a regex or string separator. Matches of the
394  * separator are not included in the result array. However, if `separator` is a regex that contains
395  * capturing groups, backreferences are spliced into the result each time `separator` is matched.
396  * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably
397  * cross-browser.
398  * @param {String} str String to split.
399  * @param {RegExp|String} separator Regex or string to use for separating the string.
400  * @param {Number} [limit] Maximum number of items to include in the result array.
401  * @returns {Array} Array of substrings.
402  * @example
403  *
404  * // Basic use
405  * split('a b c d', ' ');
406  * // -> ['a', 'b', 'c', 'd']
407  *
408  * // With limit
409  * split('a b c d', ' ', 2);
410  * // -> ['a', 'b']
411  *
412  * // Backreferences in result array
413  * split('..word1 word2..', /([a-z]+)(\d+)/i);
414  * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
415  */
416 module.exports = (function split(undef) {
417
418   var nativeSplit = String.prototype.split,
419     compliantExecNpcg = /()??/.exec("")[1] === undef,
420     // NPCG: nonparticipating capturing group
421     self;
422
423   self = function(str, separator, limit) {
424     // If `separator` is not a regex, use `nativeSplit`
425     if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
426       return nativeSplit.call(str, separator, limit);
427     }
428     var output = [],
429       flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6
430       (separator.sticky ? "y" : ""),
431       // Firefox 3+
432       lastLastIndex = 0,
433       // Make `global` and avoid `lastIndex` issues by working with a copy
434       separator = new RegExp(separator.source, flags + "g"),
435       separator2, match, lastIndex, lastLength;
436     str += ""; // Type-convert
437     if (!compliantExecNpcg) {
438       // Doesn't need flags gy, but they don't hurt
439       separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
440     }
441     /* Values for `limit`, per the spec:
442      * If undefined: 4294967295 // Math.pow(2, 32) - 1
443      * If 0, Infinity, or NaN: 0
444      * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
445      * If negative number: 4294967296 - Math.floor(Math.abs(limit))
446      * If other: Type-convert, then use the above rules
447      */
448     limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1
449     limit >>> 0; // ToUint32(limit)
450     while (match = separator.exec(str)) {
451       // `separator.lastIndex` is not reliable cross-browser
452       lastIndex = match.index + match[0].length;
453       if (lastIndex > lastLastIndex) {
454         output.push(str.slice(lastLastIndex, match.index));
455         // Fix browsers whose `exec` methods don't consistently return `undefined` for
456         // nonparticipating capturing groups
457         if (!compliantExecNpcg && match.length > 1) {
458           match[0].replace(separator2, function() {
459             for (var i = 1; i < arguments.length - 2; i++) {
460               if (arguments[i] === undef) {
461                 match[i] = undef;
462               }
463             }
464           });
465         }
466         if (match.length > 1 && match.index < str.length) {
467           Array.prototype.push.apply(output, match.slice(1));
468         }
469         lastLength = match[0].length;
470         lastLastIndex = lastIndex;
471         if (output.length >= limit) {
472           break;
473         }
474       }
475       if (separator.lastIndex === match.index) {
476         separator.lastIndex++; // Avoid an infinite loop
477       }
478     }
479     if (lastLastIndex === str.length) {
480       if (lastLength || !separator.test("")) {
481         output.push("");
482       }
483     } else {
484       output.push(str.slice(lastLastIndex));
485     }
486     return output.length > limit ? output.slice(0, limit) : output;
487   };
488
489   return self;
490 })();
491
492 },{}],6:[function(require,module,exports){
493 // shim for using process in browser
494 var process = module.exports = {};
495
496 // cached from whatever global is present so that test runners that stub it
497 // don't break things.  But we need to wrap it in a try catch in case it is
498 // wrapped in strict mode code which doesn't define any globals.  It's inside a
499 // function because try/catches deoptimize in certain engines.
500
501 var cachedSetTimeout;
502 var cachedClearTimeout;
503
504 function defaultSetTimout() {
505     throw new Error('setTimeout has not been defined');
506 }
507 function defaultClearTimeout () {
508     throw new Error('clearTimeout has not been defined');
509 }
510 (function () {
511     try {
512         if (typeof setTimeout === 'function') {
513             cachedSetTimeout = setTimeout;
514         } else {
515             cachedSetTimeout = defaultSetTimout;
516         }
517     } catch (e) {
518         cachedSetTimeout = defaultSetTimout;
519     }
520     try {
521         if (typeof clearTimeout === 'function') {
522             cachedClearTimeout = clearTimeout;
523         } else {
524             cachedClearTimeout = defaultClearTimeout;
525         }
526     } catch (e) {
527         cachedClearTimeout = defaultClearTimeout;
528     }
529 } ())
530 function runTimeout(fun) {
531     if (cachedSetTimeout === setTimeout) {
532         //normal enviroments in sane situations
533         return setTimeout(fun, 0);
534     }
535     // if setTimeout wasn't available but was latter defined
536     if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
537         cachedSetTimeout = setTimeout;
538         return setTimeout(fun, 0);
539     }
540     try {
541         // when when somebody has screwed with setTimeout but no I.E. maddness
542         return cachedSetTimeout(fun, 0);
543     } catch(e){
544         try {
545             // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
546             return cachedSetTimeout.call(null, fun, 0);
547         } catch(e){
548             // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
549             return cachedSetTimeout.call(this, fun, 0);
550         }
551     }
552
553
554 }
555 function runClearTimeout(marker) {
556     if (cachedClearTimeout === clearTimeout) {
557         //normal enviroments in sane situations
558         return clearTimeout(marker);
559     }
560     // if clearTimeout wasn't available but was latter defined
561     if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
562         cachedClearTimeout = clearTimeout;
563         return clearTimeout(marker);
564     }
565     try {
566         // when when somebody has screwed with setTimeout but no I.E. maddness
567         return cachedClearTimeout(marker);
568     } catch (e){
569         try {
570             // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
571             return cachedClearTimeout.call(null, marker);
572         } catch (e){
573             // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
574             // Some versions of I.E. have different rules for clearTimeout vs setTimeout
575             return cachedClearTimeout.call(this, marker);
576         }
577     }
578
579
580
581 }
582 var queue = [];
583 var draining = false;
584 var currentQueue;
585 var queueIndex = -1;
586
587 function cleanUpNextTick() {
588     if (!draining || !currentQueue) {
589         return;
590     }
591     draining = false;
592     if (currentQueue.length) {
593         queue = currentQueue.concat(queue);
594     } else {
595         queueIndex = -1;
596     }
597     if (queue.length) {
598         drainQueue();
599     }
600 }
601
602 function drainQueue() {
603     if (draining) {
604         return;
605     }
606     var timeout = runTimeout(cleanUpNextTick);
607     draining = true;
608
609     var len = queue.length;
610     while(len) {
611         currentQueue = queue;
612         queue = [];
613         while (++queueIndex < len) {
614             if (currentQueue) {
615                 currentQueue[queueIndex].run();
616             }
617         }
618         queueIndex = -1;
619         len = queue.length;
620     }
621     currentQueue = null;
622     draining = false;
623     runClearTimeout(timeout);
624 }
625
626 process.nextTick = function (fun) {
627     var args = new Array(arguments.length - 1);
628     if (arguments.length > 1) {
629         for (var i = 1; i < arguments.length; i++) {
630             args[i - 1] = arguments[i];
631         }
632     }
633     queue.push(new Item(fun, args));
634     if (queue.length === 1 && !draining) {
635         runTimeout(drainQueue);
636     }
637 };
638
639 // v8 likes predictible objects
640 function Item(fun, array) {
641     this.fun = fun;
642     this.array = array;
643 }
644 Item.prototype.run = function () {
645     this.fun.apply(null, this.array);
646 };
647 process.title = 'browser';
648 process.browser = true;
649 process.env = {};
650 process.argv = [];
651 process.version = ''; // empty string to avoid regexp issues
652 process.versions = {};
653
654 function noop() {}
655
656 process.on = noop;
657 process.addListener = noop;
658 process.once = noop;
659 process.off = noop;
660 process.removeListener = noop;
661 process.removeAllListeners = noop;
662 process.emit = noop;
663 process.prependListener = noop;
664 process.prependOnceListener = noop;
665
666 process.listeners = function (name) { return [] }
667
668 process.binding = function (name) {
669     throw new Error('process.binding is not supported');
670 };
671
672 process.cwd = function () { return '/' };
673 process.chdir = function (dir) {
674     throw new Error('process.chdir is not supported');
675 };
676 process.umask = function() { return 0; };
677
678 },{}],7:[function(require,module,exports){
679 /*!
680  * The buffer module from node.js, for the browser.
681  *
682  * @author   Feross Aboukhadijeh <https://feross.org>
683  * @license  MIT
684  */
685 /* eslint-disable no-proto */
686
687 'use strict'
688
689 var base64 = require('base64-js')
690 var ieee754 = require('ieee754')
691
692 exports.Buffer = Buffer
693 exports.SlowBuffer = SlowBuffer
694 exports.INSPECT_MAX_BYTES = 50
695
696 var K_MAX_LENGTH = 0x7fffffff
697 exports.kMaxLength = K_MAX_LENGTH
698
699 /**
700  * If `Buffer.TYPED_ARRAY_SUPPORT`:
701  *   === true    Use Uint8Array implementation (fastest)
702  *   === false   Print warning and recommend using `buffer` v4.x which has an Object
703  *               implementation (most compatible, even IE6)
704  *
705  * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
706  * Opera 11.6+, iOS 4.2+.
707  *
708  * We report that the browser does not support typed arrays if the are not subclassable
709  * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
710  * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
711  * for __proto__ and has a buggy typed array implementation.
712  */
713 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
714
715 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
716     typeof console.error === 'function') {
717   console.error(
718     'This browser lacks typed array (Uint8Array) support which is required by ' +
719     '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
720   )
721 }
722
723 function typedArraySupport () {
724   // Can typed array instances can be augmented?
725   try {
726     var arr = new Uint8Array(1)
727     arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
728     return arr.foo() === 42
729   } catch (e) {
730     return false
731   }
732 }
733
734 function createBuffer (length) {
735   if (length > K_MAX_LENGTH) {
736     throw new RangeError('Invalid typed array length')
737   }
738   // Return an augmented `Uint8Array` instance
739   var buf = new Uint8Array(length)
740   buf.__proto__ = Buffer.prototype
741   return buf
742 }
743
744 /**
745  * The Buffer constructor returns instances of `Uint8Array` that have their
746  * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
747  * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
748  * and the `Uint8Array` methods. Square bracket notation works as expected -- it
749  * returns a single octet.
750  *
751  * The `Uint8Array` prototype remains unmodified.
752  */
753
754 function Buffer (arg, encodingOrOffset, length) {
755   // Common case.
756   if (typeof arg === 'number') {
757     if (typeof encodingOrOffset === 'string') {
758       throw new Error(
759         'If encoding is specified then the first argument must be a string'
760       )
761     }
762     return allocUnsafe(arg)
763   }
764   return from(arg, encodingOrOffset, length)
765 }
766
767 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
768 if (typeof Symbol !== 'undefined' && Symbol.species &&
769     Buffer[Symbol.species] === Buffer) {
770   Object.defineProperty(Buffer, Symbol.species, {
771     value: null,
772     configurable: true,
773     enumerable: false,
774     writable: false
775   })
776 }
777
778 Buffer.poolSize = 8192 // not used by this implementation
779
780 function from (value, encodingOrOffset, length) {
781   if (typeof value === 'number') {
782     throw new TypeError('"value" argument must not be a number')
783   }
784
785   if (isArrayBuffer(value)) {
786     return fromArrayBuffer(value, encodingOrOffset, length)
787   }
788
789   if (typeof value === 'string') {
790     return fromString(value, encodingOrOffset)
791   }
792
793   return fromObject(value)
794 }
795
796 /**
797  * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
798  * if value is a number.
799  * Buffer.from(str[, encoding])
800  * Buffer.from(array)
801  * Buffer.from(buffer)
802  * Buffer.from(arrayBuffer[, byteOffset[, length]])
803  **/
804 Buffer.from = function (value, encodingOrOffset, length) {
805   return from(value, encodingOrOffset, length)
806 }
807
808 // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
809 // https://github.com/feross/buffer/pull/148
810 Buffer.prototype.__proto__ = Uint8Array.prototype
811 Buffer.__proto__ = Uint8Array
812
813 function assertSize (size) {
814   if (typeof size !== 'number') {
815     throw new TypeError('"size" argument must be a number')
816   } else if (size < 0) {
817     throw new RangeError('"size" argument must not be negative')
818   }
819 }
820
821 function alloc (size, fill, encoding) {
822   assertSize(size)
823   if (size <= 0) {
824     return createBuffer(size)
825   }
826   if (fill !== undefined) {
827     // Only pay attention to encoding if it's a string. This
828     // prevents accidentally sending in a number that would
829     // be interpretted as a start offset.
830     return typeof encoding === 'string'
831       ? createBuffer(size).fill(fill, encoding)
832       : createBuffer(size).fill(fill)
833   }
834   return createBuffer(size)
835 }
836
837 /**
838  * Creates a new filled Buffer instance.
839  * alloc(size[, fill[, encoding]])
840  **/
841 Buffer.alloc = function (size, fill, encoding) {
842   return alloc(size, fill, encoding)
843 }
844
845 function allocUnsafe (size) {
846   assertSize(size)
847   return createBuffer(size < 0 ? 0 : checked(size) | 0)
848 }
849
850 /**
851  * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
852  * */
853 Buffer.allocUnsafe = function (size) {
854   return allocUnsafe(size)
855 }
856 /**
857  * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
858  */
859 Buffer.allocUnsafeSlow = function (size) {
860   return allocUnsafe(size)
861 }
862
863 function fromString (string, encoding) {
864   if (typeof encoding !== 'string' || encoding === '') {
865     encoding = 'utf8'
866   }
867
868   if (!Buffer.isEncoding(encoding)) {
869     throw new TypeError('"encoding" must be a valid string encoding')
870   }
871
872   var length = byteLength(string, encoding) | 0
873   var buf = createBuffer(length)
874
875   var actual = buf.write(string, encoding)
876
877   if (actual !== length) {
878     // Writing a hex string, for example, that contains invalid characters will
879     // cause everything after the first invalid character to be ignored. (e.g.
880     // 'abxxcd' will be treated as 'ab')
881     buf = buf.slice(0, actual)
882   }
883
884   return buf
885 }
886
887 function fromArrayLike (array) {
888   var length = array.length < 0 ? 0 : checked(array.length) | 0
889   var buf = createBuffer(length)
890   for (var i = 0; i < length; i += 1) {
891     buf[i] = array[i] & 255
892   }
893   return buf
894 }
895
896 function fromArrayBuffer (array, byteOffset, length) {
897   if (byteOffset < 0 || array.byteLength < byteOffset) {
898     throw new RangeError('\'offset\' is out of bounds')
899   }
900
901   if (array.byteLength < byteOffset + (length || 0)) {
902     throw new RangeError('\'length\' is out of bounds')
903   }
904
905   var buf
906   if (byteOffset === undefined && length === undefined) {
907     buf = new Uint8Array(array)
908   } else if (length === undefined) {
909     buf = new Uint8Array(array, byteOffset)
910   } else {
911     buf = new Uint8Array(array, byteOffset, length)
912   }
913
914   // Return an augmented `Uint8Array` instance
915   buf.__proto__ = Buffer.prototype
916   return buf
917 }
918
919 function fromObject (obj) {
920   if (Buffer.isBuffer(obj)) {
921     var len = checked(obj.length) | 0
922     var buf = createBuffer(len)
923
924     if (buf.length === 0) {
925       return buf
926     }
927
928     obj.copy(buf, 0, 0, len)
929     return buf
930   }
931
932   if (obj) {
933     if (isArrayBufferView(obj) || 'length' in obj) {
934       if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
935         return createBuffer(0)
936       }
937       return fromArrayLike(obj)
938     }
939
940     if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
941       return fromArrayLike(obj.data)
942     }
943   }
944
945   throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
946 }
947
948 function checked (length) {
949   // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
950   // length is NaN (which is otherwise coerced to zero.)
951   if (length >= K_MAX_LENGTH) {
952     throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
953                          'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
954   }
955   return length | 0
956 }
957
958 function SlowBuffer (length) {
959   if (+length != length) { // eslint-disable-line eqeqeq
960     length = 0
961   }
962   return Buffer.alloc(+length)
963 }
964
965 Buffer.isBuffer = function isBuffer (b) {
966   return b != null && b._isBuffer === true
967 }
968
969 Buffer.compare = function compare (a, b) {
970   if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
971     throw new TypeError('Arguments must be Buffers')
972   }
973
974   if (a === b) return 0
975
976   var x = a.length
977   var y = b.length
978
979   for (var i = 0, len = Math.min(x, y); i < len; ++i) {
980     if (a[i] !== b[i]) {
981       x = a[i]
982       y = b[i]
983       break
984     }
985   }
986
987   if (x < y) return -1
988   if (y < x) return 1
989   return 0
990 }
991
992 Buffer.isEncoding = function isEncoding (encoding) {
993   switch (String(encoding).toLowerCase()) {
994     case 'hex':
995     case 'utf8':
996     case 'utf-8':
997     case 'ascii':
998     case 'latin1':
999     case 'binary':
1000     case 'base64':
1001     case 'ucs2':
1002     case 'ucs-2':
1003     case 'utf16le':
1004     case 'utf-16le':
1005       return true
1006     default:
1007       return false
1008   }
1009 }
1010
1011 Buffer.concat = function concat (list, length) {
1012   if (!Array.isArray(list)) {
1013     throw new TypeError('"list" argument must be an Array of Buffers')
1014   }
1015
1016   if (list.length === 0) {
1017     return Buffer.alloc(0)
1018   }
1019
1020   var i
1021   if (length === undefined) {
1022     length = 0
1023     for (i = 0; i < list.length; ++i) {
1024       length += list[i].length
1025     }
1026   }
1027
1028   var buffer = Buffer.allocUnsafe(length)
1029   var pos = 0
1030   for (i = 0; i < list.length; ++i) {
1031     var buf = list[i]
1032     if (!Buffer.isBuffer(buf)) {
1033       throw new TypeError('"list" argument must be an Array of Buffers')
1034     }
1035     buf.copy(buffer, pos)
1036     pos += buf.length
1037   }
1038   return buffer
1039 }
1040
1041 function byteLength (string, encoding) {
1042   if (Buffer.isBuffer(string)) {
1043     return string.length
1044   }
1045   if (isArrayBufferView(string) || isArrayBuffer(string)) {
1046     return string.byteLength
1047   }
1048   if (typeof string !== 'string') {
1049     string = '' + string
1050   }
1051
1052   var len = string.length
1053   if (len === 0) return 0
1054
1055   // Use a for loop to avoid recursion
1056   var loweredCase = false
1057   for (;;) {
1058     switch (encoding) {
1059       case 'ascii':
1060       case 'latin1':
1061       case 'binary':
1062         return len
1063       case 'utf8':
1064       case 'utf-8':
1065       case undefined:
1066         return utf8ToBytes(string).length
1067       case 'ucs2':
1068       case 'ucs-2':
1069       case 'utf16le':
1070       case 'utf-16le':
1071         return len * 2
1072       case 'hex':
1073         return len >>> 1
1074       case 'base64':
1075         return base64ToBytes(string).length
1076       default:
1077         if (loweredCase) return utf8ToBytes(string).length // assume utf8
1078         encoding = ('' + encoding).toLowerCase()
1079         loweredCase = true
1080     }
1081   }
1082 }
1083 Buffer.byteLength = byteLength
1084
1085 function slowToString (encoding, start, end) {
1086   var loweredCase = false
1087
1088   // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1089   // property of a typed array.
1090
1091   // This behaves neither like String nor Uint8Array in that we set start/end
1092   // to their upper/lower bounds if the value passed is out of range.
1093   // undefined is handled specially as per ECMA-262 6th Edition,
1094   // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1095   if (start === undefined || start < 0) {
1096     start = 0
1097   }
1098   // Return early if start > this.length. Done here to prevent potential uint32
1099   // coercion fail below.
1100   if (start > this.length) {
1101     return ''
1102   }
1103
1104   if (end === undefined || end > this.length) {
1105     end = this.length
1106   }
1107
1108   if (end <= 0) {
1109     return ''
1110   }
1111
1112   // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1113   end >>>= 0
1114   start >>>= 0
1115
1116   if (end <= start) {
1117     return ''
1118   }
1119
1120   if (!encoding) encoding = 'utf8'
1121
1122   while (true) {
1123     switch (encoding) {
1124       case 'hex':
1125         return hexSlice(this, start, end)
1126
1127       case 'utf8':
1128       case 'utf-8':
1129         return utf8Slice(this, start, end)
1130
1131       case 'ascii':
1132         return asciiSlice(this, start, end)
1133
1134       case 'latin1':
1135       case 'binary':
1136         return latin1Slice(this, start, end)
1137
1138       case 'base64':
1139         return base64Slice(this, start, end)
1140
1141       case 'ucs2':
1142       case 'ucs-2':
1143       case 'utf16le':
1144       case 'utf-16le':
1145         return utf16leSlice(this, start, end)
1146
1147       default:
1148         if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1149         encoding = (encoding + '').toLowerCase()
1150         loweredCase = true
1151     }
1152   }
1153 }
1154
1155 // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1156 // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1157 // reliably in a browserify context because there could be multiple different
1158 // copies of the 'buffer' package in use. This method works even for Buffer
1159 // instances that were created from another copy of the `buffer` package.
1160 // See: https://github.com/feross/buffer/issues/154
1161 Buffer.prototype._isBuffer = true
1162
1163 function swap (b, n, m) {
1164   var i = b[n]
1165   b[n] = b[m]
1166   b[m] = i
1167 }
1168
1169 Buffer.prototype.swap16 = function swap16 () {
1170   var len = this.length
1171   if (len % 2 !== 0) {
1172     throw new RangeError('Buffer size must be a multiple of 16-bits')
1173   }
1174   for (var i = 0; i < len; i += 2) {
1175     swap(this, i, i + 1)
1176   }
1177   return this
1178 }
1179
1180 Buffer.prototype.swap32 = function swap32 () {
1181   var len = this.length
1182   if (len % 4 !== 0) {
1183     throw new RangeError('Buffer size must be a multiple of 32-bits')
1184   }
1185   for (var i = 0; i < len; i += 4) {
1186     swap(this, i, i + 3)
1187     swap(this, i + 1, i + 2)
1188   }
1189   return this
1190 }
1191
1192 Buffer.prototype.swap64 = function swap64 () {
1193   var len = this.length
1194   if (len % 8 !== 0) {
1195     throw new RangeError('Buffer size must be a multiple of 64-bits')
1196   }
1197   for (var i = 0; i < len; i += 8) {
1198     swap(this, i, i + 7)
1199     swap(this, i + 1, i + 6)
1200     swap(this, i + 2, i + 5)
1201     swap(this, i + 3, i + 4)
1202   }
1203   return this
1204 }
1205
1206 Buffer.prototype.toString = function toString () {
1207   var length = this.length
1208   if (length === 0) return ''
1209   if (arguments.length === 0) return utf8Slice(this, 0, length)
1210   return slowToString.apply(this, arguments)
1211 }
1212
1213 Buffer.prototype.equals = function equals (b) {
1214   if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1215   if (this === b) return true
1216   return Buffer.compare(this, b) === 0
1217 }
1218
1219 Buffer.prototype.inspect = function inspect () {
1220   var str = ''
1221   var max = exports.INSPECT_MAX_BYTES
1222   if (this.length > 0) {
1223     str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1224     if (this.length > max) str += ' ... '
1225   }
1226   return '<Buffer ' + str + '>'
1227 }
1228
1229 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1230   if (!Buffer.isBuffer(target)) {
1231     throw new TypeError('Argument must be a Buffer')
1232   }
1233
1234   if (start === undefined) {
1235     start = 0
1236   }
1237   if (end === undefined) {
1238     end = target ? target.length : 0
1239   }
1240   if (thisStart === undefined) {
1241     thisStart = 0
1242   }
1243   if (thisEnd === undefined) {
1244     thisEnd = this.length
1245   }
1246
1247   if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1248     throw new RangeError('out of range index')
1249   }
1250
1251   if (thisStart >= thisEnd && start >= end) {
1252     return 0
1253   }
1254   if (thisStart >= thisEnd) {
1255     return -1
1256   }
1257   if (start >= end) {
1258     return 1
1259   }
1260
1261   start >>>= 0
1262   end >>>= 0
1263   thisStart >>>= 0
1264   thisEnd >>>= 0
1265
1266   if (this === target) return 0
1267
1268   var x = thisEnd - thisStart
1269   var y = end - start
1270   var len = Math.min(x, y)
1271
1272   var thisCopy = this.slice(thisStart, thisEnd)
1273   var targetCopy = target.slice(start, end)
1274
1275   for (var i = 0; i < len; ++i) {
1276     if (thisCopy[i] !== targetCopy[i]) {
1277       x = thisCopy[i]
1278       y = targetCopy[i]
1279       break
1280     }
1281   }
1282
1283   if (x < y) return -1
1284   if (y < x) return 1
1285   return 0
1286 }
1287
1288 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1289 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1290 //
1291 // Arguments:
1292 // - buffer - a Buffer to search
1293 // - val - a string, Buffer, or number
1294 // - byteOffset - an index into `buffer`; will be clamped to an int32
1295 // - encoding - an optional encoding, relevant is val is a string
1296 // - dir - true for indexOf, false for lastIndexOf
1297 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1298   // Empty buffer means no match
1299   if (buffer.length === 0) return -1
1300
1301   // Normalize byteOffset
1302   if (typeof byteOffset === 'string') {
1303     encoding = byteOffset
1304     byteOffset = 0
1305   } else if (byteOffset > 0x7fffffff) {
1306     byteOffset = 0x7fffffff
1307   } else if (byteOffset < -0x80000000) {
1308     byteOffset = -0x80000000
1309   }
1310   byteOffset = +byteOffset  // Coerce to Number.
1311   if (numberIsNaN(byteOffset)) {
1312     // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1313     byteOffset = dir ? 0 : (buffer.length - 1)
1314   }
1315
1316   // Normalize byteOffset: negative offsets start from the end of the buffer
1317   if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1318   if (byteOffset >= buffer.length) {
1319     if (dir) return -1
1320     else byteOffset = buffer.length - 1
1321   } else if (byteOffset < 0) {
1322     if (dir) byteOffset = 0
1323     else return -1
1324   }
1325
1326   // Normalize val
1327   if (typeof val === 'string') {
1328     val = Buffer.from(val, encoding)
1329   }
1330
1331   // Finally, search either indexOf (if dir is true) or lastIndexOf
1332   if (Buffer.isBuffer(val)) {
1333     // Special case: looking for empty string/buffer always fails
1334     if (val.length === 0) {
1335       return -1
1336     }
1337     return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1338   } else if (typeof val === 'number') {
1339     val = val & 0xFF // Search for a byte value [0-255]
1340     if (typeof Uint8Array.prototype.indexOf === 'function') {
1341       if (dir) {
1342         return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1343       } else {
1344         return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1345       }
1346     }
1347     return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1348   }
1349
1350   throw new TypeError('val must be string, number or Buffer')
1351 }
1352
1353 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1354   var indexSize = 1
1355   var arrLength = arr.length
1356   var valLength = val.length
1357
1358   if (encoding !== undefined) {
1359     encoding = String(encoding).toLowerCase()
1360     if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1361         encoding === 'utf16le' || encoding === 'utf-16le') {
1362       if (arr.length < 2 || val.length < 2) {
1363         return -1
1364       }
1365       indexSize = 2
1366       arrLength /= 2
1367       valLength /= 2
1368       byteOffset /= 2
1369     }
1370   }
1371
1372   function read (buf, i) {
1373     if (indexSize === 1) {
1374       return buf[i]
1375     } else {
1376       return buf.readUInt16BE(i * indexSize)
1377     }
1378   }
1379
1380   var i
1381   if (dir) {
1382     var foundIndex = -1
1383     for (i = byteOffset; i < arrLength; i++) {
1384       if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1385         if (foundIndex === -1) foundIndex = i
1386         if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1387       } else {
1388         if (foundIndex !== -1) i -= i - foundIndex
1389         foundIndex = -1
1390       }
1391     }
1392   } else {
1393     if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1394     for (i = byteOffset; i >= 0; i--) {
1395       var found = true
1396       for (var j = 0; j < valLength; j++) {
1397         if (read(arr, i + j) !== read(val, j)) {
1398           found = false
1399           break
1400         }
1401       }
1402       if (found) return i
1403     }
1404   }
1405
1406   return -1
1407 }
1408
1409 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1410   return this.indexOf(val, byteOffset, encoding) !== -1
1411 }
1412
1413 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1414   return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1415 }
1416
1417 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1418   return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1419 }
1420
1421 function hexWrite (buf, string, offset, length) {
1422   offset = Number(offset) || 0
1423   var remaining = buf.length - offset
1424   if (!length) {
1425     length = remaining
1426   } else {
1427     length = Number(length)
1428     if (length > remaining) {
1429       length = remaining
1430     }
1431   }
1432
1433   // must be an even number of digits
1434   var strLen = string.length
1435   if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1436
1437   if (length > strLen / 2) {
1438     length = strLen / 2
1439   }
1440   for (var i = 0; i < length; ++i) {
1441     var parsed = parseInt(string.substr(i * 2, 2), 16)
1442     if (numberIsNaN(parsed)) return i
1443     buf[offset + i] = parsed
1444   }
1445   return i
1446 }
1447
1448 function utf8Write (buf, string, offset, length) {
1449   return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1450 }
1451
1452 function asciiWrite (buf, string, offset, length) {
1453   return blitBuffer(asciiToBytes(string), buf, offset, length)
1454 }
1455
1456 function latin1Write (buf, string, offset, length) {
1457   return asciiWrite(buf, string, offset, length)
1458 }
1459
1460 function base64Write (buf, string, offset, length) {
1461   return blitBuffer(base64ToBytes(string), buf, offset, length)
1462 }
1463
1464 function ucs2Write (buf, string, offset, length) {
1465   return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1466 }
1467
1468 Buffer.prototype.write = function write (string, offset, length, encoding) {
1469   // Buffer#write(string)
1470   if (offset === undefined) {
1471     encoding = 'utf8'
1472     length = this.length
1473     offset = 0
1474   // Buffer#write(string, encoding)
1475   } else if (length === undefined && typeof offset === 'string') {
1476     encoding = offset
1477     length = this.length
1478     offset = 0
1479   // Buffer#write(string, offset[, length][, encoding])
1480   } else if (isFinite(offset)) {
1481     offset = offset >>> 0
1482     if (isFinite(length)) {
1483       length = length >>> 0
1484       if (encoding === undefined) encoding = 'utf8'
1485     } else {
1486       encoding = length
1487       length = undefined
1488     }
1489   } else {
1490     throw new Error(
1491       'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1492     )
1493   }
1494
1495   var remaining = this.length - offset
1496   if (length === undefined || length > remaining) length = remaining
1497
1498   if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1499     throw new RangeError('Attempt to write outside buffer bounds')
1500   }
1501
1502   if (!encoding) encoding = 'utf8'
1503
1504   var loweredCase = false
1505   for (;;) {
1506     switch (encoding) {
1507       case 'hex':
1508         return hexWrite(this, string, offset, length)
1509
1510       case 'utf8':
1511       case 'utf-8':
1512         return utf8Write(this, string, offset, length)
1513
1514       case 'ascii':
1515         return asciiWrite(this, string, offset, length)
1516
1517       case 'latin1':
1518       case 'binary':
1519         return latin1Write(this, string, offset, length)
1520
1521       case 'base64':
1522         // Warning: maxLength not taken into account in base64Write
1523         return base64Write(this, string, offset, length)
1524
1525       case 'ucs2':
1526       case 'ucs-2':
1527       case 'utf16le':
1528       case 'utf-16le':
1529         return ucs2Write(this, string, offset, length)
1530
1531       default:
1532         if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1533         encoding = ('' + encoding).toLowerCase()
1534         loweredCase = true
1535     }
1536   }
1537 }
1538
1539 Buffer.prototype.toJSON = function toJSON () {
1540   return {
1541     type: 'Buffer',
1542     data: Array.prototype.slice.call(this._arr || this, 0)
1543   }
1544 }
1545
1546 function base64Slice (buf, start, end) {
1547   if (start === 0 && end === buf.length) {
1548     return base64.fromByteArray(buf)
1549   } else {
1550     return base64.fromByteArray(buf.slice(start, end))
1551   }
1552 }
1553
1554 function utf8Slice (buf, start, end) {
1555   end = Math.min(buf.length, end)
1556   var res = []
1557
1558   var i = start
1559   while (i < end) {
1560     var firstByte = buf[i]
1561     var codePoint = null
1562     var bytesPerSequence = (firstByte > 0xEF) ? 4
1563       : (firstByte > 0xDF) ? 3
1564       : (firstByte > 0xBF) ? 2
1565       : 1
1566
1567     if (i + bytesPerSequence <= end) {
1568       var secondByte, thirdByte, fourthByte, tempCodePoint
1569
1570       switch (bytesPerSequence) {
1571         case 1:
1572           if (firstByte < 0x80) {
1573             codePoint = firstByte
1574           }
1575           break
1576         case 2:
1577           secondByte = buf[i + 1]
1578           if ((secondByte & 0xC0) === 0x80) {
1579             tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1580             if (tempCodePoint > 0x7F) {
1581               codePoint = tempCodePoint
1582             }
1583           }
1584           break
1585         case 3:
1586           secondByte = buf[i + 1]
1587           thirdByte = buf[i + 2]
1588           if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1589             tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1590             if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1591               codePoint = tempCodePoint
1592             }
1593           }
1594           break
1595         case 4:
1596           secondByte = buf[i + 1]
1597           thirdByte = buf[i + 2]
1598           fourthByte = buf[i + 3]
1599           if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1600             tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1601             if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1602               codePoint = tempCodePoint
1603             }
1604           }
1605       }
1606     }
1607
1608     if (codePoint === null) {
1609       // we did not generate a valid codePoint so insert a
1610       // replacement char (U+FFFD) and advance only 1 byte
1611       codePoint = 0xFFFD
1612       bytesPerSequence = 1
1613     } else if (codePoint > 0xFFFF) {
1614       // encode to utf16 (surrogate pair dance)
1615       codePoint -= 0x10000
1616       res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1617       codePoint = 0xDC00 | codePoint & 0x3FF
1618     }
1619
1620     res.push(codePoint)
1621     i += bytesPerSequence
1622   }
1623
1624   return decodeCodePointsArray(res)
1625 }
1626
1627 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1628 // the lowest limit is Chrome, with 0x10000 args.
1629 // We go 1 magnitude less, for safety
1630 var MAX_ARGUMENTS_LENGTH = 0x1000
1631
1632 function decodeCodePointsArray (codePoints) {
1633   var len = codePoints.length
1634   if (len <= MAX_ARGUMENTS_LENGTH) {
1635     return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1636   }
1637
1638   // Decode in chunks to avoid "call stack size exceeded".
1639   var res = ''
1640   var i = 0
1641   while (i < len) {
1642     res += String.fromCharCode.apply(
1643       String,
1644       codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1645     )
1646   }
1647   return res
1648 }
1649
1650 function asciiSlice (buf, start, end) {
1651   var ret = ''
1652   end = Math.min(buf.length, end)
1653
1654   for (var i = start; i < end; ++i) {
1655     ret += String.fromCharCode(buf[i] & 0x7F)
1656   }
1657   return ret
1658 }
1659
1660 function latin1Slice (buf, start, end) {
1661   var ret = ''
1662   end = Math.min(buf.length, end)
1663
1664   for (var i = start; i < end; ++i) {
1665     ret += String.fromCharCode(buf[i])
1666   }
1667   return ret
1668 }
1669
1670 function hexSlice (buf, start, end) {
1671   var len = buf.length
1672
1673   if (!start || start < 0) start = 0
1674   if (!end || end < 0 || end > len) end = len
1675
1676   var out = ''
1677   for (var i = start; i < end; ++i) {
1678     out += toHex(buf[i])
1679   }
1680   return out
1681 }
1682
1683 function utf16leSlice (buf, start, end) {
1684   var bytes = buf.slice(start, end)
1685   var res = ''
1686   for (var i = 0; i < bytes.length; i += 2) {
1687     res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1688   }
1689   return res
1690 }
1691
1692 Buffer.prototype.slice = function slice (start, end) {
1693   var len = this.length
1694   start = ~~start
1695   end = end === undefined ? len : ~~end
1696
1697   if (start < 0) {
1698     start += len
1699     if (start < 0) start = 0
1700   } else if (start > len) {
1701     start = len
1702   }
1703
1704   if (end < 0) {
1705     end += len
1706     if (end < 0) end = 0
1707   } else if (end > len) {
1708     end = len
1709   }
1710
1711   if (end < start) end = start
1712
1713   var newBuf = this.subarray(start, end)
1714   // Return an augmented `Uint8Array` instance
1715   newBuf.__proto__ = Buffer.prototype
1716   return newBuf
1717 }
1718
1719 /*
1720  * Need to make sure that buffer isn't trying to write out of bounds.
1721  */
1722 function checkOffset (offset, ext, length) {
1723   if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1724   if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1725 }
1726
1727 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1728   offset = offset >>> 0
1729   byteLength = byteLength >>> 0
1730   if (!noAssert) checkOffset(offset, byteLength, this.length)
1731
1732   var val = this[offset]
1733   var mul = 1
1734   var i = 0
1735   while (++i < byteLength && (mul *= 0x100)) {
1736     val += this[offset + i] * mul
1737   }
1738
1739   return val
1740 }
1741
1742 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1743   offset = offset >>> 0
1744   byteLength = byteLength >>> 0
1745   if (!noAssert) {
1746     checkOffset(offset, byteLength, this.length)
1747   }
1748
1749   var val = this[offset + --byteLength]
1750   var mul = 1
1751   while (byteLength > 0 && (mul *= 0x100)) {
1752     val += this[offset + --byteLength] * mul
1753   }
1754
1755   return val
1756 }
1757
1758 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1759   offset = offset >>> 0
1760   if (!noAssert) checkOffset(offset, 1, this.length)
1761   return this[offset]
1762 }
1763
1764 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1765   offset = offset >>> 0
1766   if (!noAssert) checkOffset(offset, 2, this.length)
1767   return this[offset] | (this[offset + 1] << 8)
1768 }
1769
1770 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1771   offset = offset >>> 0
1772   if (!noAssert) checkOffset(offset, 2, this.length)
1773   return (this[offset] << 8) | this[offset + 1]
1774 }
1775
1776 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1777   offset = offset >>> 0
1778   if (!noAssert) checkOffset(offset, 4, this.length)
1779
1780   return ((this[offset]) |
1781       (this[offset + 1] << 8) |
1782       (this[offset + 2] << 16)) +
1783       (this[offset + 3] * 0x1000000)
1784 }
1785
1786 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1787   offset = offset >>> 0
1788   if (!noAssert) checkOffset(offset, 4, this.length)
1789
1790   return (this[offset] * 0x1000000) +
1791     ((this[offset + 1] << 16) |
1792     (this[offset + 2] << 8) |
1793     this[offset + 3])
1794 }
1795
1796 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1797   offset = offset >>> 0
1798   byteLength = byteLength >>> 0
1799   if (!noAssert) checkOffset(offset, byteLength, this.length)
1800
1801   var val = this[offset]
1802   var mul = 1
1803   var i = 0
1804   while (++i < byteLength && (mul *= 0x100)) {
1805     val += this[offset + i] * mul
1806   }
1807   mul *= 0x80
1808
1809   if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1810
1811   return val
1812 }
1813
1814 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1815   offset = offset >>> 0
1816   byteLength = byteLength >>> 0
1817   if (!noAssert) checkOffset(offset, byteLength, this.length)
1818
1819   var i = byteLength
1820   var mul = 1
1821   var val = this[offset + --i]
1822   while (i > 0 && (mul *= 0x100)) {
1823     val += this[offset + --i] * mul
1824   }
1825   mul *= 0x80
1826
1827   if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1828
1829   return val
1830 }
1831
1832 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1833   offset = offset >>> 0
1834   if (!noAssert) checkOffset(offset, 1, this.length)
1835   if (!(this[offset] & 0x80)) return (this[offset])
1836   return ((0xff - this[offset] + 1) * -1)
1837 }
1838
1839 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1840   offset = offset >>> 0
1841   if (!noAssert) checkOffset(offset, 2, this.length)
1842   var val = this[offset] | (this[offset + 1] << 8)
1843   return (val & 0x8000) ? val | 0xFFFF0000 : val
1844 }
1845
1846 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1847   offset = offset >>> 0
1848   if (!noAssert) checkOffset(offset, 2, this.length)
1849   var val = this[offset + 1] | (this[offset] << 8)
1850   return (val & 0x8000) ? val | 0xFFFF0000 : val
1851 }
1852
1853 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1854   offset = offset >>> 0
1855   if (!noAssert) checkOffset(offset, 4, this.length)
1856
1857   return (this[offset]) |
1858     (this[offset + 1] << 8) |
1859     (this[offset + 2] << 16) |
1860     (this[offset + 3] << 24)
1861 }
1862
1863 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1864   offset = offset >>> 0
1865   if (!noAssert) checkOffset(offset, 4, this.length)
1866
1867   return (this[offset] << 24) |
1868     (this[offset + 1] << 16) |
1869     (this[offset + 2] << 8) |
1870     (this[offset + 3])
1871 }
1872
1873 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1874   offset = offset >>> 0
1875   if (!noAssert) checkOffset(offset, 4, this.length)
1876   return ieee754.read(this, offset, true, 23, 4)
1877 }
1878
1879 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1880   offset = offset >>> 0
1881   if (!noAssert) checkOffset(offset, 4, this.length)
1882   return ieee754.read(this, offset, false, 23, 4)
1883 }
1884
1885 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1886   offset = offset >>> 0
1887   if (!noAssert) checkOffset(offset, 8, this.length)
1888   return ieee754.read(this, offset, true, 52, 8)
1889 }
1890
1891 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1892   offset = offset >>> 0
1893   if (!noAssert) checkOffset(offset, 8, this.length)
1894   return ieee754.read(this, offset, false, 52, 8)
1895 }
1896
1897 function checkInt (buf, value, offset, ext, max, min) {
1898   if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1899   if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1900   if (offset + ext > buf.length) throw new RangeError('Index out of range')
1901 }
1902
1903 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1904   value = +value
1905   offset = offset >>> 0
1906   byteLength = byteLength >>> 0
1907   if (!noAssert) {
1908     var maxBytes = Math.pow(2, 8 * byteLength) - 1
1909     checkInt(this, value, offset, byteLength, maxBytes, 0)
1910   }
1911
1912   var mul = 1
1913   var i = 0
1914   this[offset] = value & 0xFF
1915   while (++i < byteLength && (mul *= 0x100)) {
1916     this[offset + i] = (value / mul) & 0xFF
1917   }
1918
1919   return offset + byteLength
1920 }
1921
1922 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1923   value = +value
1924   offset = offset >>> 0
1925   byteLength = byteLength >>> 0
1926   if (!noAssert) {
1927     var maxBytes = Math.pow(2, 8 * byteLength) - 1
1928     checkInt(this, value, offset, byteLength, maxBytes, 0)
1929   }
1930
1931   var i = byteLength - 1
1932   var mul = 1
1933   this[offset + i] = value & 0xFF
1934   while (--i >= 0 && (mul *= 0x100)) {
1935     this[offset + i] = (value / mul) & 0xFF
1936   }
1937
1938   return offset + byteLength
1939 }
1940
1941 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1942   value = +value
1943   offset = offset >>> 0
1944   if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1945   this[offset] = (value & 0xff)
1946   return offset + 1
1947 }
1948
1949 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1950   value = +value
1951   offset = offset >>> 0
1952   if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1953   this[offset] = (value & 0xff)
1954   this[offset + 1] = (value >>> 8)
1955   return offset + 2
1956 }
1957
1958 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1959   value = +value
1960   offset = offset >>> 0
1961   if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1962   this[offset] = (value >>> 8)
1963   this[offset + 1] = (value & 0xff)
1964   return offset + 2
1965 }
1966
1967 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1968   value = +value
1969   offset = offset >>> 0
1970   if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1971   this[offset + 3] = (value >>> 24)
1972   this[offset + 2] = (value >>> 16)
1973   this[offset + 1] = (value >>> 8)
1974   this[offset] = (value & 0xff)
1975   return offset + 4
1976 }
1977
1978 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1979   value = +value
1980   offset = offset >>> 0
1981   if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1982   this[offset] = (value >>> 24)
1983   this[offset + 1] = (value >>> 16)
1984   this[offset + 2] = (value >>> 8)
1985   this[offset + 3] = (value & 0xff)
1986   return offset + 4
1987 }
1988
1989 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1990   value = +value
1991   offset = offset >>> 0
1992   if (!noAssert) {
1993     var limit = Math.pow(2, (8 * byteLength) - 1)
1994
1995     checkInt(this, value, offset, byteLength, limit - 1, -limit)
1996   }
1997
1998   var i = 0
1999   var mul = 1
2000   var sub = 0
2001   this[offset] = value & 0xFF
2002   while (++i < byteLength && (mul *= 0x100)) {
2003     if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2004       sub = 1
2005     }
2006     this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2007   }
2008
2009   return offset + byteLength
2010 }
2011
2012 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2013   value = +value
2014   offset = offset >>> 0
2015   if (!noAssert) {
2016     var limit = Math.pow(2, (8 * byteLength) - 1)
2017
2018     checkInt(this, value, offset, byteLength, limit - 1, -limit)
2019   }
2020
2021   var i = byteLength - 1
2022   var mul = 1
2023   var sub = 0
2024   this[offset + i] = value & 0xFF
2025   while (--i >= 0 && (mul *= 0x100)) {
2026     if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2027       sub = 1
2028     }
2029     this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2030   }
2031
2032   return offset + byteLength
2033 }
2034
2035 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2036   value = +value
2037   offset = offset >>> 0
2038   if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2039   if (value < 0) value = 0xff + value + 1
2040   this[offset] = (value & 0xff)
2041   return offset + 1
2042 }
2043
2044 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2045   value = +value
2046   offset = offset >>> 0
2047   if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2048   this[offset] = (value & 0xff)
2049   this[offset + 1] = (value >>> 8)
2050   return offset + 2
2051 }
2052
2053 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2054   value = +value
2055   offset = offset >>> 0
2056   if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2057   this[offset] = (value >>> 8)
2058   this[offset + 1] = (value & 0xff)
2059   return offset + 2
2060 }
2061
2062 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2063   value = +value
2064   offset = offset >>> 0
2065   if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2066   this[offset] = (value & 0xff)
2067   this[offset + 1] = (value >>> 8)
2068   this[offset + 2] = (value >>> 16)
2069   this[offset + 3] = (value >>> 24)
2070   return offset + 4
2071 }
2072
2073 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2074   value = +value
2075   offset = offset >>> 0
2076   if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2077   if (value < 0) value = 0xffffffff + value + 1
2078   this[offset] = (value >>> 24)
2079   this[offset + 1] = (value >>> 16)
2080   this[offset + 2] = (value >>> 8)
2081   this[offset + 3] = (value & 0xff)
2082   return offset + 4
2083 }
2084
2085 function checkIEEE754 (buf, value, offset, ext, max, min) {
2086   if (offset + ext > buf.length) throw new RangeError('Index out of range')
2087   if (offset < 0) throw new RangeError('Index out of range')
2088 }
2089
2090 function writeFloat (buf, value, offset, littleEndian, noAssert) {
2091   value = +value
2092   offset = offset >>> 0
2093   if (!noAssert) {
2094     checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2095   }
2096   ieee754.write(buf, value, offset, littleEndian, 23, 4)
2097   return offset + 4
2098 }
2099
2100 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2101   return writeFloat(this, value, offset, true, noAssert)
2102 }
2103
2104 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2105   return writeFloat(this, value, offset, false, noAssert)
2106 }
2107
2108 function writeDouble (buf, value, offset, littleEndian, noAssert) {
2109   value = +value
2110   offset = offset >>> 0
2111   if (!noAssert) {
2112     checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2113   }
2114   ieee754.write(buf, value, offset, littleEndian, 52, 8)
2115   return offset + 8
2116 }
2117
2118 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2119   return writeDouble(this, value, offset, true, noAssert)
2120 }
2121
2122 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2123   return writeDouble(this, value, offset, false, noAssert)
2124 }
2125
2126 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2127 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2128   if (!start) start = 0
2129   if (!end && end !== 0) end = this.length
2130   if (targetStart >= target.length) targetStart = target.length
2131   if (!targetStart) targetStart = 0
2132   if (end > 0 && end < start) end = start
2133
2134   // Copy 0 bytes; we're done
2135   if (end === start) return 0
2136   if (target.length === 0 || this.length === 0) return 0
2137
2138   // Fatal error conditions
2139   if (targetStart < 0) {
2140     throw new RangeError('targetStart out of bounds')
2141   }
2142   if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2143   if (end < 0) throw new RangeError('sourceEnd out of bounds')
2144
2145   // Are we oob?
2146   if (end > this.length) end = this.length
2147   if (target.length - targetStart < end - start) {
2148     end = target.length - targetStart + start
2149   }
2150
2151   var len = end - start
2152   var i
2153
2154   if (this === target && start < targetStart && targetStart < end) {
2155     // descending copy from end
2156     for (i = len - 1; i >= 0; --i) {
2157       target[i + targetStart] = this[i + start]
2158     }
2159   } else if (len < 1000) {
2160     // ascending copy from start
2161     for (i = 0; i < len; ++i) {
2162       target[i + targetStart] = this[i + start]
2163     }
2164   } else {
2165     Uint8Array.prototype.set.call(
2166       target,
2167       this.subarray(start, start + len),
2168       targetStart
2169     )
2170   }
2171
2172   return len
2173 }
2174
2175 // Usage:
2176 //    buffer.fill(number[, offset[, end]])
2177 //    buffer.fill(buffer[, offset[, end]])
2178 //    buffer.fill(string[, offset[, end]][, encoding])
2179 Buffer.prototype.fill = function fill (val, start, end, encoding) {
2180   // Handle string cases:
2181   if (typeof val === 'string') {
2182     if (typeof start === 'string') {
2183       encoding = start
2184       start = 0
2185       end = this.length
2186     } else if (typeof end === 'string') {
2187       encoding = end
2188       end = this.length
2189     }
2190     if (val.length === 1) {
2191       var code = val.charCodeAt(0)
2192       if (code < 256) {
2193         val = code
2194       }
2195     }
2196     if (encoding !== undefined && typeof encoding !== 'string') {
2197       throw new TypeError('encoding must be a string')
2198     }
2199     if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2200       throw new TypeError('Unknown encoding: ' + encoding)
2201     }
2202   } else if (typeof val === 'number') {
2203     val = val & 255
2204   }
2205
2206   // Invalid ranges are not set to a default, so can range check early.
2207   if (start < 0 || this.length < start || this.length < end) {
2208     throw new RangeError('Out of range index')
2209   }
2210
2211   if (end <= start) {
2212     return this
2213   }
2214
2215   start = start >>> 0
2216   end = end === undefined ? this.length : end >>> 0
2217
2218   if (!val) val = 0
2219
2220   var i
2221   if (typeof val === 'number') {
2222     for (i = start; i < end; ++i) {
2223       this[i] = val
2224     }
2225   } else {
2226     var bytes = Buffer.isBuffer(val)
2227       ? val
2228       : new Buffer(val, encoding)
2229     var len = bytes.length
2230     for (i = 0; i < end - start; ++i) {
2231       this[i + start] = bytes[i % len]
2232     }
2233   }
2234
2235   return this
2236 }
2237
2238 // HELPER FUNCTIONS
2239 // ================
2240
2241 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2242
2243 function base64clean (str) {
2244   // Node strips out invalid characters like \n and \t from the string, base64-js does not
2245   str = str.trim().replace(INVALID_BASE64_RE, '')
2246   // Node converts strings with length < 2 to ''
2247   if (str.length < 2) return ''
2248   // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2249   while (str.length % 4 !== 0) {
2250     str = str + '='
2251   }
2252   return str
2253 }
2254
2255 function toHex (n) {
2256   if (n < 16) return '0' + n.toString(16)
2257   return n.toString(16)
2258 }
2259
2260 function utf8ToBytes (string, units) {
2261   units = units || Infinity
2262   var codePoint
2263   var length = string.length
2264   var leadSurrogate = null
2265   var bytes = []
2266
2267   for (var i = 0; i < length; ++i) {
2268     codePoint = string.charCodeAt(i)
2269
2270     // is surrogate component
2271     if (codePoint > 0xD7FF && codePoint < 0xE000) {
2272       // last char was a lead
2273       if (!leadSurrogate) {
2274         // no lead yet
2275         if (codePoint > 0xDBFF) {
2276           // unexpected trail
2277           if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2278           continue
2279         } else if (i + 1 === length) {
2280           // unpaired lead
2281           if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2282           continue
2283         }
2284
2285         // valid lead
2286         leadSurrogate = codePoint
2287
2288         continue
2289       }
2290
2291       // 2 leads in a row
2292       if (codePoint < 0xDC00) {
2293         if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2294         leadSurrogate = codePoint
2295         continue
2296       }
2297
2298       // valid surrogate pair
2299       codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2300     } else if (leadSurrogate) {
2301       // valid bmp char, but last char was a lead
2302       if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2303     }
2304
2305     leadSurrogate = null
2306
2307     // encode utf8
2308     if (codePoint < 0x80) {
2309       if ((units -= 1) < 0) break
2310       bytes.push(codePoint)
2311     } else if (codePoint < 0x800) {
2312       if ((units -= 2) < 0) break
2313       bytes.push(
2314         codePoint >> 0x6 | 0xC0,
2315         codePoint & 0x3F | 0x80
2316       )
2317     } else if (codePoint < 0x10000) {
2318       if ((units -= 3) < 0) break
2319       bytes.push(
2320         codePoint >> 0xC | 0xE0,
2321         codePoint >> 0x6 & 0x3F | 0x80,
2322         codePoint & 0x3F | 0x80
2323       )
2324     } else if (codePoint < 0x110000) {
2325       if ((units -= 4) < 0) break
2326       bytes.push(
2327         codePoint >> 0x12 | 0xF0,
2328         codePoint >> 0xC & 0x3F | 0x80,
2329         codePoint >> 0x6 & 0x3F | 0x80,
2330         codePoint & 0x3F | 0x80
2331       )
2332     } else {
2333       throw new Error('Invalid code point')
2334     }
2335   }
2336
2337   return bytes
2338 }
2339
2340 function asciiToBytes (str) {
2341   var byteArray = []
2342   for (var i = 0; i < str.length; ++i) {
2343     // Node's code seems to be doing this and not & 0x7F..
2344     byteArray.push(str.charCodeAt(i) & 0xFF)
2345   }
2346   return byteArray
2347 }
2348
2349 function utf16leToBytes (str, units) {
2350   var c, hi, lo
2351   var byteArray = []
2352   for (var i = 0; i < str.length; ++i) {
2353     if ((units -= 2) < 0) break
2354
2355     c = str.charCodeAt(i)
2356     hi = c >> 8
2357     lo = c % 256
2358     byteArray.push(lo)
2359     byteArray.push(hi)
2360   }
2361
2362   return byteArray
2363 }
2364
2365 function base64ToBytes (str) {
2366   return base64.toByteArray(base64clean(str))
2367 }
2368
2369 function blitBuffer (src, dst, offset, length) {
2370   for (var i = 0; i < length; ++i) {
2371     if ((i + offset >= dst.length) || (i >= src.length)) break
2372     dst[i + offset] = src[i]
2373   }
2374   return i
2375 }
2376
2377 // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
2378 // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
2379 function isArrayBuffer (obj) {
2380   return obj instanceof ArrayBuffer ||
2381     (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
2382       typeof obj.byteLength === 'number')
2383 }
2384
2385 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2386 function isArrayBufferView (obj) {
2387   return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2388 }
2389
2390 function numberIsNaN (obj) {
2391   return obj !== obj // eslint-disable-line no-self-compare
2392 }
2393
2394 },{"base64-js":3,"ieee754":17}],8:[function(require,module,exports){
2395 'use strict';
2396
2397 module.exports = earcut;
2398 module.exports.default = earcut;
2399
2400 function earcut(data, holeIndices, dim) {
2401
2402     dim = dim || 2;
2403
2404     var hasHoles = holeIndices && holeIndices.length,
2405         outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2406         outerNode = linkedList(data, 0, outerLen, dim, true),
2407         triangles = [];
2408
2409     if (!outerNode) return triangles;
2410
2411     var minX, minY, maxX, maxY, x, y, invSize;
2412
2413     if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2414
2415     // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2416     if (data.length > 80 * dim) {
2417         minX = maxX = data[0];
2418         minY = maxY = data[1];
2419
2420         for (var i = dim; i < outerLen; i += dim) {
2421             x = data[i];
2422             y = data[i + 1];
2423             if (x < minX) minX = x;
2424             if (y < minY) minY = y;
2425             if (x > maxX) maxX = x;
2426             if (y > maxY) maxY = y;
2427         }
2428
2429         // minX, minY and invSize are later used to transform coords into integers for z-order calculation
2430         invSize = Math.max(maxX - minX, maxY - minY);
2431         invSize = invSize !== 0 ? 1 / invSize : 0;
2432     }
2433
2434     earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
2435
2436     return triangles;
2437 }
2438
2439 // create a circular doubly linked list from polygon points in the specified winding order
2440 function linkedList(data, start, end, dim, clockwise) {
2441     var i, last;
2442
2443     if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2444         for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2445     } else {
2446         for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2447     }
2448
2449     if (last && equals(last, last.next)) {
2450         removeNode(last);
2451         last = last.next;
2452     }
2453
2454     return last;
2455 }
2456
2457 // eliminate colinear or duplicate points
2458 function filterPoints(start, end) {
2459     if (!start) return start;
2460     if (!end) end = start;
2461
2462     var p = start,
2463         again;
2464     do {
2465         again = false;
2466
2467         if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2468             removeNode(p);
2469             p = end = p.prev;
2470             if (p === p.next) break;
2471             again = true;
2472
2473         } else {
2474             p = p.next;
2475         }
2476     } while (again || p !== end);
2477
2478     return end;
2479 }
2480
2481 // main ear slicing loop which triangulates a polygon (given as a linked list)
2482 function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
2483     if (!ear) return;
2484
2485     // interlink polygon nodes in z-order
2486     if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
2487
2488     var stop = ear,
2489         prev, next;
2490
2491     // iterate through ears, slicing them one by one
2492     while (ear.prev !== ear.next) {
2493         prev = ear.prev;
2494         next = ear.next;
2495
2496         if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
2497             // cut off the triangle
2498             triangles.push(prev.i / dim);
2499             triangles.push(ear.i / dim);
2500             triangles.push(next.i / dim);
2501
2502             removeNode(ear);
2503
2504             // skipping the next vertice leads to less sliver triangles
2505             ear = next.next;
2506             stop = next.next;
2507
2508             continue;
2509         }
2510
2511         ear = next;
2512
2513         // if we looped through the whole remaining polygon and can't find any more ears
2514         if (ear === stop) {
2515             // try filtering points and slicing again
2516             if (!pass) {
2517                 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
2518
2519             // if this didn't work, try curing all small self-intersections locally
2520             } else if (pass === 1) {
2521                 ear = cureLocalIntersections(ear, triangles, dim);
2522                 earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
2523
2524             // as a last resort, try splitting the remaining polygon into two
2525             } else if (pass === 2) {
2526                 splitEarcut(ear, triangles, dim, minX, minY, invSize);
2527             }
2528
2529             break;
2530         }
2531     }
2532 }
2533
2534 // check whether a polygon node forms a valid ear with adjacent nodes
2535 function isEar(ear) {
2536     var a = ear.prev,
2537         b = ear,
2538         c = ear.next;
2539
2540     if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2541
2542     // now make sure we don't have other points inside the potential ear
2543     var p = ear.next.next;
2544
2545     while (p !== ear.prev) {
2546         if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2547             area(p.prev, p, p.next) >= 0) return false;
2548         p = p.next;
2549     }
2550
2551     return true;
2552 }
2553
2554 function isEarHashed(ear, minX, minY, invSize) {
2555     var a = ear.prev,
2556         b = ear,
2557         c = ear.next;
2558
2559     if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2560
2561     // triangle bbox; min & max are calculated like this for speed
2562     var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2563         minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2564         maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2565         maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2566
2567     // z-order range for the current triangle bbox;
2568     var minZ = zOrder(minTX, minTY, minX, minY, invSize),
2569         maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
2570
2571     var p = ear.prevZ,
2572         n = ear.nextZ;
2573
2574     // look for points inside the triangle in both directions
2575     while (p && p.z >= minZ && n && n.z <= maxZ) {
2576         if (p !== ear.prev && p !== ear.next &&
2577             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2578             area(p.prev, p, p.next) >= 0) return false;
2579         p = p.prevZ;
2580
2581         if (n !== ear.prev && n !== ear.next &&
2582             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
2583             area(n.prev, n, n.next) >= 0) return false;
2584         n = n.nextZ;
2585     }
2586
2587     // look for remaining points in decreasing z-order
2588     while (p && p.z >= minZ) {
2589         if (p !== ear.prev && p !== ear.next &&
2590             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2591             area(p.prev, p, p.next) >= 0) return false;
2592         p = p.prevZ;
2593     }
2594
2595     // look for remaining points in increasing z-order
2596     while (n && n.z <= maxZ) {
2597         if (n !== ear.prev && n !== ear.next &&
2598             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
2599             area(n.prev, n, n.next) >= 0) return false;
2600         n = n.nextZ;
2601     }
2602
2603     return true;
2604 }
2605
2606 // go through all polygon nodes and cure small local self-intersections
2607 function cureLocalIntersections(start, triangles, dim) {
2608     var p = start;
2609     do {
2610         var a = p.prev,
2611             b = p.next.next;
2612
2613         if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2614
2615             triangles.push(a.i / dim);
2616             triangles.push(p.i / dim);
2617             triangles.push(b.i / dim);
2618
2619             // remove two nodes involved
2620             removeNode(p);
2621             removeNode(p.next);
2622
2623             p = start = b;
2624         }
2625         p = p.next;
2626     } while (p !== start);
2627
2628     return p;
2629 }
2630
2631 // try splitting polygon into two and triangulate them independently
2632 function splitEarcut(start, triangles, dim, minX, minY, invSize) {
2633     // look for a valid diagonal that divides the polygon into two
2634     var a = start;
2635     do {
2636         var b = a.next.next;
2637         while (b !== a.prev) {
2638             if (a.i !== b.i && isValidDiagonal(a, b)) {
2639                 // split the polygon in two by the diagonal
2640                 var c = splitPolygon(a, b);
2641
2642                 // filter colinear points around the cuts
2643                 a = filterPoints(a, a.next);
2644                 c = filterPoints(c, c.next);
2645
2646                 // run earcut on each half
2647                 earcutLinked(a, triangles, dim, minX, minY, invSize);
2648                 earcutLinked(c, triangles, dim, minX, minY, invSize);
2649                 return;
2650             }
2651             b = b.next;
2652         }
2653         a = a.next;
2654     } while (a !== start);
2655 }
2656
2657 // link every hole into the outer loop, producing a single-ring polygon without holes
2658 function eliminateHoles(data, holeIndices, outerNode, dim) {
2659     var queue = [],
2660         i, len, start, end, list;
2661
2662     for (i = 0, len = holeIndices.length; i < len; i++) {
2663         start = holeIndices[i] * dim;
2664         end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2665         list = linkedList(data, start, end, dim, false);
2666         if (list === list.next) list.steiner = true;
2667         queue.push(getLeftmost(list));
2668     }
2669
2670     queue.sort(compareX);
2671
2672     // process holes from left to right
2673     for (i = 0; i < queue.length; i++) {
2674         eliminateHole(queue[i], outerNode);
2675         outerNode = filterPoints(outerNode, outerNode.next);
2676     }
2677
2678     return outerNode;
2679 }
2680
2681 function compareX(a, b) {
2682     return a.x - b.x;
2683 }
2684
2685 // find a bridge between vertices that connects hole with an outer ring and and link it
2686 function eliminateHole(hole, outerNode) {
2687     outerNode = findHoleBridge(hole, outerNode);
2688     if (outerNode) {
2689         var b = splitPolygon(outerNode, hole);
2690         filterPoints(b, b.next);
2691     }
2692 }
2693
2694 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2695 function findHoleBridge(hole, outerNode) {
2696     var p = outerNode,
2697         hx = hole.x,
2698         hy = hole.y,
2699         qx = -Infinity,
2700         m;
2701
2702     // find a segment intersected by a ray from the hole's leftmost point to the left;
2703     // segment's endpoint with lesser x will be potential connection point
2704     do {
2705         if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
2706             var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2707             if (x <= hx && x > qx) {
2708                 qx = x;
2709                 if (x === hx) {
2710                     if (hy === p.y) return p;
2711                     if (hy === p.next.y) return p.next;
2712                 }
2713                 m = p.x < p.next.x ? p : p.next;
2714             }
2715         }
2716         p = p.next;
2717     } while (p !== outerNode);
2718
2719     if (!m) return null;
2720
2721     if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2722
2723     // look for points inside the triangle of hole point, segment intersection and endpoint;
2724     // if there are no points found, we have a valid connection;
2725     // otherwise choose the point of the minimum angle with the ray as connection point
2726
2727     var stop = m,
2728         mx = m.x,
2729         my = m.y,
2730         tanMin = Infinity,
2731         tan;
2732
2733     p = m.next;
2734
2735     while (p !== stop) {
2736         if (hx >= p.x && p.x >= mx && hx !== p.x &&
2737                 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2738
2739             tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2740
2741             if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2742                 m = p;
2743                 tanMin = tan;
2744             }
2745         }
2746
2747         p = p.next;
2748     }
2749
2750     return m;
2751 }
2752
2753 // interlink polygon nodes in z-order
2754 function indexCurve(start, minX, minY, invSize) {
2755     var p = start;
2756     do {
2757         if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
2758         p.prevZ = p.prev;
2759         p.nextZ = p.next;
2760         p = p.next;
2761     } while (p !== start);
2762
2763     p.prevZ.nextZ = null;
2764     p.prevZ = null;
2765
2766     sortLinked(p);
2767 }
2768
2769 // Simon Tatham's linked list merge sort algorithm
2770 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2771 function sortLinked(list) {
2772     var i, p, q, e, tail, numMerges, pSize, qSize,
2773         inSize = 1;
2774
2775     do {
2776         p = list;
2777         list = null;
2778         tail = null;
2779         numMerges = 0;
2780
2781         while (p) {
2782             numMerges++;
2783             q = p;
2784             pSize = 0;
2785             for (i = 0; i < inSize; i++) {
2786                 pSize++;
2787                 q = q.nextZ;
2788                 if (!q) break;
2789             }
2790             qSize = inSize;
2791
2792             while (pSize > 0 || (qSize > 0 && q)) {
2793
2794                 if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
2795                     e = p;
2796                     p = p.nextZ;
2797                     pSize--;
2798                 } else {
2799                     e = q;
2800                     q = q.nextZ;
2801                     qSize--;
2802                 }
2803
2804                 if (tail) tail.nextZ = e;
2805                 else list = e;
2806
2807                 e.prevZ = tail;
2808                 tail = e;
2809             }
2810
2811             p = q;
2812         }
2813
2814         tail.nextZ = null;
2815         inSize *= 2;
2816
2817     } while (numMerges > 1);
2818
2819     return list;
2820 }
2821
2822 // z-order of a point given coords and inverse of the longer side of data bbox
2823 function zOrder(x, y, minX, minY, invSize) {
2824     // coords are transformed into non-negative 15-bit integer range
2825     x = 32767 * (x - minX) * invSize;
2826     y = 32767 * (y - minY) * invSize;
2827
2828     x = (x | (x << 8)) & 0x00FF00FF;
2829     x = (x | (x << 4)) & 0x0F0F0F0F;
2830     x = (x | (x << 2)) & 0x33333333;
2831     x = (x | (x << 1)) & 0x55555555;
2832
2833     y = (y | (y << 8)) & 0x00FF00FF;
2834     y = (y | (y << 4)) & 0x0F0F0F0F;
2835     y = (y | (y << 2)) & 0x33333333;
2836     y = (y | (y << 1)) & 0x55555555;
2837
2838     return x | (y << 1);
2839 }
2840
2841 // find the leftmost node of a polygon ring
2842 function getLeftmost(start) {
2843     var p = start,
2844         leftmost = start;
2845     do {
2846         if (p.x < leftmost.x) leftmost = p;
2847         p = p.next;
2848     } while (p !== start);
2849
2850     return leftmost;
2851 }
2852
2853 // check if a point lies within a convex triangle
2854 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2855     return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2856            (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2857            (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2858 }
2859
2860 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2861 function isValidDiagonal(a, b) {
2862     return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2863            locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2864 }
2865
2866 // signed area of a triangle
2867 function area(p, q, r) {
2868     return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2869 }
2870
2871 // check if two points are equal
2872 function equals(p1, p2) {
2873     return p1.x === p2.x && p1.y === p2.y;
2874 }
2875
2876 // check if two segments intersect
2877 function intersects(p1, q1, p2, q2) {
2878     if ((equals(p1, q1) && equals(p2, q2)) ||
2879         (equals(p1, q2) && equals(p2, q1))) return true;
2880     return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2881            area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2882 }
2883
2884 // check if a polygon diagonal intersects any polygon segments
2885 function intersectsPolygon(a, b) {
2886     var p = a;
2887     do {
2888         if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2889                 intersects(p, p.next, a, b)) return true;
2890         p = p.next;
2891     } while (p !== a);
2892
2893     return false;
2894 }
2895
2896 // check if a polygon diagonal is locally inside the polygon
2897 function locallyInside(a, b) {
2898     return area(a.prev, a, a.next) < 0 ?
2899         area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2900         area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2901 }
2902
2903 // check if the middle point of a polygon diagonal is inside the polygon
2904 function middleInside(a, b) {
2905     var p = a,
2906         inside = false,
2907         px = (a.x + b.x) / 2,
2908         py = (a.y + b.y) / 2;
2909     do {
2910         if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
2911                 (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2912             inside = !inside;
2913         p = p.next;
2914     } while (p !== a);
2915
2916     return inside;
2917 }
2918
2919 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2920 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2921 function splitPolygon(a, b) {
2922     var a2 = new Node(a.i, a.x, a.y),
2923         b2 = new Node(b.i, b.x, b.y),
2924         an = a.next,
2925         bp = b.prev;
2926
2927     a.next = b;
2928     b.prev = a;
2929
2930     a2.next = an;
2931     an.prev = a2;
2932
2933     b2.next = a2;
2934     a2.prev = b2;
2935
2936     bp.next = b2;
2937     b2.prev = bp;
2938
2939     return b2;
2940 }
2941
2942 // create a node and optionally link it with previous one (in a circular doubly linked list)
2943 function insertNode(i, x, y, last) {
2944     var p = new Node(i, x, y);
2945
2946     if (!last) {
2947         p.prev = p;
2948         p.next = p;
2949
2950     } else {
2951         p.next = last.next;
2952         p.prev = last;
2953         last.next.prev = p;
2954         last.next = p;
2955     }
2956     return p;
2957 }
2958
2959 function removeNode(p) {
2960     p.next.prev = p.prev;
2961     p.prev.next = p.next;
2962
2963     if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2964     if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2965 }
2966
2967 function Node(i, x, y) {
2968     // vertice index in coordinates array
2969     this.i = i;
2970
2971     // vertex coordinates
2972     this.x = x;
2973     this.y = y;
2974
2975     // previous and next vertice nodes in a polygon ring
2976     this.prev = null;
2977     this.next = null;
2978
2979     // z-order curve value
2980     this.z = null;
2981
2982     // previous and next nodes in z-order
2983     this.prevZ = null;
2984     this.nextZ = null;
2985
2986     // indicates whether this is a steiner point
2987     this.steiner = false;
2988 }
2989
2990 // return a percentage difference between the polygon area and its triangulation area;
2991 // used to verify correctness of triangulation
2992 earcut.deviation = function (data, holeIndices, dim, triangles) {
2993     var hasHoles = holeIndices && holeIndices.length;
2994     var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2995
2996     var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2997     if (hasHoles) {
2998         for (var i = 0, len = holeIndices.length; i < len; i++) {
2999             var start = holeIndices[i] * dim;
3000             var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
3001             polygonArea -= Math.abs(signedArea(data, start, end, dim));
3002         }
3003     }
3004
3005     var trianglesArea = 0;
3006     for (i = 0; i < triangles.length; i += 3) {
3007         var a = triangles[i] * dim;
3008         var b = triangles[i + 1] * dim;
3009         var c = triangles[i + 2] * dim;
3010         trianglesArea += Math.abs(
3011             (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
3012             (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
3013     }
3014
3015     return polygonArea === 0 && trianglesArea === 0 ? 0 :
3016         Math.abs((trianglesArea - polygonArea) / polygonArea);
3017 };
3018
3019 function signedArea(data, start, end, dim) {
3020     var sum = 0;
3021     for (var i = start, j = end - dim; i < end; i += dim) {
3022         sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
3023         j = i;
3024     }
3025     return sum;
3026 }
3027
3028 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
3029 earcut.flatten = function (data) {
3030     var dim = data[0][0].length,
3031         result = {vertices: [], holes: [], dimensions: dim},
3032         holeIndex = 0;
3033
3034     for (var i = 0; i < data.length; i++) {
3035         for (var j = 0; j < data[i].length; j++) {
3036             for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
3037         }
3038         if (i > 0) {
3039             holeIndex += data[i - 1].length;
3040             result.holes.push(holeIndex);
3041         }
3042     }
3043     return result;
3044 };
3045
3046 },{}],9:[function(require,module,exports){
3047 'use strict';
3048
3049 var OneVersionConstraint = require('individual/one-version');
3050
3051 var MY_VERSION = '7';
3052 OneVersionConstraint('ev-store', MY_VERSION);
3053
3054 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
3055
3056 module.exports = EvStore;
3057
3058 function EvStore(elem) {
3059     var hash = elem[hashKey];
3060
3061     if (!hash) {
3062         hash = elem[hashKey] = {};
3063     }
3064
3065     return hash;
3066 }
3067
3068 },{"individual/one-version":19}],10:[function(require,module,exports){
3069 'use strict';
3070 var request = require('./request');
3071 var buildQueryObject = require('./buildQueryObject');
3072 var isArray = Array.isArray;
3073
3074 function simpleExtend(obj, obj2) {
3075   var prop;
3076   for (prop in obj2) {
3077     obj[prop] = obj2[prop];
3078   }
3079   return obj;
3080 }
3081
3082 function XMLHttpSource(jsongUrl, config) {
3083   this._jsongUrl = jsongUrl;
3084   if (typeof config === 'number') {
3085     var newConfig = {
3086       timeout: config
3087     };
3088     config = newConfig;
3089   }
3090   this._config = simpleExtend({
3091     timeout: 15000,
3092     headers: {}
3093   }, config || {});
3094 }
3095
3096 XMLHttpSource.prototype = {
3097   // because javascript
3098   constructor: XMLHttpSource,
3099   /**
3100    * buildQueryObject helper
3101    */
3102   buildQueryObject: buildQueryObject,
3103
3104   /**
3105    * @inheritDoc DataSource#get
3106    */
3107   get: function httpSourceGet(pathSet) {
3108     var method = 'GET';
3109     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3110       paths: pathSet,
3111       method: 'get'
3112     });
3113     var config = simpleExtend(queryObject, this._config);
3114     // pass context for onBeforeRequest callback
3115     var context = this;
3116     return request(method, config, context);
3117   },
3118
3119   /**
3120    * @inheritDoc DataSource#set
3121    */
3122   set: function httpSourceSet(jsongEnv) {
3123     var method = 'POST';
3124     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3125       jsonGraph: jsongEnv,
3126       method: 'set'
3127     });
3128     var config = simpleExtend(queryObject, this._config);
3129     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3130     
3131     // pass context for onBeforeRequest callback
3132     var context = this;
3133     return request(method, config, context);
3134
3135   },
3136
3137   /**
3138    * @inheritDoc DataSource#call
3139    */
3140   call: function httpSourceCall(callPath, args, pathSuffix, paths) {
3141     // arguments defaults
3142     args = args || [];
3143     pathSuffix = pathSuffix || [];
3144     paths = paths || [];
3145
3146     var method = 'POST';
3147     var queryData = [];
3148     queryData.push('method=call');
3149     queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
3150     queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
3151     queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
3152     queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
3153
3154     var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
3155     var config = simpleExtend(queryObject, this._config);
3156     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3157     
3158     // pass context for onBeforeRequest callback
3159     var context = this;
3160     return request(method, config, context);
3161   }
3162 };
3163 // ES6 modules
3164 XMLHttpSource.XMLHttpSource = XMLHttpSource;
3165 XMLHttpSource['default'] = XMLHttpSource;
3166 // commonjs
3167 module.exports = XMLHttpSource;
3168
3169 },{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){
3170 'use strict';
3171 module.exports = function buildQueryObject(url, method, queryData) {
3172   var qData = [];
3173   var keys;
3174   var data = {url: url};
3175   var isQueryParamUrl = url.indexOf('?') !== -1;
3176   var startUrl = (isQueryParamUrl) ? '&' : '?';
3177
3178   if (typeof queryData === 'string') {
3179     qData.push(queryData);
3180   } else {
3181
3182     keys = Object.keys(queryData);
3183     keys.forEach(function (k) {
3184       var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
3185       qData.push(k + '=' + encodeURIComponent(value));
3186     });
3187   }
3188
3189   if (method === 'GET') {
3190     data.url += startUrl + qData.join('&');
3191   } else {
3192     data.data = qData.join('&');
3193   }
3194
3195   return data;
3196 };
3197
3198 },{}],12:[function(require,module,exports){
3199 (function (global){
3200 'use strict';
3201 // Get CORS support even for older IE
3202 module.exports = function getCORSRequest() {
3203     var xhr = new global.XMLHttpRequest();
3204     if ('withCredentials' in xhr) {
3205         return xhr;
3206     } else if (!!global.XDomainRequest) {
3207         return new XDomainRequest();
3208     } else {
3209         throw new Error('CORS is not supported by your browser');
3210     }
3211 };
3212
3213 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3214
3215 },{}],13:[function(require,module,exports){
3216 (function (global){
3217 'use strict';
3218 module.exports = function getXMLHttpRequest() {
3219   var progId,
3220     progIds,
3221     i;
3222   if (global.XMLHttpRequest) {
3223     return new global.XMLHttpRequest();
3224   } else {
3225     try {
3226     progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3227     for (i = 0; i < 3; i++) {
3228       try {
3229         progId = progIds[i];
3230         if (new global.ActiveXObject(progId)) {
3231           break;
3232         }
3233       } catch(e) { }
3234     }
3235     return new global.ActiveXObject(progId);
3236     } catch (e) {
3237     throw new Error('XMLHttpRequest is not supported by your browser');
3238     }
3239   }
3240 };
3241
3242 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3243
3244 },{}],14:[function(require,module,exports){
3245 'use strict';
3246 var getXMLHttpRequest = require('./getXMLHttpRequest');
3247 var getCORSRequest = require('./getCORSRequest');
3248 var hasOwnProp = Object.prototype.hasOwnProperty;
3249
3250 var noop = function() {};
3251
3252 function Observable() {}
3253
3254 Observable.create = function(subscribe) {
3255   var o = new Observable();
3256
3257   o.subscribe = function(onNext, onError, onCompleted) {
3258
3259     var observer;
3260     var disposable;
3261
3262     if (typeof onNext === 'function') {
3263         observer = {
3264             onNext: onNext,
3265             onError: (onError || noop),
3266             onCompleted: (onCompleted || noop)
3267         };
3268     } else {
3269         observer = onNext;
3270     }
3271
3272     disposable = subscribe(observer);
3273
3274     if (typeof disposable === 'function') {
3275       return {
3276         dispose: disposable
3277       };
3278     } else {
3279       return disposable;
3280     }
3281   };
3282
3283   return o;
3284 };
3285
3286 function request(method, options, context) {
3287   return Observable.create(function requestObserver(observer) {
3288
3289     var config = {
3290       method: method || 'GET',
3291       crossDomain: false,
3292       async: true,
3293       headers: {},
3294       responseType: 'json'
3295     };
3296
3297     var xhr,
3298       isDone,
3299       headers,
3300       header,
3301       prop;
3302
3303     for (prop in options) {
3304       if (hasOwnProp.call(options, prop)) {
3305         config[prop] = options[prop];
3306       }
3307     }
3308
3309     // Add request with Headers
3310     if (!config.crossDomain && !config.headers['X-Requested-With']) {
3311       config.headers['X-Requested-With'] = 'XMLHttpRequest';
3312     }
3313
3314     // allow the user to mutate the config open
3315     if (context.onBeforeRequest != null) {
3316       context.onBeforeRequest(config);
3317     }
3318
3319     // create xhr
3320     try {
3321       xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3322     } catch (err) {
3323       observer.onError(err);
3324     }
3325     try {
3326       // Takes the url and opens the connection
3327       if (config.user) {
3328         xhr.open(config.method, config.url, config.async, config.user, config.password);
3329       } else {
3330         xhr.open(config.method, config.url, config.async);
3331       }
3332
3333       // Sets timeout information
3334       xhr.timeout = config.timeout;
3335
3336       // Anything but explicit false results in true.
3337       xhr.withCredentials = config.withCredentials !== false;
3338
3339       // Fills the request headers
3340       headers = config.headers;
3341       for (header in headers) {
3342         if (hasOwnProp.call(headers, header)) {
3343           xhr.setRequestHeader(header, headers[header]);
3344         }
3345       }
3346
3347       if (config.responseType) {
3348         try {
3349           xhr.responseType = config.responseType;
3350         } catch (e) {
3351           // WebKit added support for the json responseType value on 09/03/2013
3352           // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3353           // known to throw when setting the value "json" as the response type. Other older
3354           // browsers implementing the responseType
3355           //
3356           // The json response type can be ignored if not supported, because JSON payloads are
3357           // parsed on the client-side regardless.
3358           if (config.responseType !== 'json') {
3359             throw e;
3360           }
3361         }
3362       }
3363
3364       xhr.onreadystatechange = function onreadystatechange(e) {
3365         // Complete
3366         if (xhr.readyState === 4) {
3367           if (!isDone) {
3368             isDone = true;
3369             onXhrLoad(observer, xhr, e);
3370           }
3371         }
3372       };
3373
3374       // Timeout
3375       xhr.ontimeout = function ontimeout(e) {
3376         if (!isDone) {
3377           isDone = true;
3378           onXhrError(observer, xhr, 'timeout error', e);
3379         }
3380       };
3381
3382       // Send Request
3383       xhr.send(config.data);
3384
3385     } catch (e) {
3386       observer.onError(e);
3387     }
3388     // Dispose
3389     return function dispose() {
3390       // Doesn't work in IE9
3391       if (!isDone && xhr.readyState !== 4) {
3392         isDone = true;
3393         xhr.abort();
3394       }
3395     };//Dispose
3396   });
3397 }
3398
3399 /*
3400  * General handling of ultimate failure (after appropriate retries)
3401  */
3402 function _handleXhrError(observer, textStatus, errorThrown) {
3403   // IE9: cross-domain request may be considered errors
3404   if (!errorThrown) {
3405     errorThrown = new Error(textStatus);
3406   }
3407
3408   observer.onError(errorThrown);
3409 }
3410
3411 function onXhrLoad(observer, xhr, e) {
3412   var responseData,
3413     responseObject,
3414     responseType;
3415
3416   // If there's no observer, the request has been (or is being) cancelled.
3417   if (xhr && observer) {
3418     responseType = xhr.responseType;
3419     // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3420     // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3421     responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3422
3423     // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3424     var status = (xhr.status === 1223) ? 204 : xhr.status;
3425
3426     if (status >= 200 && status <= 399) {
3427       try {
3428         if (responseType !== 'json') {
3429           responseData = JSON.parse(responseData || '');
3430         }
3431         if (typeof responseData === 'string') {
3432           responseData = JSON.parse(responseData || '');
3433         }
3434       } catch (e) {
3435         _handleXhrError(observer, 'invalid json', e);
3436       }
3437       observer.onNext(responseData);
3438       observer.onCompleted();
3439       return;
3440
3441     } else if (status === 401 || status === 403 || status === 407) {
3442
3443       return _handleXhrError(observer, responseData);
3444
3445     } else if (status === 410) {
3446       // TODO: Retry ?
3447       return _handleXhrError(observer, responseData);
3448
3449     } else if (status === 408 || status === 504) {
3450       // TODO: Retry ?
3451       return _handleXhrError(observer, responseData);
3452
3453     } else {
3454
3455       return _handleXhrError(observer, responseData || ('Response code ' + status));
3456
3457     }//if
3458   }//if
3459 }//onXhrLoad
3460
3461 function onXhrError(observer, xhr, status, e) {
3462   _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3463 }
3464
3465 module.exports = request;
3466
3467 },{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){
3468 (function (global){
3469 !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(){
3470 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);
3471 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(){
3472 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(){
3473 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)});
3474 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3475
3476 },{}],16:[function(require,module,exports){
3477 (function (global){
3478 var topLevel = typeof global !== 'undefined' ? global :
3479     typeof window !== 'undefined' ? window : {}
3480 var minDoc = require('min-document');
3481
3482 var doccy;
3483
3484 if (typeof document !== 'undefined') {
3485     doccy = document;
3486 } else {
3487     doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3488
3489     if (!doccy) {
3490         doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3491     }
3492 }
3493
3494 module.exports = doccy;
3495
3496 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3497
3498 },{"min-document":4}],17:[function(require,module,exports){
3499 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3500   var e, m
3501   var eLen = nBytes * 8 - mLen - 1
3502   var eMax = (1 << eLen) - 1
3503   var eBias = eMax >> 1
3504   var nBits = -7
3505   var i = isLE ? (nBytes - 1) : 0
3506   var d = isLE ? -1 : 1
3507   var s = buffer[offset + i]
3508
3509   i += d
3510
3511   e = s & ((1 << (-nBits)) - 1)
3512   s >>= (-nBits)
3513   nBits += eLen
3514   for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3515
3516   m = e & ((1 << (-nBits)) - 1)
3517   e >>= (-nBits)
3518   nBits += mLen
3519   for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3520
3521   if (e === 0) {
3522     e = 1 - eBias
3523   } else if (e === eMax) {
3524     return m ? NaN : ((s ? -1 : 1) * Infinity)
3525   } else {
3526     m = m + Math.pow(2, mLen)
3527     e = e - eBias
3528   }
3529   return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3530 }
3531
3532 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3533   var e, m, c
3534   var eLen = nBytes * 8 - mLen - 1
3535   var eMax = (1 << eLen) - 1
3536   var eBias = eMax >> 1
3537   var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3538   var i = isLE ? 0 : (nBytes - 1)
3539   var d = isLE ? 1 : -1
3540   var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3541
3542   value = Math.abs(value)
3543
3544   if (isNaN(value) || value === Infinity) {
3545     m = isNaN(value) ? 1 : 0
3546     e = eMax
3547   } else {
3548     e = Math.floor(Math.log(value) / Math.LN2)
3549     if (value * (c = Math.pow(2, -e)) < 1) {
3550       e--
3551       c *= 2
3552     }
3553     if (e + eBias >= 1) {
3554       value += rt / c
3555     } else {
3556       value += rt * Math.pow(2, 1 - eBias)
3557     }
3558     if (value * c >= 2) {
3559       e++
3560       c /= 2
3561     }
3562
3563     if (e + eBias >= eMax) {
3564       m = 0
3565       e = eMax
3566     } else if (e + eBias >= 1) {
3567       m = (value * c - 1) * Math.pow(2, mLen)
3568       e = e + eBias
3569     } else {
3570       m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3571       e = 0
3572     }
3573   }
3574
3575   for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3576
3577   e = (e << mLen) | m
3578   eLen += mLen
3579   for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3580
3581   buffer[offset + i - d] |= s * 128
3582 }
3583
3584 },{}],18:[function(require,module,exports){
3585 (function (global){
3586 'use strict';
3587
3588 /*global window, global*/
3589
3590 var root = typeof window !== 'undefined' ?
3591     window : typeof global !== 'undefined' ?
3592     global : {};
3593
3594 module.exports = Individual;
3595
3596 function Individual(key, value) {
3597     if (key in root) {
3598         return root[key];
3599     }
3600
3601     root[key] = value;
3602
3603     return value;
3604 }
3605
3606 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3607
3608 },{}],19:[function(require,module,exports){
3609 'use strict';
3610
3611 var Individual = require('./index.js');
3612
3613 module.exports = OneVersion;
3614
3615 function OneVersion(moduleName, version, defaultValue) {
3616     var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3617     var enforceKey = key + '_ENFORCE_SINGLETON';
3618
3619     var versionValue = Individual(enforceKey, version);
3620
3621     if (versionValue !== version) {
3622         throw new Error('Can only have one copy of ' +
3623             moduleName + '.\n' +
3624             'You already have version ' + versionValue +
3625             ' installed.\n' +
3626             'This means you cannot install version ' + version);
3627     }
3628
3629     return Individual(key, defaultValue);
3630 }
3631
3632 },{"./index.js":18}],20:[function(require,module,exports){
3633 "use strict";
3634
3635 module.exports = function isObject(x) {
3636         return typeof x === "object" && x !== null;
3637 };
3638
3639 },{}],21:[function(require,module,exports){
3640 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3641 /* Geohash encoding/decoding and associated functions   (c) Chris Veness 2014-2016 / MIT Licence  */
3642 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3643
3644 'use strict';
3645
3646
3647 /**
3648  * Geohash encode, decode, bounds, neighbours.
3649  *
3650  * @namespace
3651  */
3652 var Geohash = {};
3653
3654 /* (Geohash-specific) Base32 map */
3655 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3656
3657 /**
3658  * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3659  * evaluated precision.
3660  *
3661  * @param   {number} lat - Latitude in degrees.
3662  * @param   {number} lon - Longitude in degrees.
3663  * @param   {number} [precision] - Number of characters in resulting geohash.
3664  * @returns {string} Geohash of supplied latitude/longitude.
3665  * @throws  Invalid geohash.
3666  *
3667  * @example
3668  *     var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3669  */
3670 Geohash.encode = function(lat, lon, precision) {
3671     // infer precision?
3672     if (typeof precision == 'undefined') {
3673         // refine geohash until it matches precision of supplied lat/lon
3674         for (var p=1; p<=12; p++) {
3675             var hash = Geohash.encode(lat, lon, p);
3676             var posn = Geohash.decode(hash);
3677             if (posn.lat==lat && posn.lon==lon) return hash;
3678         }
3679         precision = 12; // set to maximum
3680     }
3681
3682     lat = Number(lat);
3683     lon = Number(lon);
3684     precision = Number(precision);
3685
3686     if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3687
3688     var idx = 0; // index into base32 map
3689     var bit = 0; // each char holds 5 bits
3690     var evenBit = true;
3691     var geohash = '';
3692
3693     var latMin =  -90, latMax =  90;
3694     var lonMin = -180, lonMax = 180;
3695
3696     while (geohash.length < precision) {
3697         if (evenBit) {
3698             // bisect E-W longitude
3699             var lonMid = (lonMin + lonMax) / 2;
3700             if (lon >= lonMid) {
3701                 idx = idx*2 + 1;
3702                 lonMin = lonMid;
3703             } else {
3704                 idx = idx*2;
3705                 lonMax = lonMid;
3706             }
3707         } else {
3708             // bisect N-S latitude
3709             var latMid = (latMin + latMax) / 2;
3710             if (lat >= latMid) {
3711                 idx = idx*2 + 1;
3712                 latMin = latMid;
3713             } else {
3714                 idx = idx*2;
3715                 latMax = latMid;
3716             }
3717         }
3718         evenBit = !evenBit;
3719
3720         if (++bit == 5) {
3721             // 5 bits gives us a character: append it and start over
3722             geohash += Geohash.base32.charAt(idx);
3723             bit = 0;
3724             idx = 0;
3725         }
3726     }
3727
3728     return geohash;
3729 };
3730
3731
3732 /**
3733  * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3734  *     to reasonable precision).
3735  *
3736  * @param   {string} geohash - Geohash string to be converted to latitude/longitude.
3737  * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3738  * @throws  Invalid geohash.
3739  *
3740  * @example
3741  *     var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3742  */
3743 Geohash.decode = function(geohash) {
3744
3745     var bounds = Geohash.bounds(geohash); // <-- the hard work
3746     // now just determine the centre of the cell...
3747
3748     var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3749     var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3750
3751     // cell centre
3752     var lat = (latMin + latMax)/2;
3753     var lon = (lonMin + lonMax)/2;
3754
3755     // round to close to centre without excessive precision: âŒŠ2-log10(Δ°)⌋ decimal places
3756     lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3757     lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3758
3759     return { lat: Number(lat), lon: Number(lon) };
3760 };
3761
3762
3763 /**
3764  * Returns SW/NE latitude/longitude bounds of specified geohash.
3765  *
3766  * @param   {string} geohash - Cell that bounds are required of.
3767  * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3768  * @throws  Invalid geohash.
3769  */
3770 Geohash.bounds = function(geohash) {
3771     if (geohash.length === 0) throw new Error('Invalid geohash');
3772
3773     geohash = geohash.toLowerCase();
3774
3775     var evenBit = true;
3776     var latMin =  -90, latMax =  90;
3777     var lonMin = -180, lonMax = 180;
3778
3779     for (var i=0; i<geohash.length; i++) {
3780         var chr = geohash.charAt(i);
3781         var idx = Geohash.base32.indexOf(chr);
3782         if (idx == -1) throw new Error('Invalid geohash');
3783
3784         for (var n=4; n>=0; n--) {
3785             var bitN = idx >> n & 1;
3786             if (evenBit) {
3787                 // longitude
3788                 var lonMid = (lonMin+lonMax) / 2;
3789                 if (bitN == 1) {
3790                     lonMin = lonMid;
3791                 } else {
3792                     lonMax = lonMid;
3793                 }
3794             } else {
3795                 // latitude
3796                 var latMid = (latMin+latMax) / 2;
3797                 if (bitN == 1) {
3798                     latMin = latMid;
3799                 } else {
3800                     latMax = latMid;
3801                 }
3802             }
3803             evenBit = !evenBit;
3804         }
3805     }
3806
3807     var bounds = {
3808         sw: { lat: latMin, lon: lonMin },
3809         ne: { lat: latMax, lon: lonMax },
3810     };
3811
3812     return bounds;
3813 };
3814
3815
3816 /**
3817  * Determines adjacent cell in given direction.
3818  *
3819  * @param   geohash - Cell to which adjacent cell is required.
3820  * @param   direction - Direction from geohash (N/S/E/W).
3821  * @returns {string} Geocode of adjacent cell.
3822  * @throws  Invalid geohash.
3823  */
3824 Geohash.adjacent = function(geohash, direction) {
3825     // based on github.com/davetroy/geohash-js
3826
3827     geohash = geohash.toLowerCase();
3828     direction = direction.toLowerCase();
3829
3830     if (geohash.length === 0) throw new Error('Invalid geohash');
3831     if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3832
3833     var neighbour = {
3834         n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3835         s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3836         e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3837         w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3838     };
3839     var border = {
3840         n: [ 'prxz',     'bcfguvyz' ],
3841         s: [ '028b',     '0145hjnp' ],
3842         e: [ 'bcfguvyz', 'prxz'     ],
3843         w: [ '0145hjnp', '028b'     ],
3844     };
3845
3846     var lastCh = geohash.slice(-1);    // last character of hash
3847     var parent = geohash.slice(0, -1); // hash without last character
3848
3849     var type = geohash.length % 2;
3850
3851     // check for edge-cases which don't share common prefix
3852     if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3853         parent = Geohash.adjacent(parent, direction);
3854     }
3855
3856     // append letter for direction to parent
3857     return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3858 };
3859
3860
3861 /**
3862  * Returns all 8 adjacent cells to specified geohash.
3863  *
3864  * @param   {string} geohash - Geohash neighbours are required of.
3865  * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3866  * @throws  Invalid geohash.
3867  */
3868 Geohash.neighbours = function(geohash) {
3869     return {
3870         'n':  Geohash.adjacent(geohash, 'n'),
3871         'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3872         'e':  Geohash.adjacent(geohash, 'e'),
3873         'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3874         's':  Geohash.adjacent(geohash, 's'),
3875         'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3876         'w':  Geohash.adjacent(geohash, 'w'),
3877         'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3878     };
3879 };
3880
3881
3882 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3883 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3884
3885 },{}],22:[function(require,module,exports){
3886 /**
3887  * martinez v0.5.0
3888  * Martinez polygon clipping algorithm, does boolean operation on polygons (multipolygons, polygons with holes etc): intersection, union, difference, xor
3889  *
3890  * @author Alex Milevski <info@w8r.name>
3891  * @license MIT
3892  * @preserve
3893  */
3894
3895 (function (global, factory) {
3896   typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3897   typeof define === 'function' && define.amd ? define(['exports'], factory) :
3898   (factory((global.martinez = {})));
3899 }(this, (function (exports) { 'use strict';
3900
3901   function DEFAULT_COMPARE (a, b) { return a > b ? 1 : a < b ? -1 : 0; }
3902
3903   var SplayTree = function SplayTree(compare, noDuplicates) {
3904     if ( compare === void 0 ) compare = DEFAULT_COMPARE;
3905     if ( noDuplicates === void 0 ) noDuplicates = false;
3906
3907     this._compare = compare;
3908     this._root = null;
3909     this._size = 0;
3910     this._noDuplicates = !!noDuplicates;
3911   };
3912
3913   var prototypeAccessors = { size: { configurable: true } };
3914
3915
3916   SplayTree.prototype.rotateLeft = function rotateLeft (x) {
3917     var y = x.right;
3918     if (y) {
3919       x.right = y.left;
3920       if (y.left) { y.left.parent = x; }
3921       y.parent = x.parent;
3922     }
3923
3924     if (!x.parent)              { this._root = y; }
3925     else if (x === x.parent.left) { x.parent.left = y; }
3926     else                        { x.parent.right = y; }
3927     if (y) { y.left = x; }
3928     x.parent = y;
3929   };
3930
3931
3932   SplayTree.prototype.rotateRight = function rotateRight (x) {
3933     var y = x.left;
3934     if (y) {
3935       x.left = y.right;
3936       if (y.right) { y.right.parent = x; }
3937       y.parent = x.parent;
3938     }
3939
3940     if (!x.parent)             { this._root = y; }
3941     else if(x === x.parent.left) { x.parent.left = y; }
3942     else                       { x.parent.right = y; }
3943     if (y) { y.right = x; }
3944     x.parent = y;
3945   };
3946
3947
3948   SplayTree.prototype._splay = function _splay (x) {
3949       var this$1 = this;
3950
3951     while (x.parent) {
3952       var p = x.parent;
3953       if (!p.parent) {
3954         if (p.left === x) { this$1.rotateRight(p); }
3955         else            { this$1.rotateLeft(p); }
3956       } else if (p.left === x && p.parent.left === p) {
3957         this$1.rotateRight(p.parent);
3958         this$1.rotateRight(p);
3959       } else if (p.right === x && p.parent.right === p) {
3960         this$1.rotateLeft(p.parent);
3961         this$1.rotateLeft(p);
3962       } else if (p.left === x && p.parent.right === p) {
3963         this$1.rotateRight(p);
3964         this$1.rotateLeft(p);
3965       } else {
3966         this$1.rotateLeft(p);
3967         this$1.rotateRight(p);
3968       }
3969     }
3970   };
3971
3972
3973   SplayTree.prototype.splay = function splay (x) {
3974       var this$1 = this;
3975
3976     var p, gp, ggp, l, r;
3977
3978     while (x.parent) {
3979       p = x.parent;
3980       gp = p.parent;
3981
3982       if (gp && gp.parent) {
3983         ggp = gp.parent;
3984         if (ggp.left === gp) { ggp.left= x; }
3985         else               { ggp.right = x; }
3986         x.parent = ggp;
3987       } else {
3988         x.parent = null;
3989         this$1._root = x;
3990       }
3991
3992       l = x.left; r = x.right;
3993
3994       if (x === p.left) { // left
3995         if (gp) {
3996           if (gp.left === p) {
3997             /* zig-zig */
3998             if (p.right) {
3999               gp.left = p.right;
4000               gp.left.parent = gp;
4001             } else { gp.left = null; }
4002
4003             p.right = gp;
4004             gp.parent = p;
4005           } else {
4006             /* zig-zag */
4007             if (l) {
4008               gp.right = l;
4009               l.parent = gp;
4010             } else { gp.right = null; }
4011
4012             x.left  = gp;
4013             gp.parent = x;
4014           }
4015         }
4016         if (r) {
4017           p.left = r;
4018           r.parent = p;
4019         } else { p.left = null; }
4020
4021         x.right= p;
4022         p.parent = x;
4023       } else { // right
4024         if (gp) {
4025           if (gp.right === p) {
4026             /* zig-zig */
4027             if (p.left) {
4028               gp.right = p.left;
4029               gp.right.parent = gp;
4030             } else { gp.right = null; }
4031
4032             p.left = gp;
4033             gp.parent = p;
4034           } else {
4035             /* zig-zag */
4036             if (r) {
4037               gp.left = r;
4038               r.parent = gp;
4039             } else { gp.left = null; }
4040
4041             x.right = gp;
4042             gp.parent = x;
4043           }
4044         }
4045         if (l) {
4046           p.right = l;
4047           l.parent = p;
4048         } else { p.right = null; }
4049
4050         x.left = p;
4051         p.parent = x;
4052       }
4053     }
4054   };
4055
4056
4057   SplayTree.prototype.replace = function replace (u, v) {
4058     if (!u.parent) { this._root = v; }
4059     else if (u === u.parent.left) { u.parent.left = v; }
4060     else { u.parent.right = v; }
4061     if (v) { v.parent = u.parent; }
4062   };
4063
4064
4065   SplayTree.prototype.minNode = function minNode (u) {
4066       if ( u === void 0 ) u = this._root;
4067
4068     if (u) { while (u.left) { u = u.left; } }
4069     return u;
4070   };
4071
4072
4073   SplayTree.prototype.maxNode = function maxNode (u) {
4074       if ( u === void 0 ) u = this._root;
4075
4076     if (u) { while (u.right) { u = u.right; } }
4077     return u;
4078   };
4079
4080
4081   SplayTree.prototype.insert = function insert (key, data) {
4082     var z = this._root;
4083     var p = null;
4084     var comp = this._compare;
4085     var cmp;
4086
4087     if (this._noDuplicates) {
4088       while (z) {
4089         p = z;
4090         cmp = comp(z.key, key);
4091         if (cmp === 0) { return; }
4092         else if (comp(z.key, key) < 0) { z = z.right; }
4093         else { z = z.left; }
4094       }
4095     } else {
4096       while (z) {
4097         p = z;
4098         if (comp(z.key, key) < 0) { z = z.right; }
4099         else { z = z.left; }
4100       }
4101     }
4102
4103     z = { key: key, data: data, left: null, right: null, parent: p };
4104
4105     if (!p)                        { this._root = z; }
4106     else if (comp(p.key, z.key) < 0) { p.right = z; }
4107     else                           { p.left= z; }
4108
4109     this.splay(z);
4110     this._size++;
4111     return z;
4112   };
4113
4114
4115   SplayTree.prototype.find = function find (key) {
4116     var z  = this._root;
4117     var comp = this._compare;
4118     while (z) {
4119       var cmp = comp(z.key, key);
4120       if    (cmp < 0) { z = z.right; }
4121       else if (cmp > 0) { z = z.left; }
4122       else            { return z; }
4123     }
4124     return null;
4125   };
4126
4127   /**
4128    * Whether the tree contains a node with the given key
4129    * @param{Key} key
4130    * @return {boolean} true/false
4131    */
4132   SplayTree.prototype.contains = function contains (key) {
4133     var node     = this._root;
4134     var comparator = this._compare;
4135     while (node){
4136       var cmp = comparator(key, node.key);
4137       if    (cmp === 0) { return true; }
4138       else if (cmp < 0) { node = node.left; }
4139       else              { node = node.right; }
4140     }
4141
4142     return false;
4143   };
4144
4145
4146   SplayTree.prototype.remove = function remove (key) {
4147     var z = this.find(key);
4148
4149     if (!z) { return false; }
4150
4151     this.splay(z);
4152
4153     if (!z.left) { this.replace(z, z.right); }
4154     else if (!z.right) { this.replace(z, z.left); }
4155     else {
4156       var y = this.minNode(z.right);
4157       if (y.parent !== z) {
4158         this.replace(y, y.right);
4159         y.right = z.right;
4160         y.right.parent = y;
4161       }
4162       this.replace(z, y);
4163       y.left = z.left;
4164       y.left.parent = y;
4165     }
4166
4167     this._size--;
4168     return true;
4169   };
4170
4171
4172   SplayTree.prototype.removeNode = function removeNode (z) {
4173     if (!z) { return false; }
4174
4175     this.splay(z);
4176
4177     if (!z.left) { this.replace(z, z.right); }
4178     else if (!z.right) { this.replace(z, z.left); }
4179     else {
4180       var y = this.minNode(z.right);
4181       if (y.parent !== z) {
4182         this.replace(y, y.right);
4183         y.right = z.right;
4184         y.right.parent = y;
4185       }
4186       this.replace(z, y);
4187       y.left = z.left;
4188       y.left.parent = y;
4189     }
4190
4191     this._size--;
4192     return true;
4193   };
4194
4195
4196   SplayTree.prototype.erase = function erase (key) {
4197     var z = this.find(key);
4198     if (!z) { return; }
4199
4200     this.splay(z);
4201
4202     var s = z.left;
4203     var t = z.right;
4204
4205     var sMax = null;
4206     if (s) {
4207       s.parent = null;
4208       sMax = this.maxNode(s);
4209       this.splay(sMax);
4210       this._root = sMax;
4211     }
4212     if (t) {
4213       if (s) { sMax.right = t; }
4214       else { this._root = t; }
4215       t.parent = sMax;
4216     }
4217
4218     this._size--;
4219   };
4220
4221   /**
4222    * Removes and returns the node with smallest key
4223    * @return {?Node}
4224    */
4225   SplayTree.prototype.pop = function pop () {
4226     var node = this._root, returnValue = null;
4227     if (node) {
4228       while (node.left) { node = node.left; }
4229       returnValue = { key: node.key, data: node.data };
4230       this.remove(node.key);
4231     }
4232     return returnValue;
4233   };
4234
4235
4236   /* eslint-disable class-methods-use-this */
4237
4238   /**
4239    * Successor node
4240    * @param{Node} node
4241    * @return {?Node}
4242    */
4243   SplayTree.prototype.next = function next (node) {
4244     var successor = node;
4245     if (successor) {
4246       if (successor.right) {
4247         successor = successor.right;
4248         while (successor && successor.left) { successor = successor.left; }
4249       } else {
4250         successor = node.parent;
4251         while (successor && successor.right === node) {
4252           node = successor; successor = successor.parent;
4253         }
4254       }
4255     }
4256     return successor;
4257   };
4258
4259
4260   /**
4261    * Predecessor node
4262    * @param{Node} node
4263    * @return {?Node}
4264    */
4265   SplayTree.prototype.prev = function prev (node) {
4266     var predecessor = node;
4267     if (predecessor) {
4268       if (predecessor.left) {
4269         predecessor = predecessor.left;
4270         while (predecessor && predecessor.right) { predecessor = predecessor.right; }
4271       } else {
4272         predecessor = node.parent;
4273         while (predecessor && predecessor.left === node) {
4274           node = predecessor;
4275           predecessor = predecessor.parent;
4276         }
4277       }
4278     }
4279     return predecessor;
4280   };
4281   /* eslint-enable class-methods-use-this */
4282
4283
4284   /**
4285    * @param{forEachCallback} callback
4286    * @return {SplayTree}
4287    */
4288   SplayTree.prototype.forEach = function forEach (callback) {
4289     var current = this._root;
4290     var s = [], done = false, i = 0;
4291
4292     while (!done) {
4293       // Reach the left most Node of the current Node
4294       if (current) {
4295         // Place pointer to a tree node on the stack
4296         // before traversing the node's left subtree
4297         s.push(current);
4298         current = current.left;
4299       } else {
4300         // BackTrack from the empty subtree and visit the Node
4301         // at the top of the stack; however, if the stack is
4302         // empty you are done
4303         if (s.length > 0) {
4304           current = s.pop();
4305           callback(current, i++);
4306
4307           // We have visited the node and its left
4308           // subtree. Now, it's right subtree's turn
4309           current = current.right;
4310         } else { done = true; }
4311       }
4312     }
4313     return this;
4314   };
4315
4316
4317   /**
4318    * Walk key range from `low` to `high`. Stops if `fn` returns a value.
4319    * @param{Key}    low
4320    * @param{Key}    high
4321    * @param{Function} fn
4322    * @param{*?}     ctx
4323    * @return {SplayTree}
4324    */
4325   SplayTree.prototype.range = function range (low, high, fn, ctx) {
4326       var this$1 = this;
4327
4328     var Q = [];
4329     var compare = this._compare;
4330     var node = this._root, cmp;
4331
4332     while (Q.length !== 0 || node) {
4333       if (node) {
4334         Q.push(node);
4335         node = node.left;
4336       } else {
4337         node = Q.pop();
4338         cmp = compare(node.key, high);
4339         if (cmp > 0) {
4340           break;
4341         } else if (compare(node.key, low) >= 0) {
4342           if (fn.call(ctx, node)) { return this$1; } // stop if smth is returned
4343         }
4344         node = node.right;
4345       }
4346     }
4347     return this;
4348   };
4349
4350   /**
4351    * Returns all keys in order
4352    * @return {Array<Key>}
4353    */
4354   SplayTree.prototype.keys = function keys () {
4355     var current = this._root;
4356     var s = [], r = [], done = false;
4357
4358     while (!done) {
4359       if (current) {
4360         s.push(current);
4361         current = current.left;
4362       } else {
4363         if (s.length > 0) {
4364           current = s.pop();
4365           r.push(current.key);
4366           current = current.right;
4367         } else { done = true; }
4368       }
4369     }
4370     return r;
4371   };
4372
4373
4374   /**
4375    * Returns `data` fields of all nodes in order.
4376    * @return {Array<Value>}
4377    */
4378   SplayTree.prototype.values = function values () {
4379     var current = this._root;
4380     var s = [], r = [], done = false;
4381
4382     while (!done) {
4383       if (current) {
4384         s.push(current);
4385         current = current.left;
4386       } else {
4387         if (s.length > 0) {
4388           current = s.pop();
4389           r.push(current.data);
4390           current = current.right;
4391         } else { done = true; }
4392       }
4393     }
4394     return r;
4395   };
4396
4397
4398   /**
4399    * Returns node at given index
4400    * @param{number} index
4401    * @return {?Node}
4402    */
4403   SplayTree.prototype.at = function at (index) {
4404     // removed after a consideration, more misleading than useful
4405     // index = index % this.size;
4406     // if (index < 0) index = this.size - index;
4407
4408     var current = this._root;
4409     var s = [], done = false, i = 0;
4410
4411     while (!done) {
4412       if (current) {
4413         s.push(current);
4414         current = current.left;
4415       } else {
4416         if (s.length > 0) {
4417           current = s.pop();
4418           if (i === index) { return current; }
4419           i++;
4420           current = current.right;
4421         } else { done = true; }
4422       }
4423     }
4424     return null;
4425   };
4426
4427   /**
4428    * Bulk-load items. Both array have to be same size
4429    * @param{Array<Key>}  keys
4430    * @param{Array<Value>}[values]
4431    * @param{Boolean}     [presort=false] Pre-sort keys and values, using
4432    *                                       tree's comparator. Sorting is done
4433    *                                       in-place
4434    * @return {AVLTree}
4435    */
4436   SplayTree.prototype.load = function load (keys, values, presort) {
4437       if ( keys === void 0 ) keys = [];
4438       if ( values === void 0 ) values = [];
4439       if ( presort === void 0 ) presort = false;
4440
4441     if (this._size !== 0) { throw new Error('bulk-load: tree is not empty'); }
4442     var size = keys.length;
4443     if (presort) { sort(keys, values, 0, size - 1, this._compare); }
4444     this._root = loadRecursive(null, keys, values, 0, size);
4445     this._size = size;
4446     return this;
4447   };
4448
4449
4450   SplayTree.prototype.min = function min () {
4451     var node = this.minNode(this._root);
4452     if (node) { return node.key; }
4453     else    { return null; }
4454   };
4455
4456
4457   SplayTree.prototype.max = function max () {
4458     var node = this.maxNode(this._root);
4459     if (node) { return node.key; }
4460     else    { return null; }
4461   };
4462
4463   SplayTree.prototype.isEmpty = function isEmpty () { return this._root === null; };
4464   prototypeAccessors.size.get = function () { return this._size; };
4465
4466
4467   /**
4468    * Create a tree and load it with items
4469    * @param{Array<Key>}        keys
4470    * @param{Array<Value>?}      [values]
4471
4472    * @param{Function?}          [comparator]
4473    * @param{Boolean?}           [presort=false] Pre-sort keys and values, using
4474    *                                             tree's comparator. Sorting is done
4475    *                                             in-place
4476    * @param{Boolean?}           [noDuplicates=false] Allow duplicates
4477    * @return {SplayTree}
4478    */
4479   SplayTree.createTree = function createTree (keys, values, comparator, presort, noDuplicates) {
4480     return new SplayTree(comparator, noDuplicates).load(keys, values, presort);
4481   };
4482
4483   Object.defineProperties( SplayTree.prototype, prototypeAccessors );
4484
4485
4486   function loadRecursive (parent, keys, values, start, end) {
4487     var size = end - start;
4488     if (size > 0) {
4489       var middle = start + Math.floor(size / 2);
4490       var key    = keys[middle];
4491       var data   = values[middle];
4492       var node   = { key: key, data: data, parent: parent };
4493       node.left    = loadRecursive(node, keys, values, start, middle);
4494       node.right   = loadRecursive(node, keys, values, middle + 1, end);
4495       return node;
4496     }
4497     return null;
4498   }
4499
4500
4501   function sort(keys, values, left, right, compare) {
4502     if (left >= right) { return; }
4503
4504     var pivot = keys[(left + right) >> 1];
4505     var i = left - 1;
4506     var j = right + 1;
4507
4508     while (true) {
4509       do { i++; } while (compare(keys[i], pivot) < 0);
4510       do { j--; } while (compare(keys[j], pivot) > 0);
4511       if (i >= j) { break; }
4512
4513       var tmp = keys[i];
4514       keys[i] = keys[j];
4515       keys[j] = tmp;
4516
4517       tmp = values[i];
4518       values[i] = values[j];
4519       values[j] = tmp;
4520     }
4521
4522     sort(keys, values,  left,     j, compare);
4523     sort(keys, values, j + 1, right, compare);
4524   }
4525
4526   var NORMAL               = 0;
4527   var NON_CONTRIBUTING     = 1;
4528   var SAME_TRANSITION      = 2;
4529   var DIFFERENT_TRANSITION = 3;
4530
4531   var INTERSECTION = 0;
4532   var UNION        = 1;
4533   var DIFFERENCE   = 2;
4534   var XOR          = 3;
4535
4536   /**
4537    * @param  {SweepEvent} event
4538    * @param  {SweepEvent} prev
4539    * @param  {Operation} operation
4540    */
4541   function computeFields (event, prev, operation) {
4542     // compute inOut and otherInOut fields
4543     if (prev === null) {
4544       event.inOut      = false;
4545       event.otherInOut = true;
4546
4547     // previous line segment in sweepline belongs to the same polygon
4548     } else {
4549       if (event.isSubject === prev.isSubject) {
4550         event.inOut      = !prev.inOut;
4551         event.otherInOut = prev.otherInOut;
4552
4553       // previous line segment in sweepline belongs to the clipping polygon
4554       } else {
4555         event.inOut      = !prev.otherInOut;
4556         event.otherInOut = prev.isVertical() ? !prev.inOut : prev.inOut;
4557       }
4558
4559       // compute prevInResult field
4560       if (prev) {
4561         event.prevInResult = (!inResult(prev, operation) || prev.isVertical())
4562           ? prev.prevInResult : prev;
4563       }
4564     }
4565
4566     // check if the line segment belongs to the Boolean operation
4567     event.inResult = inResult(event, operation);
4568   }
4569
4570
4571   /* eslint-disable indent */
4572   function inResult(event, operation) {
4573     switch (event.type) {
4574       case NORMAL:
4575         switch (operation) {
4576           case INTERSECTION:
4577             return !event.otherInOut;
4578           case UNION:
4579             return event.otherInOut;
4580           case DIFFERENCE:
4581             // return (event.isSubject && !event.otherInOut) ||
4582             //         (!event.isSubject && event.otherInOut);
4583             return (event.isSubject && event.otherInOut) ||
4584                     (!event.isSubject && !event.otherInOut);
4585           case XOR:
4586             return true;
4587         }
4588         break;
4589       case SAME_TRANSITION:
4590         return operation === INTERSECTION || operation === UNION;
4591       case DIFFERENT_TRANSITION:
4592         return operation === DIFFERENCE;
4593       case NON_CONTRIBUTING:
4594         return false;
4595     }
4596     return false;
4597   }
4598   /* eslint-enable indent */
4599
4600   var SweepEvent = function SweepEvent (point, left, otherEvent, isSubject, edgeType) {
4601
4602     /**
4603      * Is left endpoint?
4604      * @type {Boolean}
4605      */
4606     this.left = left;
4607
4608     /**
4609      * @type {Array.<Number>}
4610      */
4611     this.point = point;
4612
4613     /**
4614      * Other edge reference
4615      * @type {SweepEvent}
4616      */
4617     this.otherEvent = otherEvent;
4618
4619     /**
4620      * Belongs to source or clipping polygon
4621      * @type {Boolean}
4622      */
4623     this.isSubject = isSubject;
4624
4625     /**
4626      * Edge contribution type
4627      * @type {Number}
4628      */
4629     this.type = edgeType || NORMAL;
4630
4631
4632     /**
4633      * In-out transition for the sweepline crossing polygon
4634      * @type {Boolean}
4635      */
4636     this.inOut = false;
4637
4638
4639     /**
4640      * @type {Boolean}
4641      */
4642     this.otherInOut = false;
4643
4644     /**
4645      * Previous event in result?
4646      * @type {SweepEvent}
4647      */
4648     this.prevInResult = null;
4649
4650     /**
4651      * Does event belong to result?
4652      * @type {Boolean}
4653      */
4654     this.inResult = false;
4655
4656
4657     // connection step
4658
4659     /**
4660      * @type {Boolean}
4661      */
4662     this.resultInOut = false;
4663
4664     this.isExteriorRing = true;
4665   };
4666
4667
4668   /**
4669    * @param{Array.<Number>}p
4670    * @return {Boolean}
4671    */
4672   SweepEvent.prototype.isBelow = function isBelow (p) {
4673     var p0 = this.point, p1 = this.otherEvent.point;
4674     return this.left
4675       ? (p0[0] - p[0]) * (p1[1] - p[1]) - (p1[0] - p[0]) * (p0[1] - p[1]) > 0
4676       // signedArea(this.point, this.otherEvent.point, p) > 0 :
4677       : (p1[0] - p[0]) * (p0[1] - p[1]) - (p0[0] - p[0]) * (p1[1] - p[1]) > 0;
4678       //signedArea(this.otherEvent.point, this.point, p) > 0;
4679   };
4680
4681
4682   /**
4683    * @param{Array.<Number>}p
4684    * @return {Boolean}
4685    */
4686   SweepEvent.prototype.isAbove = function isAbove (p) {
4687     return !this.isBelow(p);
4688   };
4689
4690
4691   /**
4692    * @return {Boolean}
4693    */
4694   SweepEvent.prototype.isVertical = function isVertical () {
4695     return this.point[0] === this.otherEvent.point[0];
4696   };
4697
4698
4699   SweepEvent.prototype.clone = function clone () {
4700     var copy = new SweepEvent(
4701       this.point, this.left, this.otherEvent, this.isSubject, this.type);
4702
4703     copy.inResult     = this.inResult;
4704     copy.prevInResult = this.prevInResult;
4705     copy.isExteriorRing = this.isExteriorRing;
4706     copy.inOut        = this.inOut;
4707     copy.otherInOut   = this.otherInOut;
4708
4709     return copy;
4710   };
4711
4712   function equals(p1, p2) {
4713     if (p1[0] === p2[0]) {
4714       if (p1[1] === p2[1]) {
4715         return true;
4716       } else {
4717         return false;
4718       }
4719     }
4720     return false;
4721   }
4722
4723   // const EPSILON = 1e-9;
4724   // const abs = Math.abs;
4725   // TODO https://github.com/w8r/martinez/issues/6#issuecomment-262847164
4726   // Precision problem.
4727   //
4728   // module.exports = function equals(p1, p2) {
4729   //   return abs(p1[0] - p2[0]) <= EPSILON && abs(p1[1] - p2[1]) <= EPSILON;
4730   // };
4731
4732   /**
4733    * Signed area of the triangle (p0, p1, p2)
4734    * @param  {Array.<Number>} p0
4735    * @param  {Array.<Number>} p1
4736    * @param  {Array.<Number>} p2
4737    * @return {Number}
4738    */
4739   function signedArea(p0, p1, p2) {
4740     return (p0[0] - p2[0]) * (p1[1] - p2[1]) - (p1[0] - p2[0]) * (p0[1] - p2[1]);
4741   }
4742
4743   /**
4744    * @param  {SweepEvent} e1
4745    * @param  {SweepEvent} e2
4746    * @return {Number}
4747    */
4748   function compareEvents(e1, e2) {
4749     var p1 = e1.point;
4750     var p2 = e2.point;
4751
4752     // Different x-coordinate
4753     if (p1[0] > p2[0]) { return 1; }
4754     if (p1[0] < p2[0]) { return -1; }
4755
4756     // Different points, but same x-coordinate
4757     // Event with lower y-coordinate is processed first
4758     if (p1[1] !== p2[1]) { return p1[1] > p2[1] ? 1 : -1; }
4759
4760     return specialCases(e1, e2, p1, p2);
4761   }
4762
4763
4764   /* eslint-disable no-unused-vars */
4765   function specialCases(e1, e2, p1, p2) {
4766     // Same coordinates, but one is a left endpoint and the other is
4767     // a right endpoint. The right endpoint is processed first
4768     if (e1.left !== e2.left)
4769       { return e1.left ? 1 : -1; }
4770
4771     // const p2 = e1.otherEvent.point, p3 = e2.otherEvent.point;
4772     // const sa = (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
4773     // Same coordinates, both events
4774     // are left endpoints or right endpoints.
4775     // not collinear
4776     if (signedArea(p1, e1.otherEvent.point, e2.otherEvent.point) !== 0) {
4777       // the event associate to the bottom segment is processed first
4778       return (!e1.isBelow(e2.otherEvent.point)) ? 1 : -1;
4779     }
4780
4781     return (!e1.isSubject && e2.isSubject) ? 1 : -1;
4782   }
4783   /* eslint-enable no-unused-vars */
4784
4785   /**
4786    * @param  {SweepEvent} se
4787    * @param  {Array.<Number>} p
4788    * @param  {Queue} queue
4789    * @return {Queue}
4790    */
4791   function divideSegment(se, p, queue)  {
4792     var r = new SweepEvent(p, false, se,            se.isSubject);
4793     var l = new SweepEvent(p, true,  se.otherEvent, se.isSubject);
4794
4795     /* eslint-disable no-console */
4796     if (equals(se.point, se.otherEvent.point)) {
4797
4798       console.warn('what is that, a collapsed segment?', se);
4799     }
4800     /* eslint-enable no-console */
4801
4802     r.contourId = l.contourId = se.contourId;
4803
4804     // avoid a rounding error. The left event would be processed after the right event
4805     if (compareEvents(l, se.otherEvent) > 0) {
4806       se.otherEvent.left = true;
4807       l.left = false;
4808     }
4809
4810     // avoid a rounding error. The left event would be processed after the right event
4811     // if (compareEvents(se, r) > 0) {}
4812
4813     se.otherEvent.otherEvent = l;
4814     se.otherEvent = r;
4815
4816     queue.push(l);
4817     queue.push(r);
4818
4819     return queue;
4820   }
4821
4822   //const EPS = 1e-9;
4823
4824   /**
4825    * Finds the magnitude of the cross product of two vectors (if we pretend
4826    * they're in three dimensions)
4827    *
4828    * @param {Object} a First vector
4829    * @param {Object} b Second vector
4830    * @private
4831    * @returns {Number} The magnitude of the cross product
4832    */
4833   function crossProduct(a, b) {
4834     return (a[0] * b[1]) - (a[1] * b[0]);
4835   }
4836
4837   /**
4838    * Finds the dot product of two vectors.
4839    *
4840    * @param {Object} a First vector
4841    * @param {Object} b Second vector
4842    * @private
4843    * @returns {Number} The dot product
4844    */
4845   function dotProduct(a, b) {
4846     return (a[0] * b[0]) + (a[1] * b[1]);
4847   }
4848
4849   /**
4850    * Finds the intersection (if any) between two line segments a and b, given the
4851    * line segments' end points a1, a2 and b1, b2.
4852    *
4853    * This algorithm is based on Schneider and Eberly.
4854    * http://www.cimec.org.ar/~ncalvo/Schneider_Eberly.pdf
4855    * Page 244.
4856    *
4857    * @param {Array.<Number>} a1 point of first line
4858    * @param {Array.<Number>} a2 point of first line
4859    * @param {Array.<Number>} b1 point of second line
4860    * @param {Array.<Number>} b2 point of second line
4861    * @param {Boolean=}       noEndpointTouch whether to skip single touchpoints
4862    *                                         (meaning connected segments) as
4863    *                                         intersections
4864    * @returns {Array.<Array.<Number>>|Null} If the lines intersect, the point of
4865    * intersection. If they overlap, the two end points of the overlapping segment.
4866    * Otherwise, null.
4867    */
4868   function intersection (a1, a2, b1, b2, noEndpointTouch) {
4869     // The algorithm expects our lines in the form P + sd, where P is a point,
4870     // s is on the interval [0, 1], and d is a vector.
4871     // We are passed two points. P can be the first point of each pair. The
4872     // vector, then, could be thought of as the distance (in x and y components)
4873     // from the first point to the second point.
4874     // So first, let's make our vectors:
4875     var va = [a2[0] - a1[0], a2[1] - a1[1]];
4876     var vb = [b2[0] - b1[0], b2[1] - b1[1]];
4877     // We also define a function to convert back to regular point form:
4878
4879     /* eslint-disable arrow-body-style */
4880
4881     function toPoint(p, s, d) {
4882       return [
4883         p[0] + s * d[0],
4884         p[1] + s * d[1]
4885       ];
4886     }
4887
4888     /* eslint-enable arrow-body-style */
4889
4890     // The rest is pretty much a straight port of the algorithm.
4891     var e = [b1[0] - a1[0], b1[1] - a1[1]];
4892     var kross    = crossProduct(va, vb);
4893     var sqrKross = kross * kross;
4894     var sqrLenA  = dotProduct(va, va);
4895     //const sqrLenB  = dotProduct(vb, vb);
4896
4897     // Check for line intersection. This works because of the properties of the
4898     // cross product -- specifically, two vectors are parallel if and only if the
4899     // cross product is the 0 vector. The full calculation involves relative error
4900     // to account for possible very small line segments. See Schneider & Eberly
4901     // for details.
4902     if (sqrKross > 0/* EPS * sqrLenB * sqLenA */) {
4903       // If they're not parallel, then (because these are line segments) they
4904       // still might not actually intersect. This code checks that the
4905       // intersection point of the lines is actually on both line segments.
4906       var s = crossProduct(e, vb) / kross;
4907       if (s < 0 || s > 1) {
4908         // not on line segment a
4909         return null;
4910       }
4911       var t = crossProduct(e, va) / kross;
4912       if (t < 0 || t > 1) {
4913         // not on line segment b
4914         return null;
4915       }
4916       if (s === 0 || s === 1) {
4917         // on an endpoint of line segment a
4918         return noEndpointTouch ? null : [toPoint(a1, s, va)];
4919       }
4920       if (t === 0 || t === 1) {
4921         // on an endpoint of line segment b
4922         return noEndpointTouch ? null : [toPoint(b1, t, vb)];
4923       }
4924       return [toPoint(a1, s, va)];
4925     }
4926
4927     // If we've reached this point, then the lines are either parallel or the
4928     // same, but the segments could overlap partially or fully, or not at all.
4929     // So we need to find the overlap, if any. To do that, we can use e, which is
4930     // the (vector) difference between the two initial points. If this is parallel
4931     // with the line itself, then the two lines are the same line, and there will
4932     // be overlap.
4933     //const sqrLenE = dotProduct(e, e);
4934     kross = crossProduct(e, va);
4935     sqrKross = kross * kross;
4936
4937     if (sqrKross > 0 /* EPS * sqLenB * sqLenE */) {
4938     // Lines are just parallel, not the same. No overlap.
4939       return null;
4940     }
4941
4942     var sa = dotProduct(va, e) / sqrLenA;
4943     var sb = sa + dotProduct(va, vb) / sqrLenA;
4944     var smin = Math.min(sa, sb);
4945     var smax = Math.max(sa, sb);
4946
4947     // this is, essentially, the FindIntersection acting on floats from
4948     // Schneider & Eberly, just inlined into this function.
4949     if (smin <= 1 && smax >= 0) {
4950
4951       // overlap on an end point
4952       if (smin === 1) {
4953         return noEndpointTouch ? null : [toPoint(a1, smin > 0 ? smin : 0, va)];
4954       }
4955
4956       if (smax === 0) {
4957         return noEndpointTouch ? null : [toPoint(a1, smax < 1 ? smax : 1, va)];
4958       }
4959
4960       if (noEndpointTouch && smin === 0 && smax === 1) { return null; }
4961
4962       // There's overlap on a segment -- two points of intersection. Return both.
4963       return [
4964         toPoint(a1, smin > 0 ? smin : 0, va),
4965         toPoint(a1, smax < 1 ? smax : 1, va)
4966       ];
4967     }
4968
4969     return null;
4970   }
4971
4972   /**
4973    * @param  {SweepEvent} se1
4974    * @param  {SweepEvent} se2
4975    * @param  {Queue}      queue
4976    * @return {Number}
4977    */
4978   function possibleIntersection (se1, se2, queue) {
4979     // that disallows self-intersecting polygons,
4980     // did cost us half a day, so I'll leave it
4981     // out of respect
4982     // if (se1.isSubject === se2.isSubject) return;
4983     var inter = intersection(
4984       se1.point, se1.otherEvent.point,
4985       se2.point, se2.otherEvent.point
4986     );
4987
4988     var nintersections = inter ? inter.length : 0;
4989     if (nintersections === 0) { return 0; } // no intersection
4990
4991     // the line segments intersect at an endpoint of both line segments
4992     if ((nintersections === 1) &&
4993         (equals(se1.point, se2.point) ||
4994          equals(se1.otherEvent.point, se2.otherEvent.point))) {
4995       return 0;
4996     }
4997
4998     if (nintersections === 2 && se1.isSubject === se2.isSubject) {
4999       // if(se1.contourId === se2.contourId){
5000       // console.warn('Edges of the same polygon overlap',
5001       //   se1.point, se1.otherEvent.point, se2.point, se2.otherEvent.point);
5002       // }
5003       //throw new Error('Edges of the same polygon overlap');
5004       return 0;
5005     }
5006
5007     // The line segments associated to se1 and se2 intersect
5008     if (nintersections === 1) {
5009
5010       // if the intersection point is not an endpoint of se1
5011       if (!equals(se1.point, inter[0]) && !equals(se1.otherEvent.point, inter[0])) {
5012         divideSegment(se1, inter[0], queue);
5013       }
5014
5015       // if the intersection point is not an endpoint of se2
5016       if (!equals(se2.point, inter[0]) && !equals(se2.otherEvent.point, inter[0])) {
5017         divideSegment(se2, inter[0], queue);
5018       }
5019       return 1;
5020     }
5021
5022     // The line segments associated to se1 and se2 overlap
5023     var events        = [];
5024     var leftCoincide  = false;
5025     var rightCoincide = false;
5026
5027     if (equals(se1.point, se2.point)) {
5028       leftCoincide = true; // linked
5029     } else if (compareEvents(se1, se2) === 1) {
5030       events.push(se2, se1);
5031     } else {
5032       events.push(se1, se2);
5033     }
5034
5035     if (equals(se1.otherEvent.point, se2.otherEvent.point)) {
5036       rightCoincide = true;
5037     } else if (compareEvents(se1.otherEvent, se2.otherEvent) === 1) {
5038       events.push(se2.otherEvent, se1.otherEvent);
5039     } else {
5040       events.push(se1.otherEvent, se2.otherEvent);
5041     }
5042
5043     if ((leftCoincide && rightCoincide) || leftCoincide) {
5044       // both line segments are equal or share the left endpoint
5045       se2.type = NON_CONTRIBUTING;
5046       se1.type = (se2.inOut === se1.inOut)
5047         ? SAME_TRANSITION : DIFFERENT_TRANSITION;
5048
5049       if (leftCoincide && !rightCoincide) {
5050         // honestly no idea, but changing events selection from [2, 1]
5051         // to [0, 1] fixes the overlapping self-intersecting polygons issue
5052         divideSegment(events[1].otherEvent, events[0].point, queue);
5053       }
5054       return 2;
5055     }
5056
5057     // the line segments share the right endpoint
5058     if (rightCoincide) {
5059       divideSegment(events[0], events[1].point, queue);
5060       return 3;
5061     }
5062
5063     // no line segment includes totally the other one
5064     if (events[0] !== events[3].otherEvent) {
5065       divideSegment(events[0], events[1].point, queue);
5066       divideSegment(events[1], events[2].point, queue);
5067       return 3;
5068     }
5069
5070     // one line segment includes the other one
5071     divideSegment(events[0], events[1].point, queue);
5072     divideSegment(events[3].otherEvent, events[2].point, queue);
5073
5074     return 3;
5075   }
5076
5077   /**
5078    * @param  {SweepEvent} le1
5079    * @param  {SweepEvent} le2
5080    * @return {Number}
5081    */
5082   function compareSegments(le1, le2) {
5083     if (le1 === le2) { return 0; }
5084
5085     // Segments are not collinear
5086     if (signedArea(le1.point, le1.otherEvent.point, le2.point) !== 0 ||
5087       signedArea(le1.point, le1.otherEvent.point, le2.otherEvent.point) !== 0) {
5088
5089       // If they share their left endpoint use the right endpoint to sort
5090       if (equals(le1.point, le2.point)) { return le1.isBelow(le2.otherEvent.point) ? -1 : 1; }
5091
5092       // Different left endpoint: use the left endpoint to sort
5093       if (le1.point[0] === le2.point[0]) { return le1.point[1] < le2.point[1] ? -1 : 1; }
5094
5095       // has the line segment associated to e1 been inserted
5096       // into S after the line segment associated to e2 ?
5097       if (compareEvents(le1, le2) === 1) { return le2.isAbove(le1.point) ? -1 : 1; }
5098
5099       // The line segment associated to e2 has been inserted
5100       // into S after the line segment associated to e1
5101       return le1.isBelow(le2.point) ? -1 : 1;
5102     }
5103
5104     if (le1.isSubject === le2.isSubject) { // same polygon
5105       var p1 = le1.point, p2 = le2.point;
5106       if (p1[0] === p2[0] && p1[1] === p2[1]/*equals(le1.point, le2.point)*/) {
5107         p1 = le1.otherEvent.point; p2 = le2.otherEvent.point;
5108         if (p1[0] === p2[0] && p1[1] === p2[1]) { return 0; }
5109         else { return le1.contourId > le2.contourId ? 1 : -1; }
5110       }
5111     } else { // Segments are collinear, but belong to separate polygons
5112       return le1.isSubject ? -1 : 1;
5113     }
5114
5115     return compareEvents(le1, le2) === 1 ? 1 : -1;
5116   }
5117
5118   function subdivide(eventQueue, subject, clipping, sbbox, cbbox, operation) {
5119     var sweepLine = new SplayTree(compareSegments);
5120     var sortedEvents = [];
5121
5122     var rightbound = Math.min(sbbox[2], cbbox[2]);
5123
5124     var prev, next, begin;
5125
5126     while (eventQueue.length !== 0) {
5127       var event = eventQueue.pop();
5128       sortedEvents.push(event);
5129
5130       // optimization by bboxes for intersection and difference goes here
5131       if ((operation === INTERSECTION && event.point[0] > rightbound) ||
5132           (operation === DIFFERENCE   && event.point[0] > sbbox[2])) {
5133         break;
5134       }
5135
5136       if (event.left) {
5137         next  = prev = sweepLine.insert(event);
5138         begin = sweepLine.minNode();
5139
5140         if (prev !== begin) { prev = sweepLine.prev(prev); }
5141         else                { prev = null; }
5142
5143         next = sweepLine.next(next);
5144
5145         var prevEvent = prev ? prev.key : null;
5146         var prevprevEvent = (void 0);
5147         computeFields(event, prevEvent, operation);
5148         if (next) {
5149           if (possibleIntersection(event, next.key, eventQueue) === 2) {
5150             computeFields(event, prevEvent, operation);
5151             computeFields(event, next.key, operation);
5152           }
5153         }
5154
5155         if (prev) {
5156           if (possibleIntersection(prev.key, event, eventQueue) === 2) {
5157             var prevprev = prev;
5158             if (prevprev !== begin) { prevprev = sweepLine.prev(prevprev); }
5159             else                    { prevprev = null; }
5160
5161             prevprevEvent = prevprev ? prevprev.key : null;
5162             computeFields(prevEvent, prevprevEvent, operation);
5163             computeFields(event,     prevEvent,     operation);
5164           }
5165         }
5166       } else {
5167         event = event.otherEvent;
5168         next = prev = sweepLine.find(event);
5169
5170         if (prev && next) {
5171
5172           if (prev !== begin) { prev = sweepLine.prev(prev); }
5173           else                { prev = null; }
5174
5175           next = sweepLine.next(next);
5176           sweepLine.remove(event);
5177
5178           if (next && prev) {
5179             possibleIntersection(prev.key, next.key, eventQueue);
5180           }
5181         }
5182       }
5183     }
5184     return sortedEvents;
5185   }
5186
5187   /**
5188    * @param  {Array.<SweepEvent>} sortedEvents
5189    * @return {Array.<SweepEvent>}
5190    */
5191   function orderEvents(sortedEvents) {
5192     var event, i, len, tmp;
5193     var resultEvents = [];
5194     for (i = 0, len = sortedEvents.length; i < len; i++) {
5195       event = sortedEvents[i];
5196       if ((event.left && event.inResult) ||
5197         (!event.left && event.otherEvent.inResult)) {
5198         resultEvents.push(event);
5199       }
5200     }
5201     // Due to overlapping edges the resultEvents array can be not wholly sorted
5202     var sorted = false;
5203     while (!sorted) {
5204       sorted = true;
5205       for (i = 0, len = resultEvents.length; i < len; i++) {
5206         if ((i + 1) < len &&
5207           compareEvents(resultEvents[i], resultEvents[i + 1]) === 1) {
5208           tmp = resultEvents[i];
5209           resultEvents[i] = resultEvents[i + 1];
5210           resultEvents[i + 1] = tmp;
5211           sorted = false;
5212         }
5213       }
5214     }
5215
5216
5217     for (i = 0, len = resultEvents.length; i < len; i++) {
5218       event = resultEvents[i];
5219       event.pos = i;
5220     }
5221
5222     // imagine, the right event is found in the beginning of the queue,
5223     // when his left counterpart is not marked yet
5224     for (i = 0, len = resultEvents.length; i < len; i++) {
5225       event = resultEvents[i];
5226       if (!event.left) {
5227         tmp = event.pos;
5228         event.pos = event.otherEvent.pos;
5229         event.otherEvent.pos = tmp;
5230       }
5231     }
5232
5233     return resultEvents;
5234   }
5235
5236
5237   /**
5238    * @param  {Number} pos
5239    * @param  {Array.<SweepEvent>} resultEvents
5240    * @param  {Object>}    processed
5241    * @return {Number}
5242    */
5243   function nextPos(pos, resultEvents, processed, origIndex) {
5244     var p, p1;
5245     var newPos = pos + 1;
5246     var length = resultEvents.length;
5247
5248     p  = resultEvents[pos].point;
5249
5250     if (newPos < length)
5251       { p1 = resultEvents[newPos].point; }
5252
5253
5254     // while in range and not the current one by value
5255     while (newPos < length && p1[0] === p[0] && p1[1] === p[1]) {
5256       if (!processed[newPos]) {
5257         return newPos;
5258       } else   {
5259         newPos++;
5260       }
5261       p1 = resultEvents[newPos].point;
5262     }
5263
5264     newPos = pos - 1;
5265
5266     while (processed[newPos] && newPos >= origIndex) {
5267       newPos--;
5268     }
5269     return newPos;
5270   }
5271
5272
5273   /**
5274    * @param  {Array.<SweepEvent>} sortedEvents
5275    * @return {Array.<*>} polygons
5276    */
5277   function connectEdges(sortedEvents, operation) {
5278     var i, len;
5279     var resultEvents = orderEvents(sortedEvents);
5280
5281     // "false"-filled array
5282     var processed = {};
5283     var result = [];
5284     var event;
5285
5286     for (i = 0, len = resultEvents.length; i < len; i++) {
5287       if (processed[i]) { continue; }
5288       var contour = [[]];
5289
5290       if (!resultEvents[i].isExteriorRing) {
5291         if (operation === DIFFERENCE && !resultEvents[i].isSubject && result.length === 0) {
5292           result.push(contour);
5293         } else if (result.length === 0) {
5294           result.push([[contour]]);
5295         } else {
5296           result[result.length - 1].push(contour[0]);
5297         }
5298       } else if (operation === DIFFERENCE && !resultEvents[i].isSubject && result.length > 1) {
5299         result[result.length - 1].push(contour[0]);
5300       } else {
5301         result.push(contour);
5302       }
5303
5304       var ringId = result.length - 1;
5305       var pos = i;
5306
5307       var initial = resultEvents[i].point;
5308       contour[0].push(initial);
5309
5310       while (pos >= i) {
5311         event = resultEvents[pos];
5312         processed[pos] = true;
5313
5314         if (event.left) {
5315           event.resultInOut = false;
5316           event.contourId   = ringId;
5317         } else {
5318           event.otherEvent.resultInOut = true;
5319           event.otherEvent.contourId   = ringId;
5320         }
5321
5322         pos = event.pos;
5323         processed[pos] = true;
5324         contour[0].push(resultEvents[pos].point);
5325         pos = nextPos(pos, resultEvents, processed, i);
5326       }
5327
5328       pos = pos === -1 ? i : pos;
5329
5330       event = resultEvents[pos];
5331       processed[pos] = processed[event.pos] = true;
5332       event.otherEvent.resultInOut = true;
5333       event.otherEvent.contourId   = ringId;
5334     }
5335
5336     // Handle if the result is a polygon (eg not multipoly)
5337     // Commented it again, let's see what do we mean by that
5338     // if (result.length === 1) result = result[0];
5339     return result;
5340   }
5341
5342   var tinyqueue = TinyQueue;
5343   var default_1 = TinyQueue;
5344
5345   function TinyQueue(data, compare) {
5346       var this$1 = this;
5347
5348       if (!(this instanceof TinyQueue)) { return new TinyQueue(data, compare); }
5349
5350       this.data = data || [];
5351       this.length = this.data.length;
5352       this.compare = compare || defaultCompare;
5353
5354       if (this.length > 0) {
5355           for (var i = (this.length >> 1) - 1; i >= 0; i--) { this$1._down(i); }
5356       }
5357   }
5358
5359   function defaultCompare(a, b) {
5360       return a < b ? -1 : a > b ? 1 : 0;
5361   }
5362
5363   TinyQueue.prototype = {
5364
5365       push: function (item) {
5366           this.data.push(item);
5367           this.length++;
5368           this._up(this.length - 1);
5369       },
5370
5371       pop: function () {
5372           if (this.length === 0) { return undefined; }
5373
5374           var top = this.data[0];
5375           this.length--;
5376
5377           if (this.length > 0) {
5378               this.data[0] = this.data[this.length];
5379               this._down(0);
5380           }
5381           this.data.pop();
5382
5383           return top;
5384       },
5385
5386       peek: function () {
5387           return this.data[0];
5388       },
5389
5390       _up: function (pos) {
5391           var data = this.data;
5392           var compare = this.compare;
5393           var item = data[pos];
5394
5395           while (pos > 0) {
5396               var parent = (pos - 1) >> 1;
5397               var current = data[parent];
5398               if (compare(item, current) >= 0) { break; }
5399               data[pos] = current;
5400               pos = parent;
5401           }
5402
5403           data[pos] = item;
5404       },
5405
5406       _down: function (pos) {
5407           var this$1 = this;
5408
5409           var data = this.data;
5410           var compare = this.compare;
5411           var halfLength = this.length >> 1;
5412           var item = data[pos];
5413
5414           while (pos < halfLength) {
5415               var left = (pos << 1) + 1;
5416               var right = left + 1;
5417               var best = data[left];
5418
5419               if (right < this$1.length && compare(data[right], best) < 0) {
5420                   left = right;
5421                   best = data[right];
5422               }
5423               if (compare(best, item) >= 0) { break; }
5424
5425               data[pos] = best;
5426               pos = left;
5427           }
5428
5429           data[pos] = item;
5430       }
5431   };
5432   tinyqueue.default = default_1;
5433
5434   var max = Math.max;
5435   var min = Math.min;
5436
5437   var contourId = 0;
5438
5439
5440   function processPolygon(contourOrHole, isSubject, depth, Q, bbox, isExteriorRing) {
5441     var i, len, s1, s2, e1, e2;
5442     for (i = 0, len = contourOrHole.length - 1; i < len; i++) {
5443       s1 = contourOrHole[i];
5444       s2 = contourOrHole[i + 1];
5445       e1 = new SweepEvent(s1, false, undefined, isSubject);
5446       e2 = new SweepEvent(s2, false, e1,        isSubject);
5447       e1.otherEvent = e2;
5448
5449       if (s1[0] === s2[0] && s1[1] === s2[1]) {
5450         continue; // skip collapsed edges, or it breaks
5451       }
5452
5453       e1.contourId = e2.contourId = depth;
5454       if (!isExteriorRing) {
5455         e1.isExteriorRing = false;
5456         e2.isExteriorRing = false;
5457       }
5458       if (compareEvents(e1, e2) > 0) {
5459         e2.left = true;
5460       } else {
5461         e1.left = true;
5462       }
5463
5464       var x = s1[0], y = s1[1];
5465       bbox[0] = min(bbox[0], x);
5466       bbox[1] = min(bbox[1], y);
5467       bbox[2] = max(bbox[2], x);
5468       bbox[3] = max(bbox[3], y);
5469
5470       // Pushing it so the queue is sorted from left to right,
5471       // with object on the left having the highest priority.
5472       Q.push(e1);
5473       Q.push(e2);
5474     }
5475   }
5476
5477
5478   function fillQueue(subject, clipping, sbbox, cbbox, operation) {
5479     var eventQueue = new tinyqueue(null, compareEvents);
5480     var polygonSet, isExteriorRing, i, ii, j, jj; //, k, kk;
5481
5482     for (i = 0, ii = subject.length; i < ii; i++) {
5483       polygonSet = subject[i];
5484       for (j = 0, jj = polygonSet.length; j < jj; j++) {
5485         isExteriorRing = j === 0;
5486         if (isExteriorRing) { contourId++; }
5487         processPolygon(polygonSet[j], true, contourId, eventQueue, sbbox, isExteriorRing);
5488       }
5489     }
5490
5491     for (i = 0, ii = clipping.length; i < ii; i++) {
5492       polygonSet = clipping[i];
5493       for (j = 0, jj = polygonSet.length; j < jj; j++) {
5494         isExteriorRing = j === 0;
5495         if (operation === DIFFERENCE) { isExteriorRing = false; }
5496         if (isExteriorRing) { contourId++; }
5497         processPolygon(polygonSet[j], false, contourId, eventQueue, cbbox, isExteriorRing);
5498       }
5499     }
5500
5501     return eventQueue;
5502   }
5503
5504   var EMPTY = [];
5505
5506
5507   function trivialOperation(subject, clipping, operation) {
5508     var result = null;
5509     if (subject.length * clipping.length === 0) {
5510       if        (operation === INTERSECTION) {
5511         result = EMPTY;
5512       } else if (operation === DIFFERENCE) {
5513         result = subject;
5514       } else if (operation === UNION ||
5515                  operation === XOR) {
5516         result = (subject.length === 0) ? clipping : subject;
5517       }
5518     }
5519     return result;
5520   }
5521
5522
5523   function compareBBoxes(subject, clipping, sbbox, cbbox, operation) {
5524     var result = null;
5525     if (sbbox[0] > cbbox[2] ||
5526         cbbox[0] > sbbox[2] ||
5527         sbbox[1] > cbbox[3] ||
5528         cbbox[1] > sbbox[3]) {
5529       if        (operation === INTERSECTION) {
5530         result = EMPTY;
5531       } else if (operation === DIFFERENCE) {
5532         result = subject;
5533       } else if (operation === UNION ||
5534                  operation === XOR) {
5535         result = subject.concat(clipping);
5536       }
5537     }
5538     return result;
5539   }
5540
5541
5542   function boolean(subject, clipping, operation) {
5543     if (typeof subject[0][0][0] === 'number') {
5544       subject = [subject];
5545     }
5546     if (typeof clipping[0][0][0] === 'number') {
5547       clipping = [clipping];
5548     }
5549     var trivial = trivialOperation(subject, clipping, operation);
5550     if (trivial) {
5551       return trivial === EMPTY ? null : trivial;
5552     }
5553     var sbbox = [Infinity, Infinity, -Infinity, -Infinity];
5554     var cbbox = [Infinity, Infinity, -Infinity, -Infinity];
5555
5556     //console.time('fill queue');
5557     var eventQueue = fillQueue(subject, clipping, sbbox, cbbox, operation);
5558     //console.timeEnd('fill queue');
5559
5560     trivial = compareBBoxes(subject, clipping, sbbox, cbbox, operation);
5561     if (trivial) {
5562       return trivial === EMPTY ? null : trivial;
5563     }
5564     //console.time('subdivide edges');
5565     var sortedEvents = subdivide(eventQueue, subject, clipping, sbbox, cbbox, operation);
5566     //console.timeEnd('subdivide edges');
5567
5568     //console.time('connect vertices');
5569     var result = connectEdges(sortedEvents, operation);
5570     //console.timeEnd('connect vertices');
5571     return result;
5572   }
5573
5574   function union (subject, clipping) {
5575     return boolean(subject, clipping, UNION);
5576   }
5577
5578   function diff (subject, clipping) {
5579     return boolean(subject, clipping, DIFFERENCE);
5580   }
5581
5582   function xor (subject, clipping){
5583     return boolean(subject, clipping, XOR);
5584   }
5585
5586   function intersection$1 (subject, clipping) {
5587     return boolean(subject, clipping, INTERSECTION);
5588   }
5589
5590   /**
5591    * @enum {Number}
5592    */
5593   var operations = { UNION: UNION, DIFFERENCE: DIFFERENCE, INTERSECTION: INTERSECTION, XOR: XOR };
5594
5595   exports.union = union;
5596   exports.diff = diff;
5597   exports.xor = xor;
5598   exports.intersection = intersection$1;
5599   exports.operations = operations;
5600
5601   Object.defineProperty(exports, '__esModule', { value: true });
5602
5603 })));
5604
5605
5606 },{}],23:[function(require,module,exports){
5607 (function (process){
5608 // Copyright Joyent, Inc. and other Node contributors.
5609 //
5610 // Permission is hereby granted, free of charge, to any person obtaining a
5611 // copy of this software and associated documentation files (the
5612 // "Software"), to deal in the Software without restriction, including
5613 // without limitation the rights to use, copy, modify, merge, publish,
5614 // distribute, sublicense, and/or sell copies of the Software, and to permit
5615 // persons to whom the Software is furnished to do so, subject to the
5616 // following conditions:
5617 //
5618 // The above copyright notice and this permission notice shall be included
5619 // in all copies or substantial portions of the Software.
5620 //
5621 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5622 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5623 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5624 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5625 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5626 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5627 // USE OR OTHER DEALINGS IN THE SOFTWARE.
5628
5629 // resolves . and .. elements in a path array with directory names there
5630 // must be no slashes, empty elements, or device names (c:\) in the array
5631 // (so also no leading and trailing slashes - it does not distinguish
5632 // relative and absolute paths)
5633 function normalizeArray(parts, allowAboveRoot) {
5634   // if the path tries to go above the root, `up` ends up > 0
5635   var up = 0;
5636   for (var i = parts.length - 1; i >= 0; i--) {
5637     var last = parts[i];
5638     if (last === '.') {
5639       parts.splice(i, 1);
5640     } else if (last === '..') {
5641       parts.splice(i, 1);
5642       up++;
5643     } else if (up) {
5644       parts.splice(i, 1);
5645       up--;
5646     }
5647   }
5648
5649   // if the path is allowed to go above the root, restore leading ..s
5650   if (allowAboveRoot) {
5651     for (; up--; up) {
5652       parts.unshift('..');
5653     }
5654   }
5655
5656   return parts;
5657 }
5658
5659 // Split a filename into [root, dir, basename, ext], unix version
5660 // 'root' is just a slash, or nothing.
5661 var splitPathRe =
5662     /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
5663 var splitPath = function(filename) {
5664   return splitPathRe.exec(filename).slice(1);
5665 };
5666
5667 // path.resolve([from ...], to)
5668 // posix version
5669 exports.resolve = function() {
5670   var resolvedPath = '',
5671       resolvedAbsolute = false;
5672
5673   for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
5674     var path = (i >= 0) ? arguments[i] : process.cwd();
5675
5676     // Skip empty and invalid entries
5677     if (typeof path !== 'string') {
5678       throw new TypeError('Arguments to path.resolve must be strings');
5679     } else if (!path) {
5680       continue;
5681     }
5682
5683     resolvedPath = path + '/' + resolvedPath;
5684     resolvedAbsolute = path.charAt(0) === '/';
5685   }
5686
5687   // At this point the path should be resolved to a full absolute path, but
5688   // handle relative paths to be safe (might happen when process.cwd() fails)
5689
5690   // Normalize the path
5691   resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
5692     return !!p;
5693   }), !resolvedAbsolute).join('/');
5694
5695   return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
5696 };
5697
5698 // path.normalize(path)
5699 // posix version
5700 exports.normalize = function(path) {
5701   var isAbsolute = exports.isAbsolute(path),
5702       trailingSlash = substr(path, -1) === '/';
5703
5704   // Normalize the path
5705   path = normalizeArray(filter(path.split('/'), function(p) {
5706     return !!p;
5707   }), !isAbsolute).join('/');
5708
5709   if (!path && !isAbsolute) {
5710     path = '.';
5711   }
5712   if (path && trailingSlash) {
5713     path += '/';
5714   }
5715
5716   return (isAbsolute ? '/' : '') + path;
5717 };
5718
5719 // posix version
5720 exports.isAbsolute = function(path) {
5721   return path.charAt(0) === '/';
5722 };
5723
5724 // posix version
5725 exports.join = function() {
5726   var paths = Array.prototype.slice.call(arguments, 0);
5727   return exports.normalize(filter(paths, function(p, index) {
5728     if (typeof p !== 'string') {
5729       throw new TypeError('Arguments to path.join must be strings');
5730     }
5731     return p;
5732   }).join('/'));
5733 };
5734
5735
5736 // path.relative(from, to)
5737 // posix version
5738 exports.relative = function(from, to) {
5739   from = exports.resolve(from).substr(1);
5740   to = exports.resolve(to).substr(1);
5741
5742   function trim(arr) {
5743     var start = 0;
5744     for (; start < arr.length; start++) {
5745       if (arr[start] !== '') break;
5746     }
5747
5748     var end = arr.length - 1;
5749     for (; end >= 0; end--) {
5750       if (arr[end] !== '') break;
5751     }
5752
5753     if (start > end) return [];
5754     return arr.slice(start, end - start + 1);
5755   }
5756
5757   var fromParts = trim(from.split('/'));
5758   var toParts = trim(to.split('/'));
5759
5760   var length = Math.min(fromParts.length, toParts.length);
5761   var samePartsLength = length;
5762   for (var i = 0; i < length; i++) {
5763     if (fromParts[i] !== toParts[i]) {
5764       samePartsLength = i;
5765       break;
5766     }
5767   }
5768
5769   var outputParts = [];
5770   for (var i = samePartsLength; i < fromParts.length; i++) {
5771     outputParts.push('..');
5772   }
5773
5774   outputParts = outputParts.concat(toParts.slice(samePartsLength));
5775
5776   return outputParts.join('/');
5777 };
5778
5779 exports.sep = '/';
5780 exports.delimiter = ':';
5781
5782 exports.dirname = function(path) {
5783   var result = splitPath(path),
5784       root = result[0],
5785       dir = result[1];
5786
5787   if (!root && !dir) {
5788     // No dirname whatsoever
5789     return '.';
5790   }
5791
5792   if (dir) {
5793     // It has a dirname, strip trailing slash
5794     dir = dir.substr(0, dir.length - 1);
5795   }
5796
5797   return root + dir;
5798 };
5799
5800
5801 exports.basename = function(path, ext) {
5802   var f = splitPath(path)[2];
5803   // TODO: make this comparison case-insensitive on windows?
5804   if (ext && f.substr(-1 * ext.length) === ext) {
5805     f = f.substr(0, f.length - ext.length);
5806   }
5807   return f;
5808 };
5809
5810
5811 exports.extname = function(path) {
5812   return splitPath(path)[3];
5813 };
5814
5815 function filter (xs, f) {
5816     if (xs.filter) return xs.filter(f);
5817     var res = [];
5818     for (var i = 0; i < xs.length; i++) {
5819         if (f(xs[i], i, xs)) res.push(xs[i]);
5820     }
5821     return res;
5822 }
5823
5824 // String.prototype.substr - negative index don't work in IE8
5825 var substr = 'ab'.substr(-1) === 'b'
5826     ? function (str, start, len) { return str.substr(start, len) }
5827     : function (str, start, len) {
5828         if (start < 0) start = str.length + start;
5829         return str.substr(start, len);
5830     }
5831 ;
5832
5833 }).call(this,require('_process'))
5834
5835 },{"_process":6}],24:[function(require,module,exports){
5836 'use strict';
5837
5838 module.exports = Pbf;
5839
5840 var ieee754 = require('ieee754');
5841
5842 function Pbf(buf) {
5843     this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
5844     this.pos = 0;
5845     this.type = 0;
5846     this.length = this.buf.length;
5847 }
5848
5849 Pbf.Varint  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
5850 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
5851 Pbf.Bytes   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
5852 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
5853
5854 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
5855     SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
5856
5857 Pbf.prototype = {
5858
5859     destroy: function() {
5860         this.buf = null;
5861     },
5862
5863     // === READING =================================================================
5864
5865     readFields: function(readField, result, end) {
5866         end = end || this.length;
5867
5868         while (this.pos < end) {
5869             var val = this.readVarint(),
5870                 tag = val >> 3,
5871                 startPos = this.pos;
5872
5873             this.type = val & 0x7;
5874             readField(tag, result, this);
5875
5876             if (this.pos === startPos) this.skip(val);
5877         }
5878         return result;
5879     },
5880
5881     readMessage: function(readField, result) {
5882         return this.readFields(readField, result, this.readVarint() + this.pos);
5883     },
5884
5885     readFixed32: function() {
5886         var val = readUInt32(this.buf, this.pos);
5887         this.pos += 4;
5888         return val;
5889     },
5890
5891     readSFixed32: function() {
5892         var val = readInt32(this.buf, this.pos);
5893         this.pos += 4;
5894         return val;
5895     },
5896
5897     // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
5898
5899     readFixed64: function() {
5900         var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
5901         this.pos += 8;
5902         return val;
5903     },
5904
5905     readSFixed64: function() {
5906         var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
5907         this.pos += 8;
5908         return val;
5909     },
5910
5911     readFloat: function() {
5912         var val = ieee754.read(this.buf, this.pos, true, 23, 4);
5913         this.pos += 4;
5914         return val;
5915     },
5916
5917     readDouble: function() {
5918         var val = ieee754.read(this.buf, this.pos, true, 52, 8);
5919         this.pos += 8;
5920         return val;
5921     },
5922
5923     readVarint: function(isSigned) {
5924         var buf = this.buf,
5925             val, b;
5926
5927         b = buf[this.pos++]; val  =  b & 0x7f;        if (b < 0x80) return val;
5928         b = buf[this.pos++]; val |= (b & 0x7f) << 7;  if (b < 0x80) return val;
5929         b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
5930         b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
5931         b = buf[this.pos];   val |= (b & 0x0f) << 28;
5932
5933         return readVarintRemainder(val, isSigned, this);
5934     },
5935
5936     readVarint64: function() { // for compatibility with v2.0.1
5937         return this.readVarint(true);
5938     },
5939
5940     readSVarint: function() {
5941         var num = this.readVarint();
5942         return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
5943     },
5944
5945     readBoolean: function() {
5946         return Boolean(this.readVarint());
5947     },
5948
5949     readString: function() {
5950         var end = this.readVarint() + this.pos,
5951             str = readUtf8(this.buf, this.pos, end);
5952         this.pos = end;
5953         return str;
5954     },
5955
5956     readBytes: function() {
5957         var end = this.readVarint() + this.pos,
5958             buffer = this.buf.subarray(this.pos, end);
5959         this.pos = end;
5960         return buffer;
5961     },
5962
5963     // verbose for performance reasons; doesn't affect gzipped size
5964
5965     readPackedVarint: function(arr, isSigned) {
5966         var end = readPackedEnd(this);
5967         arr = arr || [];
5968         while (this.pos < end) arr.push(this.readVarint(isSigned));
5969         return arr;
5970     },
5971     readPackedSVarint: function(arr) {
5972         var end = readPackedEnd(this);
5973         arr = arr || [];
5974         while (this.pos < end) arr.push(this.readSVarint());
5975         return arr;
5976     },
5977     readPackedBoolean: function(arr) {
5978         var end = readPackedEnd(this);
5979         arr = arr || [];
5980         while (this.pos < end) arr.push(this.readBoolean());
5981         return arr;
5982     },
5983     readPackedFloat: function(arr) {
5984         var end = readPackedEnd(this);
5985         arr = arr || [];
5986         while (this.pos < end) arr.push(this.readFloat());
5987         return arr;
5988     },
5989     readPackedDouble: function(arr) {
5990         var end = readPackedEnd(this);
5991         arr = arr || [];
5992         while (this.pos < end) arr.push(this.readDouble());
5993         return arr;
5994     },
5995     readPackedFixed32: function(arr) {
5996         var end = readPackedEnd(this);
5997         arr = arr || [];
5998         while (this.pos < end) arr.push(this.readFixed32());
5999         return arr;
6000     },
6001     readPackedSFixed32: function(arr) {
6002         var end = readPackedEnd(this);
6003         arr = arr || [];
6004         while (this.pos < end) arr.push(this.readSFixed32());
6005         return arr;
6006     },
6007     readPackedFixed64: function(arr) {
6008         var end = readPackedEnd(this);
6009         arr = arr || [];
6010         while (this.pos < end) arr.push(this.readFixed64());
6011         return arr;
6012     },
6013     readPackedSFixed64: function(arr) {
6014         var end = readPackedEnd(this);
6015         arr = arr || [];
6016         while (this.pos < end) arr.push(this.readSFixed64());
6017         return arr;
6018     },
6019
6020     skip: function(val) {
6021         var type = val & 0x7;
6022         if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
6023         else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
6024         else if (type === Pbf.Fixed32) this.pos += 4;
6025         else if (type === Pbf.Fixed64) this.pos += 8;
6026         else throw new Error('Unimplemented type: ' + type);
6027     },
6028
6029     // === WRITING =================================================================
6030
6031     writeTag: function(tag, type) {
6032         this.writeVarint((tag << 3) | type);
6033     },
6034
6035     realloc: function(min) {
6036         var length = this.length || 16;
6037
6038         while (length < this.pos + min) length *= 2;
6039
6040         if (length !== this.length) {
6041             var buf = new Uint8Array(length);
6042             buf.set(this.buf);
6043             this.buf = buf;
6044             this.length = length;
6045         }
6046     },
6047
6048     finish: function() {
6049         this.length = this.pos;
6050         this.pos = 0;
6051         return this.buf.subarray(0, this.length);
6052     },
6053
6054     writeFixed32: function(val) {
6055         this.realloc(4);
6056         writeInt32(this.buf, val, this.pos);
6057         this.pos += 4;
6058     },
6059
6060     writeSFixed32: function(val) {
6061         this.realloc(4);
6062         writeInt32(this.buf, val, this.pos);
6063         this.pos += 4;
6064     },
6065
6066     writeFixed64: function(val) {
6067         this.realloc(8);
6068         writeInt32(this.buf, val & -1, this.pos);
6069         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
6070         this.pos += 8;
6071     },
6072
6073     writeSFixed64: function(val) {
6074         this.realloc(8);
6075         writeInt32(this.buf, val & -1, this.pos);
6076         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
6077         this.pos += 8;
6078     },
6079
6080     writeVarint: function(val) {
6081         val = +val || 0;
6082
6083         if (val > 0xfffffff || val < 0) {
6084             writeBigVarint(val, this);
6085             return;
6086         }
6087
6088         this.realloc(4);
6089
6090         this.buf[this.pos++] =           val & 0x7f  | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
6091         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
6092         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
6093         this.buf[this.pos++] =   (val >>> 7) & 0x7f;
6094     },
6095
6096     writeSVarint: function(val) {
6097         this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
6098     },
6099
6100     writeBoolean: function(val) {
6101         this.writeVarint(Boolean(val));
6102     },
6103
6104     writeString: function(str) {
6105         str = String(str);
6106         this.realloc(str.length * 4);
6107
6108         this.pos++; // reserve 1 byte for short string length
6109
6110         var startPos = this.pos;
6111         // write the string directly to the buffer and see how much was written
6112         this.pos = writeUtf8(this.buf, str, this.pos);
6113         var len = this.pos - startPos;
6114
6115         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
6116
6117         // finally, write the message length in the reserved place and restore the position
6118         this.pos = startPos - 1;
6119         this.writeVarint(len);
6120         this.pos += len;
6121     },
6122
6123     writeFloat: function(val) {
6124         this.realloc(4);
6125         ieee754.write(this.buf, val, this.pos, true, 23, 4);
6126         this.pos += 4;
6127     },
6128
6129     writeDouble: function(val) {
6130         this.realloc(8);
6131         ieee754.write(this.buf, val, this.pos, true, 52, 8);
6132         this.pos += 8;
6133     },
6134
6135     writeBytes: function(buffer) {
6136         var len = buffer.length;
6137         this.writeVarint(len);
6138         this.realloc(len);
6139         for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
6140     },
6141
6142     writeRawMessage: function(fn, obj) {
6143         this.pos++; // reserve 1 byte for short message length
6144
6145         // write the message directly to the buffer and see how much was written
6146         var startPos = this.pos;
6147         fn(obj, this);
6148         var len = this.pos - startPos;
6149
6150         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
6151
6152         // finally, write the message length in the reserved place and restore the position
6153         this.pos = startPos - 1;
6154         this.writeVarint(len);
6155         this.pos += len;
6156     },
6157
6158     writeMessage: function(tag, fn, obj) {
6159         this.writeTag(tag, Pbf.Bytes);
6160         this.writeRawMessage(fn, obj);
6161     },
6162
6163     writePackedVarint:   function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr);   },
6164     writePackedSVarint:  function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr);  },
6165     writePackedBoolean:  function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr);  },
6166     writePackedFloat:    function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr);    },
6167     writePackedDouble:   function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr);   },
6168     writePackedFixed32:  function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr);  },
6169     writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
6170     writePackedFixed64:  function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr);  },
6171     writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
6172
6173     writeBytesField: function(tag, buffer) {
6174         this.writeTag(tag, Pbf.Bytes);
6175         this.writeBytes(buffer);
6176     },
6177     writeFixed32Field: function(tag, val) {
6178         this.writeTag(tag, Pbf.Fixed32);
6179         this.writeFixed32(val);
6180     },
6181     writeSFixed32Field: function(tag, val) {
6182         this.writeTag(tag, Pbf.Fixed32);
6183         this.writeSFixed32(val);
6184     },
6185     writeFixed64Field: function(tag, val) {
6186         this.writeTag(tag, Pbf.Fixed64);
6187         this.writeFixed64(val);
6188     },
6189     writeSFixed64Field: function(tag, val) {
6190         this.writeTag(tag, Pbf.Fixed64);
6191         this.writeSFixed64(val);
6192     },
6193     writeVarintField: function(tag, val) {
6194         this.writeTag(tag, Pbf.Varint);
6195         this.writeVarint(val);
6196     },
6197     writeSVarintField: function(tag, val) {
6198         this.writeTag(tag, Pbf.Varint);
6199         this.writeSVarint(val);
6200     },
6201     writeStringField: function(tag, str) {
6202         this.writeTag(tag, Pbf.Bytes);
6203         this.writeString(str);
6204     },
6205     writeFloatField: function(tag, val) {
6206         this.writeTag(tag, Pbf.Fixed32);
6207         this.writeFloat(val);
6208     },
6209     writeDoubleField: function(tag, val) {
6210         this.writeTag(tag, Pbf.Fixed64);
6211         this.writeDouble(val);
6212     },
6213     writeBooleanField: function(tag, val) {
6214         this.writeVarintField(tag, Boolean(val));
6215     }
6216 };
6217
6218 function readVarintRemainder(l, s, p) {
6219     var buf = p.buf,
6220         h, b;
6221
6222     b = buf[p.pos++]; h  = (b & 0x70) >> 4;  if (b < 0x80) return toNum(l, h, s);
6223     b = buf[p.pos++]; h |= (b & 0x7f) << 3;  if (b < 0x80) return toNum(l, h, s);
6224     b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
6225     b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
6226     b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
6227     b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
6228
6229     throw new Error('Expected varint not more than 10 bytes');
6230 }
6231
6232 function readPackedEnd(pbf) {
6233     return pbf.type === Pbf.Bytes ?
6234         pbf.readVarint() + pbf.pos : pbf.pos + 1;
6235 }
6236
6237 function toNum(low, high, isSigned) {
6238     if (isSigned) {
6239         return high * 0x100000000 + (low >>> 0);
6240     }
6241
6242     return ((high >>> 0) * 0x100000000) + (low >>> 0);
6243 }
6244
6245 function writeBigVarint(val, pbf) {
6246     var low, high;
6247
6248     if (val >= 0) {
6249         low  = (val % 0x100000000) | 0;
6250         high = (val / 0x100000000) | 0;
6251     } else {
6252         low  = ~(-val % 0x100000000);
6253         high = ~(-val / 0x100000000);
6254
6255         if (low ^ 0xffffffff) {
6256             low = (low + 1) | 0;
6257         } else {
6258             low = 0;
6259             high = (high + 1) | 0;
6260         }
6261     }
6262
6263     if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
6264         throw new Error('Given varint doesn\'t fit into 10 bytes');
6265     }
6266
6267     pbf.realloc(10);
6268
6269     writeBigVarintLow(low, high, pbf);
6270     writeBigVarintHigh(high, pbf);
6271 }
6272
6273 function writeBigVarintLow(low, high, pbf) {
6274     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
6275     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
6276     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
6277     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
6278     pbf.buf[pbf.pos]   = low & 0x7f;
6279 }
6280
6281 function writeBigVarintHigh(high, pbf) {
6282     var lsb = (high & 0x07) << 4;
6283
6284     pbf.buf[pbf.pos++] |= lsb         | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
6285     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
6286     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
6287     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
6288     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
6289     pbf.buf[pbf.pos++]  = high & 0x7f;
6290 }
6291
6292 function makeRoomForExtraLength(startPos, len, pbf) {
6293     var extraLen =
6294         len <= 0x3fff ? 1 :
6295         len <= 0x1fffff ? 2 :
6296         len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
6297
6298     // if 1 byte isn't enough for encoding message length, shift the data to the right
6299     pbf.realloc(extraLen);
6300     for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
6301 }
6302
6303 function writePackedVarint(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);   }
6304 function writePackedSVarint(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);  }
6305 function writePackedFloat(arr, pbf)    { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);    }
6306 function writePackedDouble(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);   }
6307 function writePackedBoolean(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);  }
6308 function writePackedFixed32(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);  }
6309 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
6310 function writePackedFixed64(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);  }
6311 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
6312
6313 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
6314
6315 function readUInt32(buf, pos) {
6316     return ((buf[pos]) |
6317         (buf[pos + 1] << 8) |
6318         (buf[pos + 2] << 16)) +
6319         (buf[pos + 3] * 0x1000000);
6320 }
6321
6322 function writeInt32(buf, val, pos) {
6323     buf[pos] = val;
6324     buf[pos + 1] = (val >>> 8);
6325     buf[pos + 2] = (val >>> 16);
6326     buf[pos + 3] = (val >>> 24);
6327 }
6328
6329 function readInt32(buf, pos) {
6330     return ((buf[pos]) |
6331         (buf[pos + 1] << 8) |
6332         (buf[pos + 2] << 16)) +
6333         (buf[pos + 3] << 24);
6334 }
6335
6336 function readUtf8(buf, pos, end) {
6337     var str = '';
6338     var i = pos;
6339
6340     while (i < end) {
6341         var b0 = buf[i];
6342         var c = null; // codepoint
6343         var bytesPerSequence =
6344             b0 > 0xEF ? 4 :
6345             b0 > 0xDF ? 3 :
6346             b0 > 0xBF ? 2 : 1;
6347
6348         if (i + bytesPerSequence > end) break;
6349
6350         var b1, b2, b3;
6351
6352         if (bytesPerSequence === 1) {
6353             if (b0 < 0x80) {
6354                 c = b0;
6355             }
6356         } else if (bytesPerSequence === 2) {
6357             b1 = buf[i + 1];
6358             if ((b1 & 0xC0) === 0x80) {
6359                 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
6360                 if (c <= 0x7F) {
6361                     c = null;
6362                 }
6363             }
6364         } else if (bytesPerSequence === 3) {
6365             b1 = buf[i + 1];
6366             b2 = buf[i + 2];
6367             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
6368                 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
6369                 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
6370                     c = null;
6371                 }
6372             }
6373         } else if (bytesPerSequence === 4) {
6374             b1 = buf[i + 1];
6375             b2 = buf[i + 2];
6376             b3 = buf[i + 3];
6377             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
6378                 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
6379                 if (c <= 0xFFFF || c >= 0x110000) {
6380                     c = null;
6381                 }
6382             }
6383         }
6384
6385         if (c === null) {
6386             c = 0xFFFD;
6387             bytesPerSequence = 1;
6388
6389         } else if (c > 0xFFFF) {
6390             c -= 0x10000;
6391             str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
6392             c = 0xDC00 | c & 0x3FF;
6393         }
6394
6395         str += String.fromCharCode(c);
6396         i += bytesPerSequence;
6397     }
6398
6399     return str;
6400 }
6401
6402 function writeUtf8(buf, str, pos) {
6403     for (var i = 0, c, lead; i < str.length; i++) {
6404         c = str.charCodeAt(i); // code point
6405
6406         if (c > 0xD7FF && c < 0xE000) {
6407             if (lead) {
6408                 if (c < 0xDC00) {
6409                     buf[pos++] = 0xEF;
6410                     buf[pos++] = 0xBF;
6411                     buf[pos++] = 0xBD;
6412                     lead = c;
6413                     continue;
6414                 } else {
6415                     c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
6416                     lead = null;
6417                 }
6418             } else {
6419                 if (c > 0xDBFF || (i + 1 === str.length)) {
6420                     buf[pos++] = 0xEF;
6421                     buf[pos++] = 0xBF;
6422                     buf[pos++] = 0xBD;
6423                 } else {
6424                     lead = c;
6425                 }
6426                 continue;
6427             }
6428         } else if (lead) {
6429             buf[pos++] = 0xEF;
6430             buf[pos++] = 0xBF;
6431             buf[pos++] = 0xBD;
6432             lead = null;
6433         }
6434
6435         if (c < 0x80) {
6436             buf[pos++] = c;
6437         } else {
6438             if (c < 0x800) {
6439                 buf[pos++] = c >> 0x6 | 0xC0;
6440             } else {
6441                 if (c < 0x10000) {
6442                     buf[pos++] = c >> 0xC | 0xE0;
6443                 } else {
6444                     buf[pos++] = c >> 0x12 | 0xF0;
6445                     buf[pos++] = c >> 0xC & 0x3F | 0x80;
6446                 }
6447                 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
6448             }
6449             buf[pos++] = c & 0x3F | 0x80;
6450         }
6451     }
6452     return pos;
6453 }
6454
6455 },{"ieee754":17}],25:[function(require,module,exports){
6456 (function (global, factory) {
6457         typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
6458         typeof define === 'function' && define.amd ? define(factory) :
6459         (global.quickselect = factory());
6460 }(this, (function () { 'use strict';
6461
6462 function quickselect(arr, k, left, right, compare) {
6463     quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
6464 }
6465
6466 function quickselectStep(arr, k, left, right, compare) {
6467
6468     while (right > left) {
6469         if (right - left > 600) {
6470             var n = right - left + 1;
6471             var m = k - left + 1;
6472             var z = Math.log(n);
6473             var s = 0.5 * Math.exp(2 * z / 3);
6474             var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
6475             var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
6476             var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
6477             quickselectStep(arr, k, newLeft, newRight, compare);
6478         }
6479
6480         var t = arr[k];
6481         var i = left;
6482         var j = right;
6483
6484         swap(arr, left, k);
6485         if (compare(arr[right], t) > 0) swap(arr, left, right);
6486
6487         while (i < j) {
6488             swap(arr, i, j);
6489             i++;
6490             j--;
6491             while (compare(arr[i], t) < 0) i++;
6492             while (compare(arr[j], t) > 0) j--;
6493         }
6494
6495         if (compare(arr[left], t) === 0) swap(arr, left, j);
6496         else {
6497             j++;
6498             swap(arr, j, right);
6499         }
6500
6501         if (j <= k) left = j + 1;
6502         if (k <= j) right = j - 1;
6503     }
6504 }
6505
6506 function swap(arr, i, j) {
6507     var tmp = arr[i];
6508     arr[i] = arr[j];
6509     arr[j] = tmp;
6510 }
6511
6512 function defaultCompare(a, b) {
6513     return a < b ? -1 : a > b ? 1 : 0;
6514 }
6515
6516 return quickselect;
6517
6518 })));
6519
6520 },{}],26:[function(require,module,exports){
6521 'use strict';
6522
6523 module.exports = rbush;
6524 module.exports.default = rbush;
6525
6526 var quickselect = require('quickselect');
6527
6528 function rbush(maxEntries, format) {
6529     if (!(this instanceof rbush)) return new rbush(maxEntries, format);
6530
6531     // max entries in a node is 9 by default; min node fill is 40% for best performance
6532     this._maxEntries = Math.max(4, maxEntries || 9);
6533     this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
6534
6535     if (format) {
6536         this._initFormat(format);
6537     }
6538
6539     this.clear();
6540 }
6541
6542 rbush.prototype = {
6543
6544     all: function () {
6545         return this._all(this.data, []);
6546     },
6547
6548     search: function (bbox) {
6549
6550         var node = this.data,
6551             result = [],
6552             toBBox = this.toBBox;
6553
6554         if (!intersects(bbox, node)) return result;
6555
6556         var nodesToSearch = [],
6557             i, len, child, childBBox;
6558
6559         while (node) {
6560             for (i = 0, len = node.children.length; i < len; i++) {
6561
6562                 child = node.children[i];
6563                 childBBox = node.leaf ? toBBox(child) : child;
6564
6565                 if (intersects(bbox, childBBox)) {
6566                     if (node.leaf) result.push(child);
6567                     else if (contains(bbox, childBBox)) this._all(child, result);
6568                     else nodesToSearch.push(child);
6569                 }
6570             }
6571             node = nodesToSearch.pop();
6572         }
6573
6574         return result;
6575     },
6576
6577     collides: function (bbox) {
6578
6579         var node = this.data,
6580             toBBox = this.toBBox;
6581
6582         if (!intersects(bbox, node)) return false;
6583
6584         var nodesToSearch = [],
6585             i, len, child, childBBox;
6586
6587         while (node) {
6588             for (i = 0, len = node.children.length; i < len; i++) {
6589
6590                 child = node.children[i];
6591                 childBBox = node.leaf ? toBBox(child) : child;
6592
6593                 if (intersects(bbox, childBBox)) {
6594                     if (node.leaf || contains(bbox, childBBox)) return true;
6595                     nodesToSearch.push(child);
6596                 }
6597             }
6598             node = nodesToSearch.pop();
6599         }
6600
6601         return false;
6602     },
6603
6604     load: function (data) {
6605         if (!(data && data.length)) return this;
6606
6607         if (data.length < this._minEntries) {
6608             for (var i = 0, len = data.length; i < len; i++) {
6609                 this.insert(data[i]);
6610             }
6611             return this;
6612         }
6613
6614         // recursively build the tree with the given data from scratch using OMT algorithm
6615         var node = this._build(data.slice(), 0, data.length - 1, 0);
6616
6617         if (!this.data.children.length) {
6618             // save as is if tree is empty
6619             this.data = node;
6620
6621         } else if (this.data.height === node.height) {
6622             // split root if trees have the same height
6623             this._splitRoot(this.data, node);
6624
6625         } else {
6626             if (this.data.height < node.height) {
6627                 // swap trees if inserted one is bigger
6628                 var tmpNode = this.data;
6629                 this.data = node;
6630                 node = tmpNode;
6631             }
6632
6633             // insert the small tree into the large tree at appropriate level
6634             this._insert(node, this.data.height - node.height - 1, true);
6635         }
6636
6637         return this;
6638     },
6639
6640     insert: function (item) {
6641         if (item) this._insert(item, this.data.height - 1);
6642         return this;
6643     },
6644
6645     clear: function () {
6646         this.data = createNode([]);
6647         return this;
6648     },
6649
6650     remove: function (item, equalsFn) {
6651         if (!item) return this;
6652
6653         var node = this.data,
6654             bbox = this.toBBox(item),
6655             path = [],
6656             indexes = [],
6657             i, parent, index, goingUp;
6658
6659         // depth-first iterative tree traversal
6660         while (node || path.length) {
6661
6662             if (!node) { // go up
6663                 node = path.pop();
6664                 parent = path[path.length - 1];
6665                 i = indexes.pop();
6666                 goingUp = true;
6667             }
6668
6669             if (node.leaf) { // check current node
6670                 index = findItem(item, node.children, equalsFn);
6671
6672                 if (index !== -1) {
6673                     // item found, remove the item and condense tree upwards
6674                     node.children.splice(index, 1);
6675                     path.push(node);
6676                     this._condense(path);
6677                     return this;
6678                 }
6679             }
6680
6681             if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
6682                 path.push(node);
6683                 indexes.push(i);
6684                 i = 0;
6685                 parent = node;
6686                 node = node.children[0];
6687
6688             } else if (parent) { // go right
6689                 i++;
6690                 node = parent.children[i];
6691                 goingUp = false;
6692
6693             } else node = null; // nothing found
6694         }
6695
6696         return this;
6697     },
6698
6699     toBBox: function (item) { return item; },
6700
6701     compareMinX: compareNodeMinX,
6702     compareMinY: compareNodeMinY,
6703
6704     toJSON: function () { return this.data; },
6705
6706     fromJSON: function (data) {
6707         this.data = data;
6708         return this;
6709     },
6710
6711     _all: function (node, result) {
6712         var nodesToSearch = [];
6713         while (node) {
6714             if (node.leaf) result.push.apply(result, node.children);
6715             else nodesToSearch.push.apply(nodesToSearch, node.children);
6716
6717             node = nodesToSearch.pop();
6718         }
6719         return result;
6720     },
6721
6722     _build: function (items, left, right, height) {
6723
6724         var N = right - left + 1,
6725             M = this._maxEntries,
6726             node;
6727
6728         if (N <= M) {
6729             // reached leaf level; return leaf
6730             node = createNode(items.slice(left, right + 1));
6731             calcBBox(node, this.toBBox);
6732             return node;
6733         }
6734
6735         if (!height) {
6736             // target height of the bulk-loaded tree
6737             height = Math.ceil(Math.log(N) / Math.log(M));
6738
6739             // target number of root entries to maximize storage utilization
6740             M = Math.ceil(N / Math.pow(M, height - 1));
6741         }
6742
6743         node = createNode([]);
6744         node.leaf = false;
6745         node.height = height;
6746
6747         // split the items into M mostly square tiles
6748
6749         var N2 = Math.ceil(N / M),
6750             N1 = N2 * Math.ceil(Math.sqrt(M)),
6751             i, j, right2, right3;
6752
6753         multiSelect(items, left, right, N1, this.compareMinX);
6754
6755         for (i = left; i <= right; i += N1) {
6756
6757             right2 = Math.min(i + N1 - 1, right);
6758
6759             multiSelect(items, i, right2, N2, this.compareMinY);
6760
6761             for (j = i; j <= right2; j += N2) {
6762
6763                 right3 = Math.min(j + N2 - 1, right2);
6764
6765                 // pack each entry recursively
6766                 node.children.push(this._build(items, j, right3, height - 1));
6767             }
6768         }
6769
6770         calcBBox(node, this.toBBox);
6771
6772         return node;
6773     },
6774
6775     _chooseSubtree: function (bbox, node, level, path) {
6776
6777         var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
6778
6779         while (true) {
6780             path.push(node);
6781
6782             if (node.leaf || path.length - 1 === level) break;
6783
6784             minArea = minEnlargement = Infinity;
6785
6786             for (i = 0, len = node.children.length; i < len; i++) {
6787                 child = node.children[i];
6788                 area = bboxArea(child);
6789                 enlargement = enlargedArea(bbox, child) - area;
6790
6791                 // choose entry with the least area enlargement
6792                 if (enlargement < minEnlargement) {
6793                     minEnlargement = enlargement;
6794                     minArea = area < minArea ? area : minArea;
6795                     targetNode = child;
6796
6797                 } else if (enlargement === minEnlargement) {
6798                     // otherwise choose one with the smallest area
6799                     if (area < minArea) {
6800                         minArea = area;
6801                         targetNode = child;
6802                     }
6803                 }
6804             }
6805
6806             node = targetNode || node.children[0];
6807         }
6808
6809         return node;
6810     },
6811
6812     _insert: function (item, level, isNode) {
6813
6814         var toBBox = this.toBBox,
6815             bbox = isNode ? item : toBBox(item),
6816             insertPath = [];
6817
6818         // find the best node for accommodating the item, saving all nodes along the path too
6819         var node = this._chooseSubtree(bbox, this.data, level, insertPath);
6820
6821         // put the item into the node
6822         node.children.push(item);
6823         extend(node, bbox);
6824
6825         // split on node overflow; propagate upwards if necessary
6826         while (level >= 0) {
6827             if (insertPath[level].children.length > this._maxEntries) {
6828                 this._split(insertPath, level);
6829                 level--;
6830             } else break;
6831         }
6832
6833         // adjust bboxes along the insertion path
6834         this._adjustParentBBoxes(bbox, insertPath, level);
6835     },
6836
6837     // split overflowed node into two
6838     _split: function (insertPath, level) {
6839
6840         var node = insertPath[level],
6841             M = node.children.length,
6842             m = this._minEntries;
6843
6844         this._chooseSplitAxis(node, m, M);
6845
6846         var splitIndex = this._chooseSplitIndex(node, m, M);
6847
6848         var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
6849         newNode.height = node.height;
6850         newNode.leaf = node.leaf;
6851
6852         calcBBox(node, this.toBBox);
6853         calcBBox(newNode, this.toBBox);
6854
6855         if (level) insertPath[level - 1].children.push(newNode);
6856         else this._splitRoot(node, newNode);
6857     },
6858
6859     _splitRoot: function (node, newNode) {
6860         // split root node
6861         this.data = createNode([node, newNode]);
6862         this.data.height = node.height + 1;
6863         this.data.leaf = false;
6864         calcBBox(this.data, this.toBBox);
6865     },
6866
6867     _chooseSplitIndex: function (node, m, M) {
6868
6869         var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
6870
6871         minOverlap = minArea = Infinity;
6872
6873         for (i = m; i <= M - m; i++) {
6874             bbox1 = distBBox(node, 0, i, this.toBBox);
6875             bbox2 = distBBox(node, i, M, this.toBBox);
6876
6877             overlap = intersectionArea(bbox1, bbox2);
6878             area = bboxArea(bbox1) + bboxArea(bbox2);
6879
6880             // choose distribution with minimum overlap
6881             if (overlap < minOverlap) {
6882                 minOverlap = overlap;
6883                 index = i;
6884
6885                 minArea = area < minArea ? area : minArea;
6886
6887             } else if (overlap === minOverlap) {
6888                 // otherwise choose distribution with minimum area
6889                 if (area < minArea) {
6890                     minArea = area;
6891                     index = i;
6892                 }
6893             }
6894         }
6895
6896         return index;
6897     },
6898
6899     // sorts node children by the best axis for split
6900     _chooseSplitAxis: function (node, m, M) {
6901
6902         var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
6903             compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
6904             xMargin = this._allDistMargin(node, m, M, compareMinX),
6905             yMargin = this._allDistMargin(node, m, M, compareMinY);
6906
6907         // if total distributions margin value is minimal for x, sort by minX,
6908         // otherwise it's already sorted by minY
6909         if (xMargin < yMargin) node.children.sort(compareMinX);
6910     },
6911
6912     // total margin of all possible split distributions where each node is at least m full
6913     _allDistMargin: function (node, m, M, compare) {
6914
6915         node.children.sort(compare);
6916
6917         var toBBox = this.toBBox,
6918             leftBBox = distBBox(node, 0, m, toBBox),
6919             rightBBox = distBBox(node, M - m, M, toBBox),
6920             margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
6921             i, child;
6922
6923         for (i = m; i < M - m; i++) {
6924             child = node.children[i];
6925             extend(leftBBox, node.leaf ? toBBox(child) : child);
6926             margin += bboxMargin(leftBBox);
6927         }
6928
6929         for (i = M - m - 1; i >= m; i--) {
6930             child = node.children[i];
6931             extend(rightBBox, node.leaf ? toBBox(child) : child);
6932             margin += bboxMargin(rightBBox);
6933         }
6934
6935         return margin;
6936     },
6937
6938     _adjustParentBBoxes: function (bbox, path, level) {
6939         // adjust bboxes along the given tree path
6940         for (var i = level; i >= 0; i--) {
6941             extend(path[i], bbox);
6942         }
6943     },
6944
6945     _condense: function (path) {
6946         // go through the path, removing empty nodes and updating bboxes
6947         for (var i = path.length - 1, siblings; i >= 0; i--) {
6948             if (path[i].children.length === 0) {
6949                 if (i > 0) {
6950                     siblings = path[i - 1].children;
6951                     siblings.splice(siblings.indexOf(path[i]), 1);
6952
6953                 } else this.clear();
6954
6955             } else calcBBox(path[i], this.toBBox);
6956         }
6957     },
6958
6959     _initFormat: function (format) {
6960         // data format (minX, minY, maxX, maxY accessors)
6961
6962         // uses eval-type function compilation instead of just accepting a toBBox function
6963         // because the algorithms are very sensitive to sorting functions performance,
6964         // so they should be dead simple and without inner calls
6965
6966         var compareArr = ['return a', ' - b', ';'];
6967
6968         this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
6969         this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
6970
6971         this.toBBox = new Function('a',
6972             'return {minX: a' + format[0] +
6973             ', minY: a' + format[1] +
6974             ', maxX: a' + format[2] +
6975             ', maxY: a' + format[3] + '};');
6976     }
6977 };
6978
6979 function findItem(item, items, equalsFn) {
6980     if (!equalsFn) return items.indexOf(item);
6981
6982     for (var i = 0; i < items.length; i++) {
6983         if (equalsFn(item, items[i])) return i;
6984     }
6985     return -1;
6986 }
6987
6988 // calculate node's bbox from bboxes of its children
6989 function calcBBox(node, toBBox) {
6990     distBBox(node, 0, node.children.length, toBBox, node);
6991 }
6992
6993 // min bounding rectangle of node children from k to p-1
6994 function distBBox(node, k, p, toBBox, destNode) {
6995     if (!destNode) destNode = createNode(null);
6996     destNode.minX = Infinity;
6997     destNode.minY = Infinity;
6998     destNode.maxX = -Infinity;
6999     destNode.maxY = -Infinity;
7000
7001     for (var i = k, child; i < p; i++) {
7002         child = node.children[i];
7003         extend(destNode, node.leaf ? toBBox(child) : child);
7004     }
7005
7006     return destNode;
7007 }
7008
7009 function extend(a, b) {
7010     a.minX = Math.min(a.minX, b.minX);
7011     a.minY = Math.min(a.minY, b.minY);
7012     a.maxX = Math.max(a.maxX, b.maxX);
7013     a.maxY = Math.max(a.maxY, b.maxY);
7014     return a;
7015 }
7016
7017 function compareNodeMinX(a, b) { return a.minX - b.minX; }
7018 function compareNodeMinY(a, b) { return a.minY - b.minY; }
7019
7020 function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
7021 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
7022
7023 function enlargedArea(a, b) {
7024     return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
7025            (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
7026 }
7027
7028 function intersectionArea(a, b) {
7029     var minX = Math.max(a.minX, b.minX),
7030         minY = Math.max(a.minY, b.minY),
7031         maxX = Math.min(a.maxX, b.maxX),
7032         maxY = Math.min(a.maxY, b.maxY);
7033
7034     return Math.max(0, maxX - minX) *
7035            Math.max(0, maxY - minY);
7036 }
7037
7038 function contains(a, b) {
7039     return a.minX <= b.minX &&
7040            a.minY <= b.minY &&
7041            b.maxX <= a.maxX &&
7042            b.maxY <= a.maxY;
7043 }
7044
7045 function intersects(a, b) {
7046     return b.minX <= a.maxX &&
7047            b.minY <= a.maxY &&
7048            b.maxX >= a.minX &&
7049            b.maxY >= a.minY;
7050 }
7051
7052 function createNode(children) {
7053     return {
7054         children: children,
7055         height: 1,
7056         leaf: true,
7057         minX: Infinity,
7058         minY: Infinity,
7059         maxX: -Infinity,
7060         maxY: -Infinity
7061     };
7062 }
7063
7064 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
7065 // combines selection algorithm with binary divide & conquer approach
7066
7067 function multiSelect(arr, left, right, n, compare) {
7068     var stack = [left, right],
7069         mid;
7070
7071     while (stack.length) {
7072         right = stack.pop();
7073         left = stack.pop();
7074
7075         if (right - left <= n) continue;
7076
7077         mid = left + Math.ceil((right - left) / n / 2) * n;
7078         quickselect(arr, mid, left, right, compare);
7079
7080         stack.push(left, mid, mid, right);
7081     }
7082 }
7083
7084 },{"quickselect":25}],27:[function(require,module,exports){
7085 "use strict";
7086 Object.defineProperty(exports, "__esModule", { value: true });
7087 var Observable_1 = require("./internal/Observable");
7088 exports.Observable = Observable_1.Observable;
7089 var ConnectableObservable_1 = require("./internal/observable/ConnectableObservable");
7090 exports.ConnectableObservable = ConnectableObservable_1.ConnectableObservable;
7091 var groupBy_1 = require("./internal/operators/groupBy");
7092 exports.GroupedObservable = groupBy_1.GroupedObservable;
7093 var observable_1 = require("./internal/symbol/observable");
7094 exports.observable = observable_1.observable;
7095 var Subject_1 = require("./internal/Subject");
7096 exports.Subject = Subject_1.Subject;
7097 var BehaviorSubject_1 = require("./internal/BehaviorSubject");
7098 exports.BehaviorSubject = BehaviorSubject_1.BehaviorSubject;
7099 var ReplaySubject_1 = require("./internal/ReplaySubject");
7100 exports.ReplaySubject = ReplaySubject_1.ReplaySubject;
7101 var AsyncSubject_1 = require("./internal/AsyncSubject");
7102 exports.AsyncSubject = AsyncSubject_1.AsyncSubject;
7103 var asap_1 = require("./internal/scheduler/asap");
7104 exports.asapScheduler = asap_1.asap;
7105 var async_1 = require("./internal/scheduler/async");
7106 exports.asyncScheduler = async_1.async;
7107 var queue_1 = require("./internal/scheduler/queue");
7108 exports.queueScheduler = queue_1.queue;
7109 var animationFrame_1 = require("./internal/scheduler/animationFrame");
7110 exports.animationFrameScheduler = animationFrame_1.animationFrame;
7111 var VirtualTimeScheduler_1 = require("./internal/scheduler/VirtualTimeScheduler");
7112 exports.VirtualTimeScheduler = VirtualTimeScheduler_1.VirtualTimeScheduler;
7113 exports.VirtualAction = VirtualTimeScheduler_1.VirtualAction;
7114 var Scheduler_1 = require("./internal/Scheduler");
7115 exports.Scheduler = Scheduler_1.Scheduler;
7116 var Subscription_1 = require("./internal/Subscription");
7117 exports.Subscription = Subscription_1.Subscription;
7118 var Subscriber_1 = require("./internal/Subscriber");
7119 exports.Subscriber = Subscriber_1.Subscriber;
7120 var Notification_1 = require("./internal/Notification");
7121 exports.Notification = Notification_1.Notification;
7122 var pipe_1 = require("./internal/util/pipe");
7123 exports.pipe = pipe_1.pipe;
7124 var noop_1 = require("./internal/util/noop");
7125 exports.noop = noop_1.noop;
7126 var identity_1 = require("./internal/util/identity");
7127 exports.identity = identity_1.identity;
7128 var isObservable_1 = require("./internal/util/isObservable");
7129 exports.isObservable = isObservable_1.isObservable;
7130 var ArgumentOutOfRangeError_1 = require("./internal/util/ArgumentOutOfRangeError");
7131 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
7132 var EmptyError_1 = require("./internal/util/EmptyError");
7133 exports.EmptyError = EmptyError_1.EmptyError;
7134 var ObjectUnsubscribedError_1 = require("./internal/util/ObjectUnsubscribedError");
7135 exports.ObjectUnsubscribedError = ObjectUnsubscribedError_1.ObjectUnsubscribedError;
7136 var UnsubscriptionError_1 = require("./internal/util/UnsubscriptionError");
7137 exports.UnsubscriptionError = UnsubscriptionError_1.UnsubscriptionError;
7138 var TimeoutError_1 = require("./internal/util/TimeoutError");
7139 exports.TimeoutError = TimeoutError_1.TimeoutError;
7140 var bindCallback_1 = require("./internal/observable/bindCallback");
7141 exports.bindCallback = bindCallback_1.bindCallback;
7142 var bindNodeCallback_1 = require("./internal/observable/bindNodeCallback");
7143 exports.bindNodeCallback = bindNodeCallback_1.bindNodeCallback;
7144 var combineLatest_1 = require("./internal/observable/combineLatest");
7145 exports.combineLatest = combineLatest_1.combineLatest;
7146 var concat_1 = require("./internal/observable/concat");
7147 exports.concat = concat_1.concat;
7148 var defer_1 = require("./internal/observable/defer");
7149 exports.defer = defer_1.defer;
7150 var empty_1 = require("./internal/observable/empty");
7151 exports.empty = empty_1.empty;
7152 var forkJoin_1 = require("./internal/observable/forkJoin");
7153 exports.forkJoin = forkJoin_1.forkJoin;
7154 var from_1 = require("./internal/observable/from");
7155 exports.from = from_1.from;
7156 var fromEvent_1 = require("./internal/observable/fromEvent");
7157 exports.fromEvent = fromEvent_1.fromEvent;
7158 var fromEventPattern_1 = require("./internal/observable/fromEventPattern");
7159 exports.fromEventPattern = fromEventPattern_1.fromEventPattern;
7160 var generate_1 = require("./internal/observable/generate");
7161 exports.generate = generate_1.generate;
7162 var iif_1 = require("./internal/observable/iif");
7163 exports.iif = iif_1.iif;
7164 var interval_1 = require("./internal/observable/interval");
7165 exports.interval = interval_1.interval;
7166 var merge_1 = require("./internal/observable/merge");
7167 exports.merge = merge_1.merge;
7168 var never_1 = require("./internal/observable/never");
7169 exports.never = never_1.never;
7170 var of_1 = require("./internal/observable/of");
7171 exports.of = of_1.of;
7172 var onErrorResumeNext_1 = require("./internal/observable/onErrorResumeNext");
7173 exports.onErrorResumeNext = onErrorResumeNext_1.onErrorResumeNext;
7174 var pairs_1 = require("./internal/observable/pairs");
7175 exports.pairs = pairs_1.pairs;
7176 var race_1 = require("./internal/observable/race");
7177 exports.race = race_1.race;
7178 var range_1 = require("./internal/observable/range");
7179 exports.range = range_1.range;
7180 var throwError_1 = require("./internal/observable/throwError");
7181 exports.throwError = throwError_1.throwError;
7182 var timer_1 = require("./internal/observable/timer");
7183 exports.timer = timer_1.timer;
7184 var using_1 = require("./internal/observable/using");
7185 exports.using = using_1.using;
7186 var zip_1 = require("./internal/observable/zip");
7187 exports.zip = zip_1.zip;
7188 var empty_2 = require("./internal/observable/empty");
7189 exports.EMPTY = empty_2.EMPTY;
7190 var never_2 = require("./internal/observable/never");
7191 exports.NEVER = never_2.NEVER;
7192 var config_1 = require("./internal/config");
7193 exports.config = config_1.config;
7194
7195 },{"./internal/AsyncSubject":28,"./internal/BehaviorSubject":29,"./internal/Notification":31,"./internal/Observable":32,"./internal/ReplaySubject":35,"./internal/Scheduler":36,"./internal/Subject":37,"./internal/Subscriber":39,"./internal/Subscription":40,"./internal/config":41,"./internal/observable/ConnectableObservable":42,"./internal/observable/bindCallback":44,"./internal/observable/bindNodeCallback":45,"./internal/observable/combineLatest":46,"./internal/observable/concat":47,"./internal/observable/defer":48,"./internal/observable/empty":49,"./internal/observable/forkJoin":50,"./internal/observable/from":51,"./internal/observable/fromEvent":53,"./internal/observable/fromEventPattern":54,"./internal/observable/generate":58,"./internal/observable/iif":59,"./internal/observable/interval":60,"./internal/observable/merge":61,"./internal/observable/never":62,"./internal/observable/of":63,"./internal/observable/onErrorResumeNext":64,"./internal/observable/pairs":65,"./internal/observable/race":66,"./internal/observable/range":67,"./internal/observable/throwError":69,"./internal/observable/timer":70,"./internal/observable/using":71,"./internal/observable/zip":72,"./internal/operators/groupBy":108,"./internal/scheduler/VirtualTimeScheduler":185,"./internal/scheduler/animationFrame":186,"./internal/scheduler/asap":187,"./internal/scheduler/async":188,"./internal/scheduler/queue":189,"./internal/symbol/observable":191,"./internal/util/ArgumentOutOfRangeError":193,"./internal/util/EmptyError":194,"./internal/util/ObjectUnsubscribedError":196,"./internal/util/TimeoutError":197,"./internal/util/UnsubscriptionError":198,"./internal/util/identity":202,"./internal/util/isObservable":211,"./internal/util/noop":214,"./internal/util/pipe":216}],28:[function(require,module,exports){
7196 "use strict";
7197 var __extends = (this && this.__extends) || (function () {
7198     var extendStatics = function (d, b) {
7199         extendStatics = Object.setPrototypeOf ||
7200             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7201             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7202         return extendStatics(d, b);
7203     }
7204     return function (d, b) {
7205         extendStatics(d, b);
7206         function __() { this.constructor = d; }
7207         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7208     };
7209 })();
7210 Object.defineProperty(exports, "__esModule", { value: true });
7211 var Subject_1 = require("./Subject");
7212 var Subscription_1 = require("./Subscription");
7213 var AsyncSubject = (function (_super) {
7214     __extends(AsyncSubject, _super);
7215     function AsyncSubject() {
7216         var _this = _super !== null && _super.apply(this, arguments) || this;
7217         _this.value = null;
7218         _this.hasNext = false;
7219         _this.hasCompleted = false;
7220         return _this;
7221     }
7222     AsyncSubject.prototype._subscribe = function (subscriber) {
7223         if (this.hasError) {
7224             subscriber.error(this.thrownError);
7225             return Subscription_1.Subscription.EMPTY;
7226         }
7227         else if (this.hasCompleted && this.hasNext) {
7228             subscriber.next(this.value);
7229             subscriber.complete();
7230             return Subscription_1.Subscription.EMPTY;
7231         }
7232         return _super.prototype._subscribe.call(this, subscriber);
7233     };
7234     AsyncSubject.prototype.next = function (value) {
7235         if (!this.hasCompleted) {
7236             this.value = value;
7237             this.hasNext = true;
7238         }
7239     };
7240     AsyncSubject.prototype.error = function (error) {
7241         if (!this.hasCompleted) {
7242             _super.prototype.error.call(this, error);
7243         }
7244     };
7245     AsyncSubject.prototype.complete = function () {
7246         this.hasCompleted = true;
7247         if (this.hasNext) {
7248             _super.prototype.next.call(this, this.value);
7249         }
7250         _super.prototype.complete.call(this);
7251     };
7252     return AsyncSubject;
7253 }(Subject_1.Subject));
7254 exports.AsyncSubject = AsyncSubject;
7255
7256 },{"./Subject":37,"./Subscription":40}],29:[function(require,module,exports){
7257 "use strict";
7258 var __extends = (this && this.__extends) || (function () {
7259     var extendStatics = function (d, b) {
7260         extendStatics = Object.setPrototypeOf ||
7261             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7262             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7263         return extendStatics(d, b);
7264     }
7265     return function (d, b) {
7266         extendStatics(d, b);
7267         function __() { this.constructor = d; }
7268         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7269     };
7270 })();
7271 Object.defineProperty(exports, "__esModule", { value: true });
7272 var Subject_1 = require("./Subject");
7273 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
7274 var BehaviorSubject = (function (_super) {
7275     __extends(BehaviorSubject, _super);
7276     function BehaviorSubject(_value) {
7277         var _this = _super.call(this) || this;
7278         _this._value = _value;
7279         return _this;
7280     }
7281     Object.defineProperty(BehaviorSubject.prototype, "value", {
7282         get: function () {
7283             return this.getValue();
7284         },
7285         enumerable: true,
7286         configurable: true
7287     });
7288     BehaviorSubject.prototype._subscribe = function (subscriber) {
7289         var subscription = _super.prototype._subscribe.call(this, subscriber);
7290         if (subscription && !subscription.closed) {
7291             subscriber.next(this._value);
7292         }
7293         return subscription;
7294     };
7295     BehaviorSubject.prototype.getValue = function () {
7296         if (this.hasError) {
7297             throw this.thrownError;
7298         }
7299         else if (this.closed) {
7300             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
7301         }
7302         else {
7303             return this._value;
7304         }
7305     };
7306     BehaviorSubject.prototype.next = function (value) {
7307         _super.prototype.next.call(this, this._value = value);
7308     };
7309     return BehaviorSubject;
7310 }(Subject_1.Subject));
7311 exports.BehaviorSubject = BehaviorSubject;
7312
7313 },{"./Subject":37,"./util/ObjectUnsubscribedError":196}],30:[function(require,module,exports){
7314 "use strict";
7315 var __extends = (this && this.__extends) || (function () {
7316     var extendStatics = function (d, b) {
7317         extendStatics = Object.setPrototypeOf ||
7318             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7319             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7320         return extendStatics(d, b);
7321     }
7322     return function (d, b) {
7323         extendStatics(d, b);
7324         function __() { this.constructor = d; }
7325         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7326     };
7327 })();
7328 Object.defineProperty(exports, "__esModule", { value: true });
7329 var Subscriber_1 = require("./Subscriber");
7330 var InnerSubscriber = (function (_super) {
7331     __extends(InnerSubscriber, _super);
7332     function InnerSubscriber(parent, outerValue, outerIndex) {
7333         var _this = _super.call(this) || this;
7334         _this.parent = parent;
7335         _this.outerValue = outerValue;
7336         _this.outerIndex = outerIndex;
7337         _this.index = 0;
7338         return _this;
7339     }
7340     InnerSubscriber.prototype._next = function (value) {
7341         this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
7342     };
7343     InnerSubscriber.prototype._error = function (error) {
7344         this.parent.notifyError(error, this);
7345         this.unsubscribe();
7346     };
7347     InnerSubscriber.prototype._complete = function () {
7348         this.parent.notifyComplete(this);
7349         this.unsubscribe();
7350     };
7351     return InnerSubscriber;
7352 }(Subscriber_1.Subscriber));
7353 exports.InnerSubscriber = InnerSubscriber;
7354
7355 },{"./Subscriber":39}],31:[function(require,module,exports){
7356 "use strict";
7357 Object.defineProperty(exports, "__esModule", { value: true });
7358 var empty_1 = require("./observable/empty");
7359 var of_1 = require("./observable/of");
7360 var throwError_1 = require("./observable/throwError");
7361 var Notification = (function () {
7362     function Notification(kind, value, error) {
7363         this.kind = kind;
7364         this.value = value;
7365         this.error = error;
7366         this.hasValue = kind === 'N';
7367     }
7368     Notification.prototype.observe = function (observer) {
7369         switch (this.kind) {
7370             case 'N':
7371                 return observer.next && observer.next(this.value);
7372             case 'E':
7373                 return observer.error && observer.error(this.error);
7374             case 'C':
7375                 return observer.complete && observer.complete();
7376         }
7377     };
7378     Notification.prototype.do = function (next, error, complete) {
7379         var kind = this.kind;
7380         switch (kind) {
7381             case 'N':
7382                 return next && next(this.value);
7383             case 'E':
7384                 return error && error(this.error);
7385             case 'C':
7386                 return complete && complete();
7387         }
7388     };
7389     Notification.prototype.accept = function (nextOrObserver, error, complete) {
7390         if (nextOrObserver && typeof nextOrObserver.next === 'function') {
7391             return this.observe(nextOrObserver);
7392         }
7393         else {
7394             return this.do(nextOrObserver, error, complete);
7395         }
7396     };
7397     Notification.prototype.toObservable = function () {
7398         var kind = this.kind;
7399         switch (kind) {
7400             case 'N':
7401                 return of_1.of(this.value);
7402             case 'E':
7403                 return throwError_1.throwError(this.error);
7404             case 'C':
7405                 return empty_1.empty();
7406         }
7407         throw new Error('unexpected notification kind value');
7408     };
7409     Notification.createNext = function (value) {
7410         if (typeof value !== 'undefined') {
7411             return new Notification('N', value);
7412         }
7413         return Notification.undefinedValueNotification;
7414     };
7415     Notification.createError = function (err) {
7416         return new Notification('E', undefined, err);
7417     };
7418     Notification.createComplete = function () {
7419         return Notification.completeNotification;
7420     };
7421     Notification.completeNotification = new Notification('C');
7422     Notification.undefinedValueNotification = new Notification('N', undefined);
7423     return Notification;
7424 }());
7425 exports.Notification = Notification;
7426
7427 },{"./observable/empty":49,"./observable/of":63,"./observable/throwError":69}],32:[function(require,module,exports){
7428 "use strict";
7429 Object.defineProperty(exports, "__esModule", { value: true });
7430 var canReportError_1 = require("./util/canReportError");
7431 var toSubscriber_1 = require("./util/toSubscriber");
7432 var observable_1 = require("../internal/symbol/observable");
7433 var pipe_1 = require("./util/pipe");
7434 var config_1 = require("./config");
7435 var Observable = (function () {
7436     function Observable(subscribe) {
7437         this._isScalar = false;
7438         if (subscribe) {
7439             this._subscribe = subscribe;
7440         }
7441     }
7442     Observable.prototype.lift = function (operator) {
7443         var observable = new Observable();
7444         observable.source = this;
7445         observable.operator = operator;
7446         return observable;
7447     };
7448     Observable.prototype.subscribe = function (observerOrNext, error, complete) {
7449         var operator = this.operator;
7450         var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
7451         if (operator) {
7452             operator.call(sink, this.source);
7453         }
7454         else {
7455             sink.add(this.source || (config_1.config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
7456                 this._subscribe(sink) :
7457                 this._trySubscribe(sink));
7458         }
7459         if (config_1.config.useDeprecatedSynchronousErrorHandling) {
7460             if (sink.syncErrorThrowable) {
7461                 sink.syncErrorThrowable = false;
7462                 if (sink.syncErrorThrown) {
7463                     throw sink.syncErrorValue;
7464                 }
7465             }
7466         }
7467         return sink;
7468     };
7469     Observable.prototype._trySubscribe = function (sink) {
7470         try {
7471             return this._subscribe(sink);
7472         }
7473         catch (err) {
7474             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
7475                 sink.syncErrorThrown = true;
7476                 sink.syncErrorValue = err;
7477             }
7478             if (canReportError_1.canReportError(sink)) {
7479                 sink.error(err);
7480             }
7481             else {
7482                 console.warn(err);
7483             }
7484         }
7485     };
7486     Observable.prototype.forEach = function (next, promiseCtor) {
7487         var _this = this;
7488         promiseCtor = getPromiseCtor(promiseCtor);
7489         return new promiseCtor(function (resolve, reject) {
7490             var subscription;
7491             subscription = _this.subscribe(function (value) {
7492                 try {
7493                     next(value);
7494                 }
7495                 catch (err) {
7496                     reject(err);
7497                     if (subscription) {
7498                         subscription.unsubscribe();
7499                     }
7500                 }
7501             }, reject, resolve);
7502         });
7503     };
7504     Observable.prototype._subscribe = function (subscriber) {
7505         var source = this.source;
7506         return source && source.subscribe(subscriber);
7507     };
7508     Observable.prototype[observable_1.observable] = function () {
7509         return this;
7510     };
7511     Observable.prototype.pipe = function () {
7512         var operations = [];
7513         for (var _i = 0; _i < arguments.length; _i++) {
7514             operations[_i] = arguments[_i];
7515         }
7516         if (operations.length === 0) {
7517             return this;
7518         }
7519         return pipe_1.pipeFromArray(operations)(this);
7520     };
7521     Observable.prototype.toPromise = function (promiseCtor) {
7522         var _this = this;
7523         promiseCtor = getPromiseCtor(promiseCtor);
7524         return new promiseCtor(function (resolve, reject) {
7525             var value;
7526             _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
7527         });
7528     };
7529     Observable.create = function (subscribe) {
7530         return new Observable(subscribe);
7531     };
7532     return Observable;
7533 }());
7534 exports.Observable = Observable;
7535 function getPromiseCtor(promiseCtor) {
7536     if (!promiseCtor) {
7537         promiseCtor = config_1.config.Promise || Promise;
7538     }
7539     if (!promiseCtor) {
7540         throw new Error('no Promise impl found');
7541     }
7542     return promiseCtor;
7543 }
7544
7545 },{"../internal/symbol/observable":191,"./config":41,"./util/canReportError":199,"./util/pipe":216,"./util/toSubscriber":223}],33:[function(require,module,exports){
7546 "use strict";
7547 Object.defineProperty(exports, "__esModule", { value: true });
7548 var config_1 = require("./config");
7549 var hostReportError_1 = require("./util/hostReportError");
7550 exports.empty = {
7551     closed: true,
7552     next: function (value) { },
7553     error: function (err) {
7554         if (config_1.config.useDeprecatedSynchronousErrorHandling) {
7555             throw err;
7556         }
7557         else {
7558             hostReportError_1.hostReportError(err);
7559         }
7560     },
7561     complete: function () { }
7562 };
7563
7564 },{"./config":41,"./util/hostReportError":201}],34:[function(require,module,exports){
7565 "use strict";
7566 var __extends = (this && this.__extends) || (function () {
7567     var extendStatics = function (d, b) {
7568         extendStatics = Object.setPrototypeOf ||
7569             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7570             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7571         return extendStatics(d, b);
7572     }
7573     return function (d, b) {
7574         extendStatics(d, b);
7575         function __() { this.constructor = d; }
7576         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7577     };
7578 })();
7579 Object.defineProperty(exports, "__esModule", { value: true });
7580 var Subscriber_1 = require("./Subscriber");
7581 var OuterSubscriber = (function (_super) {
7582     __extends(OuterSubscriber, _super);
7583     function OuterSubscriber() {
7584         return _super !== null && _super.apply(this, arguments) || this;
7585     }
7586     OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
7587         this.destination.next(innerValue);
7588     };
7589     OuterSubscriber.prototype.notifyError = function (error, innerSub) {
7590         this.destination.error(error);
7591     };
7592     OuterSubscriber.prototype.notifyComplete = function (innerSub) {
7593         this.destination.complete();
7594     };
7595     return OuterSubscriber;
7596 }(Subscriber_1.Subscriber));
7597 exports.OuterSubscriber = OuterSubscriber;
7598
7599 },{"./Subscriber":39}],35:[function(require,module,exports){
7600 "use strict";
7601 var __extends = (this && this.__extends) || (function () {
7602     var extendStatics = function (d, b) {
7603         extendStatics = Object.setPrototypeOf ||
7604             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7605             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7606         return extendStatics(d, b);
7607     }
7608     return function (d, b) {
7609         extendStatics(d, b);
7610         function __() { this.constructor = d; }
7611         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7612     };
7613 })();
7614 Object.defineProperty(exports, "__esModule", { value: true });
7615 var Subject_1 = require("./Subject");
7616 var queue_1 = require("./scheduler/queue");
7617 var Subscription_1 = require("./Subscription");
7618 var observeOn_1 = require("./operators/observeOn");
7619 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
7620 var SubjectSubscription_1 = require("./SubjectSubscription");
7621 var ReplaySubject = (function (_super) {
7622     __extends(ReplaySubject, _super);
7623     function ReplaySubject(bufferSize, windowTime, scheduler) {
7624         if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
7625         if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
7626         var _this = _super.call(this) || this;
7627         _this.scheduler = scheduler;
7628         _this._events = [];
7629         _this._infiniteTimeWindow = false;
7630         _this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
7631         _this._windowTime = windowTime < 1 ? 1 : windowTime;
7632         if (windowTime === Number.POSITIVE_INFINITY) {
7633             _this._infiniteTimeWindow = true;
7634             _this.next = _this.nextInfiniteTimeWindow;
7635         }
7636         else {
7637             _this.next = _this.nextTimeWindow;
7638         }
7639         return _this;
7640     }
7641     ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) {
7642         var _events = this._events;
7643         _events.push(value);
7644         if (_events.length > this._bufferSize) {
7645             _events.shift();
7646         }
7647         _super.prototype.next.call(this, value);
7648     };
7649     ReplaySubject.prototype.nextTimeWindow = function (value) {
7650         this._events.push(new ReplayEvent(this._getNow(), value));
7651         this._trimBufferThenGetEvents();
7652         _super.prototype.next.call(this, value);
7653     };
7654     ReplaySubject.prototype._subscribe = function (subscriber) {
7655         var _infiniteTimeWindow = this._infiniteTimeWindow;
7656         var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
7657         var scheduler = this.scheduler;
7658         var len = _events.length;
7659         var subscription;
7660         if (this.closed) {
7661             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
7662         }
7663         else if (this.isStopped || this.hasError) {
7664             subscription = Subscription_1.Subscription.EMPTY;
7665         }
7666         else {
7667             this.observers.push(subscriber);
7668             subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
7669         }
7670         if (scheduler) {
7671             subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
7672         }
7673         if (_infiniteTimeWindow) {
7674             for (var i = 0; i < len && !subscriber.closed; i++) {
7675                 subscriber.next(_events[i]);
7676             }
7677         }
7678         else {
7679             for (var i = 0; i < len && !subscriber.closed; i++) {
7680                 subscriber.next(_events[i].value);
7681             }
7682         }
7683         if (this.hasError) {
7684             subscriber.error(this.thrownError);
7685         }
7686         else if (this.isStopped) {
7687             subscriber.complete();
7688         }
7689         return subscription;
7690     };
7691     ReplaySubject.prototype._getNow = function () {
7692         return (this.scheduler || queue_1.queue).now();
7693     };
7694     ReplaySubject.prototype._trimBufferThenGetEvents = function () {
7695         var now = this._getNow();
7696         var _bufferSize = this._bufferSize;
7697         var _windowTime = this._windowTime;
7698         var _events = this._events;
7699         var eventsCount = _events.length;
7700         var spliceCount = 0;
7701         while (spliceCount < eventsCount) {
7702             if ((now - _events[spliceCount].time) < _windowTime) {
7703                 break;
7704             }
7705             spliceCount++;
7706         }
7707         if (eventsCount > _bufferSize) {
7708             spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
7709         }
7710         if (spliceCount > 0) {
7711             _events.splice(0, spliceCount);
7712         }
7713         return _events;
7714     };
7715     return ReplaySubject;
7716 }(Subject_1.Subject));
7717 exports.ReplaySubject = ReplaySubject;
7718 var ReplayEvent = (function () {
7719     function ReplayEvent(time, value) {
7720         this.time = time;
7721         this.value = value;
7722     }
7723     return ReplayEvent;
7724 }());
7725
7726 },{"./Subject":37,"./SubjectSubscription":38,"./Subscription":40,"./operators/observeOn":123,"./scheduler/queue":189,"./util/ObjectUnsubscribedError":196}],36:[function(require,module,exports){
7727 "use strict";
7728 Object.defineProperty(exports, "__esModule", { value: true });
7729 var Scheduler = (function () {
7730     function Scheduler(SchedulerAction, now) {
7731         if (now === void 0) { now = Scheduler.now; }
7732         this.SchedulerAction = SchedulerAction;
7733         this.now = now;
7734     }
7735     Scheduler.prototype.schedule = function (work, delay, state) {
7736         if (delay === void 0) { delay = 0; }
7737         return new this.SchedulerAction(this, work).schedule(state, delay);
7738     };
7739     Scheduler.now = function () { return Date.now(); };
7740     return Scheduler;
7741 }());
7742 exports.Scheduler = Scheduler;
7743
7744 },{}],37:[function(require,module,exports){
7745 "use strict";
7746 var __extends = (this && this.__extends) || (function () {
7747     var extendStatics = function (d, b) {
7748         extendStatics = Object.setPrototypeOf ||
7749             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7750             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7751         return extendStatics(d, b);
7752     }
7753     return function (d, b) {
7754         extendStatics(d, b);
7755         function __() { this.constructor = d; }
7756         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7757     };
7758 })();
7759 Object.defineProperty(exports, "__esModule", { value: true });
7760 var Observable_1 = require("./Observable");
7761 var Subscriber_1 = require("./Subscriber");
7762 var Subscription_1 = require("./Subscription");
7763 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
7764 var SubjectSubscription_1 = require("./SubjectSubscription");
7765 var rxSubscriber_1 = require("../internal/symbol/rxSubscriber");
7766 var SubjectSubscriber = (function (_super) {
7767     __extends(SubjectSubscriber, _super);
7768     function SubjectSubscriber(destination) {
7769         var _this = _super.call(this, destination) || this;
7770         _this.destination = destination;
7771         return _this;
7772     }
7773     return SubjectSubscriber;
7774 }(Subscriber_1.Subscriber));
7775 exports.SubjectSubscriber = SubjectSubscriber;
7776 var Subject = (function (_super) {
7777     __extends(Subject, _super);
7778     function Subject() {
7779         var _this = _super.call(this) || this;
7780         _this.observers = [];
7781         _this.closed = false;
7782         _this.isStopped = false;
7783         _this.hasError = false;
7784         _this.thrownError = null;
7785         return _this;
7786     }
7787     Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
7788         return new SubjectSubscriber(this);
7789     };
7790     Subject.prototype.lift = function (operator) {
7791         var subject = new AnonymousSubject(this, this);
7792         subject.operator = operator;
7793         return subject;
7794     };
7795     Subject.prototype.next = function (value) {
7796         if (this.closed) {
7797             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
7798         }
7799         if (!this.isStopped) {
7800             var observers = this.observers;
7801             var len = observers.length;
7802             var copy = observers.slice();
7803             for (var i = 0; i < len; i++) {
7804                 copy[i].next(value);
7805             }
7806         }
7807     };
7808     Subject.prototype.error = function (err) {
7809         if (this.closed) {
7810             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
7811         }
7812         this.hasError = true;
7813         this.thrownError = err;
7814         this.isStopped = true;
7815         var observers = this.observers;
7816         var len = observers.length;
7817         var copy = observers.slice();
7818         for (var i = 0; i < len; i++) {
7819             copy[i].error(err);
7820         }
7821         this.observers.length = 0;
7822     };
7823     Subject.prototype.complete = function () {
7824         if (this.closed) {
7825             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
7826         }
7827         this.isStopped = true;
7828         var observers = this.observers;
7829         var len = observers.length;
7830         var copy = observers.slice();
7831         for (var i = 0; i < len; i++) {
7832             copy[i].complete();
7833         }
7834         this.observers.length = 0;
7835     };
7836     Subject.prototype.unsubscribe = function () {
7837         this.isStopped = true;
7838         this.closed = true;
7839         this.observers = null;
7840     };
7841     Subject.prototype._trySubscribe = function (subscriber) {
7842         if (this.closed) {
7843             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
7844         }
7845         else {
7846             return _super.prototype._trySubscribe.call(this, subscriber);
7847         }
7848     };
7849     Subject.prototype._subscribe = function (subscriber) {
7850         if (this.closed) {
7851             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
7852         }
7853         else if (this.hasError) {
7854             subscriber.error(this.thrownError);
7855             return Subscription_1.Subscription.EMPTY;
7856         }
7857         else if (this.isStopped) {
7858             subscriber.complete();
7859             return Subscription_1.Subscription.EMPTY;
7860         }
7861         else {
7862             this.observers.push(subscriber);
7863             return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
7864         }
7865     };
7866     Subject.prototype.asObservable = function () {
7867         var observable = new Observable_1.Observable();
7868         observable.source = this;
7869         return observable;
7870     };
7871     Subject.create = function (destination, source) {
7872         return new AnonymousSubject(destination, source);
7873     };
7874     return Subject;
7875 }(Observable_1.Observable));
7876 exports.Subject = Subject;
7877 var AnonymousSubject = (function (_super) {
7878     __extends(AnonymousSubject, _super);
7879     function AnonymousSubject(destination, source) {
7880         var _this = _super.call(this) || this;
7881         _this.destination = destination;
7882         _this.source = source;
7883         return _this;
7884     }
7885     AnonymousSubject.prototype.next = function (value) {
7886         var destination = this.destination;
7887         if (destination && destination.next) {
7888             destination.next(value);
7889         }
7890     };
7891     AnonymousSubject.prototype.error = function (err) {
7892         var destination = this.destination;
7893         if (destination && destination.error) {
7894             this.destination.error(err);
7895         }
7896     };
7897     AnonymousSubject.prototype.complete = function () {
7898         var destination = this.destination;
7899         if (destination && destination.complete) {
7900             this.destination.complete();
7901         }
7902     };
7903     AnonymousSubject.prototype._subscribe = function (subscriber) {
7904         var source = this.source;
7905         if (source) {
7906             return this.source.subscribe(subscriber);
7907         }
7908         else {
7909             return Subscription_1.Subscription.EMPTY;
7910         }
7911     };
7912     return AnonymousSubject;
7913 }(Subject));
7914 exports.AnonymousSubject = AnonymousSubject;
7915
7916 },{"../internal/symbol/rxSubscriber":192,"./Observable":32,"./SubjectSubscription":38,"./Subscriber":39,"./Subscription":40,"./util/ObjectUnsubscribedError":196}],38:[function(require,module,exports){
7917 "use strict";
7918 var __extends = (this && this.__extends) || (function () {
7919     var extendStatics = function (d, b) {
7920         extendStatics = Object.setPrototypeOf ||
7921             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7922             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7923         return extendStatics(d, b);
7924     }
7925     return function (d, b) {
7926         extendStatics(d, b);
7927         function __() { this.constructor = d; }
7928         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7929     };
7930 })();
7931 Object.defineProperty(exports, "__esModule", { value: true });
7932 var Subscription_1 = require("./Subscription");
7933 var SubjectSubscription = (function (_super) {
7934     __extends(SubjectSubscription, _super);
7935     function SubjectSubscription(subject, subscriber) {
7936         var _this = _super.call(this) || this;
7937         _this.subject = subject;
7938         _this.subscriber = subscriber;
7939         _this.closed = false;
7940         return _this;
7941     }
7942     SubjectSubscription.prototype.unsubscribe = function () {
7943         if (this.closed) {
7944             return;
7945         }
7946         this.closed = true;
7947         var subject = this.subject;
7948         var observers = subject.observers;
7949         this.subject = null;
7950         if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
7951             return;
7952         }
7953         var subscriberIndex = observers.indexOf(this.subscriber);
7954         if (subscriberIndex !== -1) {
7955             observers.splice(subscriberIndex, 1);
7956         }
7957     };
7958     return SubjectSubscription;
7959 }(Subscription_1.Subscription));
7960 exports.SubjectSubscription = SubjectSubscription;
7961
7962 },{"./Subscription":40}],39:[function(require,module,exports){
7963 "use strict";
7964 var __extends = (this && this.__extends) || (function () {
7965     var extendStatics = function (d, b) {
7966         extendStatics = Object.setPrototypeOf ||
7967             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7968             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7969         return extendStatics(d, b);
7970     }
7971     return function (d, b) {
7972         extendStatics(d, b);
7973         function __() { this.constructor = d; }
7974         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7975     };
7976 })();
7977 Object.defineProperty(exports, "__esModule", { value: true });
7978 var isFunction_1 = require("./util/isFunction");
7979 var Observer_1 = require("./Observer");
7980 var Subscription_1 = require("./Subscription");
7981 var rxSubscriber_1 = require("../internal/symbol/rxSubscriber");
7982 var config_1 = require("./config");
7983 var hostReportError_1 = require("./util/hostReportError");
7984 var Subscriber = (function (_super) {
7985     __extends(Subscriber, _super);
7986     function Subscriber(destinationOrNext, error, complete) {
7987         var _this = _super.call(this) || this;
7988         _this.syncErrorValue = null;
7989         _this.syncErrorThrown = false;
7990         _this.syncErrorThrowable = false;
7991         _this.isStopped = false;
7992         _this._parentSubscription = null;
7993         switch (arguments.length) {
7994             case 0:
7995                 _this.destination = Observer_1.empty;
7996                 break;
7997             case 1:
7998                 if (!destinationOrNext) {
7999                     _this.destination = Observer_1.empty;
8000                     break;
8001                 }
8002                 if (typeof destinationOrNext === 'object') {
8003                     if (destinationOrNext instanceof Subscriber) {
8004                         _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
8005                         _this.destination = destinationOrNext;
8006                         destinationOrNext.add(_this);
8007                     }
8008                     else {
8009                         _this.syncErrorThrowable = true;
8010                         _this.destination = new SafeSubscriber(_this, destinationOrNext);
8011                     }
8012                     break;
8013                 }
8014             default:
8015                 _this.syncErrorThrowable = true;
8016                 _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
8017                 break;
8018         }
8019         return _this;
8020     }
8021     Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
8022     Subscriber.create = function (next, error, complete) {
8023         var subscriber = new Subscriber(next, error, complete);
8024         subscriber.syncErrorThrowable = false;
8025         return subscriber;
8026     };
8027     Subscriber.prototype.next = function (value) {
8028         if (!this.isStopped) {
8029             this._next(value);
8030         }
8031     };
8032     Subscriber.prototype.error = function (err) {
8033         if (!this.isStopped) {
8034             this.isStopped = true;
8035             this._error(err);
8036         }
8037     };
8038     Subscriber.prototype.complete = function () {
8039         if (!this.isStopped) {
8040             this.isStopped = true;
8041             this._complete();
8042         }
8043     };
8044     Subscriber.prototype.unsubscribe = function () {
8045         if (this.closed) {
8046             return;
8047         }
8048         this.isStopped = true;
8049         _super.prototype.unsubscribe.call(this);
8050     };
8051     Subscriber.prototype._next = function (value) {
8052         this.destination.next(value);
8053     };
8054     Subscriber.prototype._error = function (err) {
8055         this.destination.error(err);
8056         this.unsubscribe();
8057     };
8058     Subscriber.prototype._complete = function () {
8059         this.destination.complete();
8060         this.unsubscribe();
8061     };
8062     Subscriber.prototype._unsubscribeAndRecycle = function () {
8063         var _a = this, _parent = _a._parent, _parents = _a._parents;
8064         this._parent = null;
8065         this._parents = null;
8066         this.unsubscribe();
8067         this.closed = false;
8068         this.isStopped = false;
8069         this._parent = _parent;
8070         this._parents = _parents;
8071         this._parentSubscription = null;
8072         return this;
8073     };
8074     return Subscriber;
8075 }(Subscription_1.Subscription));
8076 exports.Subscriber = Subscriber;
8077 var SafeSubscriber = (function (_super) {
8078     __extends(SafeSubscriber, _super);
8079     function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
8080         var _this = _super.call(this) || this;
8081         _this._parentSubscriber = _parentSubscriber;
8082         var next;
8083         var context = _this;
8084         if (isFunction_1.isFunction(observerOrNext)) {
8085             next = observerOrNext;
8086         }
8087         else if (observerOrNext) {
8088             next = observerOrNext.next;
8089             error = observerOrNext.error;
8090             complete = observerOrNext.complete;
8091             if (observerOrNext !== Observer_1.empty) {
8092                 context = Object.create(observerOrNext);
8093                 if (isFunction_1.isFunction(context.unsubscribe)) {
8094                     _this.add(context.unsubscribe.bind(context));
8095                 }
8096                 context.unsubscribe = _this.unsubscribe.bind(_this);
8097             }
8098         }
8099         _this._context = context;
8100         _this._next = next;
8101         _this._error = error;
8102         _this._complete = complete;
8103         return _this;
8104     }
8105     SafeSubscriber.prototype.next = function (value) {
8106         if (!this.isStopped && this._next) {
8107             var _parentSubscriber = this._parentSubscriber;
8108             if (!config_1.config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
8109                 this.__tryOrUnsub(this._next, value);
8110             }
8111             else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
8112                 this.unsubscribe();
8113             }
8114         }
8115     };
8116     SafeSubscriber.prototype.error = function (err) {
8117         if (!this.isStopped) {
8118             var _parentSubscriber = this._parentSubscriber;
8119             var useDeprecatedSynchronousErrorHandling = config_1.config.useDeprecatedSynchronousErrorHandling;
8120             if (this._error) {
8121                 if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
8122                     this.__tryOrUnsub(this._error, err);
8123                     this.unsubscribe();
8124                 }
8125                 else {
8126                     this.__tryOrSetError(_parentSubscriber, this._error, err);
8127                     this.unsubscribe();
8128                 }
8129             }
8130             else if (!_parentSubscriber.syncErrorThrowable) {
8131                 this.unsubscribe();
8132                 if (useDeprecatedSynchronousErrorHandling) {
8133                     throw err;
8134                 }
8135                 hostReportError_1.hostReportError(err);
8136             }
8137             else {
8138                 if (useDeprecatedSynchronousErrorHandling) {
8139                     _parentSubscriber.syncErrorValue = err;
8140                     _parentSubscriber.syncErrorThrown = true;
8141                 }
8142                 else {
8143                     hostReportError_1.hostReportError(err);
8144                 }
8145                 this.unsubscribe();
8146             }
8147         }
8148     };
8149     SafeSubscriber.prototype.complete = function () {
8150         var _this = this;
8151         if (!this.isStopped) {
8152             var _parentSubscriber = this._parentSubscriber;
8153             if (this._complete) {
8154                 var wrappedComplete = function () { return _this._complete.call(_this._context); };
8155                 if (!config_1.config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
8156                     this.__tryOrUnsub(wrappedComplete);
8157                     this.unsubscribe();
8158                 }
8159                 else {
8160                     this.__tryOrSetError(_parentSubscriber, wrappedComplete);
8161                     this.unsubscribe();
8162                 }
8163             }
8164             else {
8165                 this.unsubscribe();
8166             }
8167         }
8168     };
8169     SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
8170         try {
8171             fn.call(this._context, value);
8172         }
8173         catch (err) {
8174             this.unsubscribe();
8175             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
8176                 throw err;
8177             }
8178             else {
8179                 hostReportError_1.hostReportError(err);
8180             }
8181         }
8182     };
8183     SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
8184         if (!config_1.config.useDeprecatedSynchronousErrorHandling) {
8185             throw new Error('bad call');
8186         }
8187         try {
8188             fn.call(this._context, value);
8189         }
8190         catch (err) {
8191             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
8192                 parent.syncErrorValue = err;
8193                 parent.syncErrorThrown = true;
8194                 return true;
8195             }
8196             else {
8197                 hostReportError_1.hostReportError(err);
8198                 return true;
8199             }
8200         }
8201         return false;
8202     };
8203     SafeSubscriber.prototype._unsubscribe = function () {
8204         var _parentSubscriber = this._parentSubscriber;
8205         this._context = null;
8206         this._parentSubscriber = null;
8207         _parentSubscriber.unsubscribe();
8208     };
8209     return SafeSubscriber;
8210 }(Subscriber));
8211 exports.SafeSubscriber = SafeSubscriber;
8212
8213 },{"../internal/symbol/rxSubscriber":192,"./Observer":33,"./Subscription":40,"./config":41,"./util/hostReportError":201,"./util/isFunction":206}],40:[function(require,module,exports){
8214 "use strict";
8215 Object.defineProperty(exports, "__esModule", { value: true });
8216 var isArray_1 = require("./util/isArray");
8217 var isObject_1 = require("./util/isObject");
8218 var isFunction_1 = require("./util/isFunction");
8219 var tryCatch_1 = require("./util/tryCatch");
8220 var errorObject_1 = require("./util/errorObject");
8221 var UnsubscriptionError_1 = require("./util/UnsubscriptionError");
8222 var Subscription = (function () {
8223     function Subscription(unsubscribe) {
8224         this.closed = false;
8225         this._parent = null;
8226         this._parents = null;
8227         this._subscriptions = null;
8228         if (unsubscribe) {
8229             this._unsubscribe = unsubscribe;
8230         }
8231     }
8232     Subscription.prototype.unsubscribe = function () {
8233         var hasErrors = false;
8234         var errors;
8235         if (this.closed) {
8236             return;
8237         }
8238         var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
8239         this.closed = true;
8240         this._parent = null;
8241         this._parents = null;
8242         this._subscriptions = null;
8243         var index = -1;
8244         var len = _parents ? _parents.length : 0;
8245         while (_parent) {
8246             _parent.remove(this);
8247             _parent = ++index < len && _parents[index] || null;
8248         }
8249         if (isFunction_1.isFunction(_unsubscribe)) {
8250             var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
8251             if (trial === errorObject_1.errorObject) {
8252                 hasErrors = true;
8253                 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
8254                     flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
8255             }
8256         }
8257         if (isArray_1.isArray(_subscriptions)) {
8258             index = -1;
8259             len = _subscriptions.length;
8260             while (++index < len) {
8261                 var sub = _subscriptions[index];
8262                 if (isObject_1.isObject(sub)) {
8263                     var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
8264                     if (trial === errorObject_1.errorObject) {
8265                         hasErrors = true;
8266                         errors = errors || [];
8267                         var err = errorObject_1.errorObject.e;
8268                         if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
8269                             errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
8270                         }
8271                         else {
8272                             errors.push(err);
8273                         }
8274                     }
8275                 }
8276             }
8277         }
8278         if (hasErrors) {
8279             throw new UnsubscriptionError_1.UnsubscriptionError(errors);
8280         }
8281     };
8282     Subscription.prototype.add = function (teardown) {
8283         if (!teardown || (teardown === Subscription.EMPTY)) {
8284             return Subscription.EMPTY;
8285         }
8286         if (teardown === this) {
8287             return this;
8288         }
8289         var subscription = teardown;
8290         switch (typeof teardown) {
8291             case 'function':
8292                 subscription = new Subscription(teardown);
8293             case 'object':
8294                 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
8295                     return subscription;
8296                 }
8297                 else if (this.closed) {
8298                     subscription.unsubscribe();
8299                     return subscription;
8300                 }
8301                 else if (typeof subscription._addParent !== 'function') {
8302                     var tmp = subscription;
8303                     subscription = new Subscription();
8304                     subscription._subscriptions = [tmp];
8305                 }
8306                 break;
8307             default:
8308                 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
8309         }
8310         var subscriptions = this._subscriptions || (this._subscriptions = []);
8311         subscriptions.push(subscription);
8312         subscription._addParent(this);
8313         return subscription;
8314     };
8315     Subscription.prototype.remove = function (subscription) {
8316         var subscriptions = this._subscriptions;
8317         if (subscriptions) {
8318             var subscriptionIndex = subscriptions.indexOf(subscription);
8319             if (subscriptionIndex !== -1) {
8320                 subscriptions.splice(subscriptionIndex, 1);
8321             }
8322         }
8323     };
8324     Subscription.prototype._addParent = function (parent) {
8325         var _a = this, _parent = _a._parent, _parents = _a._parents;
8326         if (!_parent || _parent === parent) {
8327             this._parent = parent;
8328         }
8329         else if (!_parents) {
8330             this._parents = [parent];
8331         }
8332         else if (_parents.indexOf(parent) === -1) {
8333             _parents.push(parent);
8334         }
8335     };
8336     Subscription.EMPTY = (function (empty) {
8337         empty.closed = true;
8338         return empty;
8339     }(new Subscription()));
8340     return Subscription;
8341 }());
8342 exports.Subscription = Subscription;
8343 function flattenUnsubscriptionErrors(errors) {
8344     return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
8345 }
8346
8347 },{"./util/UnsubscriptionError":198,"./util/errorObject":200,"./util/isArray":203,"./util/isFunction":206,"./util/isObject":210,"./util/tryCatch":224}],41:[function(require,module,exports){
8348 "use strict";
8349 Object.defineProperty(exports, "__esModule", { value: true });
8350 var _enable_super_gross_mode_that_will_cause_bad_things = false;
8351 exports.config = {
8352     Promise: undefined,
8353     set useDeprecatedSynchronousErrorHandling(value) {
8354         if (value) {
8355             var error = new Error();
8356             console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
8357         }
8358         else if (_enable_super_gross_mode_that_will_cause_bad_things) {
8359             console.log('RxJS: Back to a better error behavior. Thank you. <3');
8360         }
8361         _enable_super_gross_mode_that_will_cause_bad_things = value;
8362     },
8363     get useDeprecatedSynchronousErrorHandling() {
8364         return _enable_super_gross_mode_that_will_cause_bad_things;
8365     },
8366 };
8367
8368 },{}],42:[function(require,module,exports){
8369 "use strict";
8370 var __extends = (this && this.__extends) || (function () {
8371     var extendStatics = function (d, b) {
8372         extendStatics = Object.setPrototypeOf ||
8373             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8374             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8375         return extendStatics(d, b);
8376     }
8377     return function (d, b) {
8378         extendStatics(d, b);
8379         function __() { this.constructor = d; }
8380         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8381     };
8382 })();
8383 Object.defineProperty(exports, "__esModule", { value: true });
8384 var Subject_1 = require("../Subject");
8385 var Observable_1 = require("../Observable");
8386 var Subscriber_1 = require("../Subscriber");
8387 var Subscription_1 = require("../Subscription");
8388 var refCount_1 = require("../operators/refCount");
8389 var ConnectableObservable = (function (_super) {
8390     __extends(ConnectableObservable, _super);
8391     function ConnectableObservable(source, subjectFactory) {
8392         var _this = _super.call(this) || this;
8393         _this.source = source;
8394         _this.subjectFactory = subjectFactory;
8395         _this._refCount = 0;
8396         _this._isComplete = false;
8397         return _this;
8398     }
8399     ConnectableObservable.prototype._subscribe = function (subscriber) {
8400         return this.getSubject().subscribe(subscriber);
8401     };
8402     ConnectableObservable.prototype.getSubject = function () {
8403         var subject = this._subject;
8404         if (!subject || subject.isStopped) {
8405             this._subject = this.subjectFactory();
8406         }
8407         return this._subject;
8408     };
8409     ConnectableObservable.prototype.connect = function () {
8410         var connection = this._connection;
8411         if (!connection) {
8412             this._isComplete = false;
8413             connection = this._connection = new Subscription_1.Subscription();
8414             connection.add(this.source
8415                 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
8416             if (connection.closed) {
8417                 this._connection = null;
8418                 connection = Subscription_1.Subscription.EMPTY;
8419             }
8420             else {
8421                 this._connection = connection;
8422             }
8423         }
8424         return connection;
8425     };
8426     ConnectableObservable.prototype.refCount = function () {
8427         return refCount_1.refCount()(this);
8428     };
8429     return ConnectableObservable;
8430 }(Observable_1.Observable));
8431 exports.ConnectableObservable = ConnectableObservable;
8432 var connectableProto = ConnectableObservable.prototype;
8433 exports.connectableObservableDescriptor = {
8434     operator: { value: null },
8435     _refCount: { value: 0, writable: true },
8436     _subject: { value: null, writable: true },
8437     _connection: { value: null, writable: true },
8438     _subscribe: { value: connectableProto._subscribe },
8439     _isComplete: { value: connectableProto._isComplete, writable: true },
8440     getSubject: { value: connectableProto.getSubject },
8441     connect: { value: connectableProto.connect },
8442     refCount: { value: connectableProto.refCount }
8443 };
8444 var ConnectableSubscriber = (function (_super) {
8445     __extends(ConnectableSubscriber, _super);
8446     function ConnectableSubscriber(destination, connectable) {
8447         var _this = _super.call(this, destination) || this;
8448         _this.connectable = connectable;
8449         return _this;
8450     }
8451     ConnectableSubscriber.prototype._error = function (err) {
8452         this._unsubscribe();
8453         _super.prototype._error.call(this, err);
8454     };
8455     ConnectableSubscriber.prototype._complete = function () {
8456         this.connectable._isComplete = true;
8457         this._unsubscribe();
8458         _super.prototype._complete.call(this);
8459     };
8460     ConnectableSubscriber.prototype._unsubscribe = function () {
8461         var connectable = this.connectable;
8462         if (connectable) {
8463             this.connectable = null;
8464             var connection = connectable._connection;
8465             connectable._refCount = 0;
8466             connectable._subject = null;
8467             connectable._connection = null;
8468             if (connection) {
8469                 connection.unsubscribe();
8470             }
8471         }
8472     };
8473     return ConnectableSubscriber;
8474 }(Subject_1.SubjectSubscriber));
8475 var RefCountOperator = (function () {
8476     function RefCountOperator(connectable) {
8477         this.connectable = connectable;
8478     }
8479     RefCountOperator.prototype.call = function (subscriber, source) {
8480         var connectable = this.connectable;
8481         connectable._refCount++;
8482         var refCounter = new RefCountSubscriber(subscriber, connectable);
8483         var subscription = source.subscribe(refCounter);
8484         if (!refCounter.closed) {
8485             refCounter.connection = connectable.connect();
8486         }
8487         return subscription;
8488     };
8489     return RefCountOperator;
8490 }());
8491 var RefCountSubscriber = (function (_super) {
8492     __extends(RefCountSubscriber, _super);
8493     function RefCountSubscriber(destination, connectable) {
8494         var _this = _super.call(this, destination) || this;
8495         _this.connectable = connectable;
8496         return _this;
8497     }
8498     RefCountSubscriber.prototype._unsubscribe = function () {
8499         var connectable = this.connectable;
8500         if (!connectable) {
8501             this.connection = null;
8502             return;
8503         }
8504         this.connectable = null;
8505         var refCount = connectable._refCount;
8506         if (refCount <= 0) {
8507             this.connection = null;
8508             return;
8509         }
8510         connectable._refCount = refCount - 1;
8511         if (refCount > 1) {
8512             this.connection = null;
8513             return;
8514         }
8515         var connection = this.connection;
8516         var sharedConnection = connectable._connection;
8517         this.connection = null;
8518         if (sharedConnection && (!connection || sharedConnection === connection)) {
8519             sharedConnection.unsubscribe();
8520         }
8521     };
8522     return RefCountSubscriber;
8523 }(Subscriber_1.Subscriber));
8524
8525 },{"../Observable":32,"../Subject":37,"../Subscriber":39,"../Subscription":40,"../operators/refCount":134}],43:[function(require,module,exports){
8526 "use strict";
8527 var __extends = (this && this.__extends) || (function () {
8528     var extendStatics = function (d, b) {
8529         extendStatics = Object.setPrototypeOf ||
8530             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8531             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8532         return extendStatics(d, b);
8533     }
8534     return function (d, b) {
8535         extendStatics(d, b);
8536         function __() { this.constructor = d; }
8537         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8538     };
8539 })();
8540 Object.defineProperty(exports, "__esModule", { value: true });
8541 var Observable_1 = require("../Observable");
8542 var asap_1 = require("../scheduler/asap");
8543 var isNumeric_1 = require("../util/isNumeric");
8544 var SubscribeOnObservable = (function (_super) {
8545     __extends(SubscribeOnObservable, _super);
8546     function SubscribeOnObservable(source, delayTime, scheduler) {
8547         if (delayTime === void 0) { delayTime = 0; }
8548         if (scheduler === void 0) { scheduler = asap_1.asap; }
8549         var _this = _super.call(this) || this;
8550         _this.source = source;
8551         _this.delayTime = delayTime;
8552         _this.scheduler = scheduler;
8553         if (!isNumeric_1.isNumeric(delayTime) || delayTime < 0) {
8554             _this.delayTime = 0;
8555         }
8556         if (!scheduler || typeof scheduler.schedule !== 'function') {
8557             _this.scheduler = asap_1.asap;
8558         }
8559         return _this;
8560     }
8561     SubscribeOnObservable.create = function (source, delay, scheduler) {
8562         if (delay === void 0) { delay = 0; }
8563         if (scheduler === void 0) { scheduler = asap_1.asap; }
8564         return new SubscribeOnObservable(source, delay, scheduler);
8565     };
8566     SubscribeOnObservable.dispatch = function (arg) {
8567         var source = arg.source, subscriber = arg.subscriber;
8568         return this.add(source.subscribe(subscriber));
8569     };
8570     SubscribeOnObservable.prototype._subscribe = function (subscriber) {
8571         var delay = this.delayTime;
8572         var source = this.source;
8573         var scheduler = this.scheduler;
8574         return scheduler.schedule(SubscribeOnObservable.dispatch, delay, {
8575             source: source, subscriber: subscriber
8576         });
8577     };
8578     return SubscribeOnObservable;
8579 }(Observable_1.Observable));
8580 exports.SubscribeOnObservable = SubscribeOnObservable;
8581
8582 },{"../Observable":32,"../scheduler/asap":187,"../util/isNumeric":209}],44:[function(require,module,exports){
8583 "use strict";
8584 Object.defineProperty(exports, "__esModule", { value: true });
8585 var Observable_1 = require("../Observable");
8586 var AsyncSubject_1 = require("../AsyncSubject");
8587 var map_1 = require("../operators/map");
8588 var canReportError_1 = require("../util/canReportError");
8589 var isArray_1 = require("../util/isArray");
8590 var isScheduler_1 = require("../util/isScheduler");
8591 function bindCallback(callbackFunc, resultSelector, scheduler) {
8592     if (resultSelector) {
8593         if (isScheduler_1.isScheduler(resultSelector)) {
8594             scheduler = resultSelector;
8595         }
8596         else {
8597             return function () {
8598                 var args = [];
8599                 for (var _i = 0; _i < arguments.length; _i++) {
8600                     args[_i] = arguments[_i];
8601                 }
8602                 return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
8603             };
8604         }
8605     }
8606     return function () {
8607         var args = [];
8608         for (var _i = 0; _i < arguments.length; _i++) {
8609             args[_i] = arguments[_i];
8610         }
8611         var context = this;
8612         var subject;
8613         var params = {
8614             context: context,
8615             subject: subject,
8616             callbackFunc: callbackFunc,
8617             scheduler: scheduler,
8618         };
8619         return new Observable_1.Observable(function (subscriber) {
8620             if (!scheduler) {
8621                 if (!subject) {
8622                     subject = new AsyncSubject_1.AsyncSubject();
8623                     var handler = function () {
8624                         var innerArgs = [];
8625                         for (var _i = 0; _i < arguments.length; _i++) {
8626                             innerArgs[_i] = arguments[_i];
8627                         }
8628                         subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
8629                         subject.complete();
8630                     };
8631                     try {
8632                         callbackFunc.apply(context, args.concat([handler]));
8633                     }
8634                     catch (err) {
8635                         if (canReportError_1.canReportError(subject)) {
8636                             subject.error(err);
8637                         }
8638                         else {
8639                             console.warn(err);
8640                         }
8641                     }
8642                 }
8643                 return subject.subscribe(subscriber);
8644             }
8645             else {
8646                 var state = {
8647                     args: args, subscriber: subscriber, params: params,
8648                 };
8649                 return scheduler.schedule(dispatch, 0, state);
8650             }
8651         });
8652     };
8653 }
8654 exports.bindCallback = bindCallback;
8655 function dispatch(state) {
8656     var _this = this;
8657     var self = this;
8658     var args = state.args, subscriber = state.subscriber, params = state.params;
8659     var callbackFunc = params.callbackFunc, context = params.context, scheduler = params.scheduler;
8660     var subject = params.subject;
8661     if (!subject) {
8662         subject = params.subject = new AsyncSubject_1.AsyncSubject();
8663         var handler = function () {
8664             var innerArgs = [];
8665             for (var _i = 0; _i < arguments.length; _i++) {
8666                 innerArgs[_i] = arguments[_i];
8667             }
8668             var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
8669             _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
8670         };
8671         try {
8672             callbackFunc.apply(context, args.concat([handler]));
8673         }
8674         catch (err) {
8675             subject.error(err);
8676         }
8677     }
8678     this.add(subject.subscribe(subscriber));
8679 }
8680 function dispatchNext(state) {
8681     var value = state.value, subject = state.subject;
8682     subject.next(value);
8683     subject.complete();
8684 }
8685 function dispatchError(state) {
8686     var err = state.err, subject = state.subject;
8687     subject.error(err);
8688 }
8689
8690 },{"../AsyncSubject":28,"../Observable":32,"../operators/map":112,"../util/canReportError":199,"../util/isArray":203,"../util/isScheduler":213}],45:[function(require,module,exports){
8691 "use strict";
8692 Object.defineProperty(exports, "__esModule", { value: true });
8693 var Observable_1 = require("../Observable");
8694 var AsyncSubject_1 = require("../AsyncSubject");
8695 var map_1 = require("../operators/map");
8696 var canReportError_1 = require("../util/canReportError");
8697 var isScheduler_1 = require("../util/isScheduler");
8698 var isArray_1 = require("../util/isArray");
8699 function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
8700     if (resultSelector) {
8701         if (isScheduler_1.isScheduler(resultSelector)) {
8702             scheduler = resultSelector;
8703         }
8704         else {
8705             return function () {
8706                 var args = [];
8707                 for (var _i = 0; _i < arguments.length; _i++) {
8708                     args[_i] = arguments[_i];
8709                 }
8710                 return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
8711             };
8712         }
8713     }
8714     return function () {
8715         var args = [];
8716         for (var _i = 0; _i < arguments.length; _i++) {
8717             args[_i] = arguments[_i];
8718         }
8719         var params = {
8720             subject: undefined,
8721             args: args,
8722             callbackFunc: callbackFunc,
8723             scheduler: scheduler,
8724             context: this,
8725         };
8726         return new Observable_1.Observable(function (subscriber) {
8727             var context = params.context;
8728             var subject = params.subject;
8729             if (!scheduler) {
8730                 if (!subject) {
8731                     subject = params.subject = new AsyncSubject_1.AsyncSubject();
8732                     var handler = function () {
8733                         var innerArgs = [];
8734                         for (var _i = 0; _i < arguments.length; _i++) {
8735                             innerArgs[_i] = arguments[_i];
8736                         }
8737                         var err = innerArgs.shift();
8738                         if (err) {
8739                             subject.error(err);
8740                             return;
8741                         }
8742                         subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
8743                         subject.complete();
8744                     };
8745                     try {
8746                         callbackFunc.apply(context, args.concat([handler]));
8747                     }
8748                     catch (err) {
8749                         if (canReportError_1.canReportError(subject)) {
8750                             subject.error(err);
8751                         }
8752                         else {
8753                             console.warn(err);
8754                         }
8755                     }
8756                 }
8757                 return subject.subscribe(subscriber);
8758             }
8759             else {
8760                 return scheduler.schedule(dispatch, 0, { params: params, subscriber: subscriber, context: context });
8761             }
8762         });
8763     };
8764 }
8765 exports.bindNodeCallback = bindNodeCallback;
8766 function dispatch(state) {
8767     var _this = this;
8768     var params = state.params, subscriber = state.subscriber, context = state.context;
8769     var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler;
8770     var subject = params.subject;
8771     if (!subject) {
8772         subject = params.subject = new AsyncSubject_1.AsyncSubject();
8773         var handler = function () {
8774             var innerArgs = [];
8775             for (var _i = 0; _i < arguments.length; _i++) {
8776                 innerArgs[_i] = arguments[_i];
8777             }
8778             var err = innerArgs.shift();
8779             if (err) {
8780                 _this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject }));
8781             }
8782             else {
8783                 var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
8784                 _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
8785             }
8786         };
8787         try {
8788             callbackFunc.apply(context, args.concat([handler]));
8789         }
8790         catch (err) {
8791             this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject }));
8792         }
8793     }
8794     this.add(subject.subscribe(subscriber));
8795 }
8796 function dispatchNext(arg) {
8797     var value = arg.value, subject = arg.subject;
8798     subject.next(value);
8799     subject.complete();
8800 }
8801 function dispatchError(arg) {
8802     var err = arg.err, subject = arg.subject;
8803     subject.error(err);
8804 }
8805
8806 },{"../AsyncSubject":28,"../Observable":32,"../operators/map":112,"../util/canReportError":199,"../util/isArray":203,"../util/isScheduler":213}],46:[function(require,module,exports){
8807 "use strict";
8808 var __extends = (this && this.__extends) || (function () {
8809     var extendStatics = function (d, b) {
8810         extendStatics = Object.setPrototypeOf ||
8811             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8812             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8813         return extendStatics(d, b);
8814     }
8815     return function (d, b) {
8816         extendStatics(d, b);
8817         function __() { this.constructor = d; }
8818         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8819     };
8820 })();
8821 Object.defineProperty(exports, "__esModule", { value: true });
8822 var isScheduler_1 = require("../util/isScheduler");
8823 var isArray_1 = require("../util/isArray");
8824 var OuterSubscriber_1 = require("../OuterSubscriber");
8825 var subscribeToResult_1 = require("../util/subscribeToResult");
8826 var fromArray_1 = require("./fromArray");
8827 var NONE = {};
8828 function combineLatest() {
8829     var observables = [];
8830     for (var _i = 0; _i < arguments.length; _i++) {
8831         observables[_i] = arguments[_i];
8832     }
8833     var resultSelector = null;
8834     var scheduler = null;
8835     if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8836         scheduler = observables.pop();
8837     }
8838     if (typeof observables[observables.length - 1] === 'function') {
8839         resultSelector = observables.pop();
8840     }
8841     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8842         observables = observables[0];
8843     }
8844     return fromArray_1.fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector));
8845 }
8846 exports.combineLatest = combineLatest;
8847 var CombineLatestOperator = (function () {
8848     function CombineLatestOperator(resultSelector) {
8849         this.resultSelector = resultSelector;
8850     }
8851     CombineLatestOperator.prototype.call = function (subscriber, source) {
8852         return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
8853     };
8854     return CombineLatestOperator;
8855 }());
8856 exports.CombineLatestOperator = CombineLatestOperator;
8857 var CombineLatestSubscriber = (function (_super) {
8858     __extends(CombineLatestSubscriber, _super);
8859     function CombineLatestSubscriber(destination, resultSelector) {
8860         var _this = _super.call(this, destination) || this;
8861         _this.resultSelector = resultSelector;
8862         _this.active = 0;
8863         _this.values = [];
8864         _this.observables = [];
8865         return _this;
8866     }
8867     CombineLatestSubscriber.prototype._next = function (observable) {
8868         this.values.push(NONE);
8869         this.observables.push(observable);
8870     };
8871     CombineLatestSubscriber.prototype._complete = function () {
8872         var observables = this.observables;
8873         var len = observables.length;
8874         if (len === 0) {
8875             this.destination.complete();
8876         }
8877         else {
8878             this.active = len;
8879             this.toRespond = len;
8880             for (var i = 0; i < len; i++) {
8881                 var observable = observables[i];
8882                 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
8883             }
8884         }
8885     };
8886     CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
8887         if ((this.active -= 1) === 0) {
8888             this.destination.complete();
8889         }
8890     };
8891     CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8892         var values = this.values;
8893         var oldVal = values[outerIndex];
8894         var toRespond = !this.toRespond
8895             ? 0
8896             : oldVal === NONE ? --this.toRespond : this.toRespond;
8897         values[outerIndex] = innerValue;
8898         if (toRespond === 0) {
8899             if (this.resultSelector) {
8900                 this._tryResultSelector(values);
8901             }
8902             else {
8903                 this.destination.next(values.slice());
8904             }
8905         }
8906     };
8907     CombineLatestSubscriber.prototype._tryResultSelector = function (values) {
8908         var result;
8909         try {
8910             result = this.resultSelector.apply(this, values);
8911         }
8912         catch (err) {
8913             this.destination.error(err);
8914             return;
8915         }
8916         this.destination.next(result);
8917     };
8918     return CombineLatestSubscriber;
8919 }(OuterSubscriber_1.OuterSubscriber));
8920 exports.CombineLatestSubscriber = CombineLatestSubscriber;
8921
8922 },{"../OuterSubscriber":34,"../util/isArray":203,"../util/isScheduler":213,"../util/subscribeToResult":222,"./fromArray":52}],47:[function(require,module,exports){
8923 "use strict";
8924 Object.defineProperty(exports, "__esModule", { value: true });
8925 var isScheduler_1 = require("../util/isScheduler");
8926 var of_1 = require("./of");
8927 var from_1 = require("./from");
8928 var concatAll_1 = require("../operators/concatAll");
8929 function concat() {
8930     var observables = [];
8931     for (var _i = 0; _i < arguments.length; _i++) {
8932         observables[_i] = arguments[_i];
8933     }
8934     if (observables.length === 1 || (observables.length === 2 && isScheduler_1.isScheduler(observables[1]))) {
8935         return from_1.from(observables[0]);
8936     }
8937     return concatAll_1.concatAll()(of_1.of.apply(void 0, observables));
8938 }
8939 exports.concat = concat;
8940
8941 },{"../operators/concatAll":84,"../util/isScheduler":213,"./from":51,"./of":63}],48:[function(require,module,exports){
8942 "use strict";
8943 Object.defineProperty(exports, "__esModule", { value: true });
8944 var Observable_1 = require("../Observable");
8945 var from_1 = require("./from");
8946 var empty_1 = require("./empty");
8947 function defer(observableFactory) {
8948     return new Observable_1.Observable(function (subscriber) {
8949         var input;
8950         try {
8951             input = observableFactory();
8952         }
8953         catch (err) {
8954             subscriber.error(err);
8955             return undefined;
8956         }
8957         var source = input ? from_1.from(input) : empty_1.empty();
8958         return source.subscribe(subscriber);
8959     });
8960 }
8961 exports.defer = defer;
8962
8963 },{"../Observable":32,"./empty":49,"./from":51}],49:[function(require,module,exports){
8964 "use strict";
8965 Object.defineProperty(exports, "__esModule", { value: true });
8966 var Observable_1 = require("../Observable");
8967 exports.EMPTY = new Observable_1.Observable(function (subscriber) { return subscriber.complete(); });
8968 function empty(scheduler) {
8969     return scheduler ? emptyScheduled(scheduler) : exports.EMPTY;
8970 }
8971 exports.empty = empty;
8972 function emptyScheduled(scheduler) {
8973     return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); });
8974 }
8975 exports.emptyScheduled = emptyScheduled;
8976
8977 },{"../Observable":32}],50:[function(require,module,exports){
8978 "use strict";
8979 var __extends = (this && this.__extends) || (function () {
8980     var extendStatics = function (d, b) {
8981         extendStatics = Object.setPrototypeOf ||
8982             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8983             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8984         return extendStatics(d, b);
8985     }
8986     return function (d, b) {
8987         extendStatics(d, b);
8988         function __() { this.constructor = d; }
8989         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8990     };
8991 })();
8992 Object.defineProperty(exports, "__esModule", { value: true });
8993 var Observable_1 = require("../Observable");
8994 var isArray_1 = require("../util/isArray");
8995 var empty_1 = require("./empty");
8996 var subscribeToResult_1 = require("../util/subscribeToResult");
8997 var OuterSubscriber_1 = require("../OuterSubscriber");
8998 var map_1 = require("../operators/map");
8999 function forkJoin() {
9000     var sources = [];
9001     for (var _i = 0; _i < arguments.length; _i++) {
9002         sources[_i] = arguments[_i];
9003     }
9004     var resultSelector;
9005     if (typeof sources[sources.length - 1] === 'function') {
9006         resultSelector = sources.pop();
9007     }
9008     if (sources.length === 1 && isArray_1.isArray(sources[0])) {
9009         sources = sources[0];
9010     }
9011     if (sources.length === 0) {
9012         return empty_1.EMPTY;
9013     }
9014     if (resultSelector) {
9015         return forkJoin(sources).pipe(map_1.map(function (args) { return resultSelector.apply(void 0, args); }));
9016     }
9017     return new Observable_1.Observable(function (subscriber) {
9018         return new ForkJoinSubscriber(subscriber, sources);
9019     });
9020 }
9021 exports.forkJoin = forkJoin;
9022 var ForkJoinSubscriber = (function (_super) {
9023     __extends(ForkJoinSubscriber, _super);
9024     function ForkJoinSubscriber(destination, sources) {
9025         var _this = _super.call(this, destination) || this;
9026         _this.sources = sources;
9027         _this.completed = 0;
9028         _this.haveValues = 0;
9029         var len = sources.length;
9030         _this.values = new Array(len);
9031         for (var i = 0; i < len; i++) {
9032             var source = sources[i];
9033             var innerSubscription = subscribeToResult_1.subscribeToResult(_this, source, null, i);
9034             if (innerSubscription) {
9035                 _this.add(innerSubscription);
9036             }
9037         }
9038         return _this;
9039     }
9040     ForkJoinSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9041         this.values[outerIndex] = innerValue;
9042         if (!innerSub._hasValue) {
9043             innerSub._hasValue = true;
9044             this.haveValues++;
9045         }
9046     };
9047     ForkJoinSubscriber.prototype.notifyComplete = function (innerSub) {
9048         var _a = this, destination = _a.destination, haveValues = _a.haveValues, values = _a.values;
9049         var len = values.length;
9050         if (!innerSub._hasValue) {
9051             destination.complete();
9052             return;
9053         }
9054         this.completed++;
9055         if (this.completed !== len) {
9056             return;
9057         }
9058         if (haveValues === len) {
9059             destination.next(values);
9060         }
9061         destination.complete();
9062     };
9063     return ForkJoinSubscriber;
9064 }(OuterSubscriber_1.OuterSubscriber));
9065
9066 },{"../Observable":32,"../OuterSubscriber":34,"../operators/map":112,"../util/isArray":203,"../util/subscribeToResult":222,"./empty":49}],51:[function(require,module,exports){
9067 "use strict";
9068 Object.defineProperty(exports, "__esModule", { value: true });
9069 var Observable_1 = require("../Observable");
9070 var isPromise_1 = require("../util/isPromise");
9071 var isArrayLike_1 = require("../util/isArrayLike");
9072 var isInteropObservable_1 = require("../util/isInteropObservable");
9073 var isIterable_1 = require("../util/isIterable");
9074 var fromArray_1 = require("./fromArray");
9075 var fromPromise_1 = require("./fromPromise");
9076 var fromIterable_1 = require("./fromIterable");
9077 var fromObservable_1 = require("./fromObservable");
9078 var subscribeTo_1 = require("../util/subscribeTo");
9079 function from(input, scheduler) {
9080     if (!scheduler) {
9081         if (input instanceof Observable_1.Observable) {
9082             return input;
9083         }
9084         return new Observable_1.Observable(subscribeTo_1.subscribeTo(input));
9085     }
9086     if (input != null) {
9087         if (isInteropObservable_1.isInteropObservable(input)) {
9088             return fromObservable_1.fromObservable(input, scheduler);
9089         }
9090         else if (isPromise_1.isPromise(input)) {
9091             return fromPromise_1.fromPromise(input, scheduler);
9092         }
9093         else if (isArrayLike_1.isArrayLike(input)) {
9094             return fromArray_1.fromArray(input, scheduler);
9095         }
9096         else if (isIterable_1.isIterable(input) || typeof input === 'string') {
9097             return fromIterable_1.fromIterable(input, scheduler);
9098         }
9099     }
9100     throw new TypeError((input !== null && typeof input || input) + ' is not observable');
9101 }
9102 exports.from = from;
9103
9104 },{"../Observable":32,"../util/isArrayLike":204,"../util/isInteropObservable":207,"../util/isIterable":208,"../util/isPromise":212,"../util/subscribeTo":217,"./fromArray":52,"./fromIterable":55,"./fromObservable":56,"./fromPromise":57}],52:[function(require,module,exports){
9105 "use strict";
9106 Object.defineProperty(exports, "__esModule", { value: true });
9107 var Observable_1 = require("../Observable");
9108 var Subscription_1 = require("../Subscription");
9109 var subscribeToArray_1 = require("../util/subscribeToArray");
9110 function fromArray(input, scheduler) {
9111     if (!scheduler) {
9112         return new Observable_1.Observable(subscribeToArray_1.subscribeToArray(input));
9113     }
9114     else {
9115         return new Observable_1.Observable(function (subscriber) {
9116             var sub = new Subscription_1.Subscription();
9117             var i = 0;
9118             sub.add(scheduler.schedule(function () {
9119                 if (i === input.length) {
9120                     subscriber.complete();
9121                     return;
9122                 }
9123                 subscriber.next(input[i++]);
9124                 if (!subscriber.closed) {
9125                     sub.add(this.schedule());
9126                 }
9127             }));
9128             return sub;
9129         });
9130     }
9131 }
9132 exports.fromArray = fromArray;
9133
9134 },{"../Observable":32,"../Subscription":40,"../util/subscribeToArray":218}],53:[function(require,module,exports){
9135 "use strict";
9136 Object.defineProperty(exports, "__esModule", { value: true });
9137 var Observable_1 = require("../Observable");
9138 var isArray_1 = require("../util/isArray");
9139 var isFunction_1 = require("../util/isFunction");
9140 var map_1 = require("../operators/map");
9141 var toString = Object.prototype.toString;
9142 function fromEvent(target, eventName, options, resultSelector) {
9143     if (isFunction_1.isFunction(options)) {
9144         resultSelector = options;
9145         options = undefined;
9146     }
9147     if (resultSelector) {
9148         return fromEvent(target, eventName, options).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
9149     }
9150     return new Observable_1.Observable(function (subscriber) {
9151         function handler(e) {
9152             if (arguments.length > 1) {
9153                 subscriber.next(Array.prototype.slice.call(arguments));
9154             }
9155             else {
9156                 subscriber.next(e);
9157             }
9158         }
9159         setupSubscription(target, eventName, handler, subscriber, options);
9160     });
9161 }
9162 exports.fromEvent = fromEvent;
9163 function setupSubscription(sourceObj, eventName, handler, subscriber, options) {
9164     var unsubscribe;
9165     if (isEventTarget(sourceObj)) {
9166         var source_1 = sourceObj;
9167         sourceObj.addEventListener(eventName, handler, options);
9168         unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };
9169     }
9170     else if (isJQueryStyleEventEmitter(sourceObj)) {
9171         var source_2 = sourceObj;
9172         sourceObj.on(eventName, handler);
9173         unsubscribe = function () { return source_2.off(eventName, handler); };
9174     }
9175     else if (isNodeStyleEventEmitter(sourceObj)) {
9176         var source_3 = sourceObj;
9177         sourceObj.addListener(eventName, handler);
9178         unsubscribe = function () { return source_3.removeListener(eventName, handler); };
9179     }
9180     else if (sourceObj && sourceObj.length) {
9181         for (var i = 0, len = sourceObj.length; i < len; i++) {
9182             setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
9183         }
9184     }
9185     else {
9186         throw new TypeError('Invalid event target');
9187     }
9188     subscriber.add(unsubscribe);
9189 }
9190 function isNodeStyleEventEmitter(sourceObj) {
9191     return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
9192 }
9193 function isJQueryStyleEventEmitter(sourceObj) {
9194     return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
9195 }
9196 function isEventTarget(sourceObj) {
9197     return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
9198 }
9199
9200 },{"../Observable":32,"../operators/map":112,"../util/isArray":203,"../util/isFunction":206}],54:[function(require,module,exports){
9201 "use strict";
9202 Object.defineProperty(exports, "__esModule", { value: true });
9203 var Observable_1 = require("../Observable");
9204 var isArray_1 = require("../util/isArray");
9205 var isFunction_1 = require("../util/isFunction");
9206 var map_1 = require("../operators/map");
9207 function fromEventPattern(addHandler, removeHandler, resultSelector) {
9208     if (resultSelector) {
9209         return fromEventPattern(addHandler, removeHandler).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
9210     }
9211     return new Observable_1.Observable(function (subscriber) {
9212         var handler = function () {
9213             var e = [];
9214             for (var _i = 0; _i < arguments.length; _i++) {
9215                 e[_i] = arguments[_i];
9216             }
9217             return subscriber.next(e.length === 1 ? e[0] : e);
9218         };
9219         var retValue;
9220         try {
9221             retValue = addHandler(handler);
9222         }
9223         catch (err) {
9224             subscriber.error(err);
9225             return undefined;
9226         }
9227         if (!isFunction_1.isFunction(removeHandler)) {
9228             return undefined;
9229         }
9230         return function () { return removeHandler(handler, retValue); };
9231     });
9232 }
9233 exports.fromEventPattern = fromEventPattern;
9234
9235 },{"../Observable":32,"../operators/map":112,"../util/isArray":203,"../util/isFunction":206}],55:[function(require,module,exports){
9236 "use strict";
9237 Object.defineProperty(exports, "__esModule", { value: true });
9238 var Observable_1 = require("../Observable");
9239 var Subscription_1 = require("../Subscription");
9240 var iterator_1 = require("../symbol/iterator");
9241 var subscribeToIterable_1 = require("../util/subscribeToIterable");
9242 function fromIterable(input, scheduler) {
9243     if (!input) {
9244         throw new Error('Iterable cannot be null');
9245     }
9246     if (!scheduler) {
9247         return new Observable_1.Observable(subscribeToIterable_1.subscribeToIterable(input));
9248     }
9249     else {
9250         return new Observable_1.Observable(function (subscriber) {
9251             var sub = new Subscription_1.Subscription();
9252             var iterator;
9253             sub.add(function () {
9254                 if (iterator && typeof iterator.return === 'function') {
9255                     iterator.return();
9256                 }
9257             });
9258             sub.add(scheduler.schedule(function () {
9259                 iterator = input[iterator_1.iterator]();
9260                 sub.add(scheduler.schedule(function () {
9261                     if (subscriber.closed) {
9262                         return;
9263                     }
9264                     var value;
9265                     var done;
9266                     try {
9267                         var result = iterator.next();
9268                         value = result.value;
9269                         done = result.done;
9270                     }
9271                     catch (err) {
9272                         subscriber.error(err);
9273                         return;
9274                     }
9275                     if (done) {
9276                         subscriber.complete();
9277                     }
9278                     else {
9279                         subscriber.next(value);
9280                         this.schedule();
9281                     }
9282                 }));
9283             }));
9284             return sub;
9285         });
9286     }
9287 }
9288 exports.fromIterable = fromIterable;
9289
9290 },{"../Observable":32,"../Subscription":40,"../symbol/iterator":190,"../util/subscribeToIterable":219}],56:[function(require,module,exports){
9291 "use strict";
9292 Object.defineProperty(exports, "__esModule", { value: true });
9293 var Observable_1 = require("../Observable");
9294 var Subscription_1 = require("../Subscription");
9295 var observable_1 = require("../symbol/observable");
9296 var subscribeToObservable_1 = require("../util/subscribeToObservable");
9297 function fromObservable(input, scheduler) {
9298     if (!scheduler) {
9299         return new Observable_1.Observable(subscribeToObservable_1.subscribeToObservable(input));
9300     }
9301     else {
9302         return new Observable_1.Observable(function (subscriber) {
9303             var sub = new Subscription_1.Subscription();
9304             sub.add(scheduler.schedule(function () {
9305                 var observable = input[observable_1.observable]();
9306                 sub.add(observable.subscribe({
9307                     next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); },
9308                     error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); },
9309                     complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); },
9310                 }));
9311             }));
9312             return sub;
9313         });
9314     }
9315 }
9316 exports.fromObservable = fromObservable;
9317
9318 },{"../Observable":32,"../Subscription":40,"../symbol/observable":191,"../util/subscribeToObservable":220}],57:[function(require,module,exports){
9319 "use strict";
9320 Object.defineProperty(exports, "__esModule", { value: true });
9321 var Observable_1 = require("../Observable");
9322 var Subscription_1 = require("../Subscription");
9323 var subscribeToPromise_1 = require("../util/subscribeToPromise");
9324 function fromPromise(input, scheduler) {
9325     if (!scheduler) {
9326         return new Observable_1.Observable(subscribeToPromise_1.subscribeToPromise(input));
9327     }
9328     else {
9329         return new Observable_1.Observable(function (subscriber) {
9330             var sub = new Subscription_1.Subscription();
9331             sub.add(scheduler.schedule(function () { return input.then(function (value) {
9332                 sub.add(scheduler.schedule(function () {
9333                     subscriber.next(value);
9334                     sub.add(scheduler.schedule(function () { return subscriber.complete(); }));
9335                 }));
9336             }, function (err) {
9337                 sub.add(scheduler.schedule(function () { return subscriber.error(err); }));
9338             }); }));
9339             return sub;
9340         });
9341     }
9342 }
9343 exports.fromPromise = fromPromise;
9344
9345 },{"../Observable":32,"../Subscription":40,"../util/subscribeToPromise":221}],58:[function(require,module,exports){
9346 "use strict";
9347 Object.defineProperty(exports, "__esModule", { value: true });
9348 var Observable_1 = require("../Observable");
9349 var identity_1 = require("../util/identity");
9350 var isScheduler_1 = require("../util/isScheduler");
9351 function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) {
9352     var resultSelector;
9353     var initialState;
9354     if (arguments.length == 1) {
9355         var options = initialStateOrOptions;
9356         initialState = options.initialState;
9357         condition = options.condition;
9358         iterate = options.iterate;
9359         resultSelector = options.resultSelector || identity_1.identity;
9360         scheduler = options.scheduler;
9361     }
9362     else if (resultSelectorOrObservable === undefined || isScheduler_1.isScheduler(resultSelectorOrObservable)) {
9363         initialState = initialStateOrOptions;
9364         resultSelector = identity_1.identity;
9365         scheduler = resultSelectorOrObservable;
9366     }
9367     else {
9368         initialState = initialStateOrOptions;
9369         resultSelector = resultSelectorOrObservable;
9370     }
9371     return new Observable_1.Observable(function (subscriber) {
9372         var state = initialState;
9373         if (scheduler) {
9374             return scheduler.schedule(dispatch, 0, {
9375                 subscriber: subscriber,
9376                 iterate: iterate,
9377                 condition: condition,
9378                 resultSelector: resultSelector,
9379                 state: state
9380             });
9381         }
9382         do {
9383             if (condition) {
9384                 var conditionResult = void 0;
9385                 try {
9386                     conditionResult = condition(state);
9387                 }
9388                 catch (err) {
9389                     subscriber.error(err);
9390                     return undefined;
9391                 }
9392                 if (!conditionResult) {
9393                     subscriber.complete();
9394                     break;
9395                 }
9396             }
9397             var value = void 0;
9398             try {
9399                 value = resultSelector(state);
9400             }
9401             catch (err) {
9402                 subscriber.error(err);
9403                 return undefined;
9404             }
9405             subscriber.next(value);
9406             if (subscriber.closed) {
9407                 break;
9408             }
9409             try {
9410                 state = iterate(state);
9411             }
9412             catch (err) {
9413                 subscriber.error(err);
9414                 return undefined;
9415             }
9416         } while (true);
9417         return undefined;
9418     });
9419 }
9420 exports.generate = generate;
9421 function dispatch(state) {
9422     var subscriber = state.subscriber, condition = state.condition;
9423     if (subscriber.closed) {
9424         return undefined;
9425     }
9426     if (state.needIterate) {
9427         try {
9428             state.state = state.iterate(state.state);
9429         }
9430         catch (err) {
9431             subscriber.error(err);
9432             return undefined;
9433         }
9434     }
9435     else {
9436         state.needIterate = true;
9437     }
9438     if (condition) {
9439         var conditionResult = void 0;
9440         try {
9441             conditionResult = condition(state.state);
9442         }
9443         catch (err) {
9444             subscriber.error(err);
9445             return undefined;
9446         }
9447         if (!conditionResult) {
9448             subscriber.complete();
9449             return undefined;
9450         }
9451         if (subscriber.closed) {
9452             return undefined;
9453         }
9454     }
9455     var value;
9456     try {
9457         value = state.resultSelector(state.state);
9458     }
9459     catch (err) {
9460         subscriber.error(err);
9461         return undefined;
9462     }
9463     if (subscriber.closed) {
9464         return undefined;
9465     }
9466     subscriber.next(value);
9467     if (subscriber.closed) {
9468         return undefined;
9469     }
9470     return this.schedule(state);
9471 }
9472
9473 },{"../Observable":32,"../util/identity":202,"../util/isScheduler":213}],59:[function(require,module,exports){
9474 "use strict";
9475 Object.defineProperty(exports, "__esModule", { value: true });
9476 var defer_1 = require("./defer");
9477 var empty_1 = require("./empty");
9478 function iif(condition, trueResult, falseResult) {
9479     if (trueResult === void 0) { trueResult = empty_1.EMPTY; }
9480     if (falseResult === void 0) { falseResult = empty_1.EMPTY; }
9481     return defer_1.defer(function () { return condition() ? trueResult : falseResult; });
9482 }
9483 exports.iif = iif;
9484
9485 },{"./defer":48,"./empty":49}],60:[function(require,module,exports){
9486 "use strict";
9487 Object.defineProperty(exports, "__esModule", { value: true });
9488 var Observable_1 = require("../Observable");
9489 var async_1 = require("../scheduler/async");
9490 var isNumeric_1 = require("../util/isNumeric");
9491 function interval(period, scheduler) {
9492     if (period === void 0) { period = 0; }
9493     if (scheduler === void 0) { scheduler = async_1.async; }
9494     if (!isNumeric_1.isNumeric(period) || period < 0) {
9495         period = 0;
9496     }
9497     if (!scheduler || typeof scheduler.schedule !== 'function') {
9498         scheduler = async_1.async;
9499     }
9500     return new Observable_1.Observable(function (subscriber) {
9501         subscriber.add(scheduler.schedule(dispatch, period, { subscriber: subscriber, counter: 0, period: period }));
9502         return subscriber;
9503     });
9504 }
9505 exports.interval = interval;
9506 function dispatch(state) {
9507     var subscriber = state.subscriber, counter = state.counter, period = state.period;
9508     subscriber.next(counter);
9509     this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period);
9510 }
9511
9512 },{"../Observable":32,"../scheduler/async":188,"../util/isNumeric":209}],61:[function(require,module,exports){
9513 "use strict";
9514 Object.defineProperty(exports, "__esModule", { value: true });
9515 var Observable_1 = require("../Observable");
9516 var isScheduler_1 = require("../util/isScheduler");
9517 var mergeAll_1 = require("../operators/mergeAll");
9518 var fromArray_1 = require("./fromArray");
9519 function merge() {
9520     var observables = [];
9521     for (var _i = 0; _i < arguments.length; _i++) {
9522         observables[_i] = arguments[_i];
9523     }
9524     var concurrent = Number.POSITIVE_INFINITY;
9525     var scheduler = null;
9526     var last = observables[observables.length - 1];
9527     if (isScheduler_1.isScheduler(last)) {
9528         scheduler = observables.pop();
9529         if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
9530             concurrent = observables.pop();
9531         }
9532     }
9533     else if (typeof last === 'number') {
9534         concurrent = observables.pop();
9535     }
9536     if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
9537         return observables[0];
9538     }
9539     return mergeAll_1.mergeAll(concurrent)(fromArray_1.fromArray(observables, scheduler));
9540 }
9541 exports.merge = merge;
9542
9543 },{"../Observable":32,"../operators/mergeAll":117,"../util/isScheduler":213,"./fromArray":52}],62:[function(require,module,exports){
9544 "use strict";
9545 Object.defineProperty(exports, "__esModule", { value: true });
9546 var Observable_1 = require("../Observable");
9547 var noop_1 = require("../util/noop");
9548 exports.NEVER = new Observable_1.Observable(noop_1.noop);
9549 function never() {
9550     return exports.NEVER;
9551 }
9552 exports.never = never;
9553
9554 },{"../Observable":32,"../util/noop":214}],63:[function(require,module,exports){
9555 "use strict";
9556 Object.defineProperty(exports, "__esModule", { value: true });
9557 var isScheduler_1 = require("../util/isScheduler");
9558 var fromArray_1 = require("./fromArray");
9559 var empty_1 = require("./empty");
9560 var scalar_1 = require("./scalar");
9561 function of() {
9562     var args = [];
9563     for (var _i = 0; _i < arguments.length; _i++) {
9564         args[_i] = arguments[_i];
9565     }
9566     var scheduler = args[args.length - 1];
9567     if (isScheduler_1.isScheduler(scheduler)) {
9568         args.pop();
9569     }
9570     else {
9571         scheduler = undefined;
9572     }
9573     switch (args.length) {
9574         case 0:
9575             return empty_1.empty(scheduler);
9576         case 1:
9577             return scheduler ? fromArray_1.fromArray(args, scheduler) : scalar_1.scalar(args[0]);
9578         default:
9579             return fromArray_1.fromArray(args, scheduler);
9580     }
9581 }
9582 exports.of = of;
9583
9584 },{"../util/isScheduler":213,"./empty":49,"./fromArray":52,"./scalar":68}],64:[function(require,module,exports){
9585 "use strict";
9586 Object.defineProperty(exports, "__esModule", { value: true });
9587 var Observable_1 = require("../Observable");
9588 var from_1 = require("./from");
9589 var isArray_1 = require("../util/isArray");
9590 var empty_1 = require("./empty");
9591 function onErrorResumeNext() {
9592     var sources = [];
9593     for (var _i = 0; _i < arguments.length; _i++) {
9594         sources[_i] = arguments[_i];
9595     }
9596     if (sources.length === 0) {
9597         return empty_1.EMPTY;
9598     }
9599     var first = sources[0], remainder = sources.slice(1);
9600     if (sources.length === 1 && isArray_1.isArray(first)) {
9601         return onErrorResumeNext.apply(void 0, first);
9602     }
9603     return new Observable_1.Observable(function (subscriber) {
9604         var subNext = function () { return subscriber.add(onErrorResumeNext.apply(void 0, remainder).subscribe(subscriber)); };
9605         return from_1.from(first).subscribe({
9606             next: function (value) { subscriber.next(value); },
9607             error: subNext,
9608             complete: subNext,
9609         });
9610     });
9611 }
9612 exports.onErrorResumeNext = onErrorResumeNext;
9613
9614 },{"../Observable":32,"../util/isArray":203,"./empty":49,"./from":51}],65:[function(require,module,exports){
9615 "use strict";
9616 Object.defineProperty(exports, "__esModule", { value: true });
9617 var Observable_1 = require("../Observable");
9618 var Subscription_1 = require("../Subscription");
9619 function pairs(obj, scheduler) {
9620     if (!scheduler) {
9621         return new Observable_1.Observable(function (subscriber) {
9622             var keys = Object.keys(obj);
9623             for (var i = 0; i < keys.length && !subscriber.closed; i++) {
9624                 var key = keys[i];
9625                 if (obj.hasOwnProperty(key)) {
9626                     subscriber.next([key, obj[key]]);
9627                 }
9628             }
9629             subscriber.complete();
9630         });
9631     }
9632     else {
9633         return new Observable_1.Observable(function (subscriber) {
9634             var keys = Object.keys(obj);
9635             var subscription = new Subscription_1.Subscription();
9636             subscription.add(scheduler.schedule(dispatch, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj }));
9637             return subscription;
9638         });
9639     }
9640 }
9641 exports.pairs = pairs;
9642 function dispatch(state) {
9643     var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj;
9644     if (!subscriber.closed) {
9645         if (index < keys.length) {
9646             var key = keys[index];
9647             subscriber.next([key, obj[key]]);
9648             subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj }));
9649         }
9650         else {
9651             subscriber.complete();
9652         }
9653     }
9654 }
9655 exports.dispatch = dispatch;
9656
9657 },{"../Observable":32,"../Subscription":40}],66:[function(require,module,exports){
9658 "use strict";
9659 var __extends = (this && this.__extends) || (function () {
9660     var extendStatics = function (d, b) {
9661         extendStatics = Object.setPrototypeOf ||
9662             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9663             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9664         return extendStatics(d, b);
9665     }
9666     return function (d, b) {
9667         extendStatics(d, b);
9668         function __() { this.constructor = d; }
9669         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9670     };
9671 })();
9672 Object.defineProperty(exports, "__esModule", { value: true });
9673 var isArray_1 = require("../util/isArray");
9674 var fromArray_1 = require("./fromArray");
9675 var OuterSubscriber_1 = require("../OuterSubscriber");
9676 var subscribeToResult_1 = require("../util/subscribeToResult");
9677 function race() {
9678     var observables = [];
9679     for (var _i = 0; _i < arguments.length; _i++) {
9680         observables[_i] = arguments[_i];
9681     }
9682     if (observables.length === 1) {
9683         if (isArray_1.isArray(observables[0])) {
9684             observables = observables[0];
9685         }
9686         else {
9687             return observables[0];
9688         }
9689     }
9690     return fromArray_1.fromArray(observables, undefined).lift(new RaceOperator());
9691 }
9692 exports.race = race;
9693 var RaceOperator = (function () {
9694     function RaceOperator() {
9695     }
9696     RaceOperator.prototype.call = function (subscriber, source) {
9697         return source.subscribe(new RaceSubscriber(subscriber));
9698     };
9699     return RaceOperator;
9700 }());
9701 exports.RaceOperator = RaceOperator;
9702 var RaceSubscriber = (function (_super) {
9703     __extends(RaceSubscriber, _super);
9704     function RaceSubscriber(destination) {
9705         var _this = _super.call(this, destination) || this;
9706         _this.hasFirst = false;
9707         _this.observables = [];
9708         _this.subscriptions = [];
9709         return _this;
9710     }
9711     RaceSubscriber.prototype._next = function (observable) {
9712         this.observables.push(observable);
9713     };
9714     RaceSubscriber.prototype._complete = function () {
9715         var observables = this.observables;
9716         var len = observables.length;
9717         if (len === 0) {
9718             this.destination.complete();
9719         }
9720         else {
9721             for (var i = 0; i < len && !this.hasFirst; i++) {
9722                 var observable = observables[i];
9723                 var subscription = subscribeToResult_1.subscribeToResult(this, observable, observable, i);
9724                 if (this.subscriptions) {
9725                     this.subscriptions.push(subscription);
9726                 }
9727                 this.add(subscription);
9728             }
9729             this.observables = null;
9730         }
9731     };
9732     RaceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9733         if (!this.hasFirst) {
9734             this.hasFirst = true;
9735             for (var i = 0; i < this.subscriptions.length; i++) {
9736                 if (i !== outerIndex) {
9737                     var subscription = this.subscriptions[i];
9738                     subscription.unsubscribe();
9739                     this.remove(subscription);
9740                 }
9741             }
9742             this.subscriptions = null;
9743         }
9744         this.destination.next(innerValue);
9745     };
9746     return RaceSubscriber;
9747 }(OuterSubscriber_1.OuterSubscriber));
9748 exports.RaceSubscriber = RaceSubscriber;
9749
9750 },{"../OuterSubscriber":34,"../util/isArray":203,"../util/subscribeToResult":222,"./fromArray":52}],67:[function(require,module,exports){
9751 "use strict";
9752 Object.defineProperty(exports, "__esModule", { value: true });
9753 var Observable_1 = require("../Observable");
9754 function range(start, count, scheduler) {
9755     if (start === void 0) { start = 0; }
9756     if (count === void 0) { count = 0; }
9757     return new Observable_1.Observable(function (subscriber) {
9758         var index = 0;
9759         var current = start;
9760         if (scheduler) {
9761             return scheduler.schedule(dispatch, 0, {
9762                 index: index, count: count, start: start, subscriber: subscriber
9763             });
9764         }
9765         else {
9766             do {
9767                 if (index++ >= count) {
9768                     subscriber.complete();
9769                     break;
9770                 }
9771                 subscriber.next(current++);
9772                 if (subscriber.closed) {
9773                     break;
9774                 }
9775             } while (true);
9776         }
9777         return undefined;
9778     });
9779 }
9780 exports.range = range;
9781 function dispatch(state) {
9782     var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber;
9783     if (index >= count) {
9784         subscriber.complete();
9785         return;
9786     }
9787     subscriber.next(start);
9788     if (subscriber.closed) {
9789         return;
9790     }
9791     state.index = index + 1;
9792     state.start = start + 1;
9793     this.schedule(state);
9794 }
9795 exports.dispatch = dispatch;
9796
9797 },{"../Observable":32}],68:[function(require,module,exports){
9798 "use strict";
9799 Object.defineProperty(exports, "__esModule", { value: true });
9800 var Observable_1 = require("../Observable");
9801 function scalar(value) {
9802     var result = new Observable_1.Observable(function (subscriber) {
9803         subscriber.next(value);
9804         subscriber.complete();
9805     });
9806     result._isScalar = true;
9807     result.value = value;
9808     return result;
9809 }
9810 exports.scalar = scalar;
9811
9812 },{"../Observable":32}],69:[function(require,module,exports){
9813 "use strict";
9814 Object.defineProperty(exports, "__esModule", { value: true });
9815 var Observable_1 = require("../Observable");
9816 function throwError(error, scheduler) {
9817     if (!scheduler) {
9818         return new Observable_1.Observable(function (subscriber) { return subscriber.error(error); });
9819     }
9820     else {
9821         return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(dispatch, 0, { error: error, subscriber: subscriber }); });
9822     }
9823 }
9824 exports.throwError = throwError;
9825 function dispatch(_a) {
9826     var error = _a.error, subscriber = _a.subscriber;
9827     subscriber.error(error);
9828 }
9829
9830 },{"../Observable":32}],70:[function(require,module,exports){
9831 "use strict";
9832 Object.defineProperty(exports, "__esModule", { value: true });
9833 var Observable_1 = require("../Observable");
9834 var async_1 = require("../scheduler/async");
9835 var isNumeric_1 = require("../util/isNumeric");
9836 var isScheduler_1 = require("../util/isScheduler");
9837 function timer(dueTime, periodOrScheduler, scheduler) {
9838     if (dueTime === void 0) { dueTime = 0; }
9839     var period = -1;
9840     if (isNumeric_1.isNumeric(periodOrScheduler)) {
9841         period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);
9842     }
9843     else if (isScheduler_1.isScheduler(periodOrScheduler)) {
9844         scheduler = periodOrScheduler;
9845     }
9846     if (!isScheduler_1.isScheduler(scheduler)) {
9847         scheduler = async_1.async;
9848     }
9849     return new Observable_1.Observable(function (subscriber) {
9850         var due = isNumeric_1.isNumeric(dueTime)
9851             ? dueTime
9852             : (+dueTime - scheduler.now());
9853         return scheduler.schedule(dispatch, due, {
9854             index: 0, period: period, subscriber: subscriber
9855         });
9856     });
9857 }
9858 exports.timer = timer;
9859 function dispatch(state) {
9860     var index = state.index, period = state.period, subscriber = state.subscriber;
9861     subscriber.next(index);
9862     if (subscriber.closed) {
9863         return;
9864     }
9865     else if (period === -1) {
9866         return subscriber.complete();
9867     }
9868     state.index = index + 1;
9869     this.schedule(state, period);
9870 }
9871
9872 },{"../Observable":32,"../scheduler/async":188,"../util/isNumeric":209,"../util/isScheduler":213}],71:[function(require,module,exports){
9873 "use strict";
9874 Object.defineProperty(exports, "__esModule", { value: true });
9875 var Observable_1 = require("../Observable");
9876 var from_1 = require("./from");
9877 var empty_1 = require("./empty");
9878 function using(resourceFactory, observableFactory) {
9879     return new Observable_1.Observable(function (subscriber) {
9880         var resource;
9881         try {
9882             resource = resourceFactory();
9883         }
9884         catch (err) {
9885             subscriber.error(err);
9886             return undefined;
9887         }
9888         var result;
9889         try {
9890             result = observableFactory(resource);
9891         }
9892         catch (err) {
9893             subscriber.error(err);
9894             return undefined;
9895         }
9896         var source = result ? from_1.from(result) : empty_1.EMPTY;
9897         var subscription = source.subscribe(subscriber);
9898         return function () {
9899             subscription.unsubscribe();
9900             if (resource) {
9901                 resource.unsubscribe();
9902             }
9903         };
9904     });
9905 }
9906 exports.using = using;
9907
9908 },{"../Observable":32,"./empty":49,"./from":51}],72:[function(require,module,exports){
9909 "use strict";
9910 var __extends = (this && this.__extends) || (function () {
9911     var extendStatics = function (d, b) {
9912         extendStatics = Object.setPrototypeOf ||
9913             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9914             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9915         return extendStatics(d, b);
9916     }
9917     return function (d, b) {
9918         extendStatics(d, b);
9919         function __() { this.constructor = d; }
9920         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9921     };
9922 })();
9923 Object.defineProperty(exports, "__esModule", { value: true });
9924 var fromArray_1 = require("./fromArray");
9925 var isArray_1 = require("../util/isArray");
9926 var Subscriber_1 = require("../Subscriber");
9927 var OuterSubscriber_1 = require("../OuterSubscriber");
9928 var subscribeToResult_1 = require("../util/subscribeToResult");
9929 var iterator_1 = require("../../internal/symbol/iterator");
9930 function zip() {
9931     var observables = [];
9932     for (var _i = 0; _i < arguments.length; _i++) {
9933         observables[_i] = arguments[_i];
9934     }
9935     var resultSelector = observables[observables.length - 1];
9936     if (typeof resultSelector === 'function') {
9937         observables.pop();
9938     }
9939     return fromArray_1.fromArray(observables, undefined).lift(new ZipOperator(resultSelector));
9940 }
9941 exports.zip = zip;
9942 var ZipOperator = (function () {
9943     function ZipOperator(resultSelector) {
9944         this.resultSelector = resultSelector;
9945     }
9946     ZipOperator.prototype.call = function (subscriber, source) {
9947         return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));
9948     };
9949     return ZipOperator;
9950 }());
9951 exports.ZipOperator = ZipOperator;
9952 var ZipSubscriber = (function (_super) {
9953     __extends(ZipSubscriber, _super);
9954     function ZipSubscriber(destination, resultSelector, values) {
9955         if (values === void 0) { values = Object.create(null); }
9956         var _this = _super.call(this, destination) || this;
9957         _this.iterators = [];
9958         _this.active = 0;
9959         _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null;
9960         _this.values = values;
9961         return _this;
9962     }
9963     ZipSubscriber.prototype._next = function (value) {
9964         var iterators = this.iterators;
9965         if (isArray_1.isArray(value)) {
9966             iterators.push(new StaticArrayIterator(value));
9967         }
9968         else if (typeof value[iterator_1.iterator] === 'function') {
9969             iterators.push(new StaticIterator(value[iterator_1.iterator]()));
9970         }
9971         else {
9972             iterators.push(new ZipBufferIterator(this.destination, this, value));
9973         }
9974     };
9975     ZipSubscriber.prototype._complete = function () {
9976         var iterators = this.iterators;
9977         var len = iterators.length;
9978         this.unsubscribe();
9979         if (len === 0) {
9980             this.destination.complete();
9981             return;
9982         }
9983         this.active = len;
9984         for (var i = 0; i < len; i++) {
9985             var iterator = iterators[i];
9986             if (iterator.stillUnsubscribed) {
9987                 var destination = this.destination;
9988                 destination.add(iterator.subscribe(iterator, i));
9989             }
9990             else {
9991                 this.active--;
9992             }
9993         }
9994     };
9995     ZipSubscriber.prototype.notifyInactive = function () {
9996         this.active--;
9997         if (this.active === 0) {
9998             this.destination.complete();
9999         }
10000     };
10001     ZipSubscriber.prototype.checkIterators = function () {
10002         var iterators = this.iterators;
10003         var len = iterators.length;
10004         var destination = this.destination;
10005         for (var i = 0; i < len; i++) {
10006             var iterator = iterators[i];
10007             if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
10008                 return;
10009             }
10010         }
10011         var shouldComplete = false;
10012         var args = [];
10013         for (var i = 0; i < len; i++) {
10014             var iterator = iterators[i];
10015             var result = iterator.next();
10016             if (iterator.hasCompleted()) {
10017                 shouldComplete = true;
10018             }
10019             if (result.done) {
10020                 destination.complete();
10021                 return;
10022             }
10023             args.push(result.value);
10024         }
10025         if (this.resultSelector) {
10026             this._tryresultSelector(args);
10027         }
10028         else {
10029             destination.next(args);
10030         }
10031         if (shouldComplete) {
10032             destination.complete();
10033         }
10034     };
10035     ZipSubscriber.prototype._tryresultSelector = function (args) {
10036         var result;
10037         try {
10038             result = this.resultSelector.apply(this, args);
10039         }
10040         catch (err) {
10041             this.destination.error(err);
10042             return;
10043         }
10044         this.destination.next(result);
10045     };
10046     return ZipSubscriber;
10047 }(Subscriber_1.Subscriber));
10048 exports.ZipSubscriber = ZipSubscriber;
10049 var StaticIterator = (function () {
10050     function StaticIterator(iterator) {
10051         this.iterator = iterator;
10052         this.nextResult = iterator.next();
10053     }
10054     StaticIterator.prototype.hasValue = function () {
10055         return true;
10056     };
10057     StaticIterator.prototype.next = function () {
10058         var result = this.nextResult;
10059         this.nextResult = this.iterator.next();
10060         return result;
10061     };
10062     StaticIterator.prototype.hasCompleted = function () {
10063         var nextResult = this.nextResult;
10064         return nextResult && nextResult.done;
10065     };
10066     return StaticIterator;
10067 }());
10068 var StaticArrayIterator = (function () {
10069     function StaticArrayIterator(array) {
10070         this.array = array;
10071         this.index = 0;
10072         this.length = 0;
10073         this.length = array.length;
10074     }
10075     StaticArrayIterator.prototype[iterator_1.iterator] = function () {
10076         return this;
10077     };
10078     StaticArrayIterator.prototype.next = function (value) {
10079         var i = this.index++;
10080         var array = this.array;
10081         return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
10082     };
10083     StaticArrayIterator.prototype.hasValue = function () {
10084         return this.array.length > this.index;
10085     };
10086     StaticArrayIterator.prototype.hasCompleted = function () {
10087         return this.array.length === this.index;
10088     };
10089     return StaticArrayIterator;
10090 }());
10091 var ZipBufferIterator = (function (_super) {
10092     __extends(ZipBufferIterator, _super);
10093     function ZipBufferIterator(destination, parent, observable) {
10094         var _this = _super.call(this, destination) || this;
10095         _this.parent = parent;
10096         _this.observable = observable;
10097         _this.stillUnsubscribed = true;
10098         _this.buffer = [];
10099         _this.isComplete = false;
10100         return _this;
10101     }
10102     ZipBufferIterator.prototype[iterator_1.iterator] = function () {
10103         return this;
10104     };
10105     ZipBufferIterator.prototype.next = function () {
10106         var buffer = this.buffer;
10107         if (buffer.length === 0 && this.isComplete) {
10108             return { value: null, done: true };
10109         }
10110         else {
10111             return { value: buffer.shift(), done: false };
10112         }
10113     };
10114     ZipBufferIterator.prototype.hasValue = function () {
10115         return this.buffer.length > 0;
10116     };
10117     ZipBufferIterator.prototype.hasCompleted = function () {
10118         return this.buffer.length === 0 && this.isComplete;
10119     };
10120     ZipBufferIterator.prototype.notifyComplete = function () {
10121         if (this.buffer.length > 0) {
10122             this.isComplete = true;
10123             this.parent.notifyInactive();
10124         }
10125         else {
10126             this.destination.complete();
10127         }
10128     };
10129     ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10130         this.buffer.push(innerValue);
10131         this.parent.checkIterators();
10132     };
10133     ZipBufferIterator.prototype.subscribe = function (value, index) {
10134         return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
10135     };
10136     return ZipBufferIterator;
10137 }(OuterSubscriber_1.OuterSubscriber));
10138
10139 },{"../../internal/symbol/iterator":190,"../OuterSubscriber":34,"../Subscriber":39,"../util/isArray":203,"../util/subscribeToResult":222,"./fromArray":52}],73:[function(require,module,exports){
10140 "use strict";
10141 var __extends = (this && this.__extends) || (function () {
10142     var extendStatics = function (d, b) {
10143         extendStatics = Object.setPrototypeOf ||
10144             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10145             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10146         return extendStatics(d, b);
10147     }
10148     return function (d, b) {
10149         extendStatics(d, b);
10150         function __() { this.constructor = d; }
10151         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10152     };
10153 })();
10154 Object.defineProperty(exports, "__esModule", { value: true });
10155 var tryCatch_1 = require("../util/tryCatch");
10156 var errorObject_1 = require("../util/errorObject");
10157 var OuterSubscriber_1 = require("../OuterSubscriber");
10158 var subscribeToResult_1 = require("../util/subscribeToResult");
10159 function audit(durationSelector) {
10160     return function auditOperatorFunction(source) {
10161         return source.lift(new AuditOperator(durationSelector));
10162     };
10163 }
10164 exports.audit = audit;
10165 var AuditOperator = (function () {
10166     function AuditOperator(durationSelector) {
10167         this.durationSelector = durationSelector;
10168     }
10169     AuditOperator.prototype.call = function (subscriber, source) {
10170         return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
10171     };
10172     return AuditOperator;
10173 }());
10174 var AuditSubscriber = (function (_super) {
10175     __extends(AuditSubscriber, _super);
10176     function AuditSubscriber(destination, durationSelector) {
10177         var _this = _super.call(this, destination) || this;
10178         _this.durationSelector = durationSelector;
10179         _this.hasValue = false;
10180         return _this;
10181     }
10182     AuditSubscriber.prototype._next = function (value) {
10183         this.value = value;
10184         this.hasValue = true;
10185         if (!this.throttled) {
10186             var duration = tryCatch_1.tryCatch(this.durationSelector)(value);
10187             if (duration === errorObject_1.errorObject) {
10188                 this.destination.error(errorObject_1.errorObject.e);
10189             }
10190             else {
10191                 var innerSubscription = subscribeToResult_1.subscribeToResult(this, duration);
10192                 if (!innerSubscription || innerSubscription.closed) {
10193                     this.clearThrottle();
10194                 }
10195                 else {
10196                     this.add(this.throttled = innerSubscription);
10197                 }
10198             }
10199         }
10200     };
10201     AuditSubscriber.prototype.clearThrottle = function () {
10202         var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;
10203         if (throttled) {
10204             this.remove(throttled);
10205             this.throttled = null;
10206             throttled.unsubscribe();
10207         }
10208         if (hasValue) {
10209             this.value = null;
10210             this.hasValue = false;
10211             this.destination.next(value);
10212         }
10213     };
10214     AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
10215         this.clearThrottle();
10216     };
10217     AuditSubscriber.prototype.notifyComplete = function () {
10218         this.clearThrottle();
10219     };
10220     return AuditSubscriber;
10221 }(OuterSubscriber_1.OuterSubscriber));
10222
10223 },{"../OuterSubscriber":34,"../util/errorObject":200,"../util/subscribeToResult":222,"../util/tryCatch":224}],74:[function(require,module,exports){
10224 "use strict";
10225 Object.defineProperty(exports, "__esModule", { value: true });
10226 var async_1 = require("../scheduler/async");
10227 var audit_1 = require("./audit");
10228 var timer_1 = require("../observable/timer");
10229 function auditTime(duration, scheduler) {
10230     if (scheduler === void 0) { scheduler = async_1.async; }
10231     return audit_1.audit(function () { return timer_1.timer(duration, scheduler); });
10232 }
10233 exports.auditTime = auditTime;
10234
10235 },{"../observable/timer":70,"../scheduler/async":188,"./audit":73}],75:[function(require,module,exports){
10236 "use strict";
10237 var __extends = (this && this.__extends) || (function () {
10238     var extendStatics = function (d, b) {
10239         extendStatics = Object.setPrototypeOf ||
10240             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10241             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10242         return extendStatics(d, b);
10243     }
10244     return function (d, b) {
10245         extendStatics(d, b);
10246         function __() { this.constructor = d; }
10247         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10248     };
10249 })();
10250 Object.defineProperty(exports, "__esModule", { value: true });
10251 var OuterSubscriber_1 = require("../OuterSubscriber");
10252 var subscribeToResult_1 = require("../util/subscribeToResult");
10253 function buffer(closingNotifier) {
10254     return function bufferOperatorFunction(source) {
10255         return source.lift(new BufferOperator(closingNotifier));
10256     };
10257 }
10258 exports.buffer = buffer;
10259 var BufferOperator = (function () {
10260     function BufferOperator(closingNotifier) {
10261         this.closingNotifier = closingNotifier;
10262     }
10263     BufferOperator.prototype.call = function (subscriber, source) {
10264         return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
10265     };
10266     return BufferOperator;
10267 }());
10268 var BufferSubscriber = (function (_super) {
10269     __extends(BufferSubscriber, _super);
10270     function BufferSubscriber(destination, closingNotifier) {
10271         var _this = _super.call(this, destination) || this;
10272         _this.buffer = [];
10273         _this.add(subscribeToResult_1.subscribeToResult(_this, closingNotifier));
10274         return _this;
10275     }
10276     BufferSubscriber.prototype._next = function (value) {
10277         this.buffer.push(value);
10278     };
10279     BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10280         var buffer = this.buffer;
10281         this.buffer = [];
10282         this.destination.next(buffer);
10283     };
10284     return BufferSubscriber;
10285 }(OuterSubscriber_1.OuterSubscriber));
10286
10287 },{"../OuterSubscriber":34,"../util/subscribeToResult":222}],76:[function(require,module,exports){
10288 "use strict";
10289 var __extends = (this && this.__extends) || (function () {
10290     var extendStatics = function (d, b) {
10291         extendStatics = Object.setPrototypeOf ||
10292             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10293             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10294         return extendStatics(d, b);
10295     }
10296     return function (d, b) {
10297         extendStatics(d, b);
10298         function __() { this.constructor = d; }
10299         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10300     };
10301 })();
10302 Object.defineProperty(exports, "__esModule", { value: true });
10303 var Subscriber_1 = require("../Subscriber");
10304 function bufferCount(bufferSize, startBufferEvery) {
10305     if (startBufferEvery === void 0) { startBufferEvery = null; }
10306     return function bufferCountOperatorFunction(source) {
10307         return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
10308     };
10309 }
10310 exports.bufferCount = bufferCount;
10311 var BufferCountOperator = (function () {
10312     function BufferCountOperator(bufferSize, startBufferEvery) {
10313         this.bufferSize = bufferSize;
10314         this.startBufferEvery = startBufferEvery;
10315         if (!startBufferEvery || bufferSize === startBufferEvery) {
10316             this.subscriberClass = BufferCountSubscriber;
10317         }
10318         else {
10319             this.subscriberClass = BufferSkipCountSubscriber;
10320         }
10321     }
10322     BufferCountOperator.prototype.call = function (subscriber, source) {
10323         return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
10324     };
10325     return BufferCountOperator;
10326 }());
10327 var BufferCountSubscriber = (function (_super) {
10328     __extends(BufferCountSubscriber, _super);
10329     function BufferCountSubscriber(destination, bufferSize) {
10330         var _this = _super.call(this, destination) || this;
10331         _this.bufferSize = bufferSize;
10332         _this.buffer = [];
10333         return _this;
10334     }
10335     BufferCountSubscriber.prototype._next = function (value) {
10336         var buffer = this.buffer;
10337         buffer.push(value);
10338         if (buffer.length == this.bufferSize) {
10339             this.destination.next(buffer);
10340             this.buffer = [];
10341         }
10342     };
10343     BufferCountSubscriber.prototype._complete = function () {
10344         var buffer = this.buffer;
10345         if (buffer.length > 0) {
10346             this.destination.next(buffer);
10347         }
10348         _super.prototype._complete.call(this);
10349     };
10350     return BufferCountSubscriber;
10351 }(Subscriber_1.Subscriber));
10352 var BufferSkipCountSubscriber = (function (_super) {
10353     __extends(BufferSkipCountSubscriber, _super);
10354     function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
10355         var _this = _super.call(this, destination) || this;
10356         _this.bufferSize = bufferSize;
10357         _this.startBufferEvery = startBufferEvery;
10358         _this.buffers = [];
10359         _this.count = 0;
10360         return _this;
10361     }
10362     BufferSkipCountSubscriber.prototype._next = function (value) {
10363         var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
10364         this.count++;
10365         if (count % startBufferEvery === 0) {
10366             buffers.push([]);
10367         }
10368         for (var i = buffers.length; i--;) {
10369             var buffer = buffers[i];
10370             buffer.push(value);
10371             if (buffer.length === bufferSize) {
10372                 buffers.splice(i, 1);
10373                 this.destination.next(buffer);
10374             }
10375         }
10376     };
10377     BufferSkipCountSubscriber.prototype._complete = function () {
10378         var _a = this, buffers = _a.buffers, destination = _a.destination;
10379         while (buffers.length > 0) {
10380             var buffer = buffers.shift();
10381             if (buffer.length > 0) {
10382                 destination.next(buffer);
10383             }
10384         }
10385         _super.prototype._complete.call(this);
10386     };
10387     return BufferSkipCountSubscriber;
10388 }(Subscriber_1.Subscriber));
10389
10390 },{"../Subscriber":39}],77:[function(require,module,exports){
10391 "use strict";
10392 var __extends = (this && this.__extends) || (function () {
10393     var extendStatics = function (d, b) {
10394         extendStatics = Object.setPrototypeOf ||
10395             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10396             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10397         return extendStatics(d, b);
10398     }
10399     return function (d, b) {
10400         extendStatics(d, b);
10401         function __() { this.constructor = d; }
10402         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10403     };
10404 })();
10405 Object.defineProperty(exports, "__esModule", { value: true });
10406 var async_1 = require("../scheduler/async");
10407 var Subscriber_1 = require("../Subscriber");
10408 var isScheduler_1 = require("../util/isScheduler");
10409 function bufferTime(bufferTimeSpan) {
10410     var length = arguments.length;
10411     var scheduler = async_1.async;
10412     if (isScheduler_1.isScheduler(arguments[arguments.length - 1])) {
10413         scheduler = arguments[arguments.length - 1];
10414         length--;
10415     }
10416     var bufferCreationInterval = null;
10417     if (length >= 2) {
10418         bufferCreationInterval = arguments[1];
10419     }
10420     var maxBufferSize = Number.POSITIVE_INFINITY;
10421     if (length >= 3) {
10422         maxBufferSize = arguments[2];
10423     }
10424     return function bufferTimeOperatorFunction(source) {
10425         return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
10426     };
10427 }
10428 exports.bufferTime = bufferTime;
10429 var BufferTimeOperator = (function () {
10430     function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
10431         this.bufferTimeSpan = bufferTimeSpan;
10432         this.bufferCreationInterval = bufferCreationInterval;
10433         this.maxBufferSize = maxBufferSize;
10434         this.scheduler = scheduler;
10435     }
10436     BufferTimeOperator.prototype.call = function (subscriber, source) {
10437         return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler));
10438     };
10439     return BufferTimeOperator;
10440 }());
10441 var Context = (function () {
10442     function Context() {
10443         this.buffer = [];
10444     }
10445     return Context;
10446 }());
10447 var BufferTimeSubscriber = (function (_super) {
10448     __extends(BufferTimeSubscriber, _super);
10449     function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
10450         var _this = _super.call(this, destination) || this;
10451         _this.bufferTimeSpan = bufferTimeSpan;
10452         _this.bufferCreationInterval = bufferCreationInterval;
10453         _this.maxBufferSize = maxBufferSize;
10454         _this.scheduler = scheduler;
10455         _this.contexts = [];
10456         var context = _this.openContext();
10457         _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
10458         if (_this.timespanOnly) {
10459             var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan };
10460             _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
10461         }
10462         else {
10463             var closeState = { subscriber: _this, context: context };
10464             var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler };
10465             _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
10466             _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
10467         }
10468         return _this;
10469     }
10470     BufferTimeSubscriber.prototype._next = function (value) {
10471         var contexts = this.contexts;
10472         var len = contexts.length;
10473         var filledBufferContext;
10474         for (var i = 0; i < len; i++) {
10475             var context_1 = contexts[i];
10476             var buffer = context_1.buffer;
10477             buffer.push(value);
10478             if (buffer.length == this.maxBufferSize) {
10479                 filledBufferContext = context_1;
10480             }
10481         }
10482         if (filledBufferContext) {
10483             this.onBufferFull(filledBufferContext);
10484         }
10485     };
10486     BufferTimeSubscriber.prototype._error = function (err) {
10487         this.contexts.length = 0;
10488         _super.prototype._error.call(this, err);
10489     };
10490     BufferTimeSubscriber.prototype._complete = function () {
10491         var _a = this, contexts = _a.contexts, destination = _a.destination;
10492         while (contexts.length > 0) {
10493             var context_2 = contexts.shift();
10494             destination.next(context_2.buffer);
10495         }
10496         _super.prototype._complete.call(this);
10497     };
10498     BufferTimeSubscriber.prototype._unsubscribe = function () {
10499         this.contexts = null;
10500     };
10501     BufferTimeSubscriber.prototype.onBufferFull = function (context) {
10502         this.closeContext(context);
10503         var closeAction = context.closeAction;
10504         closeAction.unsubscribe();
10505         this.remove(closeAction);
10506         if (!this.closed && this.timespanOnly) {
10507             context = this.openContext();
10508             var bufferTimeSpan = this.bufferTimeSpan;
10509             var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan };
10510             this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
10511         }
10512     };
10513     BufferTimeSubscriber.prototype.openContext = function () {
10514         var context = new Context();
10515         this.contexts.push(context);
10516         return context;
10517     };
10518     BufferTimeSubscriber.prototype.closeContext = function (context) {
10519         this.destination.next(context.buffer);
10520         var contexts = this.contexts;
10521         var spliceIndex = contexts ? contexts.indexOf(context) : -1;
10522         if (spliceIndex >= 0) {
10523             contexts.splice(contexts.indexOf(context), 1);
10524         }
10525     };
10526     return BufferTimeSubscriber;
10527 }(Subscriber_1.Subscriber));
10528 function dispatchBufferTimeSpanOnly(state) {
10529     var subscriber = state.subscriber;
10530     var prevContext = state.context;
10531     if (prevContext) {
10532         subscriber.closeContext(prevContext);
10533     }
10534     if (!subscriber.closed) {
10535         state.context = subscriber.openContext();
10536         state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
10537     }
10538 }
10539 function dispatchBufferCreation(state) {
10540     var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler;
10541     var context = subscriber.openContext();
10542     var action = this;
10543     if (!subscriber.closed) {
10544         subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context }));
10545         action.schedule(state, bufferCreationInterval);
10546     }
10547 }
10548 function dispatchBufferClose(arg) {
10549     var subscriber = arg.subscriber, context = arg.context;
10550     subscriber.closeContext(context);
10551 }
10552
10553 },{"../Subscriber":39,"../scheduler/async":188,"../util/isScheduler":213}],78:[function(require,module,exports){
10554 "use strict";
10555 var __extends = (this && this.__extends) || (function () {
10556     var extendStatics = function (d, b) {
10557         extendStatics = Object.setPrototypeOf ||
10558             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10559             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10560         return extendStatics(d, b);
10561     }
10562     return function (d, b) {
10563         extendStatics(d, b);
10564         function __() { this.constructor = d; }
10565         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10566     };
10567 })();
10568 Object.defineProperty(exports, "__esModule", { value: true });
10569 var Subscription_1 = require("../Subscription");
10570 var subscribeToResult_1 = require("../util/subscribeToResult");
10571 var OuterSubscriber_1 = require("../OuterSubscriber");
10572 function bufferToggle(openings, closingSelector) {
10573     return function bufferToggleOperatorFunction(source) {
10574         return source.lift(new BufferToggleOperator(openings, closingSelector));
10575     };
10576 }
10577 exports.bufferToggle = bufferToggle;
10578 var BufferToggleOperator = (function () {
10579     function BufferToggleOperator(openings, closingSelector) {
10580         this.openings = openings;
10581         this.closingSelector = closingSelector;
10582     }
10583     BufferToggleOperator.prototype.call = function (subscriber, source) {
10584         return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));
10585     };
10586     return BufferToggleOperator;
10587 }());
10588 var BufferToggleSubscriber = (function (_super) {
10589     __extends(BufferToggleSubscriber, _super);
10590     function BufferToggleSubscriber(destination, openings, closingSelector) {
10591         var _this = _super.call(this, destination) || this;
10592         _this.openings = openings;
10593         _this.closingSelector = closingSelector;
10594         _this.contexts = [];
10595         _this.add(subscribeToResult_1.subscribeToResult(_this, openings));
10596         return _this;
10597     }
10598     BufferToggleSubscriber.prototype._next = function (value) {
10599         var contexts = this.contexts;
10600         var len = contexts.length;
10601         for (var i = 0; i < len; i++) {
10602             contexts[i].buffer.push(value);
10603         }
10604     };
10605     BufferToggleSubscriber.prototype._error = function (err) {
10606         var contexts = this.contexts;
10607         while (contexts.length > 0) {
10608             var context_1 = contexts.shift();
10609             context_1.subscription.unsubscribe();
10610             context_1.buffer = null;
10611             context_1.subscription = null;
10612         }
10613         this.contexts = null;
10614         _super.prototype._error.call(this, err);
10615     };
10616     BufferToggleSubscriber.prototype._complete = function () {
10617         var contexts = this.contexts;
10618         while (contexts.length > 0) {
10619             var context_2 = contexts.shift();
10620             this.destination.next(context_2.buffer);
10621             context_2.subscription.unsubscribe();
10622             context_2.buffer = null;
10623             context_2.subscription = null;
10624         }
10625         this.contexts = null;
10626         _super.prototype._complete.call(this);
10627     };
10628     BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10629         outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);
10630     };
10631     BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) {
10632         this.closeBuffer(innerSub.context);
10633     };
10634     BufferToggleSubscriber.prototype.openBuffer = function (value) {
10635         try {
10636             var closingSelector = this.closingSelector;
10637             var closingNotifier = closingSelector.call(this, value);
10638             if (closingNotifier) {
10639                 this.trySubscribe(closingNotifier);
10640             }
10641         }
10642         catch (err) {
10643             this._error(err);
10644         }
10645     };
10646     BufferToggleSubscriber.prototype.closeBuffer = function (context) {
10647         var contexts = this.contexts;
10648         if (contexts && context) {
10649             var buffer = context.buffer, subscription = context.subscription;
10650             this.destination.next(buffer);
10651             contexts.splice(contexts.indexOf(context), 1);
10652             this.remove(subscription);
10653             subscription.unsubscribe();
10654         }
10655     };
10656     BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) {
10657         var contexts = this.contexts;
10658         var buffer = [];
10659         var subscription = new Subscription_1.Subscription();
10660         var context = { buffer: buffer, subscription: subscription };
10661         contexts.push(context);
10662         var innerSubscription = subscribeToResult_1.subscribeToResult(this, closingNotifier, context);
10663         if (!innerSubscription || innerSubscription.closed) {
10664             this.closeBuffer(context);
10665         }
10666         else {
10667             innerSubscription.context = context;
10668             this.add(innerSubscription);
10669             subscription.add(innerSubscription);
10670         }
10671     };
10672     return BufferToggleSubscriber;
10673 }(OuterSubscriber_1.OuterSubscriber));
10674
10675 },{"../OuterSubscriber":34,"../Subscription":40,"../util/subscribeToResult":222}],79:[function(require,module,exports){
10676 "use strict";
10677 var __extends = (this && this.__extends) || (function () {
10678     var extendStatics = function (d, b) {
10679         extendStatics = Object.setPrototypeOf ||
10680             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10681             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10682         return extendStatics(d, b);
10683     }
10684     return function (d, b) {
10685         extendStatics(d, b);
10686         function __() { this.constructor = d; }
10687         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10688     };
10689 })();
10690 Object.defineProperty(exports, "__esModule", { value: true });
10691 var Subscription_1 = require("../Subscription");
10692 var tryCatch_1 = require("../util/tryCatch");
10693 var errorObject_1 = require("../util/errorObject");
10694 var OuterSubscriber_1 = require("../OuterSubscriber");
10695 var subscribeToResult_1 = require("../util/subscribeToResult");
10696 function bufferWhen(closingSelector) {
10697     return function (source) {
10698         return source.lift(new BufferWhenOperator(closingSelector));
10699     };
10700 }
10701 exports.bufferWhen = bufferWhen;
10702 var BufferWhenOperator = (function () {
10703     function BufferWhenOperator(closingSelector) {
10704         this.closingSelector = closingSelector;
10705     }
10706     BufferWhenOperator.prototype.call = function (subscriber, source) {
10707         return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
10708     };
10709     return BufferWhenOperator;
10710 }());
10711 var BufferWhenSubscriber = (function (_super) {
10712     __extends(BufferWhenSubscriber, _super);
10713     function BufferWhenSubscriber(destination, closingSelector) {
10714         var _this = _super.call(this, destination) || this;
10715         _this.closingSelector = closingSelector;
10716         _this.subscribing = false;
10717         _this.openBuffer();
10718         return _this;
10719     }
10720     BufferWhenSubscriber.prototype._next = function (value) {
10721         this.buffer.push(value);
10722     };
10723     BufferWhenSubscriber.prototype._complete = function () {
10724         var buffer = this.buffer;
10725         if (buffer) {
10726             this.destination.next(buffer);
10727         }
10728         _super.prototype._complete.call(this);
10729     };
10730     BufferWhenSubscriber.prototype._unsubscribe = function () {
10731         this.buffer = null;
10732         this.subscribing = false;
10733     };
10734     BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10735         this.openBuffer();
10736     };
10737     BufferWhenSubscriber.prototype.notifyComplete = function () {
10738         if (this.subscribing) {
10739             this.complete();
10740         }
10741         else {
10742             this.openBuffer();
10743         }
10744     };
10745     BufferWhenSubscriber.prototype.openBuffer = function () {
10746         var closingSubscription = this.closingSubscription;
10747         if (closingSubscription) {
10748             this.remove(closingSubscription);
10749             closingSubscription.unsubscribe();
10750         }
10751         var buffer = this.buffer;
10752         if (this.buffer) {
10753             this.destination.next(buffer);
10754         }
10755         this.buffer = [];
10756         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
10757         if (closingNotifier === errorObject_1.errorObject) {
10758             this.error(errorObject_1.errorObject.e);
10759         }
10760         else {
10761             closingSubscription = new Subscription_1.Subscription();
10762             this.closingSubscription = closingSubscription;
10763             this.add(closingSubscription);
10764             this.subscribing = true;
10765             closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
10766             this.subscribing = false;
10767         }
10768     };
10769     return BufferWhenSubscriber;
10770 }(OuterSubscriber_1.OuterSubscriber));
10771
10772 },{"../OuterSubscriber":34,"../Subscription":40,"../util/errorObject":200,"../util/subscribeToResult":222,"../util/tryCatch":224}],80:[function(require,module,exports){
10773 "use strict";
10774 var __extends = (this && this.__extends) || (function () {
10775     var extendStatics = function (d, b) {
10776         extendStatics = Object.setPrototypeOf ||
10777             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10778             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10779         return extendStatics(d, b);
10780     }
10781     return function (d, b) {
10782         extendStatics(d, b);
10783         function __() { this.constructor = d; }
10784         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10785     };
10786 })();
10787 Object.defineProperty(exports, "__esModule", { value: true });
10788 var OuterSubscriber_1 = require("../OuterSubscriber");
10789 var InnerSubscriber_1 = require("../InnerSubscriber");
10790 var subscribeToResult_1 = require("../util/subscribeToResult");
10791 function catchError(selector) {
10792     return function catchErrorOperatorFunction(source) {
10793         var operator = new CatchOperator(selector);
10794         var caught = source.lift(operator);
10795         return (operator.caught = caught);
10796     };
10797 }
10798 exports.catchError = catchError;
10799 var CatchOperator = (function () {
10800     function CatchOperator(selector) {
10801         this.selector = selector;
10802     }
10803     CatchOperator.prototype.call = function (subscriber, source) {
10804         return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
10805     };
10806     return CatchOperator;
10807 }());
10808 var CatchSubscriber = (function (_super) {
10809     __extends(CatchSubscriber, _super);
10810     function CatchSubscriber(destination, selector, caught) {
10811         var _this = _super.call(this, destination) || this;
10812         _this.selector = selector;
10813         _this.caught = caught;
10814         return _this;
10815     }
10816     CatchSubscriber.prototype.error = function (err) {
10817         if (!this.isStopped) {
10818             var result = void 0;
10819             try {
10820                 result = this.selector(err, this.caught);
10821             }
10822             catch (err2) {
10823                 _super.prototype.error.call(this, err2);
10824                 return;
10825             }
10826             this._unsubscribeAndRecycle();
10827             var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
10828             this.add(innerSubscriber);
10829             subscribeToResult_1.subscribeToResult(this, result, undefined, undefined, innerSubscriber);
10830         }
10831     };
10832     return CatchSubscriber;
10833 }(OuterSubscriber_1.OuterSubscriber));
10834
10835 },{"../InnerSubscriber":30,"../OuterSubscriber":34,"../util/subscribeToResult":222}],81:[function(require,module,exports){
10836 "use strict";
10837 Object.defineProperty(exports, "__esModule", { value: true });
10838 var combineLatest_1 = require("../observable/combineLatest");
10839 function combineAll(project) {
10840     return function (source) { return source.lift(new combineLatest_1.CombineLatestOperator(project)); };
10841 }
10842 exports.combineAll = combineAll;
10843
10844 },{"../observable/combineLatest":46}],82:[function(require,module,exports){
10845 "use strict";
10846 Object.defineProperty(exports, "__esModule", { value: true });
10847 var isArray_1 = require("../util/isArray");
10848 var combineLatest_1 = require("../observable/combineLatest");
10849 var from_1 = require("../observable/from");
10850 var none = {};
10851 function combineLatest() {
10852     var observables = [];
10853     for (var _i = 0; _i < arguments.length; _i++) {
10854         observables[_i] = arguments[_i];
10855     }
10856     var project = null;
10857     if (typeof observables[observables.length - 1] === 'function') {
10858         project = observables.pop();
10859     }
10860     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
10861         observables = observables[0].slice();
10862     }
10863     return function (source) { return source.lift.call(from_1.from([source].concat(observables)), new combineLatest_1.CombineLatestOperator(project)); };
10864 }
10865 exports.combineLatest = combineLatest;
10866
10867 },{"../observable/combineLatest":46,"../observable/from":51,"../util/isArray":203}],83:[function(require,module,exports){
10868 "use strict";
10869 Object.defineProperty(exports, "__esModule", { value: true });
10870 var concat_1 = require("../observable/concat");
10871 function concat() {
10872     var observables = [];
10873     for (var _i = 0; _i < arguments.length; _i++) {
10874         observables[_i] = arguments[_i];
10875     }
10876     return function (source) { return source.lift.call(concat_1.concat.apply(void 0, [source].concat(observables))); };
10877 }
10878 exports.concat = concat;
10879
10880 },{"../observable/concat":47}],84:[function(require,module,exports){
10881 "use strict";
10882 Object.defineProperty(exports, "__esModule", { value: true });
10883 var mergeAll_1 = require("./mergeAll");
10884 function concatAll() {
10885     return mergeAll_1.mergeAll(1);
10886 }
10887 exports.concatAll = concatAll;
10888
10889 },{"./mergeAll":117}],85:[function(require,module,exports){
10890 "use strict";
10891 Object.defineProperty(exports, "__esModule", { value: true });
10892 var mergeMap_1 = require("./mergeMap");
10893 function concatMap(project, resultSelector) {
10894     return mergeMap_1.mergeMap(project, resultSelector, 1);
10895 }
10896 exports.concatMap = concatMap;
10897
10898 },{"./mergeMap":118}],86:[function(require,module,exports){
10899 "use strict";
10900 Object.defineProperty(exports, "__esModule", { value: true });
10901 var concatMap_1 = require("./concatMap");
10902 function concatMapTo(innerObservable, resultSelector) {
10903     return concatMap_1.concatMap(function () { return innerObservable; }, resultSelector);
10904 }
10905 exports.concatMapTo = concatMapTo;
10906
10907 },{"./concatMap":85}],87:[function(require,module,exports){
10908 "use strict";
10909 var __extends = (this && this.__extends) || (function () {
10910     var extendStatics = function (d, b) {
10911         extendStatics = Object.setPrototypeOf ||
10912             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10913             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10914         return extendStatics(d, b);
10915     }
10916     return function (d, b) {
10917         extendStatics(d, b);
10918         function __() { this.constructor = d; }
10919         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10920     };
10921 })();
10922 Object.defineProperty(exports, "__esModule", { value: true });
10923 var Subscriber_1 = require("../Subscriber");
10924 function count(predicate) {
10925     return function (source) { return source.lift(new CountOperator(predicate, source)); };
10926 }
10927 exports.count = count;
10928 var CountOperator = (function () {
10929     function CountOperator(predicate, source) {
10930         this.predicate = predicate;
10931         this.source = source;
10932     }
10933     CountOperator.prototype.call = function (subscriber, source) {
10934         return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));
10935     };
10936     return CountOperator;
10937 }());
10938 var CountSubscriber = (function (_super) {
10939     __extends(CountSubscriber, _super);
10940     function CountSubscriber(destination, predicate, source) {
10941         var _this = _super.call(this, destination) || this;
10942         _this.predicate = predicate;
10943         _this.source = source;
10944         _this.count = 0;
10945         _this.index = 0;
10946         return _this;
10947     }
10948     CountSubscriber.prototype._next = function (value) {
10949         if (this.predicate) {
10950             this._tryPredicate(value);
10951         }
10952         else {
10953             this.count++;
10954         }
10955     };
10956     CountSubscriber.prototype._tryPredicate = function (value) {
10957         var result;
10958         try {
10959             result = this.predicate(value, this.index++, this.source);
10960         }
10961         catch (err) {
10962             this.destination.error(err);
10963             return;
10964         }
10965         if (result) {
10966             this.count++;
10967         }
10968     };
10969     CountSubscriber.prototype._complete = function () {
10970         this.destination.next(this.count);
10971         this.destination.complete();
10972     };
10973     return CountSubscriber;
10974 }(Subscriber_1.Subscriber));
10975
10976 },{"../Subscriber":39}],88:[function(require,module,exports){
10977 "use strict";
10978 var __extends = (this && this.__extends) || (function () {
10979     var extendStatics = function (d, b) {
10980         extendStatics = Object.setPrototypeOf ||
10981             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10982             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10983         return extendStatics(d, b);
10984     }
10985     return function (d, b) {
10986         extendStatics(d, b);
10987         function __() { this.constructor = d; }
10988         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10989     };
10990 })();
10991 Object.defineProperty(exports, "__esModule", { value: true });
10992 var OuterSubscriber_1 = require("../OuterSubscriber");
10993 var subscribeToResult_1 = require("../util/subscribeToResult");
10994 function debounce(durationSelector) {
10995     return function (source) { return source.lift(new DebounceOperator(durationSelector)); };
10996 }
10997 exports.debounce = debounce;
10998 var DebounceOperator = (function () {
10999     function DebounceOperator(durationSelector) {
11000         this.durationSelector = durationSelector;
11001     }
11002     DebounceOperator.prototype.call = function (subscriber, source) {
11003         return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));
11004     };
11005     return DebounceOperator;
11006 }());
11007 var DebounceSubscriber = (function (_super) {
11008     __extends(DebounceSubscriber, _super);
11009     function DebounceSubscriber(destination, durationSelector) {
11010         var _this = _super.call(this, destination) || this;
11011         _this.durationSelector = durationSelector;
11012         _this.hasValue = false;
11013         _this.durationSubscription = null;
11014         return _this;
11015     }
11016     DebounceSubscriber.prototype._next = function (value) {
11017         try {
11018             var result = this.durationSelector.call(this, value);
11019             if (result) {
11020                 this._tryNext(value, result);
11021             }
11022         }
11023         catch (err) {
11024             this.destination.error(err);
11025         }
11026     };
11027     DebounceSubscriber.prototype._complete = function () {
11028         this.emitValue();
11029         this.destination.complete();
11030     };
11031     DebounceSubscriber.prototype._tryNext = function (value, duration) {
11032         var subscription = this.durationSubscription;
11033         this.value = value;
11034         this.hasValue = true;
11035         if (subscription) {
11036             subscription.unsubscribe();
11037             this.remove(subscription);
11038         }
11039         subscription = subscribeToResult_1.subscribeToResult(this, duration);
11040         if (subscription && !subscription.closed) {
11041             this.add(this.durationSubscription = subscription);
11042         }
11043     };
11044     DebounceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11045         this.emitValue();
11046     };
11047     DebounceSubscriber.prototype.notifyComplete = function () {
11048         this.emitValue();
11049     };
11050     DebounceSubscriber.prototype.emitValue = function () {
11051         if (this.hasValue) {
11052             var value = this.value;
11053             var subscription = this.durationSubscription;
11054             if (subscription) {
11055                 this.durationSubscription = null;
11056                 subscription.unsubscribe();
11057                 this.remove(subscription);
11058             }
11059             this.value = null;
11060             this.hasValue = false;
11061             _super.prototype._next.call(this, value);
11062         }
11063     };
11064     return DebounceSubscriber;
11065 }(OuterSubscriber_1.OuterSubscriber));
11066
11067 },{"../OuterSubscriber":34,"../util/subscribeToResult":222}],89:[function(require,module,exports){
11068 "use strict";
11069 var __extends = (this && this.__extends) || (function () {
11070     var extendStatics = function (d, b) {
11071         extendStatics = Object.setPrototypeOf ||
11072             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11073             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11074         return extendStatics(d, b);
11075     }
11076     return function (d, b) {
11077         extendStatics(d, b);
11078         function __() { this.constructor = d; }
11079         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11080     };
11081 })();
11082 Object.defineProperty(exports, "__esModule", { value: true });
11083 var Subscriber_1 = require("../Subscriber");
11084 var async_1 = require("../scheduler/async");
11085 function debounceTime(dueTime, scheduler) {
11086     if (scheduler === void 0) { scheduler = async_1.async; }
11087     return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
11088 }
11089 exports.debounceTime = debounceTime;
11090 var DebounceTimeOperator = (function () {
11091     function DebounceTimeOperator(dueTime, scheduler) {
11092         this.dueTime = dueTime;
11093         this.scheduler = scheduler;
11094     }
11095     DebounceTimeOperator.prototype.call = function (subscriber, source) {
11096         return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
11097     };
11098     return DebounceTimeOperator;
11099 }());
11100 var DebounceTimeSubscriber = (function (_super) {
11101     __extends(DebounceTimeSubscriber, _super);
11102     function DebounceTimeSubscriber(destination, dueTime, scheduler) {
11103         var _this = _super.call(this, destination) || this;
11104         _this.dueTime = dueTime;
11105         _this.scheduler = scheduler;
11106         _this.debouncedSubscription = null;
11107         _this.lastValue = null;
11108         _this.hasValue = false;
11109         return _this;
11110     }
11111     DebounceTimeSubscriber.prototype._next = function (value) {
11112         this.clearDebounce();
11113         this.lastValue = value;
11114         this.hasValue = true;
11115         this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
11116     };
11117     DebounceTimeSubscriber.prototype._complete = function () {
11118         this.debouncedNext();
11119         this.destination.complete();
11120     };
11121     DebounceTimeSubscriber.prototype.debouncedNext = function () {
11122         this.clearDebounce();
11123         if (this.hasValue) {
11124             var lastValue = this.lastValue;
11125             this.lastValue = null;
11126             this.hasValue = false;
11127             this.destination.next(lastValue);
11128         }
11129     };
11130     DebounceTimeSubscriber.prototype.clearDebounce = function () {
11131         var debouncedSubscription = this.debouncedSubscription;
11132         if (debouncedSubscription !== null) {
11133             this.remove(debouncedSubscription);
11134             debouncedSubscription.unsubscribe();
11135             this.debouncedSubscription = null;
11136         }
11137     };
11138     return DebounceTimeSubscriber;
11139 }(Subscriber_1.Subscriber));
11140 function dispatchNext(subscriber) {
11141     subscriber.debouncedNext();
11142 }
11143
11144 },{"../Subscriber":39,"../scheduler/async":188}],90:[function(require,module,exports){
11145 "use strict";
11146 var __extends = (this && this.__extends) || (function () {
11147     var extendStatics = function (d, b) {
11148         extendStatics = Object.setPrototypeOf ||
11149             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11150             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11151         return extendStatics(d, b);
11152     }
11153     return function (d, b) {
11154         extendStatics(d, b);
11155         function __() { this.constructor = d; }
11156         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11157     };
11158 })();
11159 Object.defineProperty(exports, "__esModule", { value: true });
11160 var Subscriber_1 = require("../Subscriber");
11161 function defaultIfEmpty(defaultValue) {
11162     if (defaultValue === void 0) { defaultValue = null; }
11163     return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };
11164 }
11165 exports.defaultIfEmpty = defaultIfEmpty;
11166 var DefaultIfEmptyOperator = (function () {
11167     function DefaultIfEmptyOperator(defaultValue) {
11168         this.defaultValue = defaultValue;
11169     }
11170     DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {
11171         return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
11172     };
11173     return DefaultIfEmptyOperator;
11174 }());
11175 var DefaultIfEmptySubscriber = (function (_super) {
11176     __extends(DefaultIfEmptySubscriber, _super);
11177     function DefaultIfEmptySubscriber(destination, defaultValue) {
11178         var _this = _super.call(this, destination) || this;
11179         _this.defaultValue = defaultValue;
11180         _this.isEmpty = true;
11181         return _this;
11182     }
11183     DefaultIfEmptySubscriber.prototype._next = function (value) {
11184         this.isEmpty = false;
11185         this.destination.next(value);
11186     };
11187     DefaultIfEmptySubscriber.prototype._complete = function () {
11188         if (this.isEmpty) {
11189             this.destination.next(this.defaultValue);
11190         }
11191         this.destination.complete();
11192     };
11193     return DefaultIfEmptySubscriber;
11194 }(Subscriber_1.Subscriber));
11195
11196 },{"../Subscriber":39}],91:[function(require,module,exports){
11197 "use strict";
11198 var __extends = (this && this.__extends) || (function () {
11199     var extendStatics = function (d, b) {
11200         extendStatics = Object.setPrototypeOf ||
11201             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11202             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11203         return extendStatics(d, b);
11204     }
11205     return function (d, b) {
11206         extendStatics(d, b);
11207         function __() { this.constructor = d; }
11208         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11209     };
11210 })();
11211 Object.defineProperty(exports, "__esModule", { value: true });
11212 var async_1 = require("../scheduler/async");
11213 var isDate_1 = require("../util/isDate");
11214 var Subscriber_1 = require("../Subscriber");
11215 var Notification_1 = require("../Notification");
11216 function delay(delay, scheduler) {
11217     if (scheduler === void 0) { scheduler = async_1.async; }
11218     var absoluteDelay = isDate_1.isDate(delay);
11219     var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
11220     return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
11221 }
11222 exports.delay = delay;
11223 var DelayOperator = (function () {
11224     function DelayOperator(delay, scheduler) {
11225         this.delay = delay;
11226         this.scheduler = scheduler;
11227     }
11228     DelayOperator.prototype.call = function (subscriber, source) {
11229         return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
11230     };
11231     return DelayOperator;
11232 }());
11233 var DelaySubscriber = (function (_super) {
11234     __extends(DelaySubscriber, _super);
11235     function DelaySubscriber(destination, delay, scheduler) {
11236         var _this = _super.call(this, destination) || this;
11237         _this.delay = delay;
11238         _this.scheduler = scheduler;
11239         _this.queue = [];
11240         _this.active = false;
11241         _this.errored = false;
11242         return _this;
11243     }
11244     DelaySubscriber.dispatch = function (state) {
11245         var source = state.source;
11246         var queue = source.queue;
11247         var scheduler = state.scheduler;
11248         var destination = state.destination;
11249         while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
11250             queue.shift().notification.observe(destination);
11251         }
11252         if (queue.length > 0) {
11253             var delay_1 = Math.max(0, queue[0].time - scheduler.now());
11254             this.schedule(state, delay_1);
11255         }
11256         else {
11257             this.unsubscribe();
11258             source.active = false;
11259         }
11260     };
11261     DelaySubscriber.prototype._schedule = function (scheduler) {
11262         this.active = true;
11263         var destination = this.destination;
11264         destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
11265             source: this, destination: this.destination, scheduler: scheduler
11266         }));
11267     };
11268     DelaySubscriber.prototype.scheduleNotification = function (notification) {
11269         if (this.errored === true) {
11270             return;
11271         }
11272         var scheduler = this.scheduler;
11273         var message = new DelayMessage(scheduler.now() + this.delay, notification);
11274         this.queue.push(message);
11275         if (this.active === false) {
11276             this._schedule(scheduler);
11277         }
11278     };
11279     DelaySubscriber.prototype._next = function (value) {
11280         this.scheduleNotification(Notification_1.Notification.createNext(value));
11281     };
11282     DelaySubscriber.prototype._error = function (err) {
11283         this.errored = true;
11284         this.queue = [];
11285         this.destination.error(err);
11286         this.unsubscribe();
11287     };
11288     DelaySubscriber.prototype._complete = function () {
11289         this.scheduleNotification(Notification_1.Notification.createComplete());
11290         this.unsubscribe();
11291     };
11292     return DelaySubscriber;
11293 }(Subscriber_1.Subscriber));
11294 var DelayMessage = (function () {
11295     function DelayMessage(time, notification) {
11296         this.time = time;
11297         this.notification = notification;
11298     }
11299     return DelayMessage;
11300 }());
11301
11302 },{"../Notification":31,"../Subscriber":39,"../scheduler/async":188,"../util/isDate":205}],92:[function(require,module,exports){
11303 "use strict";
11304 var __extends = (this && this.__extends) || (function () {
11305     var extendStatics = function (d, b) {
11306         extendStatics = Object.setPrototypeOf ||
11307             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11308             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11309         return extendStatics(d, b);
11310     }
11311     return function (d, b) {
11312         extendStatics(d, b);
11313         function __() { this.constructor = d; }
11314         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11315     };
11316 })();
11317 Object.defineProperty(exports, "__esModule", { value: true });
11318 var Subscriber_1 = require("../Subscriber");
11319 var Observable_1 = require("../Observable");
11320 var OuterSubscriber_1 = require("../OuterSubscriber");
11321 var subscribeToResult_1 = require("../util/subscribeToResult");
11322 function delayWhen(delayDurationSelector, subscriptionDelay) {
11323     if (subscriptionDelay) {
11324         return function (source) {
11325             return new SubscriptionDelayObservable(source, subscriptionDelay)
11326                 .lift(new DelayWhenOperator(delayDurationSelector));
11327         };
11328     }
11329     return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); };
11330 }
11331 exports.delayWhen = delayWhen;
11332 var DelayWhenOperator = (function () {
11333     function DelayWhenOperator(delayDurationSelector) {
11334         this.delayDurationSelector = delayDurationSelector;
11335     }
11336     DelayWhenOperator.prototype.call = function (subscriber, source) {
11337         return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));
11338     };
11339     return DelayWhenOperator;
11340 }());
11341 var DelayWhenSubscriber = (function (_super) {
11342     __extends(DelayWhenSubscriber, _super);
11343     function DelayWhenSubscriber(destination, delayDurationSelector) {
11344         var _this = _super.call(this, destination) || this;
11345         _this.delayDurationSelector = delayDurationSelector;
11346         _this.completed = false;
11347         _this.delayNotifierSubscriptions = [];
11348         _this.index = 0;
11349         return _this;
11350     }
11351     DelayWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11352         this.destination.next(outerValue);
11353         this.removeSubscription(innerSub);
11354         this.tryComplete();
11355     };
11356     DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) {
11357         this._error(error);
11358     };
11359     DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) {
11360         var value = this.removeSubscription(innerSub);
11361         if (value) {
11362             this.destination.next(value);
11363         }
11364         this.tryComplete();
11365     };
11366     DelayWhenSubscriber.prototype._next = function (value) {
11367         var index = this.index++;
11368         try {
11369             var delayNotifier = this.delayDurationSelector(value, index);
11370             if (delayNotifier) {
11371                 this.tryDelay(delayNotifier, value);
11372             }
11373         }
11374         catch (err) {
11375             this.destination.error(err);
11376         }
11377     };
11378     DelayWhenSubscriber.prototype._complete = function () {
11379         this.completed = true;
11380         this.tryComplete();
11381         this.unsubscribe();
11382     };
11383     DelayWhenSubscriber.prototype.removeSubscription = function (subscription) {
11384         subscription.unsubscribe();
11385         var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);
11386         if (subscriptionIdx !== -1) {
11387             this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);
11388         }
11389         return subscription.outerValue;
11390     };
11391     DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) {
11392         var notifierSubscription = subscribeToResult_1.subscribeToResult(this, delayNotifier, value);
11393         if (notifierSubscription && !notifierSubscription.closed) {
11394             var destination = this.destination;
11395             destination.add(notifierSubscription);
11396             this.delayNotifierSubscriptions.push(notifierSubscription);
11397         }
11398     };
11399     DelayWhenSubscriber.prototype.tryComplete = function () {
11400         if (this.completed && this.delayNotifierSubscriptions.length === 0) {
11401             this.destination.complete();
11402         }
11403     };
11404     return DelayWhenSubscriber;
11405 }(OuterSubscriber_1.OuterSubscriber));
11406 var SubscriptionDelayObservable = (function (_super) {
11407     __extends(SubscriptionDelayObservable, _super);
11408     function SubscriptionDelayObservable(source, subscriptionDelay) {
11409         var _this = _super.call(this) || this;
11410         _this.source = source;
11411         _this.subscriptionDelay = subscriptionDelay;
11412         return _this;
11413     }
11414     SubscriptionDelayObservable.prototype._subscribe = function (subscriber) {
11415         this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));
11416     };
11417     return SubscriptionDelayObservable;
11418 }(Observable_1.Observable));
11419 var SubscriptionDelaySubscriber = (function (_super) {
11420     __extends(SubscriptionDelaySubscriber, _super);
11421     function SubscriptionDelaySubscriber(parent, source) {
11422         var _this = _super.call(this) || this;
11423         _this.parent = parent;
11424         _this.source = source;
11425         _this.sourceSubscribed = false;
11426         return _this;
11427     }
11428     SubscriptionDelaySubscriber.prototype._next = function (unused) {
11429         this.subscribeToSource();
11430     };
11431     SubscriptionDelaySubscriber.prototype._error = function (err) {
11432         this.unsubscribe();
11433         this.parent.error(err);
11434     };
11435     SubscriptionDelaySubscriber.prototype._complete = function () {
11436         this.unsubscribe();
11437         this.subscribeToSource();
11438     };
11439     SubscriptionDelaySubscriber.prototype.subscribeToSource = function () {
11440         if (!this.sourceSubscribed) {
11441             this.sourceSubscribed = true;
11442             this.unsubscribe();
11443             this.source.subscribe(this.parent);
11444         }
11445     };
11446     return SubscriptionDelaySubscriber;
11447 }(Subscriber_1.Subscriber));
11448
11449 },{"../Observable":32,"../OuterSubscriber":34,"../Subscriber":39,"../util/subscribeToResult":222}],93:[function(require,module,exports){
11450 "use strict";
11451 var __extends = (this && this.__extends) || (function () {
11452     var extendStatics = function (d, b) {
11453         extendStatics = Object.setPrototypeOf ||
11454             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11455             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11456         return extendStatics(d, b);
11457     }
11458     return function (d, b) {
11459         extendStatics(d, b);
11460         function __() { this.constructor = d; }
11461         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11462     };
11463 })();
11464 Object.defineProperty(exports, "__esModule", { value: true });
11465 var Subscriber_1 = require("../Subscriber");
11466 function dematerialize() {
11467     return function dematerializeOperatorFunction(source) {
11468         return source.lift(new DeMaterializeOperator());
11469     };
11470 }
11471 exports.dematerialize = dematerialize;
11472 var DeMaterializeOperator = (function () {
11473     function DeMaterializeOperator() {
11474     }
11475     DeMaterializeOperator.prototype.call = function (subscriber, source) {
11476         return source.subscribe(new DeMaterializeSubscriber(subscriber));
11477     };
11478     return DeMaterializeOperator;
11479 }());
11480 var DeMaterializeSubscriber = (function (_super) {
11481     __extends(DeMaterializeSubscriber, _super);
11482     function DeMaterializeSubscriber(destination) {
11483         return _super.call(this, destination) || this;
11484     }
11485     DeMaterializeSubscriber.prototype._next = function (value) {
11486         value.observe(this.destination);
11487     };
11488     return DeMaterializeSubscriber;
11489 }(Subscriber_1.Subscriber));
11490
11491 },{"../Subscriber":39}],94:[function(require,module,exports){
11492 "use strict";
11493 var __extends = (this && this.__extends) || (function () {
11494     var extendStatics = function (d, b) {
11495         extendStatics = Object.setPrototypeOf ||
11496             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11497             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11498         return extendStatics(d, b);
11499     }
11500     return function (d, b) {
11501         extendStatics(d, b);
11502         function __() { this.constructor = d; }
11503         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11504     };
11505 })();
11506 Object.defineProperty(exports, "__esModule", { value: true });
11507 var OuterSubscriber_1 = require("../OuterSubscriber");
11508 var subscribeToResult_1 = require("../util/subscribeToResult");
11509 function distinct(keySelector, flushes) {
11510     return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); };
11511 }
11512 exports.distinct = distinct;
11513 var DistinctOperator = (function () {
11514     function DistinctOperator(keySelector, flushes) {
11515         this.keySelector = keySelector;
11516         this.flushes = flushes;
11517     }
11518     DistinctOperator.prototype.call = function (subscriber, source) {
11519         return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
11520     };
11521     return DistinctOperator;
11522 }());
11523 var DistinctSubscriber = (function (_super) {
11524     __extends(DistinctSubscriber, _super);
11525     function DistinctSubscriber(destination, keySelector, flushes) {
11526         var _this = _super.call(this, destination) || this;
11527         _this.keySelector = keySelector;
11528         _this.values = new Set();
11529         if (flushes) {
11530             _this.add(subscribeToResult_1.subscribeToResult(_this, flushes));
11531         }
11532         return _this;
11533     }
11534     DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11535         this.values.clear();
11536     };
11537     DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
11538         this._error(error);
11539     };
11540     DistinctSubscriber.prototype._next = function (value) {
11541         if (this.keySelector) {
11542             this._useKeySelector(value);
11543         }
11544         else {
11545             this._finalizeNext(value, value);
11546         }
11547     };
11548     DistinctSubscriber.prototype._useKeySelector = function (value) {
11549         var key;
11550         var destination = this.destination;
11551         try {
11552             key = this.keySelector(value);
11553         }
11554         catch (err) {
11555             destination.error(err);
11556             return;
11557         }
11558         this._finalizeNext(key, value);
11559     };
11560     DistinctSubscriber.prototype._finalizeNext = function (key, value) {
11561         var values = this.values;
11562         if (!values.has(key)) {
11563             values.add(key);
11564             this.destination.next(value);
11565         }
11566     };
11567     return DistinctSubscriber;
11568 }(OuterSubscriber_1.OuterSubscriber));
11569 exports.DistinctSubscriber = DistinctSubscriber;
11570
11571 },{"../OuterSubscriber":34,"../util/subscribeToResult":222}],95:[function(require,module,exports){
11572 "use strict";
11573 var __extends = (this && this.__extends) || (function () {
11574     var extendStatics = function (d, b) {
11575         extendStatics = Object.setPrototypeOf ||
11576             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11577             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11578         return extendStatics(d, b);
11579     }
11580     return function (d, b) {
11581         extendStatics(d, b);
11582         function __() { this.constructor = d; }
11583         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11584     };
11585 })();
11586 Object.defineProperty(exports, "__esModule", { value: true });
11587 var Subscriber_1 = require("../Subscriber");
11588 var tryCatch_1 = require("../util/tryCatch");
11589 var errorObject_1 = require("../util/errorObject");
11590 function distinctUntilChanged(compare, keySelector) {
11591     return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
11592 }
11593 exports.distinctUntilChanged = distinctUntilChanged;
11594 var DistinctUntilChangedOperator = (function () {
11595     function DistinctUntilChangedOperator(compare, keySelector) {
11596         this.compare = compare;
11597         this.keySelector = keySelector;
11598     }
11599     DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
11600         return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
11601     };
11602     return DistinctUntilChangedOperator;
11603 }());
11604 var DistinctUntilChangedSubscriber = (function (_super) {
11605     __extends(DistinctUntilChangedSubscriber, _super);
11606     function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
11607         var _this = _super.call(this, destination) || this;
11608         _this.keySelector = keySelector;
11609         _this.hasKey = false;
11610         if (typeof compare === 'function') {
11611             _this.compare = compare;
11612         }
11613         return _this;
11614     }
11615     DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
11616         return x === y;
11617     };
11618     DistinctUntilChangedSubscriber.prototype._next = function (value) {
11619         var keySelector = this.keySelector;
11620         var key = value;
11621         if (keySelector) {
11622             key = tryCatch_1.tryCatch(this.keySelector)(value);
11623             if (key === errorObject_1.errorObject) {
11624                 return this.destination.error(errorObject_1.errorObject.e);
11625             }
11626         }
11627         var result = false;
11628         if (this.hasKey) {
11629             result = tryCatch_1.tryCatch(this.compare)(this.key, key);
11630             if (result === errorObject_1.errorObject) {
11631                 return this.destination.error(errorObject_1.errorObject.e);
11632             }
11633         }
11634         else {
11635             this.hasKey = true;
11636         }
11637         if (Boolean(result) === false) {
11638             this.key = key;
11639             this.destination.next(value);
11640         }
11641     };
11642     return DistinctUntilChangedSubscriber;
11643 }(Subscriber_1.Subscriber));
11644
11645 },{"../Subscriber":39,"../util/errorObject":200,"../util/tryCatch":224}],96:[function(require,module,exports){
11646 "use strict";
11647 Object.defineProperty(exports, "__esModule", { value: true });
11648 var distinctUntilChanged_1 = require("./distinctUntilChanged");
11649 function distinctUntilKeyChanged(key, compare) {
11650     return distinctUntilChanged_1.distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; });
11651 }
11652 exports.distinctUntilKeyChanged = distinctUntilKeyChanged;
11653
11654 },{"./distinctUntilChanged":95}],97:[function(require,module,exports){
11655 "use strict";
11656 Object.defineProperty(exports, "__esModule", { value: true });
11657 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
11658 var filter_1 = require("./filter");
11659 var throwIfEmpty_1 = require("./throwIfEmpty");
11660 var defaultIfEmpty_1 = require("./defaultIfEmpty");
11661 var take_1 = require("./take");
11662 function elementAt(index, defaultValue) {
11663     if (index < 0) {
11664         throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError();
11665     }
11666     var hasDefaultValue = arguments.length >= 2;
11667     return function (source) { return source.pipe(filter_1.filter(function (v, i) { return i === index; }), take_1.take(1), hasDefaultValue
11668         ? defaultIfEmpty_1.defaultIfEmpty(defaultValue)
11669         : throwIfEmpty_1.throwIfEmpty(function () { return new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError(); })); };
11670 }
11671 exports.elementAt = elementAt;
11672
11673 },{"../util/ArgumentOutOfRangeError":193,"./defaultIfEmpty":90,"./filter":103,"./take":155,"./throwIfEmpty":162}],98:[function(require,module,exports){
11674 "use strict";
11675 Object.defineProperty(exports, "__esModule", { value: true });
11676 var fromArray_1 = require("../observable/fromArray");
11677 var scalar_1 = require("../observable/scalar");
11678 var empty_1 = require("../observable/empty");
11679 var concat_1 = require("../observable/concat");
11680 var isScheduler_1 = require("../util/isScheduler");
11681 function endWith() {
11682     var array = [];
11683     for (var _i = 0; _i < arguments.length; _i++) {
11684         array[_i] = arguments[_i];
11685     }
11686     return function (source) {
11687         var scheduler = array[array.length - 1];
11688         if (isScheduler_1.isScheduler(scheduler)) {
11689             array.pop();
11690         }
11691         else {
11692             scheduler = null;
11693         }
11694         var len = array.length;
11695         if (len === 1 && !scheduler) {
11696             return concat_1.concat(source, scalar_1.scalar(array[0]));
11697         }
11698         else if (len > 0) {
11699             return concat_1.concat(source, fromArray_1.fromArray(array, scheduler));
11700         }
11701         else {
11702             return concat_1.concat(source, empty_1.empty(scheduler));
11703         }
11704     };
11705 }
11706 exports.endWith = endWith;
11707
11708 },{"../observable/concat":47,"../observable/empty":49,"../observable/fromArray":52,"../observable/scalar":68,"../util/isScheduler":213}],99:[function(require,module,exports){
11709 "use strict";
11710 var __extends = (this && this.__extends) || (function () {
11711     var extendStatics = function (d, b) {
11712         extendStatics = Object.setPrototypeOf ||
11713             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11714             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11715         return extendStatics(d, b);
11716     }
11717     return function (d, b) {
11718         extendStatics(d, b);
11719         function __() { this.constructor = d; }
11720         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11721     };
11722 })();
11723 Object.defineProperty(exports, "__esModule", { value: true });
11724 var Subscriber_1 = require("../Subscriber");
11725 function every(predicate, thisArg) {
11726     return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); };
11727 }
11728 exports.every = every;
11729 var EveryOperator = (function () {
11730     function EveryOperator(predicate, thisArg, source) {
11731         this.predicate = predicate;
11732         this.thisArg = thisArg;
11733         this.source = source;
11734     }
11735     EveryOperator.prototype.call = function (observer, source) {
11736         return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
11737     };
11738     return EveryOperator;
11739 }());
11740 var EverySubscriber = (function (_super) {
11741     __extends(EverySubscriber, _super);
11742     function EverySubscriber(destination, predicate, thisArg, source) {
11743         var _this = _super.call(this, destination) || this;
11744         _this.predicate = predicate;
11745         _this.thisArg = thisArg;
11746         _this.source = source;
11747         _this.index = 0;
11748         _this.thisArg = thisArg || _this;
11749         return _this;
11750     }
11751     EverySubscriber.prototype.notifyComplete = function (everyValueMatch) {
11752         this.destination.next(everyValueMatch);
11753         this.destination.complete();
11754     };
11755     EverySubscriber.prototype._next = function (value) {
11756         var result = false;
11757         try {
11758             result = this.predicate.call(this.thisArg, value, this.index++, this.source);
11759         }
11760         catch (err) {
11761             this.destination.error(err);
11762             return;
11763         }
11764         if (!result) {
11765             this.notifyComplete(false);
11766         }
11767     };
11768     EverySubscriber.prototype._complete = function () {
11769         this.notifyComplete(true);
11770     };
11771     return EverySubscriber;
11772 }(Subscriber_1.Subscriber));
11773
11774 },{"../Subscriber":39}],100:[function(require,module,exports){
11775 "use strict";
11776 var __extends = (this && this.__extends) || (function () {
11777     var extendStatics = function (d, b) {
11778         extendStatics = Object.setPrototypeOf ||
11779             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11780             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11781         return extendStatics(d, b);
11782     }
11783     return function (d, b) {
11784         extendStatics(d, b);
11785         function __() { this.constructor = d; }
11786         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11787     };
11788 })();
11789 Object.defineProperty(exports, "__esModule", { value: true });
11790 var OuterSubscriber_1 = require("../OuterSubscriber");
11791 var subscribeToResult_1 = require("../util/subscribeToResult");
11792 function exhaust() {
11793     return function (source) { return source.lift(new SwitchFirstOperator()); };
11794 }
11795 exports.exhaust = exhaust;
11796 var SwitchFirstOperator = (function () {
11797     function SwitchFirstOperator() {
11798     }
11799     SwitchFirstOperator.prototype.call = function (subscriber, source) {
11800         return source.subscribe(new SwitchFirstSubscriber(subscriber));
11801     };
11802     return SwitchFirstOperator;
11803 }());
11804 var SwitchFirstSubscriber = (function (_super) {
11805     __extends(SwitchFirstSubscriber, _super);
11806     function SwitchFirstSubscriber(destination) {
11807         var _this = _super.call(this, destination) || this;
11808         _this.hasCompleted = false;
11809         _this.hasSubscription = false;
11810         return _this;
11811     }
11812     SwitchFirstSubscriber.prototype._next = function (value) {
11813         if (!this.hasSubscription) {
11814             this.hasSubscription = true;
11815             this.add(subscribeToResult_1.subscribeToResult(this, value));
11816         }
11817     };
11818     SwitchFirstSubscriber.prototype._complete = function () {
11819         this.hasCompleted = true;
11820         if (!this.hasSubscription) {
11821             this.destination.complete();
11822         }
11823     };
11824     SwitchFirstSubscriber.prototype.notifyComplete = function (innerSub) {
11825         this.remove(innerSub);
11826         this.hasSubscription = false;
11827         if (this.hasCompleted) {
11828             this.destination.complete();
11829         }
11830     };
11831     return SwitchFirstSubscriber;
11832 }(OuterSubscriber_1.OuterSubscriber));
11833
11834 },{"../OuterSubscriber":34,"../util/subscribeToResult":222}],101:[function(require,module,exports){
11835 "use strict";
11836 var __extends = (this && this.__extends) || (function () {
11837     var extendStatics = function (d, b) {
11838         extendStatics = Object.setPrototypeOf ||
11839             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11840             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11841         return extendStatics(d, b);
11842     }
11843     return function (d, b) {
11844         extendStatics(d, b);
11845         function __() { this.constructor = d; }
11846         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11847     };
11848 })();
11849 Object.defineProperty(exports, "__esModule", { value: true });
11850 var OuterSubscriber_1 = require("../OuterSubscriber");
11851 var InnerSubscriber_1 = require("../InnerSubscriber");
11852 var subscribeToResult_1 = require("../util/subscribeToResult");
11853 var map_1 = require("./map");
11854 var from_1 = require("../observable/from");
11855 function exhaustMap(project, resultSelector) {
11856     if (resultSelector) {
11857         return function (source) { return source.pipe(exhaustMap(function (a, i) { return from_1.from(project(a, i)).pipe(map_1.map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };
11858     }
11859     return function (source) {
11860         return source.lift(new ExhauseMapOperator(project));
11861     };
11862 }
11863 exports.exhaustMap = exhaustMap;
11864 var ExhauseMapOperator = (function () {
11865     function ExhauseMapOperator(project) {
11866         this.project = project;
11867     }
11868     ExhauseMapOperator.prototype.call = function (subscriber, source) {
11869         return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));
11870     };
11871     return ExhauseMapOperator;
11872 }());
11873 var ExhaustMapSubscriber = (function (_super) {
11874     __extends(ExhaustMapSubscriber, _super);
11875     function ExhaustMapSubscriber(destination, project) {
11876         var _this = _super.call(this, destination) || this;
11877         _this.project = project;
11878         _this.hasSubscription = false;
11879         _this.hasCompleted = false;
11880         _this.index = 0;
11881         return _this;
11882     }
11883     ExhaustMapSubscriber.prototype._next = function (value) {
11884         if (!this.hasSubscription) {
11885             this.tryNext(value);
11886         }
11887     };
11888     ExhaustMapSubscriber.prototype.tryNext = function (value) {
11889         var result;
11890         var index = this.index++;
11891         try {
11892             result = this.project(value, index);
11893         }
11894         catch (err) {
11895             this.destination.error(err);
11896             return;
11897         }
11898         this.hasSubscription = true;
11899         this._innerSub(result, value, index);
11900     };
11901     ExhaustMapSubscriber.prototype._innerSub = function (result, value, index) {
11902         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
11903         var destination = this.destination;
11904         destination.add(innerSubscriber);
11905         subscribeToResult_1.subscribeToResult(this, result, value, index, innerSubscriber);
11906     };
11907     ExhaustMapSubscriber.prototype._complete = function () {
11908         this.hasCompleted = true;
11909         if (!this.hasSubscription) {
11910             this.destination.complete();
11911         }
11912         this.unsubscribe();
11913     };
11914     ExhaustMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11915         this.destination.next(innerValue);
11916     };
11917     ExhaustMapSubscriber.prototype.notifyError = function (err) {
11918         this.destination.error(err);
11919     };
11920     ExhaustMapSubscriber.prototype.notifyComplete = function (innerSub) {
11921         var destination = this.destination;
11922         destination.remove(innerSub);
11923         this.hasSubscription = false;
11924         if (this.hasCompleted) {
11925             this.destination.complete();
11926         }
11927     };
11928     return ExhaustMapSubscriber;
11929 }(OuterSubscriber_1.OuterSubscriber));
11930
11931 },{"../InnerSubscriber":30,"../OuterSubscriber":34,"../observable/from":51,"../util/subscribeToResult":222,"./map":112}],102:[function(require,module,exports){
11932 "use strict";
11933 var __extends = (this && this.__extends) || (function () {
11934     var extendStatics = function (d, b) {
11935         extendStatics = Object.setPrototypeOf ||
11936             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11937             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11938         return extendStatics(d, b);
11939     }
11940     return function (d, b) {
11941         extendStatics(d, b);
11942         function __() { this.constructor = d; }
11943         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11944     };
11945 })();
11946 Object.defineProperty(exports, "__esModule", { value: true });
11947 var tryCatch_1 = require("../util/tryCatch");
11948 var errorObject_1 = require("../util/errorObject");
11949 var OuterSubscriber_1 = require("../OuterSubscriber");
11950 var subscribeToResult_1 = require("../util/subscribeToResult");
11951 function expand(project, concurrent, scheduler) {
11952     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
11953     if (scheduler === void 0) { scheduler = undefined; }
11954     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
11955     return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); };
11956 }
11957 exports.expand = expand;
11958 var ExpandOperator = (function () {
11959     function ExpandOperator(project, concurrent, scheduler) {
11960         this.project = project;
11961         this.concurrent = concurrent;
11962         this.scheduler = scheduler;
11963     }
11964     ExpandOperator.prototype.call = function (subscriber, source) {
11965         return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
11966     };
11967     return ExpandOperator;
11968 }());
11969 exports.ExpandOperator = ExpandOperator;
11970 var ExpandSubscriber = (function (_super) {
11971     __extends(ExpandSubscriber, _super);
11972     function ExpandSubscriber(destination, project, concurrent, scheduler) {
11973         var _this = _super.call(this, destination) || this;
11974         _this.project = project;
11975         _this.concurrent = concurrent;
11976         _this.scheduler = scheduler;
11977         _this.index = 0;
11978         _this.active = 0;
11979         _this.hasCompleted = false;
11980         if (concurrent < Number.POSITIVE_INFINITY) {
11981             _this.buffer = [];
11982         }
11983         return _this;
11984     }
11985     ExpandSubscriber.dispatch = function (arg) {
11986         var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
11987         subscriber.subscribeToProjection(result, value, index);
11988     };
11989     ExpandSubscriber.prototype._next = function (value) {
11990         var destination = this.destination;
11991         if (destination.closed) {
11992             this._complete();
11993             return;
11994         }
11995         var index = this.index++;
11996         if (this.active < this.concurrent) {
11997             destination.next(value);
11998             var result = tryCatch_1.tryCatch(this.project)(value, index);
11999             if (result === errorObject_1.errorObject) {
12000                 destination.error(errorObject_1.errorObject.e);
12001             }
12002             else if (!this.scheduler) {
12003                 this.subscribeToProjection(result, value, index);
12004             }
12005             else {
12006                 var state = { subscriber: this, result: result, value: value, index: index };
12007                 var destination_1 = this.destination;
12008                 destination_1.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
12009             }
12010         }
12011         else {
12012             this.buffer.push(value);
12013         }
12014     };
12015     ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
12016         this.active++;
12017         var destination = this.destination;
12018         destination.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
12019     };
12020     ExpandSubscriber.prototype._complete = function () {
12021         this.hasCompleted = true;
12022         if (this.hasCompleted && this.active === 0) {
12023             this.destination.complete();
12024         }
12025         this.unsubscribe();
12026     };
12027     ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12028         this._next(innerValue);
12029     };
12030     ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
12031         var buffer = this.buffer;
12032         var destination = this.destination;
12033         destination.remove(innerSub);
12034         this.active--;
12035         if (buffer && buffer.length > 0) {
12036             this._next(buffer.shift());
12037         }
12038         if (this.hasCompleted && this.active === 0) {
12039             this.destination.complete();
12040         }
12041     };
12042     return ExpandSubscriber;
12043 }(OuterSubscriber_1.OuterSubscriber));
12044 exports.ExpandSubscriber = ExpandSubscriber;
12045
12046 },{"../OuterSubscriber":34,"../util/errorObject":200,"../util/subscribeToResult":222,"../util/tryCatch":224}],103:[function(require,module,exports){
12047 "use strict";
12048 var __extends = (this && this.__extends) || (function () {
12049     var extendStatics = function (d, b) {
12050         extendStatics = Object.setPrototypeOf ||
12051             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12052             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12053         return extendStatics(d, b);
12054     }
12055     return function (d, b) {
12056         extendStatics(d, b);
12057         function __() { this.constructor = d; }
12058         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12059     };
12060 })();
12061 Object.defineProperty(exports, "__esModule", { value: true });
12062 var Subscriber_1 = require("../Subscriber");
12063 function filter(predicate, thisArg) {
12064     return function filterOperatorFunction(source) {
12065         return source.lift(new FilterOperator(predicate, thisArg));
12066     };
12067 }
12068 exports.filter = filter;
12069 var FilterOperator = (function () {
12070     function FilterOperator(predicate, thisArg) {
12071         this.predicate = predicate;
12072         this.thisArg = thisArg;
12073     }
12074     FilterOperator.prototype.call = function (subscriber, source) {
12075         return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
12076     };
12077     return FilterOperator;
12078 }());
12079 var FilterSubscriber = (function (_super) {
12080     __extends(FilterSubscriber, _super);
12081     function FilterSubscriber(destination, predicate, thisArg) {
12082         var _this = _super.call(this, destination) || this;
12083         _this.predicate = predicate;
12084         _this.thisArg = thisArg;
12085         _this.count = 0;
12086         return _this;
12087     }
12088     FilterSubscriber.prototype._next = function (value) {
12089         var result;
12090         try {
12091             result = this.predicate.call(this.thisArg, value, this.count++);
12092         }
12093         catch (err) {
12094             this.destination.error(err);
12095             return;
12096         }
12097         if (result) {
12098             this.destination.next(value);
12099         }
12100     };
12101     return FilterSubscriber;
12102 }(Subscriber_1.Subscriber));
12103
12104 },{"../Subscriber":39}],104:[function(require,module,exports){
12105 "use strict";
12106 var __extends = (this && this.__extends) || (function () {
12107     var extendStatics = function (d, b) {
12108         extendStatics = Object.setPrototypeOf ||
12109             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12110             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12111         return extendStatics(d, b);
12112     }
12113     return function (d, b) {
12114         extendStatics(d, b);
12115         function __() { this.constructor = d; }
12116         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12117     };
12118 })();
12119 Object.defineProperty(exports, "__esModule", { value: true });
12120 var Subscriber_1 = require("../Subscriber");
12121 var Subscription_1 = require("../Subscription");
12122 function finalize(callback) {
12123     return function (source) { return source.lift(new FinallyOperator(callback)); };
12124 }
12125 exports.finalize = finalize;
12126 var FinallyOperator = (function () {
12127     function FinallyOperator(callback) {
12128         this.callback = callback;
12129     }
12130     FinallyOperator.prototype.call = function (subscriber, source) {
12131         return source.subscribe(new FinallySubscriber(subscriber, this.callback));
12132     };
12133     return FinallyOperator;
12134 }());
12135 var FinallySubscriber = (function (_super) {
12136     __extends(FinallySubscriber, _super);
12137     function FinallySubscriber(destination, callback) {
12138         var _this = _super.call(this, destination) || this;
12139         _this.add(new Subscription_1.Subscription(callback));
12140         return _this;
12141     }
12142     return FinallySubscriber;
12143 }(Subscriber_1.Subscriber));
12144
12145 },{"../Subscriber":39,"../Subscription":40}],105:[function(require,module,exports){
12146 "use strict";
12147 var __extends = (this && this.__extends) || (function () {
12148     var extendStatics = function (d, b) {
12149         extendStatics = Object.setPrototypeOf ||
12150             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12151             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12152         return extendStatics(d, b);
12153     }
12154     return function (d, b) {
12155         extendStatics(d, b);
12156         function __() { this.constructor = d; }
12157         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12158     };
12159 })();
12160 Object.defineProperty(exports, "__esModule", { value: true });
12161 var Subscriber_1 = require("../Subscriber");
12162 function find(predicate, thisArg) {
12163     if (typeof predicate !== 'function') {
12164         throw new TypeError('predicate is not a function');
12165     }
12166     return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); };
12167 }
12168 exports.find = find;
12169 var FindValueOperator = (function () {
12170     function FindValueOperator(predicate, source, yieldIndex, thisArg) {
12171         this.predicate = predicate;
12172         this.source = source;
12173         this.yieldIndex = yieldIndex;
12174         this.thisArg = thisArg;
12175     }
12176     FindValueOperator.prototype.call = function (observer, source) {
12177         return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
12178     };
12179     return FindValueOperator;
12180 }());
12181 exports.FindValueOperator = FindValueOperator;
12182 var FindValueSubscriber = (function (_super) {
12183     __extends(FindValueSubscriber, _super);
12184     function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) {
12185         var _this = _super.call(this, destination) || this;
12186         _this.predicate = predicate;
12187         _this.source = source;
12188         _this.yieldIndex = yieldIndex;
12189         _this.thisArg = thisArg;
12190         _this.index = 0;
12191         return _this;
12192     }
12193     FindValueSubscriber.prototype.notifyComplete = function (value) {
12194         var destination = this.destination;
12195         destination.next(value);
12196         destination.complete();
12197         this.unsubscribe();
12198     };
12199     FindValueSubscriber.prototype._next = function (value) {
12200         var _a = this, predicate = _a.predicate, thisArg = _a.thisArg;
12201         var index = this.index++;
12202         try {
12203             var result = predicate.call(thisArg || this, value, index, this.source);
12204             if (result) {
12205                 this.notifyComplete(this.yieldIndex ? index : value);
12206             }
12207         }
12208         catch (err) {
12209             this.destination.error(err);
12210         }
12211     };
12212     FindValueSubscriber.prototype._complete = function () {
12213         this.notifyComplete(this.yieldIndex ? -1 : undefined);
12214     };
12215     return FindValueSubscriber;
12216 }(Subscriber_1.Subscriber));
12217 exports.FindValueSubscriber = FindValueSubscriber;
12218
12219 },{"../Subscriber":39}],106:[function(require,module,exports){
12220 "use strict";
12221 Object.defineProperty(exports, "__esModule", { value: true });
12222 var find_1 = require("../operators/find");
12223 function findIndex(predicate, thisArg) {
12224     return function (source) { return source.lift(new find_1.FindValueOperator(predicate, source, true, thisArg)); };
12225 }
12226 exports.findIndex = findIndex;
12227
12228 },{"../operators/find":105}],107:[function(require,module,exports){
12229 "use strict";
12230 Object.defineProperty(exports, "__esModule", { value: true });
12231 var EmptyError_1 = require("../util/EmptyError");
12232 var filter_1 = require("./filter");
12233 var take_1 = require("./take");
12234 var defaultIfEmpty_1 = require("./defaultIfEmpty");
12235 var throwIfEmpty_1 = require("./throwIfEmpty");
12236 var identity_1 = require("../util/identity");
12237 function first(predicate, defaultValue) {
12238     var hasDefaultValue = arguments.length >= 2;
12239     return function (source) { return source.pipe(predicate ? filter_1.filter(function (v, i) { return predicate(v, i, source); }) : identity_1.identity, take_1.take(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new EmptyError_1.EmptyError(); })); };
12240 }
12241 exports.first = first;
12242
12243 },{"../util/EmptyError":194,"../util/identity":202,"./defaultIfEmpty":90,"./filter":103,"./take":155,"./throwIfEmpty":162}],108:[function(require,module,exports){
12244 "use strict";
12245 var __extends = (this && this.__extends) || (function () {
12246     var extendStatics = function (d, b) {
12247         extendStatics = Object.setPrototypeOf ||
12248             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12249             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12250         return extendStatics(d, b);
12251     }
12252     return function (d, b) {
12253         extendStatics(d, b);
12254         function __() { this.constructor = d; }
12255         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12256     };
12257 })();
12258 Object.defineProperty(exports, "__esModule", { value: true });
12259 var Subscriber_1 = require("../Subscriber");
12260 var Subscription_1 = require("../Subscription");
12261 var Observable_1 = require("../Observable");
12262 var Subject_1 = require("../Subject");
12263 function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) {
12264     return function (source) {
12265         return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
12266     };
12267 }
12268 exports.groupBy = groupBy;
12269 var GroupByOperator = (function () {
12270     function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) {
12271         this.keySelector = keySelector;
12272         this.elementSelector = elementSelector;
12273         this.durationSelector = durationSelector;
12274         this.subjectSelector = subjectSelector;
12275     }
12276     GroupByOperator.prototype.call = function (subscriber, source) {
12277         return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector));
12278     };
12279     return GroupByOperator;
12280 }());
12281 var GroupBySubscriber = (function (_super) {
12282     __extends(GroupBySubscriber, _super);
12283     function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) {
12284         var _this = _super.call(this, destination) || this;
12285         _this.keySelector = keySelector;
12286         _this.elementSelector = elementSelector;
12287         _this.durationSelector = durationSelector;
12288         _this.subjectSelector = subjectSelector;
12289         _this.groups = null;
12290         _this.attemptedToUnsubscribe = false;
12291         _this.count = 0;
12292         return _this;
12293     }
12294     GroupBySubscriber.prototype._next = function (value) {
12295         var key;
12296         try {
12297             key = this.keySelector(value);
12298         }
12299         catch (err) {
12300             this.error(err);
12301             return;
12302         }
12303         this._group(value, key);
12304     };
12305     GroupBySubscriber.prototype._group = function (value, key) {
12306         var groups = this.groups;
12307         if (!groups) {
12308             groups = this.groups = new Map();
12309         }
12310         var group = groups.get(key);
12311         var element;
12312         if (this.elementSelector) {
12313             try {
12314                 element = this.elementSelector(value);
12315             }
12316             catch (err) {
12317                 this.error(err);
12318             }
12319         }
12320         else {
12321             element = value;
12322         }
12323         if (!group) {
12324             group = (this.subjectSelector ? this.subjectSelector() : new Subject_1.Subject());
12325             groups.set(key, group);
12326             var groupedObservable = new GroupedObservable(key, group, this);
12327             this.destination.next(groupedObservable);
12328             if (this.durationSelector) {
12329                 var duration = void 0;
12330                 try {
12331                     duration = this.durationSelector(new GroupedObservable(key, group));
12332                 }
12333                 catch (err) {
12334                     this.error(err);
12335                     return;
12336                 }
12337                 this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));
12338             }
12339         }
12340         if (!group.closed) {
12341             group.next(element);
12342         }
12343     };
12344     GroupBySubscriber.prototype._error = function (err) {
12345         var groups = this.groups;
12346         if (groups) {
12347             groups.forEach(function (group, key) {
12348                 group.error(err);
12349             });
12350             groups.clear();
12351         }
12352         this.destination.error(err);
12353     };
12354     GroupBySubscriber.prototype._complete = function () {
12355         var groups = this.groups;
12356         if (groups) {
12357             groups.forEach(function (group, key) {
12358                 group.complete();
12359             });
12360             groups.clear();
12361         }
12362         this.destination.complete();
12363     };
12364     GroupBySubscriber.prototype.removeGroup = function (key) {
12365         this.groups.delete(key);
12366     };
12367     GroupBySubscriber.prototype.unsubscribe = function () {
12368         if (!this.closed) {
12369             this.attemptedToUnsubscribe = true;
12370             if (this.count === 0) {
12371                 _super.prototype.unsubscribe.call(this);
12372             }
12373         }
12374     };
12375     return GroupBySubscriber;
12376 }(Subscriber_1.Subscriber));
12377 var GroupDurationSubscriber = (function (_super) {
12378     __extends(GroupDurationSubscriber, _super);
12379     function GroupDurationSubscriber(key, group, parent) {
12380         var _this = _super.call(this, group) || this;
12381         _this.key = key;
12382         _this.group = group;
12383         _this.parent = parent;
12384         return _this;
12385     }
12386     GroupDurationSubscriber.prototype._next = function (value) {
12387         this.complete();
12388     };
12389     GroupDurationSubscriber.prototype._unsubscribe = function () {
12390         var _a = this, parent = _a.parent, key = _a.key;
12391         this.key = this.parent = null;
12392         if (parent) {
12393             parent.removeGroup(key);
12394         }
12395     };
12396     return GroupDurationSubscriber;
12397 }(Subscriber_1.Subscriber));
12398 var GroupedObservable = (function (_super) {
12399     __extends(GroupedObservable, _super);
12400     function GroupedObservable(key, groupSubject, refCountSubscription) {
12401         var _this = _super.call(this) || this;
12402         _this.key = key;
12403         _this.groupSubject = groupSubject;
12404         _this.refCountSubscription = refCountSubscription;
12405         return _this;
12406     }
12407     GroupedObservable.prototype._subscribe = function (subscriber) {
12408         var subscription = new Subscription_1.Subscription();
12409         var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject;
12410         if (refCountSubscription && !refCountSubscription.closed) {
12411             subscription.add(new InnerRefCountSubscription(refCountSubscription));
12412         }
12413         subscription.add(groupSubject.subscribe(subscriber));
12414         return subscription;
12415     };
12416     return GroupedObservable;
12417 }(Observable_1.Observable));
12418 exports.GroupedObservable = GroupedObservable;
12419 var InnerRefCountSubscription = (function (_super) {
12420     __extends(InnerRefCountSubscription, _super);
12421     function InnerRefCountSubscription(parent) {
12422         var _this = _super.call(this) || this;
12423         _this.parent = parent;
12424         parent.count++;
12425         return _this;
12426     }
12427     InnerRefCountSubscription.prototype.unsubscribe = function () {
12428         var parent = this.parent;
12429         if (!parent.closed && !this.closed) {
12430             _super.prototype.unsubscribe.call(this);
12431             parent.count -= 1;
12432             if (parent.count === 0 && parent.attemptedToUnsubscribe) {
12433                 parent.unsubscribe();
12434             }
12435         }
12436     };
12437     return InnerRefCountSubscription;
12438 }(Subscription_1.Subscription));
12439
12440 },{"../Observable":32,"../Subject":37,"../Subscriber":39,"../Subscription":40}],109:[function(require,module,exports){
12441 "use strict";
12442 var __extends = (this && this.__extends) || (function () {
12443     var extendStatics = function (d, b) {
12444         extendStatics = Object.setPrototypeOf ||
12445             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12446             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12447         return extendStatics(d, b);
12448     }
12449     return function (d, b) {
12450         extendStatics(d, b);
12451         function __() { this.constructor = d; }
12452         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12453     };
12454 })();
12455 Object.defineProperty(exports, "__esModule", { value: true });
12456 var Subscriber_1 = require("../Subscriber");
12457 function ignoreElements() {
12458     return function ignoreElementsOperatorFunction(source) {
12459         return source.lift(new IgnoreElementsOperator());
12460     };
12461 }
12462 exports.ignoreElements = ignoreElements;
12463 var IgnoreElementsOperator = (function () {
12464     function IgnoreElementsOperator() {
12465     }
12466     IgnoreElementsOperator.prototype.call = function (subscriber, source) {
12467         return source.subscribe(new IgnoreElementsSubscriber(subscriber));
12468     };
12469     return IgnoreElementsOperator;
12470 }());
12471 var IgnoreElementsSubscriber = (function (_super) {
12472     __extends(IgnoreElementsSubscriber, _super);
12473     function IgnoreElementsSubscriber() {
12474         return _super !== null && _super.apply(this, arguments) || this;
12475     }
12476     IgnoreElementsSubscriber.prototype._next = function (unused) {
12477     };
12478     return IgnoreElementsSubscriber;
12479 }(Subscriber_1.Subscriber));
12480
12481 },{"../Subscriber":39}],110:[function(require,module,exports){
12482 "use strict";
12483 var __extends = (this && this.__extends) || (function () {
12484     var extendStatics = function (d, b) {
12485         extendStatics = Object.setPrototypeOf ||
12486             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12487             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12488         return extendStatics(d, b);
12489     }
12490     return function (d, b) {
12491         extendStatics(d, b);
12492         function __() { this.constructor = d; }
12493         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12494     };
12495 })();
12496 Object.defineProperty(exports, "__esModule", { value: true });
12497 var Subscriber_1 = require("../Subscriber");
12498 function isEmpty() {
12499     return function (source) { return source.lift(new IsEmptyOperator()); };
12500 }
12501 exports.isEmpty = isEmpty;
12502 var IsEmptyOperator = (function () {
12503     function IsEmptyOperator() {
12504     }
12505     IsEmptyOperator.prototype.call = function (observer, source) {
12506         return source.subscribe(new IsEmptySubscriber(observer));
12507     };
12508     return IsEmptyOperator;
12509 }());
12510 var IsEmptySubscriber = (function (_super) {
12511     __extends(IsEmptySubscriber, _super);
12512     function IsEmptySubscriber(destination) {
12513         return _super.call(this, destination) || this;
12514     }
12515     IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) {
12516         var destination = this.destination;
12517         destination.next(isEmpty);
12518         destination.complete();
12519     };
12520     IsEmptySubscriber.prototype._next = function (value) {
12521         this.notifyComplete(false);
12522     };
12523     IsEmptySubscriber.prototype._complete = function () {
12524         this.notifyComplete(true);
12525     };
12526     return IsEmptySubscriber;
12527 }(Subscriber_1.Subscriber));
12528
12529 },{"../Subscriber":39}],111:[function(require,module,exports){
12530 "use strict";
12531 Object.defineProperty(exports, "__esModule", { value: true });
12532 var EmptyError_1 = require("../util/EmptyError");
12533 var filter_1 = require("./filter");
12534 var takeLast_1 = require("./takeLast");
12535 var throwIfEmpty_1 = require("./throwIfEmpty");
12536 var defaultIfEmpty_1 = require("./defaultIfEmpty");
12537 var identity_1 = require("../util/identity");
12538 function last(predicate, defaultValue) {
12539     var hasDefaultValue = arguments.length >= 2;
12540     return function (source) { return source.pipe(predicate ? filter_1.filter(function (v, i) { return predicate(v, i, source); }) : identity_1.identity, takeLast_1.takeLast(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new EmptyError_1.EmptyError(); })); };
12541 }
12542 exports.last = last;
12543
12544 },{"../util/EmptyError":194,"../util/identity":202,"./defaultIfEmpty":90,"./filter":103,"./takeLast":156,"./throwIfEmpty":162}],112:[function(require,module,exports){
12545 "use strict";
12546 var __extends = (this && this.__extends) || (function () {
12547     var extendStatics = function (d, b) {
12548         extendStatics = Object.setPrototypeOf ||
12549             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12550             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12551         return extendStatics(d, b);
12552     }
12553     return function (d, b) {
12554         extendStatics(d, b);
12555         function __() { this.constructor = d; }
12556         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12557     };
12558 })();
12559 Object.defineProperty(exports, "__esModule", { value: true });
12560 var Subscriber_1 = require("../Subscriber");
12561 function map(project, thisArg) {
12562     return function mapOperation(source) {
12563         if (typeof project !== 'function') {
12564             throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
12565         }
12566         return source.lift(new MapOperator(project, thisArg));
12567     };
12568 }
12569 exports.map = map;
12570 var MapOperator = (function () {
12571     function MapOperator(project, thisArg) {
12572         this.project = project;
12573         this.thisArg = thisArg;
12574     }
12575     MapOperator.prototype.call = function (subscriber, source) {
12576         return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
12577     };
12578     return MapOperator;
12579 }());
12580 exports.MapOperator = MapOperator;
12581 var MapSubscriber = (function (_super) {
12582     __extends(MapSubscriber, _super);
12583     function MapSubscriber(destination, project, thisArg) {
12584         var _this = _super.call(this, destination) || this;
12585         _this.project = project;
12586         _this.count = 0;
12587         _this.thisArg = thisArg || _this;
12588         return _this;
12589     }
12590     MapSubscriber.prototype._next = function (value) {
12591         var result;
12592         try {
12593             result = this.project.call(this.thisArg, value, this.count++);
12594         }
12595         catch (err) {
12596             this.destination.error(err);
12597             return;
12598         }
12599         this.destination.next(result);
12600     };
12601     return MapSubscriber;
12602 }(Subscriber_1.Subscriber));
12603
12604 },{"../Subscriber":39}],113:[function(require,module,exports){
12605 "use strict";
12606 var __extends = (this && this.__extends) || (function () {
12607     var extendStatics = function (d, b) {
12608         extendStatics = Object.setPrototypeOf ||
12609             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12610             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12611         return extendStatics(d, b);
12612     }
12613     return function (d, b) {
12614         extendStatics(d, b);
12615         function __() { this.constructor = d; }
12616         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12617     };
12618 })();
12619 Object.defineProperty(exports, "__esModule", { value: true });
12620 var Subscriber_1 = require("../Subscriber");
12621 function mapTo(value) {
12622     return function (source) { return source.lift(new MapToOperator(value)); };
12623 }
12624 exports.mapTo = mapTo;
12625 var MapToOperator = (function () {
12626     function MapToOperator(value) {
12627         this.value = value;
12628     }
12629     MapToOperator.prototype.call = function (subscriber, source) {
12630         return source.subscribe(new MapToSubscriber(subscriber, this.value));
12631     };
12632     return MapToOperator;
12633 }());
12634 var MapToSubscriber = (function (_super) {
12635     __extends(MapToSubscriber, _super);
12636     function MapToSubscriber(destination, value) {
12637         var _this = _super.call(this, destination) || this;
12638         _this.value = value;
12639         return _this;
12640     }
12641     MapToSubscriber.prototype._next = function (x) {
12642         this.destination.next(this.value);
12643     };
12644     return MapToSubscriber;
12645 }(Subscriber_1.Subscriber));
12646
12647 },{"../Subscriber":39}],114:[function(require,module,exports){
12648 "use strict";
12649 var __extends = (this && this.__extends) || (function () {
12650     var extendStatics = function (d, b) {
12651         extendStatics = Object.setPrototypeOf ||
12652             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12653             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12654         return extendStatics(d, b);
12655     }
12656     return function (d, b) {
12657         extendStatics(d, b);
12658         function __() { this.constructor = d; }
12659         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12660     };
12661 })();
12662 Object.defineProperty(exports, "__esModule", { value: true });
12663 var Subscriber_1 = require("../Subscriber");
12664 var Notification_1 = require("../Notification");
12665 function materialize() {
12666     return function materializeOperatorFunction(source) {
12667         return source.lift(new MaterializeOperator());
12668     };
12669 }
12670 exports.materialize = materialize;
12671 var MaterializeOperator = (function () {
12672     function MaterializeOperator() {
12673     }
12674     MaterializeOperator.prototype.call = function (subscriber, source) {
12675         return source.subscribe(new MaterializeSubscriber(subscriber));
12676     };
12677     return MaterializeOperator;
12678 }());
12679 var MaterializeSubscriber = (function (_super) {
12680     __extends(MaterializeSubscriber, _super);
12681     function MaterializeSubscriber(destination) {
12682         return _super.call(this, destination) || this;
12683     }
12684     MaterializeSubscriber.prototype._next = function (value) {
12685         this.destination.next(Notification_1.Notification.createNext(value));
12686     };
12687     MaterializeSubscriber.prototype._error = function (err) {
12688         var destination = this.destination;
12689         destination.next(Notification_1.Notification.createError(err));
12690         destination.complete();
12691     };
12692     MaterializeSubscriber.prototype._complete = function () {
12693         var destination = this.destination;
12694         destination.next(Notification_1.Notification.createComplete());
12695         destination.complete();
12696     };
12697     return MaterializeSubscriber;
12698 }(Subscriber_1.Subscriber));
12699
12700 },{"../Notification":31,"../Subscriber":39}],115:[function(require,module,exports){
12701 "use strict";
12702 Object.defineProperty(exports, "__esModule", { value: true });
12703 var reduce_1 = require("./reduce");
12704 function max(comparer) {
12705     var max = (typeof comparer === 'function')
12706         ? function (x, y) { return comparer(x, y) > 0 ? x : y; }
12707         : function (x, y) { return x > y ? x : y; };
12708     return reduce_1.reduce(max);
12709 }
12710 exports.max = max;
12711
12712 },{"./reduce":133}],116:[function(require,module,exports){
12713 "use strict";
12714 Object.defineProperty(exports, "__esModule", { value: true });
12715 var merge_1 = require("../observable/merge");
12716 function merge() {
12717     var observables = [];
12718     for (var _i = 0; _i < arguments.length; _i++) {
12719         observables[_i] = arguments[_i];
12720     }
12721     return function (source) { return source.lift.call(merge_1.merge.apply(void 0, [source].concat(observables))); };
12722 }
12723 exports.merge = merge;
12724
12725 },{"../observable/merge":61}],117:[function(require,module,exports){
12726 "use strict";
12727 Object.defineProperty(exports, "__esModule", { value: true });
12728 var mergeMap_1 = require("./mergeMap");
12729 var identity_1 = require("../util/identity");
12730 function mergeAll(concurrent) {
12731     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12732     return mergeMap_1.mergeMap(identity_1.identity, concurrent);
12733 }
12734 exports.mergeAll = mergeAll;
12735
12736 },{"../util/identity":202,"./mergeMap":118}],118:[function(require,module,exports){
12737 "use strict";
12738 var __extends = (this && this.__extends) || (function () {
12739     var extendStatics = function (d, b) {
12740         extendStatics = Object.setPrototypeOf ||
12741             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12742             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12743         return extendStatics(d, b);
12744     }
12745     return function (d, b) {
12746         extendStatics(d, b);
12747         function __() { this.constructor = d; }
12748         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12749     };
12750 })();
12751 Object.defineProperty(exports, "__esModule", { value: true });
12752 var subscribeToResult_1 = require("../util/subscribeToResult");
12753 var OuterSubscriber_1 = require("../OuterSubscriber");
12754 var InnerSubscriber_1 = require("../InnerSubscriber");
12755 var map_1 = require("./map");
12756 var from_1 = require("../observable/from");
12757 function mergeMap(project, resultSelector, concurrent) {
12758     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12759     if (typeof resultSelector === 'function') {
12760         return function (source) { return source.pipe(mergeMap(function (a, i) { return from_1.from(project(a, i)).pipe(map_1.map(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); };
12761     }
12762     else if (typeof resultSelector === 'number') {
12763         concurrent = resultSelector;
12764     }
12765     return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); };
12766 }
12767 exports.mergeMap = mergeMap;
12768 var MergeMapOperator = (function () {
12769     function MergeMapOperator(project, concurrent) {
12770         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12771         this.project = project;
12772         this.concurrent = concurrent;
12773     }
12774     MergeMapOperator.prototype.call = function (observer, source) {
12775         return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));
12776     };
12777     return MergeMapOperator;
12778 }());
12779 exports.MergeMapOperator = MergeMapOperator;
12780 var MergeMapSubscriber = (function (_super) {
12781     __extends(MergeMapSubscriber, _super);
12782     function MergeMapSubscriber(destination, project, concurrent) {
12783         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12784         var _this = _super.call(this, destination) || this;
12785         _this.project = project;
12786         _this.concurrent = concurrent;
12787         _this.hasCompleted = false;
12788         _this.buffer = [];
12789         _this.active = 0;
12790         _this.index = 0;
12791         return _this;
12792     }
12793     MergeMapSubscriber.prototype._next = function (value) {
12794         if (this.active < this.concurrent) {
12795             this._tryNext(value);
12796         }
12797         else {
12798             this.buffer.push(value);
12799         }
12800     };
12801     MergeMapSubscriber.prototype._tryNext = function (value) {
12802         var result;
12803         var index = this.index++;
12804         try {
12805             result = this.project(value, index);
12806         }
12807         catch (err) {
12808             this.destination.error(err);
12809             return;
12810         }
12811         this.active++;
12812         this._innerSub(result, value, index);
12813     };
12814     MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
12815         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
12816         var destination = this.destination;
12817         destination.add(innerSubscriber);
12818         subscribeToResult_1.subscribeToResult(this, ish, value, index, innerSubscriber);
12819     };
12820     MergeMapSubscriber.prototype._complete = function () {
12821         this.hasCompleted = true;
12822         if (this.active === 0 && this.buffer.length === 0) {
12823             this.destination.complete();
12824         }
12825         this.unsubscribe();
12826     };
12827     MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12828         this.destination.next(innerValue);
12829     };
12830     MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
12831         var buffer = this.buffer;
12832         this.remove(innerSub);
12833         this.active--;
12834         if (buffer.length > 0) {
12835             this._next(buffer.shift());
12836         }
12837         else if (this.active === 0 && this.hasCompleted) {
12838             this.destination.complete();
12839         }
12840     };
12841     return MergeMapSubscriber;
12842 }(OuterSubscriber_1.OuterSubscriber));
12843 exports.MergeMapSubscriber = MergeMapSubscriber;
12844
12845 },{"../InnerSubscriber":30,"../OuterSubscriber":34,"../observable/from":51,"../util/subscribeToResult":222,"./map":112}],119:[function(require,module,exports){
12846 "use strict";
12847 Object.defineProperty(exports, "__esModule", { value: true });
12848 var mergeMap_1 = require("./mergeMap");
12849 function mergeMapTo(innerObservable, resultSelector, concurrent) {
12850     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12851     if (typeof resultSelector === 'function') {
12852         return mergeMap_1.mergeMap(function () { return innerObservable; }, resultSelector, concurrent);
12853     }
12854     if (typeof resultSelector === 'number') {
12855         concurrent = resultSelector;
12856     }
12857     return mergeMap_1.mergeMap(function () { return innerObservable; }, concurrent);
12858 }
12859 exports.mergeMapTo = mergeMapTo;
12860
12861 },{"./mergeMap":118}],120:[function(require,module,exports){
12862 "use strict";
12863 var __extends = (this && this.__extends) || (function () {
12864     var extendStatics = function (d, b) {
12865         extendStatics = Object.setPrototypeOf ||
12866             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12867             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12868         return extendStatics(d, b);
12869     }
12870     return function (d, b) {
12871         extendStatics(d, b);
12872         function __() { this.constructor = d; }
12873         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12874     };
12875 })();
12876 Object.defineProperty(exports, "__esModule", { value: true });
12877 var tryCatch_1 = require("../util/tryCatch");
12878 var errorObject_1 = require("../util/errorObject");
12879 var subscribeToResult_1 = require("../util/subscribeToResult");
12880 var OuterSubscriber_1 = require("../OuterSubscriber");
12881 var InnerSubscriber_1 = require("../InnerSubscriber");
12882 function mergeScan(accumulator, seed, concurrent) {
12883     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12884     return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); };
12885 }
12886 exports.mergeScan = mergeScan;
12887 var MergeScanOperator = (function () {
12888     function MergeScanOperator(accumulator, seed, concurrent) {
12889         this.accumulator = accumulator;
12890         this.seed = seed;
12891         this.concurrent = concurrent;
12892     }
12893     MergeScanOperator.prototype.call = function (subscriber, source) {
12894         return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent));
12895     };
12896     return MergeScanOperator;
12897 }());
12898 exports.MergeScanOperator = MergeScanOperator;
12899 var MergeScanSubscriber = (function (_super) {
12900     __extends(MergeScanSubscriber, _super);
12901     function MergeScanSubscriber(destination, accumulator, acc, concurrent) {
12902         var _this = _super.call(this, destination) || this;
12903         _this.accumulator = accumulator;
12904         _this.acc = acc;
12905         _this.concurrent = concurrent;
12906         _this.hasValue = false;
12907         _this.hasCompleted = false;
12908         _this.buffer = [];
12909         _this.active = 0;
12910         _this.index = 0;
12911         return _this;
12912     }
12913     MergeScanSubscriber.prototype._next = function (value) {
12914         if (this.active < this.concurrent) {
12915             var index = this.index++;
12916             var ish = tryCatch_1.tryCatch(this.accumulator)(this.acc, value);
12917             var destination = this.destination;
12918             if (ish === errorObject_1.errorObject) {
12919                 destination.error(errorObject_1.errorObject.e);
12920             }
12921             else {
12922                 this.active++;
12923                 this._innerSub(ish, value, index);
12924             }
12925         }
12926         else {
12927             this.buffer.push(value);
12928         }
12929     };
12930     MergeScanSubscriber.prototype._innerSub = function (ish, value, index) {
12931         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
12932         var destination = this.destination;
12933         destination.add(innerSubscriber);
12934         subscribeToResult_1.subscribeToResult(this, ish, value, index, innerSubscriber);
12935     };
12936     MergeScanSubscriber.prototype._complete = function () {
12937         this.hasCompleted = true;
12938         if (this.active === 0 && this.buffer.length === 0) {
12939             if (this.hasValue === false) {
12940                 this.destination.next(this.acc);
12941             }
12942             this.destination.complete();
12943         }
12944         this.unsubscribe();
12945     };
12946     MergeScanSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12947         var destination = this.destination;
12948         this.acc = innerValue;
12949         this.hasValue = true;
12950         destination.next(innerValue);
12951     };
12952     MergeScanSubscriber.prototype.notifyComplete = function (innerSub) {
12953         var buffer = this.buffer;
12954         var destination = this.destination;
12955         destination.remove(innerSub);
12956         this.active--;
12957         if (buffer.length > 0) {
12958             this._next(buffer.shift());
12959         }
12960         else if (this.active === 0 && this.hasCompleted) {
12961             if (this.hasValue === false) {
12962                 this.destination.next(this.acc);
12963             }
12964             this.destination.complete();
12965         }
12966     };
12967     return MergeScanSubscriber;
12968 }(OuterSubscriber_1.OuterSubscriber));
12969 exports.MergeScanSubscriber = MergeScanSubscriber;
12970
12971 },{"../InnerSubscriber":30,"../OuterSubscriber":34,"../util/errorObject":200,"../util/subscribeToResult":222,"../util/tryCatch":224}],121:[function(require,module,exports){
12972 "use strict";
12973 Object.defineProperty(exports, "__esModule", { value: true });
12974 var reduce_1 = require("./reduce");
12975 function min(comparer) {
12976     var min = (typeof comparer === 'function')
12977         ? function (x, y) { return comparer(x, y) < 0 ? x : y; }
12978         : function (x, y) { return x < y ? x : y; };
12979     return reduce_1.reduce(min);
12980 }
12981 exports.min = min;
12982
12983 },{"./reduce":133}],122:[function(require,module,exports){
12984 "use strict";
12985 Object.defineProperty(exports, "__esModule", { value: true });
12986 var ConnectableObservable_1 = require("../observable/ConnectableObservable");
12987 function multicast(subjectOrSubjectFactory, selector) {
12988     return function multicastOperatorFunction(source) {
12989         var subjectFactory;
12990         if (typeof subjectOrSubjectFactory === 'function') {
12991             subjectFactory = subjectOrSubjectFactory;
12992         }
12993         else {
12994             subjectFactory = function subjectFactory() {
12995                 return subjectOrSubjectFactory;
12996             };
12997         }
12998         if (typeof selector === 'function') {
12999             return source.lift(new MulticastOperator(subjectFactory, selector));
13000         }
13001         var connectable = Object.create(source, ConnectableObservable_1.connectableObservableDescriptor);
13002         connectable.source = source;
13003         connectable.subjectFactory = subjectFactory;
13004         return connectable;
13005     };
13006 }
13007 exports.multicast = multicast;
13008 var MulticastOperator = (function () {
13009     function MulticastOperator(subjectFactory, selector) {
13010         this.subjectFactory = subjectFactory;
13011         this.selector = selector;
13012     }
13013     MulticastOperator.prototype.call = function (subscriber, source) {
13014         var selector = this.selector;
13015         var subject = this.subjectFactory();
13016         var subscription = selector(subject).subscribe(subscriber);
13017         subscription.add(source.subscribe(subject));
13018         return subscription;
13019     };
13020     return MulticastOperator;
13021 }());
13022 exports.MulticastOperator = MulticastOperator;
13023
13024 },{"../observable/ConnectableObservable":42}],123:[function(require,module,exports){
13025 "use strict";
13026 var __extends = (this && this.__extends) || (function () {
13027     var extendStatics = function (d, b) {
13028         extendStatics = Object.setPrototypeOf ||
13029             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13030             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13031         return extendStatics(d, b);
13032     }
13033     return function (d, b) {
13034         extendStatics(d, b);
13035         function __() { this.constructor = d; }
13036         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13037     };
13038 })();
13039 Object.defineProperty(exports, "__esModule", { value: true });
13040 var Subscriber_1 = require("../Subscriber");
13041 var Notification_1 = require("../Notification");
13042 function observeOn(scheduler, delay) {
13043     if (delay === void 0) { delay = 0; }
13044     return function observeOnOperatorFunction(source) {
13045         return source.lift(new ObserveOnOperator(scheduler, delay));
13046     };
13047 }
13048 exports.observeOn = observeOn;
13049 var ObserveOnOperator = (function () {
13050     function ObserveOnOperator(scheduler, delay) {
13051         if (delay === void 0) { delay = 0; }
13052         this.scheduler = scheduler;
13053         this.delay = delay;
13054     }
13055     ObserveOnOperator.prototype.call = function (subscriber, source) {
13056         return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
13057     };
13058     return ObserveOnOperator;
13059 }());
13060 exports.ObserveOnOperator = ObserveOnOperator;
13061 var ObserveOnSubscriber = (function (_super) {
13062     __extends(ObserveOnSubscriber, _super);
13063     function ObserveOnSubscriber(destination, scheduler, delay) {
13064         if (delay === void 0) { delay = 0; }
13065         var _this = _super.call(this, destination) || this;
13066         _this.scheduler = scheduler;
13067         _this.delay = delay;
13068         return _this;
13069     }
13070     ObserveOnSubscriber.dispatch = function (arg) {
13071         var notification = arg.notification, destination = arg.destination;
13072         notification.observe(destination);
13073         this.unsubscribe();
13074     };
13075     ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
13076         var destination = this.destination;
13077         destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
13078     };
13079     ObserveOnSubscriber.prototype._next = function (value) {
13080         this.scheduleMessage(Notification_1.Notification.createNext(value));
13081     };
13082     ObserveOnSubscriber.prototype._error = function (err) {
13083         this.scheduleMessage(Notification_1.Notification.createError(err));
13084         this.unsubscribe();
13085     };
13086     ObserveOnSubscriber.prototype._complete = function () {
13087         this.scheduleMessage(Notification_1.Notification.createComplete());
13088         this.unsubscribe();
13089     };
13090     return ObserveOnSubscriber;
13091 }(Subscriber_1.Subscriber));
13092 exports.ObserveOnSubscriber = ObserveOnSubscriber;
13093 var ObserveOnMessage = (function () {
13094     function ObserveOnMessage(notification, destination) {
13095         this.notification = notification;
13096         this.destination = destination;
13097     }
13098     return ObserveOnMessage;
13099 }());
13100 exports.ObserveOnMessage = ObserveOnMessage;
13101
13102 },{"../Notification":31,"../Subscriber":39}],124:[function(require,module,exports){
13103 "use strict";
13104 var __extends = (this && this.__extends) || (function () {
13105     var extendStatics = function (d, b) {
13106         extendStatics = Object.setPrototypeOf ||
13107             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13108             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13109         return extendStatics(d, b);
13110     }
13111     return function (d, b) {
13112         extendStatics(d, b);
13113         function __() { this.constructor = d; }
13114         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13115     };
13116 })();
13117 Object.defineProperty(exports, "__esModule", { value: true });
13118 var from_1 = require("../observable/from");
13119 var isArray_1 = require("../util/isArray");
13120 var OuterSubscriber_1 = require("../OuterSubscriber");
13121 var InnerSubscriber_1 = require("../InnerSubscriber");
13122 var subscribeToResult_1 = require("../util/subscribeToResult");
13123 function onErrorResumeNext() {
13124     var nextSources = [];
13125     for (var _i = 0; _i < arguments.length; _i++) {
13126         nextSources[_i] = arguments[_i];
13127     }
13128     if (nextSources.length === 1 && isArray_1.isArray(nextSources[0])) {
13129         nextSources = nextSources[0];
13130     }
13131     return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); };
13132 }
13133 exports.onErrorResumeNext = onErrorResumeNext;
13134 function onErrorResumeNextStatic() {
13135     var nextSources = [];
13136     for (var _i = 0; _i < arguments.length; _i++) {
13137         nextSources[_i] = arguments[_i];
13138     }
13139     var source = null;
13140     if (nextSources.length === 1 && isArray_1.isArray(nextSources[0])) {
13141         nextSources = nextSources[0];
13142     }
13143     source = nextSources.shift();
13144     return from_1.from(source, null).lift(new OnErrorResumeNextOperator(nextSources));
13145 }
13146 exports.onErrorResumeNextStatic = onErrorResumeNextStatic;
13147 var OnErrorResumeNextOperator = (function () {
13148     function OnErrorResumeNextOperator(nextSources) {
13149         this.nextSources = nextSources;
13150     }
13151     OnErrorResumeNextOperator.prototype.call = function (subscriber, source) {
13152         return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources));
13153     };
13154     return OnErrorResumeNextOperator;
13155 }());
13156 var OnErrorResumeNextSubscriber = (function (_super) {
13157     __extends(OnErrorResumeNextSubscriber, _super);
13158     function OnErrorResumeNextSubscriber(destination, nextSources) {
13159         var _this = _super.call(this, destination) || this;
13160         _this.destination = destination;
13161         _this.nextSources = nextSources;
13162         return _this;
13163     }
13164     OnErrorResumeNextSubscriber.prototype.notifyError = function (error, innerSub) {
13165         this.subscribeToNextSource();
13166     };
13167     OnErrorResumeNextSubscriber.prototype.notifyComplete = function (innerSub) {
13168         this.subscribeToNextSource();
13169     };
13170     OnErrorResumeNextSubscriber.prototype._error = function (err) {
13171         this.subscribeToNextSource();
13172         this.unsubscribe();
13173     };
13174     OnErrorResumeNextSubscriber.prototype._complete = function () {
13175         this.subscribeToNextSource();
13176         this.unsubscribe();
13177     };
13178     OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () {
13179         var next = this.nextSources.shift();
13180         if (next) {
13181             var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
13182             var destination = this.destination;
13183             destination.add(innerSubscriber);
13184             subscribeToResult_1.subscribeToResult(this, next, undefined, undefined, innerSubscriber);
13185         }
13186         else {
13187             this.destination.complete();
13188         }
13189     };
13190     return OnErrorResumeNextSubscriber;
13191 }(OuterSubscriber_1.OuterSubscriber));
13192
13193 },{"../InnerSubscriber":30,"../OuterSubscriber":34,"../observable/from":51,"../util/isArray":203,"../util/subscribeToResult":222}],125:[function(require,module,exports){
13194 "use strict";
13195 var __extends = (this && this.__extends) || (function () {
13196     var extendStatics = function (d, b) {
13197         extendStatics = Object.setPrototypeOf ||
13198             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13199             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13200         return extendStatics(d, b);
13201     }
13202     return function (d, b) {
13203         extendStatics(d, b);
13204         function __() { this.constructor = d; }
13205         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13206     };
13207 })();
13208 Object.defineProperty(exports, "__esModule", { value: true });
13209 var Subscriber_1 = require("../Subscriber");
13210 function pairwise() {
13211     return function (source) { return source.lift(new PairwiseOperator()); };
13212 }
13213 exports.pairwise = pairwise;
13214 var PairwiseOperator = (function () {
13215     function PairwiseOperator() {
13216     }
13217     PairwiseOperator.prototype.call = function (subscriber, source) {
13218         return source.subscribe(new PairwiseSubscriber(subscriber));
13219     };
13220     return PairwiseOperator;
13221 }());
13222 var PairwiseSubscriber = (function (_super) {
13223     __extends(PairwiseSubscriber, _super);
13224     function PairwiseSubscriber(destination) {
13225         var _this = _super.call(this, destination) || this;
13226         _this.hasPrev = false;
13227         return _this;
13228     }
13229     PairwiseSubscriber.prototype._next = function (value) {
13230         if (this.hasPrev) {
13231             this.destination.next([this.prev, value]);
13232         }
13233         else {
13234             this.hasPrev = true;
13235         }
13236         this.prev = value;
13237     };
13238     return PairwiseSubscriber;
13239 }(Subscriber_1.Subscriber));
13240
13241 },{"../Subscriber":39}],126:[function(require,module,exports){
13242 "use strict";
13243 Object.defineProperty(exports, "__esModule", { value: true });
13244 var not_1 = require("../util/not");
13245 var filter_1 = require("./filter");
13246 function partition(predicate, thisArg) {
13247     return function (source) { return [
13248         filter_1.filter(predicate, thisArg)(source),
13249         filter_1.filter(not_1.not(predicate, thisArg))(source)
13250     ]; };
13251 }
13252 exports.partition = partition;
13253
13254 },{"../util/not":215,"./filter":103}],127:[function(require,module,exports){
13255 "use strict";
13256 Object.defineProperty(exports, "__esModule", { value: true });
13257 var map_1 = require("./map");
13258 function pluck() {
13259     var properties = [];
13260     for (var _i = 0; _i < arguments.length; _i++) {
13261         properties[_i] = arguments[_i];
13262     }
13263     var length = properties.length;
13264     if (length === 0) {
13265         throw new Error('list of properties cannot be empty.');
13266     }
13267     return function (source) { return map_1.map(plucker(properties, length))(source); };
13268 }
13269 exports.pluck = pluck;
13270 function plucker(props, length) {
13271     var mapper = function (x) {
13272         var currentProp = x;
13273         for (var i = 0; i < length; i++) {
13274             var p = currentProp[props[i]];
13275             if (typeof p !== 'undefined') {
13276                 currentProp = p;
13277             }
13278             else {
13279                 return undefined;
13280             }
13281         }
13282         return currentProp;
13283     };
13284     return mapper;
13285 }
13286
13287 },{"./map":112}],128:[function(require,module,exports){
13288 "use strict";
13289 Object.defineProperty(exports, "__esModule", { value: true });
13290 var Subject_1 = require("../Subject");
13291 var multicast_1 = require("./multicast");
13292 function publish(selector) {
13293     return selector ?
13294         multicast_1.multicast(function () { return new Subject_1.Subject(); }, selector) :
13295         multicast_1.multicast(new Subject_1.Subject());
13296 }
13297 exports.publish = publish;
13298
13299 },{"../Subject":37,"./multicast":122}],129:[function(require,module,exports){
13300 "use strict";
13301 Object.defineProperty(exports, "__esModule", { value: true });
13302 var BehaviorSubject_1 = require("../BehaviorSubject");
13303 var multicast_1 = require("./multicast");
13304 function publishBehavior(value) {
13305     return function (source) { return multicast_1.multicast(new BehaviorSubject_1.BehaviorSubject(value))(source); };
13306 }
13307 exports.publishBehavior = publishBehavior;
13308
13309 },{"../BehaviorSubject":29,"./multicast":122}],130:[function(require,module,exports){
13310 "use strict";
13311 Object.defineProperty(exports, "__esModule", { value: true });
13312 var AsyncSubject_1 = require("../AsyncSubject");
13313 var multicast_1 = require("./multicast");
13314 function publishLast() {
13315     return function (source) { return multicast_1.multicast(new AsyncSubject_1.AsyncSubject())(source); };
13316 }
13317 exports.publishLast = publishLast;
13318
13319 },{"../AsyncSubject":28,"./multicast":122}],131:[function(require,module,exports){
13320 "use strict";
13321 Object.defineProperty(exports, "__esModule", { value: true });
13322 var ReplaySubject_1 = require("../ReplaySubject");
13323 var multicast_1 = require("./multicast");
13324 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
13325     if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
13326         scheduler = selectorOrScheduler;
13327     }
13328     var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
13329     var subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
13330     return function (source) { return multicast_1.multicast(function () { return subject; }, selector)(source); };
13331 }
13332 exports.publishReplay = publishReplay;
13333
13334 },{"../ReplaySubject":35,"./multicast":122}],132:[function(require,module,exports){
13335 "use strict";
13336 Object.defineProperty(exports, "__esModule", { value: true });
13337 var isArray_1 = require("../util/isArray");
13338 var race_1 = require("../observable/race");
13339 function race() {
13340     var observables = [];
13341     for (var _i = 0; _i < arguments.length; _i++) {
13342         observables[_i] = arguments[_i];
13343     }
13344     return function raceOperatorFunction(source) {
13345         if (observables.length === 1 && isArray_1.isArray(observables[0])) {
13346             observables = observables[0];
13347         }
13348         return source.lift.call(race_1.race.apply(void 0, [source].concat(observables)));
13349     };
13350 }
13351 exports.race = race;
13352
13353 },{"../observable/race":66,"../util/isArray":203}],133:[function(require,module,exports){
13354 "use strict";
13355 Object.defineProperty(exports, "__esModule", { value: true });
13356 var scan_1 = require("./scan");
13357 var takeLast_1 = require("./takeLast");
13358 var defaultIfEmpty_1 = require("./defaultIfEmpty");
13359 var pipe_1 = require("../util/pipe");
13360 function reduce(accumulator, seed) {
13361     if (arguments.length >= 2) {
13362         return function reduceOperatorFunctionWithSeed(source) {
13363             return pipe_1.pipe(scan_1.scan(accumulator, seed), takeLast_1.takeLast(1), defaultIfEmpty_1.defaultIfEmpty(seed))(source);
13364         };
13365     }
13366     return function reduceOperatorFunction(source) {
13367         return pipe_1.pipe(scan_1.scan(function (acc, value, index) { return accumulator(acc, value, index + 1); }), takeLast_1.takeLast(1))(source);
13368     };
13369 }
13370 exports.reduce = reduce;
13371
13372 },{"../util/pipe":216,"./defaultIfEmpty":90,"./scan":141,"./takeLast":156}],134:[function(require,module,exports){
13373 "use strict";
13374 var __extends = (this && this.__extends) || (function () {
13375     var extendStatics = function (d, b) {
13376         extendStatics = Object.setPrototypeOf ||
13377             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13378             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13379         return extendStatics(d, b);
13380     }
13381     return function (d, b) {
13382         extendStatics(d, b);
13383         function __() { this.constructor = d; }
13384         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13385     };
13386 })();
13387 Object.defineProperty(exports, "__esModule", { value: true });
13388 var Subscriber_1 = require("../Subscriber");
13389 function refCount() {
13390     return function refCountOperatorFunction(source) {
13391         return source.lift(new RefCountOperator(source));
13392     };
13393 }
13394 exports.refCount = refCount;
13395 var RefCountOperator = (function () {
13396     function RefCountOperator(connectable) {
13397         this.connectable = connectable;
13398     }
13399     RefCountOperator.prototype.call = function (subscriber, source) {
13400         var connectable = this.connectable;
13401         connectable._refCount++;
13402         var refCounter = new RefCountSubscriber(subscriber, connectable);
13403         var subscription = source.subscribe(refCounter);
13404         if (!refCounter.closed) {
13405             refCounter.connection = connectable.connect();
13406         }
13407         return subscription;
13408     };
13409     return RefCountOperator;
13410 }());
13411 var RefCountSubscriber = (function (_super) {
13412     __extends(RefCountSubscriber, _super);
13413     function RefCountSubscriber(destination, connectable) {
13414         var _this = _super.call(this, destination) || this;
13415         _this.connectable = connectable;
13416         return _this;
13417     }
13418     RefCountSubscriber.prototype._unsubscribe = function () {
13419         var connectable = this.connectable;
13420         if (!connectable) {
13421             this.connection = null;
13422             return;
13423         }
13424         this.connectable = null;
13425         var refCount = connectable._refCount;
13426         if (refCount <= 0) {
13427             this.connection = null;
13428             return;
13429         }
13430         connectable._refCount = refCount - 1;
13431         if (refCount > 1) {
13432             this.connection = null;
13433             return;
13434         }
13435         var connection = this.connection;
13436         var sharedConnection = connectable._connection;
13437         this.connection = null;
13438         if (sharedConnection && (!connection || sharedConnection === connection)) {
13439             sharedConnection.unsubscribe();
13440         }
13441     };
13442     return RefCountSubscriber;
13443 }(Subscriber_1.Subscriber));
13444
13445 },{"../Subscriber":39}],135:[function(require,module,exports){
13446 "use strict";
13447 var __extends = (this && this.__extends) || (function () {
13448     var extendStatics = function (d, b) {
13449         extendStatics = Object.setPrototypeOf ||
13450             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13451             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13452         return extendStatics(d, b);
13453     }
13454     return function (d, b) {
13455         extendStatics(d, b);
13456         function __() { this.constructor = d; }
13457         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13458     };
13459 })();
13460 Object.defineProperty(exports, "__esModule", { value: true });
13461 var Subscriber_1 = require("../Subscriber");
13462 var empty_1 = require("../observable/empty");
13463 function repeat(count) {
13464     if (count === void 0) { count = -1; }
13465     return function (source) {
13466         if (count === 0) {
13467             return empty_1.empty();
13468         }
13469         else if (count < 0) {
13470             return source.lift(new RepeatOperator(-1, source));
13471         }
13472         else {
13473             return source.lift(new RepeatOperator(count - 1, source));
13474         }
13475     };
13476 }
13477 exports.repeat = repeat;
13478 var RepeatOperator = (function () {
13479     function RepeatOperator(count, source) {
13480         this.count = count;
13481         this.source = source;
13482     }
13483     RepeatOperator.prototype.call = function (subscriber, source) {
13484         return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source));
13485     };
13486     return RepeatOperator;
13487 }());
13488 var RepeatSubscriber = (function (_super) {
13489     __extends(RepeatSubscriber, _super);
13490     function RepeatSubscriber(destination, count, source) {
13491         var _this = _super.call(this, destination) || this;
13492         _this.count = count;
13493         _this.source = source;
13494         return _this;
13495     }
13496     RepeatSubscriber.prototype.complete = function () {
13497         if (!this.isStopped) {
13498             var _a = this, source = _a.source, count = _a.count;
13499             if (count === 0) {
13500                 return _super.prototype.complete.call(this);
13501             }
13502             else if (count > -1) {
13503                 this.count = count - 1;
13504             }
13505             source.subscribe(this._unsubscribeAndRecycle());
13506         }
13507     };
13508     return RepeatSubscriber;
13509 }(Subscriber_1.Subscriber));
13510
13511 },{"../Subscriber":39,"../observable/empty":49}],136:[function(require,module,exports){
13512 "use strict";
13513 var __extends = (this && this.__extends) || (function () {
13514     var extendStatics = function (d, b) {
13515         extendStatics = Object.setPrototypeOf ||
13516             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13517             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13518         return extendStatics(d, b);
13519     }
13520     return function (d, b) {
13521         extendStatics(d, b);
13522         function __() { this.constructor = d; }
13523         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13524     };
13525 })();
13526 Object.defineProperty(exports, "__esModule", { value: true });
13527 var Subject_1 = require("../Subject");
13528 var tryCatch_1 = require("../util/tryCatch");
13529 var errorObject_1 = require("../util/errorObject");
13530 var OuterSubscriber_1 = require("../OuterSubscriber");
13531 var subscribeToResult_1 = require("../util/subscribeToResult");
13532 function repeatWhen(notifier) {
13533     return function (source) { return source.lift(new RepeatWhenOperator(notifier)); };
13534 }
13535 exports.repeatWhen = repeatWhen;
13536 var RepeatWhenOperator = (function () {
13537     function RepeatWhenOperator(notifier) {
13538         this.notifier = notifier;
13539     }
13540     RepeatWhenOperator.prototype.call = function (subscriber, source) {
13541         return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source));
13542     };
13543     return RepeatWhenOperator;
13544 }());
13545 var RepeatWhenSubscriber = (function (_super) {
13546     __extends(RepeatWhenSubscriber, _super);
13547     function RepeatWhenSubscriber(destination, notifier, source) {
13548         var _this = _super.call(this, destination) || this;
13549         _this.notifier = notifier;
13550         _this.source = source;
13551         _this.sourceIsBeingSubscribedTo = true;
13552         return _this;
13553     }
13554     RepeatWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13555         this.sourceIsBeingSubscribedTo = true;
13556         this.source.subscribe(this);
13557     };
13558     RepeatWhenSubscriber.prototype.notifyComplete = function (innerSub) {
13559         if (this.sourceIsBeingSubscribedTo === false) {
13560             return _super.prototype.complete.call(this);
13561         }
13562     };
13563     RepeatWhenSubscriber.prototype.complete = function () {
13564         this.sourceIsBeingSubscribedTo = false;
13565         if (!this.isStopped) {
13566             if (!this.retries) {
13567                 this.subscribeToRetries();
13568             }
13569             if (!this.retriesSubscription || this.retriesSubscription.closed) {
13570                 return _super.prototype.complete.call(this);
13571             }
13572             this._unsubscribeAndRecycle();
13573             this.notifications.next();
13574         }
13575     };
13576     RepeatWhenSubscriber.prototype._unsubscribe = function () {
13577         var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription;
13578         if (notifications) {
13579             notifications.unsubscribe();
13580             this.notifications = null;
13581         }
13582         if (retriesSubscription) {
13583             retriesSubscription.unsubscribe();
13584             this.retriesSubscription = null;
13585         }
13586         this.retries = null;
13587     };
13588     RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () {
13589         var _unsubscribe = this._unsubscribe;
13590         this._unsubscribe = null;
13591         _super.prototype._unsubscribeAndRecycle.call(this);
13592         this._unsubscribe = _unsubscribe;
13593         return this;
13594     };
13595     RepeatWhenSubscriber.prototype.subscribeToRetries = function () {
13596         this.notifications = new Subject_1.Subject();
13597         var retries = tryCatch_1.tryCatch(this.notifier)(this.notifications);
13598         if (retries === errorObject_1.errorObject) {
13599             return _super.prototype.complete.call(this);
13600         }
13601         this.retries = retries;
13602         this.retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries);
13603     };
13604     return RepeatWhenSubscriber;
13605 }(OuterSubscriber_1.OuterSubscriber));
13606
13607 },{"../OuterSubscriber":34,"../Subject":37,"../util/errorObject":200,"../util/subscribeToResult":222,"../util/tryCatch":224}],137:[function(require,module,exports){
13608 "use strict";
13609 var __extends = (this && this.__extends) || (function () {
13610     var extendStatics = function (d, b) {
13611         extendStatics = Object.setPrototypeOf ||
13612             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13613             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13614         return extendStatics(d, b);
13615     }
13616     return function (d, b) {
13617         extendStatics(d, b);
13618         function __() { this.constructor = d; }
13619         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13620     };
13621 })();
13622 Object.defineProperty(exports, "__esModule", { value: true });
13623 var Subscriber_1 = require("../Subscriber");
13624 function retry(count) {
13625     if (count === void 0) { count = -1; }
13626     return function (source) { return source.lift(new RetryOperator(count, source)); };
13627 }
13628 exports.retry = retry;
13629 var RetryOperator = (function () {
13630     function RetryOperator(count, source) {
13631         this.count = count;
13632         this.source = source;
13633     }
13634     RetryOperator.prototype.call = function (subscriber, source) {
13635         return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
13636     };
13637     return RetryOperator;
13638 }());
13639 var RetrySubscriber = (function (_super) {
13640     __extends(RetrySubscriber, _super);
13641     function RetrySubscriber(destination, count, source) {
13642         var _this = _super.call(this, destination) || this;
13643         _this.count = count;
13644         _this.source = source;
13645         return _this;
13646     }
13647     RetrySubscriber.prototype.error = function (err) {
13648         if (!this.isStopped) {
13649             var _a = this, source = _a.source, count = _a.count;
13650             if (count === 0) {
13651                 return _super.prototype.error.call(this, err);
13652             }
13653             else if (count > -1) {
13654                 this.count = count - 1;
13655             }
13656             source.subscribe(this._unsubscribeAndRecycle());
13657         }
13658     };
13659     return RetrySubscriber;
13660 }(Subscriber_1.Subscriber));
13661
13662 },{"../Subscriber":39}],138:[function(require,module,exports){
13663 "use strict";
13664 var __extends = (this && this.__extends) || (function () {
13665     var extendStatics = function (d, b) {
13666         extendStatics = Object.setPrototypeOf ||
13667             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13668             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13669         return extendStatics(d, b);
13670     }
13671     return function (d, b) {
13672         extendStatics(d, b);
13673         function __() { this.constructor = d; }
13674         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13675     };
13676 })();
13677 Object.defineProperty(exports, "__esModule", { value: true });
13678 var Subject_1 = require("../Subject");
13679 var tryCatch_1 = require("../util/tryCatch");
13680 var errorObject_1 = require("../util/errorObject");
13681 var OuterSubscriber_1 = require("../OuterSubscriber");
13682 var subscribeToResult_1 = require("../util/subscribeToResult");
13683 function retryWhen(notifier) {
13684     return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); };
13685 }
13686 exports.retryWhen = retryWhen;
13687 var RetryWhenOperator = (function () {
13688     function RetryWhenOperator(notifier, source) {
13689         this.notifier = notifier;
13690         this.source = source;
13691     }
13692     RetryWhenOperator.prototype.call = function (subscriber, source) {
13693         return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));
13694     };
13695     return RetryWhenOperator;
13696 }());
13697 var RetryWhenSubscriber = (function (_super) {
13698     __extends(RetryWhenSubscriber, _super);
13699     function RetryWhenSubscriber(destination, notifier, source) {
13700         var _this = _super.call(this, destination) || this;
13701         _this.notifier = notifier;
13702         _this.source = source;
13703         return _this;
13704     }
13705     RetryWhenSubscriber.prototype.error = function (err) {
13706         if (!this.isStopped) {
13707             var errors = this.errors;
13708             var retries = this.retries;
13709             var retriesSubscription = this.retriesSubscription;
13710             if (!retries) {
13711                 errors = new Subject_1.Subject();
13712                 retries = tryCatch_1.tryCatch(this.notifier)(errors);
13713                 if (retries === errorObject_1.errorObject) {
13714                     return _super.prototype.error.call(this, errorObject_1.errorObject.e);
13715                 }
13716                 retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries);
13717             }
13718             else {
13719                 this.errors = null;
13720                 this.retriesSubscription = null;
13721             }
13722             this._unsubscribeAndRecycle();
13723             this.errors = errors;
13724             this.retries = retries;
13725             this.retriesSubscription = retriesSubscription;
13726             errors.next(err);
13727         }
13728     };
13729     RetryWhenSubscriber.prototype._unsubscribe = function () {
13730         var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;
13731         if (errors) {
13732             errors.unsubscribe();
13733             this.errors = null;
13734         }
13735         if (retriesSubscription) {
13736             retriesSubscription.unsubscribe();
13737             this.retriesSubscription = null;
13738         }
13739         this.retries = null;
13740     };
13741     RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13742         var _unsubscribe = this._unsubscribe;
13743         this._unsubscribe = null;
13744         this._unsubscribeAndRecycle();
13745         this._unsubscribe = _unsubscribe;
13746         this.source.subscribe(this);
13747     };
13748     return RetryWhenSubscriber;
13749 }(OuterSubscriber_1.OuterSubscriber));
13750
13751 },{"../OuterSubscriber":34,"../Subject":37,"../util/errorObject":200,"../util/subscribeToResult":222,"../util/tryCatch":224}],139:[function(require,module,exports){
13752 "use strict";
13753 var __extends = (this && this.__extends) || (function () {
13754     var extendStatics = function (d, b) {
13755         extendStatics = Object.setPrototypeOf ||
13756             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13757             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13758         return extendStatics(d, b);
13759     }
13760     return function (d, b) {
13761         extendStatics(d, b);
13762         function __() { this.constructor = d; }
13763         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13764     };
13765 })();
13766 Object.defineProperty(exports, "__esModule", { value: true });
13767 var OuterSubscriber_1 = require("../OuterSubscriber");
13768 var subscribeToResult_1 = require("../util/subscribeToResult");
13769 function sample(notifier) {
13770     return function (source) { return source.lift(new SampleOperator(notifier)); };
13771 }
13772 exports.sample = sample;
13773 var SampleOperator = (function () {
13774     function SampleOperator(notifier) {
13775         this.notifier = notifier;
13776     }
13777     SampleOperator.prototype.call = function (subscriber, source) {
13778         var sampleSubscriber = new SampleSubscriber(subscriber);
13779         var subscription = source.subscribe(sampleSubscriber);
13780         subscription.add(subscribeToResult_1.subscribeToResult(sampleSubscriber, this.notifier));
13781         return subscription;
13782     };
13783     return SampleOperator;
13784 }());
13785 var SampleSubscriber = (function (_super) {
13786     __extends(SampleSubscriber, _super);
13787     function SampleSubscriber() {
13788         var _this = _super !== null && _super.apply(this, arguments) || this;
13789         _this.hasValue = false;
13790         return _this;
13791     }
13792     SampleSubscriber.prototype._next = function (value) {
13793         this.value = value;
13794         this.hasValue = true;
13795     };
13796     SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13797         this.emitValue();
13798     };
13799     SampleSubscriber.prototype.notifyComplete = function () {
13800         this.emitValue();
13801     };
13802     SampleSubscriber.prototype.emitValue = function () {
13803         if (this.hasValue) {
13804             this.hasValue = false;
13805             this.destination.next(this.value);
13806         }
13807     };
13808     return SampleSubscriber;
13809 }(OuterSubscriber_1.OuterSubscriber));
13810
13811 },{"../OuterSubscriber":34,"../util/subscribeToResult":222}],140:[function(require,module,exports){
13812 "use strict";
13813 var __extends = (this && this.__extends) || (function () {
13814     var extendStatics = function (d, b) {
13815         extendStatics = Object.setPrototypeOf ||
13816             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13817             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13818         return extendStatics(d, b);
13819     }
13820     return function (d, b) {
13821         extendStatics(d, b);
13822         function __() { this.constructor = d; }
13823         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13824     };
13825 })();
13826 Object.defineProperty(exports, "__esModule", { value: true });
13827 var Subscriber_1 = require("../Subscriber");
13828 var async_1 = require("../scheduler/async");
13829 function sampleTime(period, scheduler) {
13830     if (scheduler === void 0) { scheduler = async_1.async; }
13831     return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); };
13832 }
13833 exports.sampleTime = sampleTime;
13834 var SampleTimeOperator = (function () {
13835     function SampleTimeOperator(period, scheduler) {
13836         this.period = period;
13837         this.scheduler = scheduler;
13838     }
13839     SampleTimeOperator.prototype.call = function (subscriber, source) {
13840         return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler));
13841     };
13842     return SampleTimeOperator;
13843 }());
13844 var SampleTimeSubscriber = (function (_super) {
13845     __extends(SampleTimeSubscriber, _super);
13846     function SampleTimeSubscriber(destination, period, scheduler) {
13847         var _this = _super.call(this, destination) || this;
13848         _this.period = period;
13849         _this.scheduler = scheduler;
13850         _this.hasValue = false;
13851         _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period: period }));
13852         return _this;
13853     }
13854     SampleTimeSubscriber.prototype._next = function (value) {
13855         this.lastValue = value;
13856         this.hasValue = true;
13857     };
13858     SampleTimeSubscriber.prototype.notifyNext = function () {
13859         if (this.hasValue) {
13860             this.hasValue = false;
13861             this.destination.next(this.lastValue);
13862         }
13863     };
13864     return SampleTimeSubscriber;
13865 }(Subscriber_1.Subscriber));
13866 function dispatchNotification(state) {
13867     var subscriber = state.subscriber, period = state.period;
13868     subscriber.notifyNext();
13869     this.schedule(state, period);
13870 }
13871
13872 },{"../Subscriber":39,"../scheduler/async":188}],141:[function(require,module,exports){
13873 "use strict";
13874 var __extends = (this && this.__extends) || (function () {
13875     var extendStatics = function (d, b) {
13876         extendStatics = Object.setPrototypeOf ||
13877             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13878             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13879         return extendStatics(d, b);
13880     }
13881     return function (d, b) {
13882         extendStatics(d, b);
13883         function __() { this.constructor = d; }
13884         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13885     };
13886 })();
13887 Object.defineProperty(exports, "__esModule", { value: true });
13888 var Subscriber_1 = require("../Subscriber");
13889 function scan(accumulator, seed) {
13890     var hasSeed = false;
13891     if (arguments.length >= 2) {
13892         hasSeed = true;
13893     }
13894     return function scanOperatorFunction(source) {
13895         return source.lift(new ScanOperator(accumulator, seed, hasSeed));
13896     };
13897 }
13898 exports.scan = scan;
13899 var ScanOperator = (function () {
13900     function ScanOperator(accumulator, seed, hasSeed) {
13901         if (hasSeed === void 0) { hasSeed = false; }
13902         this.accumulator = accumulator;
13903         this.seed = seed;
13904         this.hasSeed = hasSeed;
13905     }
13906     ScanOperator.prototype.call = function (subscriber, source) {
13907         return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
13908     };
13909     return ScanOperator;
13910 }());
13911 var ScanSubscriber = (function (_super) {
13912     __extends(ScanSubscriber, _super);
13913     function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
13914         var _this = _super.call(this, destination) || this;
13915         _this.accumulator = accumulator;
13916         _this._seed = _seed;
13917         _this.hasSeed = hasSeed;
13918         _this.index = 0;
13919         return _this;
13920     }
13921     Object.defineProperty(ScanSubscriber.prototype, "seed", {
13922         get: function () {
13923             return this._seed;
13924         },
13925         set: function (value) {
13926             this.hasSeed = true;
13927             this._seed = value;
13928         },
13929         enumerable: true,
13930         configurable: true
13931     });
13932     ScanSubscriber.prototype._next = function (value) {
13933         if (!this.hasSeed) {
13934             this.seed = value;
13935             this.destination.next(value);
13936         }
13937         else {
13938             return this._tryNext(value);
13939         }
13940     };
13941     ScanSubscriber.prototype._tryNext = function (value) {
13942         var index = this.index++;
13943         var result;
13944         try {
13945             result = this.accumulator(this.seed, value, index);
13946         }
13947         catch (err) {
13948             this.destination.error(err);
13949         }
13950         this.seed = result;
13951         this.destination.next(result);
13952     };
13953     return ScanSubscriber;
13954 }(Subscriber_1.Subscriber));
13955
13956 },{"../Subscriber":39}],142:[function(require,module,exports){
13957 "use strict";
13958 var __extends = (this && this.__extends) || (function () {
13959     var extendStatics = function (d, b) {
13960         extendStatics = Object.setPrototypeOf ||
13961             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13962             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13963         return extendStatics(d, b);
13964     }
13965     return function (d, b) {
13966         extendStatics(d, b);
13967         function __() { this.constructor = d; }
13968         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13969     };
13970 })();
13971 Object.defineProperty(exports, "__esModule", { value: true });
13972 var Subscriber_1 = require("../Subscriber");
13973 var tryCatch_1 = require("../util/tryCatch");
13974 var errorObject_1 = require("../util/errorObject");
13975 function sequenceEqual(compareTo, comparor) {
13976     return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparor)); };
13977 }
13978 exports.sequenceEqual = sequenceEqual;
13979 var SequenceEqualOperator = (function () {
13980     function SequenceEqualOperator(compareTo, comparor) {
13981         this.compareTo = compareTo;
13982         this.comparor = comparor;
13983     }
13984     SequenceEqualOperator.prototype.call = function (subscriber, source) {
13985         return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor));
13986     };
13987     return SequenceEqualOperator;
13988 }());
13989 exports.SequenceEqualOperator = SequenceEqualOperator;
13990 var SequenceEqualSubscriber = (function (_super) {
13991     __extends(SequenceEqualSubscriber, _super);
13992     function SequenceEqualSubscriber(destination, compareTo, comparor) {
13993         var _this = _super.call(this, destination) || this;
13994         _this.compareTo = compareTo;
13995         _this.comparor = comparor;
13996         _this._a = [];
13997         _this._b = [];
13998         _this._oneComplete = false;
13999         _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this)));
14000         return _this;
14001     }
14002     SequenceEqualSubscriber.prototype._next = function (value) {
14003         if (this._oneComplete && this._b.length === 0) {
14004             this.emit(false);
14005         }
14006         else {
14007             this._a.push(value);
14008             this.checkValues();
14009         }
14010     };
14011     SequenceEqualSubscriber.prototype._complete = function () {
14012         if (this._oneComplete) {
14013             this.emit(this._a.length === 0 && this._b.length === 0);
14014         }
14015         else {
14016             this._oneComplete = true;
14017         }
14018         this.unsubscribe();
14019     };
14020     SequenceEqualSubscriber.prototype.checkValues = function () {
14021         var _c = this, _a = _c._a, _b = _c._b, comparor = _c.comparor;
14022         while (_a.length > 0 && _b.length > 0) {
14023             var a = _a.shift();
14024             var b = _b.shift();
14025             var areEqual = false;
14026             if (comparor) {
14027                 areEqual = tryCatch_1.tryCatch(comparor)(a, b);
14028                 if (areEqual === errorObject_1.errorObject) {
14029                     this.destination.error(errorObject_1.errorObject.e);
14030                 }
14031             }
14032             else {
14033                 areEqual = a === b;
14034             }
14035             if (!areEqual) {
14036                 this.emit(false);
14037             }
14038         }
14039     };
14040     SequenceEqualSubscriber.prototype.emit = function (value) {
14041         var destination = this.destination;
14042         destination.next(value);
14043         destination.complete();
14044     };
14045     SequenceEqualSubscriber.prototype.nextB = function (value) {
14046         if (this._oneComplete && this._a.length === 0) {
14047             this.emit(false);
14048         }
14049         else {
14050             this._b.push(value);
14051             this.checkValues();
14052         }
14053     };
14054     SequenceEqualSubscriber.prototype.completeB = function () {
14055         if (this._oneComplete) {
14056             this.emit(this._a.length === 0 && this._b.length === 0);
14057         }
14058         else {
14059             this._oneComplete = true;
14060         }
14061     };
14062     return SequenceEqualSubscriber;
14063 }(Subscriber_1.Subscriber));
14064 exports.SequenceEqualSubscriber = SequenceEqualSubscriber;
14065 var SequenceEqualCompareToSubscriber = (function (_super) {
14066     __extends(SequenceEqualCompareToSubscriber, _super);
14067     function SequenceEqualCompareToSubscriber(destination, parent) {
14068         var _this = _super.call(this, destination) || this;
14069         _this.parent = parent;
14070         return _this;
14071     }
14072     SequenceEqualCompareToSubscriber.prototype._next = function (value) {
14073         this.parent.nextB(value);
14074     };
14075     SequenceEqualCompareToSubscriber.prototype._error = function (err) {
14076         this.parent.error(err);
14077         this.unsubscribe();
14078     };
14079     SequenceEqualCompareToSubscriber.prototype._complete = function () {
14080         this.parent.completeB();
14081         this.unsubscribe();
14082     };
14083     return SequenceEqualCompareToSubscriber;
14084 }(Subscriber_1.Subscriber));
14085
14086 },{"../Subscriber":39,"../util/errorObject":200,"../util/tryCatch":224}],143:[function(require,module,exports){
14087 "use strict";
14088 Object.defineProperty(exports, "__esModule", { value: true });
14089 var multicast_1 = require("./multicast");
14090 var refCount_1 = require("./refCount");
14091 var Subject_1 = require("../Subject");
14092 function shareSubjectFactory() {
14093     return new Subject_1.Subject();
14094 }
14095 function share() {
14096     return function (source) { return refCount_1.refCount()(multicast_1.multicast(shareSubjectFactory)(source)); };
14097 }
14098 exports.share = share;
14099
14100 },{"../Subject":37,"./multicast":122,"./refCount":134}],144:[function(require,module,exports){
14101 "use strict";
14102 Object.defineProperty(exports, "__esModule", { value: true });
14103 var ReplaySubject_1 = require("../ReplaySubject");
14104 function shareReplay(bufferSize, windowTime, scheduler) {
14105     if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
14106     if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
14107     return function (source) { return source.lift(shareReplayOperator(bufferSize, windowTime, scheduler)); };
14108 }
14109 exports.shareReplay = shareReplay;
14110 function shareReplayOperator(bufferSize, windowTime, scheduler) {
14111     var subject;
14112     var refCount = 0;
14113     var subscription;
14114     var hasError = false;
14115     var isComplete = false;
14116     return function shareReplayOperation(source) {
14117         refCount++;
14118         if (!subject || hasError) {
14119             hasError = false;
14120             subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
14121             subscription = source.subscribe({
14122                 next: function (value) { subject.next(value); },
14123                 error: function (err) {
14124                     hasError = true;
14125                     subject.error(err);
14126                 },
14127                 complete: function () {
14128                     isComplete = true;
14129                     subject.complete();
14130                 },
14131             });
14132         }
14133         var innerSub = subject.subscribe(this);
14134         return function () {
14135             refCount--;
14136             innerSub.unsubscribe();
14137             if (subscription && refCount === 0 && isComplete) {
14138                 subscription.unsubscribe();
14139             }
14140         };
14141     };
14142 }
14143
14144 },{"../ReplaySubject":35}],145:[function(require,module,exports){
14145 "use strict";
14146 var __extends = (this && this.__extends) || (function () {
14147     var extendStatics = function (d, b) {
14148         extendStatics = Object.setPrototypeOf ||
14149             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14150             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14151         return extendStatics(d, b);
14152     }
14153     return function (d, b) {
14154         extendStatics(d, b);
14155         function __() { this.constructor = d; }
14156         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14157     };
14158 })();
14159 Object.defineProperty(exports, "__esModule", { value: true });
14160 var Subscriber_1 = require("../Subscriber");
14161 var EmptyError_1 = require("../util/EmptyError");
14162 function single(predicate) {
14163     return function (source) { return source.lift(new SingleOperator(predicate, source)); };
14164 }
14165 exports.single = single;
14166 var SingleOperator = (function () {
14167     function SingleOperator(predicate, source) {
14168         this.predicate = predicate;
14169         this.source = source;
14170     }
14171     SingleOperator.prototype.call = function (subscriber, source) {
14172         return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));
14173     };
14174     return SingleOperator;
14175 }());
14176 var SingleSubscriber = (function (_super) {
14177     __extends(SingleSubscriber, _super);
14178     function SingleSubscriber(destination, predicate, source) {
14179         var _this = _super.call(this, destination) || this;
14180         _this.predicate = predicate;
14181         _this.source = source;
14182         _this.seenValue = false;
14183         _this.index = 0;
14184         return _this;
14185     }
14186     SingleSubscriber.prototype.applySingleValue = function (value) {
14187         if (this.seenValue) {
14188             this.destination.error('Sequence contains more than one element');
14189         }
14190         else {
14191             this.seenValue = true;
14192             this.singleValue = value;
14193         }
14194     };
14195     SingleSubscriber.prototype._next = function (value) {
14196         var index = this.index++;
14197         if (this.predicate) {
14198             this.tryNext(value, index);
14199         }
14200         else {
14201             this.applySingleValue(value);
14202         }
14203     };
14204     SingleSubscriber.prototype.tryNext = function (value, index) {
14205         try {
14206             if (this.predicate(value, index, this.source)) {
14207                 this.applySingleValue(value);
14208             }
14209         }
14210         catch (err) {
14211             this.destination.error(err);
14212         }
14213     };
14214     SingleSubscriber.prototype._complete = function () {
14215         var destination = this.destination;
14216         if (this.index > 0) {
14217             destination.next(this.seenValue ? this.singleValue : undefined);
14218             destination.complete();
14219         }
14220         else {
14221             destination.error(new EmptyError_1.EmptyError);
14222         }
14223     };
14224     return SingleSubscriber;
14225 }(Subscriber_1.Subscriber));
14226
14227 },{"../Subscriber":39,"../util/EmptyError":194}],146:[function(require,module,exports){
14228 "use strict";
14229 var __extends = (this && this.__extends) || (function () {
14230     var extendStatics = function (d, b) {
14231         extendStatics = Object.setPrototypeOf ||
14232             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14233             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14234         return extendStatics(d, b);
14235     }
14236     return function (d, b) {
14237         extendStatics(d, b);
14238         function __() { this.constructor = d; }
14239         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14240     };
14241 })();
14242 Object.defineProperty(exports, "__esModule", { value: true });
14243 var Subscriber_1 = require("../Subscriber");
14244 function skip(count) {
14245     return function (source) { return source.lift(new SkipOperator(count)); };
14246 }
14247 exports.skip = skip;
14248 var SkipOperator = (function () {
14249     function SkipOperator(total) {
14250         this.total = total;
14251     }
14252     SkipOperator.prototype.call = function (subscriber, source) {
14253         return source.subscribe(new SkipSubscriber(subscriber, this.total));
14254     };
14255     return SkipOperator;
14256 }());
14257 var SkipSubscriber = (function (_super) {
14258     __extends(SkipSubscriber, _super);
14259     function SkipSubscriber(destination, total) {
14260         var _this = _super.call(this, destination) || this;
14261         _this.total = total;
14262         _this.count = 0;
14263         return _this;
14264     }
14265     SkipSubscriber.prototype._next = function (x) {
14266         if (++this.count > this.total) {
14267             this.destination.next(x);
14268         }
14269     };
14270     return SkipSubscriber;
14271 }(Subscriber_1.Subscriber));
14272
14273 },{"../Subscriber":39}],147:[function(require,module,exports){
14274 "use strict";
14275 var __extends = (this && this.__extends) || (function () {
14276     var extendStatics = function (d, b) {
14277         extendStatics = Object.setPrototypeOf ||
14278             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14279             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14280         return extendStatics(d, b);
14281     }
14282     return function (d, b) {
14283         extendStatics(d, b);
14284         function __() { this.constructor = d; }
14285         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14286     };
14287 })();
14288 Object.defineProperty(exports, "__esModule", { value: true });
14289 var Subscriber_1 = require("../Subscriber");
14290 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
14291 function skipLast(count) {
14292     return function (source) { return source.lift(new SkipLastOperator(count)); };
14293 }
14294 exports.skipLast = skipLast;
14295 var SkipLastOperator = (function () {
14296     function SkipLastOperator(_skipCount) {
14297         this._skipCount = _skipCount;
14298         if (this._skipCount < 0) {
14299             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
14300         }
14301     }
14302     SkipLastOperator.prototype.call = function (subscriber, source) {
14303         if (this._skipCount === 0) {
14304             return source.subscribe(new Subscriber_1.Subscriber(subscriber));
14305         }
14306         else {
14307             return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));
14308         }
14309     };
14310     return SkipLastOperator;
14311 }());
14312 var SkipLastSubscriber = (function (_super) {
14313     __extends(SkipLastSubscriber, _super);
14314     function SkipLastSubscriber(destination, _skipCount) {
14315         var _this = _super.call(this, destination) || this;
14316         _this._skipCount = _skipCount;
14317         _this._count = 0;
14318         _this._ring = new Array(_skipCount);
14319         return _this;
14320     }
14321     SkipLastSubscriber.prototype._next = function (value) {
14322         var skipCount = this._skipCount;
14323         var count = this._count++;
14324         if (count < skipCount) {
14325             this._ring[count] = value;
14326         }
14327         else {
14328             var currentIndex = count % skipCount;
14329             var ring = this._ring;
14330             var oldValue = ring[currentIndex];
14331             ring[currentIndex] = value;
14332             this.destination.next(oldValue);
14333         }
14334     };
14335     return SkipLastSubscriber;
14336 }(Subscriber_1.Subscriber));
14337
14338 },{"../Subscriber":39,"../util/ArgumentOutOfRangeError":193}],148:[function(require,module,exports){
14339 "use strict";
14340 var __extends = (this && this.__extends) || (function () {
14341     var extendStatics = function (d, b) {
14342         extendStatics = Object.setPrototypeOf ||
14343             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14344             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14345         return extendStatics(d, b);
14346     }
14347     return function (d, b) {
14348         extendStatics(d, b);
14349         function __() { this.constructor = d; }
14350         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14351     };
14352 })();
14353 Object.defineProperty(exports, "__esModule", { value: true });
14354 var OuterSubscriber_1 = require("../OuterSubscriber");
14355 var InnerSubscriber_1 = require("../InnerSubscriber");
14356 var subscribeToResult_1 = require("../util/subscribeToResult");
14357 function skipUntil(notifier) {
14358     return function (source) { return source.lift(new SkipUntilOperator(notifier)); };
14359 }
14360 exports.skipUntil = skipUntil;
14361 var SkipUntilOperator = (function () {
14362     function SkipUntilOperator(notifier) {
14363         this.notifier = notifier;
14364     }
14365     SkipUntilOperator.prototype.call = function (destination, source) {
14366         return source.subscribe(new SkipUntilSubscriber(destination, this.notifier));
14367     };
14368     return SkipUntilOperator;
14369 }());
14370 var SkipUntilSubscriber = (function (_super) {
14371     __extends(SkipUntilSubscriber, _super);
14372     function SkipUntilSubscriber(destination, notifier) {
14373         var _this = _super.call(this, destination) || this;
14374         _this.hasValue = false;
14375         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(_this, undefined, undefined);
14376         _this.add(innerSubscriber);
14377         _this.innerSubscription = innerSubscriber;
14378         subscribeToResult_1.subscribeToResult(_this, notifier, undefined, undefined, innerSubscriber);
14379         return _this;
14380     }
14381     SkipUntilSubscriber.prototype._next = function (value) {
14382         if (this.hasValue) {
14383             _super.prototype._next.call(this, value);
14384         }
14385     };
14386     SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14387         this.hasValue = true;
14388         if (this.innerSubscription) {
14389             this.innerSubscription.unsubscribe();
14390         }
14391     };
14392     SkipUntilSubscriber.prototype.notifyComplete = function () {
14393     };
14394     return SkipUntilSubscriber;
14395 }(OuterSubscriber_1.OuterSubscriber));
14396
14397 },{"../InnerSubscriber":30,"../OuterSubscriber":34,"../util/subscribeToResult":222}],149:[function(require,module,exports){
14398 "use strict";
14399 var __extends = (this && this.__extends) || (function () {
14400     var extendStatics = function (d, b) {
14401         extendStatics = Object.setPrototypeOf ||
14402             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14403             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14404         return extendStatics(d, b);
14405     }
14406     return function (d, b) {
14407         extendStatics(d, b);
14408         function __() { this.constructor = d; }
14409         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14410     };
14411 })();
14412 Object.defineProperty(exports, "__esModule", { value: true });
14413 var Subscriber_1 = require("../Subscriber");
14414 function skipWhile(predicate) {
14415     return function (source) { return source.lift(new SkipWhileOperator(predicate)); };
14416 }
14417 exports.skipWhile = skipWhile;
14418 var SkipWhileOperator = (function () {
14419     function SkipWhileOperator(predicate) {
14420         this.predicate = predicate;
14421     }
14422     SkipWhileOperator.prototype.call = function (subscriber, source) {
14423         return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
14424     };
14425     return SkipWhileOperator;
14426 }());
14427 var SkipWhileSubscriber = (function (_super) {
14428     __extends(SkipWhileSubscriber, _super);
14429     function SkipWhileSubscriber(destination, predicate) {
14430         var _this = _super.call(this, destination) || this;
14431         _this.predicate = predicate;
14432         _this.skipping = true;
14433         _this.index = 0;
14434         return _this;
14435     }
14436     SkipWhileSubscriber.prototype._next = function (value) {
14437         var destination = this.destination;
14438         if (this.skipping) {
14439             this.tryCallPredicate(value);
14440         }
14441         if (!this.skipping) {
14442             destination.next(value);
14443         }
14444     };
14445     SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
14446         try {
14447             var result = this.predicate(value, this.index++);
14448             this.skipping = Boolean(result);
14449         }
14450         catch (err) {
14451             this.destination.error(err);
14452         }
14453     };
14454     return SkipWhileSubscriber;
14455 }(Subscriber_1.Subscriber));
14456
14457 },{"../Subscriber":39}],150:[function(require,module,exports){
14458 "use strict";
14459 Object.defineProperty(exports, "__esModule", { value: true });
14460 var fromArray_1 = require("../observable/fromArray");
14461 var scalar_1 = require("../observable/scalar");
14462 var empty_1 = require("../observable/empty");
14463 var concat_1 = require("../observable/concat");
14464 var isScheduler_1 = require("../util/isScheduler");
14465 function startWith() {
14466     var array = [];
14467     for (var _i = 0; _i < arguments.length; _i++) {
14468         array[_i] = arguments[_i];
14469     }
14470     return function (source) {
14471         var scheduler = array[array.length - 1];
14472         if (isScheduler_1.isScheduler(scheduler)) {
14473             array.pop();
14474         }
14475         else {
14476             scheduler = null;
14477         }
14478         var len = array.length;
14479         if (len === 1 && !scheduler) {
14480             return concat_1.concat(scalar_1.scalar(array[0]), source);
14481         }
14482         else if (len > 0) {
14483             return concat_1.concat(fromArray_1.fromArray(array, scheduler), source);
14484         }
14485         else {
14486             return concat_1.concat(empty_1.empty(scheduler), source);
14487         }
14488     };
14489 }
14490 exports.startWith = startWith;
14491
14492 },{"../observable/concat":47,"../observable/empty":49,"../observable/fromArray":52,"../observable/scalar":68,"../util/isScheduler":213}],151:[function(require,module,exports){
14493 "use strict";
14494 Object.defineProperty(exports, "__esModule", { value: true });
14495 var SubscribeOnObservable_1 = require("../observable/SubscribeOnObservable");
14496 function subscribeOn(scheduler, delay) {
14497     if (delay === void 0) { delay = 0; }
14498     return function subscribeOnOperatorFunction(source) {
14499         return source.lift(new SubscribeOnOperator(scheduler, delay));
14500     };
14501 }
14502 exports.subscribeOn = subscribeOn;
14503 var SubscribeOnOperator = (function () {
14504     function SubscribeOnOperator(scheduler, delay) {
14505         this.scheduler = scheduler;
14506         this.delay = delay;
14507     }
14508     SubscribeOnOperator.prototype.call = function (subscriber, source) {
14509         return new SubscribeOnObservable_1.SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber);
14510     };
14511     return SubscribeOnOperator;
14512 }());
14513
14514 },{"../observable/SubscribeOnObservable":43}],152:[function(require,module,exports){
14515 "use strict";
14516 Object.defineProperty(exports, "__esModule", { value: true });
14517 var switchMap_1 = require("./switchMap");
14518 var identity_1 = require("../util/identity");
14519 function switchAll() {
14520     return switchMap_1.switchMap(identity_1.identity);
14521 }
14522 exports.switchAll = switchAll;
14523
14524 },{"../util/identity":202,"./switchMap":153}],153:[function(require,module,exports){
14525 "use strict";
14526 var __extends = (this && this.__extends) || (function () {
14527     var extendStatics = function (d, b) {
14528         extendStatics = Object.setPrototypeOf ||
14529             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14530             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14531         return extendStatics(d, b);
14532     }
14533     return function (d, b) {
14534         extendStatics(d, b);
14535         function __() { this.constructor = d; }
14536         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14537     };
14538 })();
14539 Object.defineProperty(exports, "__esModule", { value: true });
14540 var OuterSubscriber_1 = require("../OuterSubscriber");
14541 var InnerSubscriber_1 = require("../InnerSubscriber");
14542 var subscribeToResult_1 = require("../util/subscribeToResult");
14543 var map_1 = require("./map");
14544 var from_1 = require("../observable/from");
14545 function switchMap(project, resultSelector) {
14546     if (typeof resultSelector === 'function') {
14547         return function (source) { return source.pipe(switchMap(function (a, i) { return from_1.from(project(a, i)).pipe(map_1.map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };
14548     }
14549     return function (source) { return source.lift(new SwitchMapOperator(project)); };
14550 }
14551 exports.switchMap = switchMap;
14552 var SwitchMapOperator = (function () {
14553     function SwitchMapOperator(project) {
14554         this.project = project;
14555     }
14556     SwitchMapOperator.prototype.call = function (subscriber, source) {
14557         return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));
14558     };
14559     return SwitchMapOperator;
14560 }());
14561 var SwitchMapSubscriber = (function (_super) {
14562     __extends(SwitchMapSubscriber, _super);
14563     function SwitchMapSubscriber(destination, project) {
14564         var _this = _super.call(this, destination) || this;
14565         _this.project = project;
14566         _this.index = 0;
14567         return _this;
14568     }
14569     SwitchMapSubscriber.prototype._next = function (value) {
14570         var result;
14571         var index = this.index++;
14572         try {
14573             result = this.project(value, index);
14574         }
14575         catch (error) {
14576             this.destination.error(error);
14577             return;
14578         }
14579         this._innerSub(result, value, index);
14580     };
14581     SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
14582         var innerSubscription = this.innerSubscription;
14583         if (innerSubscription) {
14584             innerSubscription.unsubscribe();
14585         }
14586         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
14587         var destination = this.destination;
14588         destination.add(innerSubscriber);
14589         this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index, innerSubscriber);
14590     };
14591     SwitchMapSubscriber.prototype._complete = function () {
14592         var innerSubscription = this.innerSubscription;
14593         if (!innerSubscription || innerSubscription.closed) {
14594             _super.prototype._complete.call(this);
14595         }
14596         this.unsubscribe();
14597     };
14598     SwitchMapSubscriber.prototype._unsubscribe = function () {
14599         this.innerSubscription = null;
14600     };
14601     SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
14602         var destination = this.destination;
14603         destination.remove(innerSub);
14604         this.innerSubscription = null;
14605         if (this.isStopped) {
14606             _super.prototype._complete.call(this);
14607         }
14608     };
14609     SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14610         this.destination.next(innerValue);
14611     };
14612     return SwitchMapSubscriber;
14613 }(OuterSubscriber_1.OuterSubscriber));
14614
14615 },{"../InnerSubscriber":30,"../OuterSubscriber":34,"../observable/from":51,"../util/subscribeToResult":222,"./map":112}],154:[function(require,module,exports){
14616 "use strict";
14617 Object.defineProperty(exports, "__esModule", { value: true });
14618 var switchMap_1 = require("./switchMap");
14619 function switchMapTo(innerObservable, resultSelector) {
14620     return resultSelector ? switchMap_1.switchMap(function () { return innerObservable; }, resultSelector) : switchMap_1.switchMap(function () { return innerObservable; });
14621 }
14622 exports.switchMapTo = switchMapTo;
14623
14624 },{"./switchMap":153}],155:[function(require,module,exports){
14625 "use strict";
14626 var __extends = (this && this.__extends) || (function () {
14627     var extendStatics = function (d, b) {
14628         extendStatics = Object.setPrototypeOf ||
14629             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14630             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14631         return extendStatics(d, b);
14632     }
14633     return function (d, b) {
14634         extendStatics(d, b);
14635         function __() { this.constructor = d; }
14636         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14637     };
14638 })();
14639 Object.defineProperty(exports, "__esModule", { value: true });
14640 var Subscriber_1 = require("../Subscriber");
14641 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
14642 var empty_1 = require("../observable/empty");
14643 function take(count) {
14644     return function (source) {
14645         if (count === 0) {
14646             return empty_1.empty();
14647         }
14648         else {
14649             return source.lift(new TakeOperator(count));
14650         }
14651     };
14652 }
14653 exports.take = take;
14654 var TakeOperator = (function () {
14655     function TakeOperator(total) {
14656         this.total = total;
14657         if (this.total < 0) {
14658             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
14659         }
14660     }
14661     TakeOperator.prototype.call = function (subscriber, source) {
14662         return source.subscribe(new TakeSubscriber(subscriber, this.total));
14663     };
14664     return TakeOperator;
14665 }());
14666 var TakeSubscriber = (function (_super) {
14667     __extends(TakeSubscriber, _super);
14668     function TakeSubscriber(destination, total) {
14669         var _this = _super.call(this, destination) || this;
14670         _this.total = total;
14671         _this.count = 0;
14672         return _this;
14673     }
14674     TakeSubscriber.prototype._next = function (value) {
14675         var total = this.total;
14676         var count = ++this.count;
14677         if (count <= total) {
14678             this.destination.next(value);
14679             if (count === total) {
14680                 this.destination.complete();
14681                 this.unsubscribe();
14682             }
14683         }
14684     };
14685     return TakeSubscriber;
14686 }(Subscriber_1.Subscriber));
14687
14688 },{"../Subscriber":39,"../observable/empty":49,"../util/ArgumentOutOfRangeError":193}],156:[function(require,module,exports){
14689 "use strict";
14690 var __extends = (this && this.__extends) || (function () {
14691     var extendStatics = function (d, b) {
14692         extendStatics = Object.setPrototypeOf ||
14693             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14694             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14695         return extendStatics(d, b);
14696     }
14697     return function (d, b) {
14698         extendStatics(d, b);
14699         function __() { this.constructor = d; }
14700         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14701     };
14702 })();
14703 Object.defineProperty(exports, "__esModule", { value: true });
14704 var Subscriber_1 = require("../Subscriber");
14705 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
14706 var empty_1 = require("../observable/empty");
14707 function takeLast(count) {
14708     return function takeLastOperatorFunction(source) {
14709         if (count === 0) {
14710             return empty_1.empty();
14711         }
14712         else {
14713             return source.lift(new TakeLastOperator(count));
14714         }
14715     };
14716 }
14717 exports.takeLast = takeLast;
14718 var TakeLastOperator = (function () {
14719     function TakeLastOperator(total) {
14720         this.total = total;
14721         if (this.total < 0) {
14722             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
14723         }
14724     }
14725     TakeLastOperator.prototype.call = function (subscriber, source) {
14726         return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
14727     };
14728     return TakeLastOperator;
14729 }());
14730 var TakeLastSubscriber = (function (_super) {
14731     __extends(TakeLastSubscriber, _super);
14732     function TakeLastSubscriber(destination, total) {
14733         var _this = _super.call(this, destination) || this;
14734         _this.total = total;
14735         _this.ring = new Array();
14736         _this.count = 0;
14737         return _this;
14738     }
14739     TakeLastSubscriber.prototype._next = function (value) {
14740         var ring = this.ring;
14741         var total = this.total;
14742         var count = this.count++;
14743         if (ring.length < total) {
14744             ring.push(value);
14745         }
14746         else {
14747             var index = count % total;
14748             ring[index] = value;
14749         }
14750     };
14751     TakeLastSubscriber.prototype._complete = function () {
14752         var destination = this.destination;
14753         var count = this.count;
14754         if (count > 0) {
14755             var total = this.count >= this.total ? this.total : this.count;
14756             var ring = this.ring;
14757             for (var i = 0; i < total; i++) {
14758                 var idx = (count++) % total;
14759                 destination.next(ring[idx]);
14760             }
14761         }
14762         destination.complete();
14763     };
14764     return TakeLastSubscriber;
14765 }(Subscriber_1.Subscriber));
14766
14767 },{"../Subscriber":39,"../observable/empty":49,"../util/ArgumentOutOfRangeError":193}],157:[function(require,module,exports){
14768 "use strict";
14769 var __extends = (this && this.__extends) || (function () {
14770     var extendStatics = function (d, b) {
14771         extendStatics = Object.setPrototypeOf ||
14772             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14773             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14774         return extendStatics(d, b);
14775     }
14776     return function (d, b) {
14777         extendStatics(d, b);
14778         function __() { this.constructor = d; }
14779         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14780     };
14781 })();
14782 Object.defineProperty(exports, "__esModule", { value: true });
14783 var OuterSubscriber_1 = require("../OuterSubscriber");
14784 var subscribeToResult_1 = require("../util/subscribeToResult");
14785 function takeUntil(notifier) {
14786     return function (source) { return source.lift(new TakeUntilOperator(notifier)); };
14787 }
14788 exports.takeUntil = takeUntil;
14789 var TakeUntilOperator = (function () {
14790     function TakeUntilOperator(notifier) {
14791         this.notifier = notifier;
14792     }
14793     TakeUntilOperator.prototype.call = function (subscriber, source) {
14794         var takeUntilSubscriber = new TakeUntilSubscriber(subscriber);
14795         var notifierSubscription = subscribeToResult_1.subscribeToResult(takeUntilSubscriber, this.notifier);
14796         if (notifierSubscription && !takeUntilSubscriber.seenValue) {
14797             takeUntilSubscriber.add(notifierSubscription);
14798             return source.subscribe(takeUntilSubscriber);
14799         }
14800         return takeUntilSubscriber;
14801     };
14802     return TakeUntilOperator;
14803 }());
14804 var TakeUntilSubscriber = (function (_super) {
14805     __extends(TakeUntilSubscriber, _super);
14806     function TakeUntilSubscriber(destination) {
14807         var _this = _super.call(this, destination) || this;
14808         _this.seenValue = false;
14809         return _this;
14810     }
14811     TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14812         this.seenValue = true;
14813         this.complete();
14814     };
14815     TakeUntilSubscriber.prototype.notifyComplete = function () {
14816     };
14817     return TakeUntilSubscriber;
14818 }(OuterSubscriber_1.OuterSubscriber));
14819
14820 },{"../OuterSubscriber":34,"../util/subscribeToResult":222}],158:[function(require,module,exports){
14821 "use strict";
14822 var __extends = (this && this.__extends) || (function () {
14823     var extendStatics = function (d, b) {
14824         extendStatics = Object.setPrototypeOf ||
14825             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14826             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14827         return extendStatics(d, b);
14828     }
14829     return function (d, b) {
14830         extendStatics(d, b);
14831         function __() { this.constructor = d; }
14832         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14833     };
14834 })();
14835 Object.defineProperty(exports, "__esModule", { value: true });
14836 var Subscriber_1 = require("../Subscriber");
14837 function takeWhile(predicate) {
14838     return function (source) { return source.lift(new TakeWhileOperator(predicate)); };
14839 }
14840 exports.takeWhile = takeWhile;
14841 var TakeWhileOperator = (function () {
14842     function TakeWhileOperator(predicate) {
14843         this.predicate = predicate;
14844     }
14845     TakeWhileOperator.prototype.call = function (subscriber, source) {
14846         return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate));
14847     };
14848     return TakeWhileOperator;
14849 }());
14850 var TakeWhileSubscriber = (function (_super) {
14851     __extends(TakeWhileSubscriber, _super);
14852     function TakeWhileSubscriber(destination, predicate) {
14853         var _this = _super.call(this, destination) || this;
14854         _this.predicate = predicate;
14855         _this.index = 0;
14856         return _this;
14857     }
14858     TakeWhileSubscriber.prototype._next = function (value) {
14859         var destination = this.destination;
14860         var result;
14861         try {
14862             result = this.predicate(value, this.index++);
14863         }
14864         catch (err) {
14865             destination.error(err);
14866             return;
14867         }
14868         this.nextOrComplete(value, result);
14869     };
14870     TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
14871         var destination = this.destination;
14872         if (Boolean(predicateResult)) {
14873             destination.next(value);
14874         }
14875         else {
14876             destination.complete();
14877         }
14878     };
14879     return TakeWhileSubscriber;
14880 }(Subscriber_1.Subscriber));
14881
14882 },{"../Subscriber":39}],159:[function(require,module,exports){
14883 "use strict";
14884 var __extends = (this && this.__extends) || (function () {
14885     var extendStatics = function (d, b) {
14886         extendStatics = Object.setPrototypeOf ||
14887             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14888             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14889         return extendStatics(d, b);
14890     }
14891     return function (d, b) {
14892         extendStatics(d, b);
14893         function __() { this.constructor = d; }
14894         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14895     };
14896 })();
14897 Object.defineProperty(exports, "__esModule", { value: true });
14898 var Subscriber_1 = require("../Subscriber");
14899 var noop_1 = require("../util/noop");
14900 var isFunction_1 = require("../util/isFunction");
14901 function tap(nextOrObserver, error, complete) {
14902     return function tapOperatorFunction(source) {
14903         return source.lift(new DoOperator(nextOrObserver, error, complete));
14904     };
14905 }
14906 exports.tap = tap;
14907 var DoOperator = (function () {
14908     function DoOperator(nextOrObserver, error, complete) {
14909         this.nextOrObserver = nextOrObserver;
14910         this.error = error;
14911         this.complete = complete;
14912     }
14913     DoOperator.prototype.call = function (subscriber, source) {
14914         return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
14915     };
14916     return DoOperator;
14917 }());
14918 var TapSubscriber = (function (_super) {
14919     __extends(TapSubscriber, _super);
14920     function TapSubscriber(destination, observerOrNext, error, complete) {
14921         var _this = _super.call(this, destination) || this;
14922         _this._tapNext = noop_1.noop;
14923         _this._tapError = noop_1.noop;
14924         _this._tapComplete = noop_1.noop;
14925         _this._tapError = error || noop_1.noop;
14926         _this._tapComplete = complete || noop_1.noop;
14927         if (isFunction_1.isFunction(observerOrNext)) {
14928             _this._context = _this;
14929             _this._tapNext = observerOrNext;
14930         }
14931         else if (observerOrNext) {
14932             _this._context = observerOrNext;
14933             _this._tapNext = observerOrNext.next || noop_1.noop;
14934             _this._tapError = observerOrNext.error || noop_1.noop;
14935             _this._tapComplete = observerOrNext.complete || noop_1.noop;
14936         }
14937         return _this;
14938     }
14939     TapSubscriber.prototype._next = function (value) {
14940         try {
14941             this._tapNext.call(this._context, value);
14942         }
14943         catch (err) {
14944             this.destination.error(err);
14945             return;
14946         }
14947         this.destination.next(value);
14948     };
14949     TapSubscriber.prototype._error = function (err) {
14950         try {
14951             this._tapError.call(this._context, err);
14952         }
14953         catch (err) {
14954             this.destination.error(err);
14955             return;
14956         }
14957         this.destination.error(err);
14958     };
14959     TapSubscriber.prototype._complete = function () {
14960         try {
14961             this._tapComplete.call(this._context);
14962         }
14963         catch (err) {
14964             this.destination.error(err);
14965             return;
14966         }
14967         return this.destination.complete();
14968     };
14969     return TapSubscriber;
14970 }(Subscriber_1.Subscriber));
14971
14972 },{"../Subscriber":39,"../util/isFunction":206,"../util/noop":214}],160:[function(require,module,exports){
14973 "use strict";
14974 var __extends = (this && this.__extends) || (function () {
14975     var extendStatics = function (d, b) {
14976         extendStatics = Object.setPrototypeOf ||
14977             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14978             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14979         return extendStatics(d, b);
14980     }
14981     return function (d, b) {
14982         extendStatics(d, b);
14983         function __() { this.constructor = d; }
14984         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14985     };
14986 })();
14987 Object.defineProperty(exports, "__esModule", { value: true });
14988 var OuterSubscriber_1 = require("../OuterSubscriber");
14989 var subscribeToResult_1 = require("../util/subscribeToResult");
14990 exports.defaultThrottleConfig = {
14991     leading: true,
14992     trailing: false
14993 };
14994 function throttle(durationSelector, config) {
14995     if (config === void 0) { config = exports.defaultThrottleConfig; }
14996     return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
14997 }
14998 exports.throttle = throttle;
14999 var ThrottleOperator = (function () {
15000     function ThrottleOperator(durationSelector, leading, trailing) {
15001         this.durationSelector = durationSelector;
15002         this.leading = leading;
15003         this.trailing = trailing;
15004     }
15005     ThrottleOperator.prototype.call = function (subscriber, source) {
15006         return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
15007     };
15008     return ThrottleOperator;
15009 }());
15010 var ThrottleSubscriber = (function (_super) {
15011     __extends(ThrottleSubscriber, _super);
15012     function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
15013         var _this = _super.call(this, destination) || this;
15014         _this.destination = destination;
15015         _this.durationSelector = durationSelector;
15016         _this._leading = _leading;
15017         _this._trailing = _trailing;
15018         _this._hasValue = false;
15019         return _this;
15020     }
15021     ThrottleSubscriber.prototype._next = function (value) {
15022         this._hasValue = true;
15023         this._sendValue = value;
15024         if (!this._throttled) {
15025             if (this._leading) {
15026                 this.send();
15027             }
15028             else {
15029                 this.throttle(value);
15030             }
15031         }
15032     };
15033     ThrottleSubscriber.prototype.send = function () {
15034         var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue;
15035         if (_hasValue) {
15036             this.destination.next(_sendValue);
15037             this.throttle(_sendValue);
15038         }
15039         this._hasValue = false;
15040         this._sendValue = null;
15041     };
15042     ThrottleSubscriber.prototype.throttle = function (value) {
15043         var duration = this.tryDurationSelector(value);
15044         if (duration) {
15045             this.add(this._throttled = subscribeToResult_1.subscribeToResult(this, duration));
15046         }
15047     };
15048     ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
15049         try {
15050             return this.durationSelector(value);
15051         }
15052         catch (err) {
15053             this.destination.error(err);
15054             return null;
15055         }
15056     };
15057     ThrottleSubscriber.prototype.throttlingDone = function () {
15058         var _a = this, _throttled = _a._throttled, _trailing = _a._trailing;
15059         if (_throttled) {
15060             _throttled.unsubscribe();
15061         }
15062         this._throttled = null;
15063         if (_trailing) {
15064             this.send();
15065         }
15066     };
15067     ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15068         this.throttlingDone();
15069     };
15070     ThrottleSubscriber.prototype.notifyComplete = function () {
15071         this.throttlingDone();
15072     };
15073     return ThrottleSubscriber;
15074 }(OuterSubscriber_1.OuterSubscriber));
15075
15076 },{"../OuterSubscriber":34,"../util/subscribeToResult":222}],161:[function(require,module,exports){
15077 "use strict";
15078 var __extends = (this && this.__extends) || (function () {
15079     var extendStatics = function (d, b) {
15080         extendStatics = Object.setPrototypeOf ||
15081             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15082             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15083         return extendStatics(d, b);
15084     }
15085     return function (d, b) {
15086         extendStatics(d, b);
15087         function __() { this.constructor = d; }
15088         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15089     };
15090 })();
15091 Object.defineProperty(exports, "__esModule", { value: true });
15092 var Subscriber_1 = require("../Subscriber");
15093 var async_1 = require("../scheduler/async");
15094 var throttle_1 = require("./throttle");
15095 function throttleTime(duration, scheduler, config) {
15096     if (scheduler === void 0) { scheduler = async_1.async; }
15097     if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
15098     return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };
15099 }
15100 exports.throttleTime = throttleTime;
15101 var ThrottleTimeOperator = (function () {
15102     function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
15103         this.duration = duration;
15104         this.scheduler = scheduler;
15105         this.leading = leading;
15106         this.trailing = trailing;
15107     }
15108     ThrottleTimeOperator.prototype.call = function (subscriber, source) {
15109         return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
15110     };
15111     return ThrottleTimeOperator;
15112 }());
15113 var ThrottleTimeSubscriber = (function (_super) {
15114     __extends(ThrottleTimeSubscriber, _super);
15115     function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
15116         var _this = _super.call(this, destination) || this;
15117         _this.duration = duration;
15118         _this.scheduler = scheduler;
15119         _this.leading = leading;
15120         _this.trailing = trailing;
15121         _this._hasTrailingValue = false;
15122         _this._trailingValue = null;
15123         return _this;
15124     }
15125     ThrottleTimeSubscriber.prototype._next = function (value) {
15126         if (this.throttled) {
15127             if (this.trailing) {
15128                 this._trailingValue = value;
15129                 this._hasTrailingValue = true;
15130             }
15131         }
15132         else {
15133             this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
15134             if (this.leading) {
15135                 this.destination.next(value);
15136             }
15137         }
15138     };
15139     ThrottleTimeSubscriber.prototype._complete = function () {
15140         if (this._hasTrailingValue) {
15141             this.destination.next(this._trailingValue);
15142             this.destination.complete();
15143         }
15144         else {
15145             this.destination.complete();
15146         }
15147     };
15148     ThrottleTimeSubscriber.prototype.clearThrottle = function () {
15149         var throttled = this.throttled;
15150         if (throttled) {
15151             if (this.trailing && this._hasTrailingValue) {
15152                 this.destination.next(this._trailingValue);
15153                 this._trailingValue = null;
15154                 this._hasTrailingValue = false;
15155             }
15156             throttled.unsubscribe();
15157             this.remove(throttled);
15158             this.throttled = null;
15159         }
15160     };
15161     return ThrottleTimeSubscriber;
15162 }(Subscriber_1.Subscriber));
15163 function dispatchNext(arg) {
15164     var subscriber = arg.subscriber;
15165     subscriber.clearThrottle();
15166 }
15167
15168 },{"../Subscriber":39,"../scheduler/async":188,"./throttle":160}],162:[function(require,module,exports){
15169 "use strict";
15170 Object.defineProperty(exports, "__esModule", { value: true });
15171 var tap_1 = require("./tap");
15172 var EmptyError_1 = require("../util/EmptyError");
15173 exports.throwIfEmpty = function (errorFactory) {
15174     if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
15175     return tap_1.tap({
15176         hasValue: false,
15177         next: function () { this.hasValue = true; },
15178         complete: function () {
15179             if (!this.hasValue) {
15180                 throw errorFactory();
15181             }
15182         }
15183     });
15184 };
15185 function defaultErrorFactory() {
15186     return new EmptyError_1.EmptyError();
15187 }
15188
15189 },{"../util/EmptyError":194,"./tap":159}],163:[function(require,module,exports){
15190 "use strict";
15191 Object.defineProperty(exports, "__esModule", { value: true });
15192 var async_1 = require("../scheduler/async");
15193 var scan_1 = require("./scan");
15194 var defer_1 = require("../observable/defer");
15195 var map_1 = require("./map");
15196 function timeInterval(scheduler) {
15197     if (scheduler === void 0) { scheduler = async_1.async; }
15198     return function (source) { return defer_1.defer(function () {
15199         return source.pipe(scan_1.scan(function (_a, value) {
15200             var current = _a.current;
15201             return ({ value: value, current: scheduler.now(), last: current });
15202         }, { current: scheduler.now(), value: undefined, last: undefined }), map_1.map(function (_a) {
15203             var current = _a.current, last = _a.last, value = _a.value;
15204             return new TimeInterval(value, current - last);
15205         }));
15206     }); };
15207 }
15208 exports.timeInterval = timeInterval;
15209 var TimeInterval = (function () {
15210     function TimeInterval(value, interval) {
15211         this.value = value;
15212         this.interval = interval;
15213     }
15214     return TimeInterval;
15215 }());
15216 exports.TimeInterval = TimeInterval;
15217
15218 },{"../observable/defer":48,"../scheduler/async":188,"./map":112,"./scan":141}],164:[function(require,module,exports){
15219 "use strict";
15220 Object.defineProperty(exports, "__esModule", { value: true });
15221 var async_1 = require("../scheduler/async");
15222 var TimeoutError_1 = require("../util/TimeoutError");
15223 var timeoutWith_1 = require("./timeoutWith");
15224 var throwError_1 = require("../observable/throwError");
15225 function timeout(due, scheduler) {
15226     if (scheduler === void 0) { scheduler = async_1.async; }
15227     return timeoutWith_1.timeoutWith(due, throwError_1.throwError(new TimeoutError_1.TimeoutError()), scheduler);
15228 }
15229 exports.timeout = timeout;
15230
15231 },{"../observable/throwError":69,"../scheduler/async":188,"../util/TimeoutError":197,"./timeoutWith":165}],165:[function(require,module,exports){
15232 "use strict";
15233 var __extends = (this && this.__extends) || (function () {
15234     var extendStatics = function (d, b) {
15235         extendStatics = Object.setPrototypeOf ||
15236             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15237             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15238         return extendStatics(d, b);
15239     }
15240     return function (d, b) {
15241         extendStatics(d, b);
15242         function __() { this.constructor = d; }
15243         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15244     };
15245 })();
15246 Object.defineProperty(exports, "__esModule", { value: true });
15247 var async_1 = require("../scheduler/async");
15248 var isDate_1 = require("../util/isDate");
15249 var OuterSubscriber_1 = require("../OuterSubscriber");
15250 var subscribeToResult_1 = require("../util/subscribeToResult");
15251 function timeoutWith(due, withObservable, scheduler) {
15252     if (scheduler === void 0) { scheduler = async_1.async; }
15253     return function (source) {
15254         var absoluteTimeout = isDate_1.isDate(due);
15255         var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
15256         return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
15257     };
15258 }
15259 exports.timeoutWith = timeoutWith;
15260 var TimeoutWithOperator = (function () {
15261     function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) {
15262         this.waitFor = waitFor;
15263         this.absoluteTimeout = absoluteTimeout;
15264         this.withObservable = withObservable;
15265         this.scheduler = scheduler;
15266     }
15267     TimeoutWithOperator.prototype.call = function (subscriber, source) {
15268         return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
15269     };
15270     return TimeoutWithOperator;
15271 }());
15272 var TimeoutWithSubscriber = (function (_super) {
15273     __extends(TimeoutWithSubscriber, _super);
15274     function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) {
15275         var _this = _super.call(this, destination) || this;
15276         _this.absoluteTimeout = absoluteTimeout;
15277         _this.waitFor = waitFor;
15278         _this.withObservable = withObservable;
15279         _this.scheduler = scheduler;
15280         _this.action = null;
15281         _this.scheduleTimeout();
15282         return _this;
15283     }
15284     TimeoutWithSubscriber.dispatchTimeout = function (subscriber) {
15285         var withObservable = subscriber.withObservable;
15286         subscriber._unsubscribeAndRecycle();
15287         subscriber.add(subscribeToResult_1.subscribeToResult(subscriber, withObservable));
15288     };
15289     TimeoutWithSubscriber.prototype.scheduleTimeout = function () {
15290         var action = this.action;
15291         if (action) {
15292             this.action = action.schedule(this, this.waitFor);
15293         }
15294         else {
15295             this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));
15296         }
15297     };
15298     TimeoutWithSubscriber.prototype._next = function (value) {
15299         if (!this.absoluteTimeout) {
15300             this.scheduleTimeout();
15301         }
15302         _super.prototype._next.call(this, value);
15303     };
15304     TimeoutWithSubscriber.prototype._unsubscribe = function () {
15305         this.action = null;
15306         this.scheduler = null;
15307         this.withObservable = null;
15308     };
15309     return TimeoutWithSubscriber;
15310 }(OuterSubscriber_1.OuterSubscriber));
15311
15312 },{"../OuterSubscriber":34,"../scheduler/async":188,"../util/isDate":205,"../util/subscribeToResult":222}],166:[function(require,module,exports){
15313 "use strict";
15314 Object.defineProperty(exports, "__esModule", { value: true });
15315 var async_1 = require("../scheduler/async");
15316 var map_1 = require("./map");
15317 function timestamp(scheduler) {
15318     if (scheduler === void 0) { scheduler = async_1.async; }
15319     return map_1.map(function (value) { return new Timestamp(value, scheduler.now()); });
15320 }
15321 exports.timestamp = timestamp;
15322 var Timestamp = (function () {
15323     function Timestamp(value, timestamp) {
15324         this.value = value;
15325         this.timestamp = timestamp;
15326     }
15327     return Timestamp;
15328 }());
15329 exports.Timestamp = Timestamp;
15330
15331 },{"../scheduler/async":188,"./map":112}],167:[function(require,module,exports){
15332 "use strict";
15333 Object.defineProperty(exports, "__esModule", { value: true });
15334 var reduce_1 = require("./reduce");
15335 function toArrayReducer(arr, item, index) {
15336     if (index === 0) {
15337         return [item];
15338     }
15339     arr.push(item);
15340     return arr;
15341 }
15342 function toArray() {
15343     return reduce_1.reduce(toArrayReducer, []);
15344 }
15345 exports.toArray = toArray;
15346
15347 },{"./reduce":133}],168:[function(require,module,exports){
15348 "use strict";
15349 var __extends = (this && this.__extends) || (function () {
15350     var extendStatics = function (d, b) {
15351         extendStatics = Object.setPrototypeOf ||
15352             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15353             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15354         return extendStatics(d, b);
15355     }
15356     return function (d, b) {
15357         extendStatics(d, b);
15358         function __() { this.constructor = d; }
15359         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15360     };
15361 })();
15362 Object.defineProperty(exports, "__esModule", { value: true });
15363 var Subject_1 = require("../Subject");
15364 var OuterSubscriber_1 = require("../OuterSubscriber");
15365 var subscribeToResult_1 = require("../util/subscribeToResult");
15366 function window(windowBoundaries) {
15367     return function windowOperatorFunction(source) {
15368         return source.lift(new WindowOperator(windowBoundaries));
15369     };
15370 }
15371 exports.window = window;
15372 var WindowOperator = (function () {
15373     function WindowOperator(windowBoundaries) {
15374         this.windowBoundaries = windowBoundaries;
15375     }
15376     WindowOperator.prototype.call = function (subscriber, source) {
15377         var windowSubscriber = new WindowSubscriber(subscriber);
15378         var sourceSubscription = source.subscribe(windowSubscriber);
15379         if (!sourceSubscription.closed) {
15380             windowSubscriber.add(subscribeToResult_1.subscribeToResult(windowSubscriber, this.windowBoundaries));
15381         }
15382         return sourceSubscription;
15383     };
15384     return WindowOperator;
15385 }());
15386 var WindowSubscriber = (function (_super) {
15387     __extends(WindowSubscriber, _super);
15388     function WindowSubscriber(destination) {
15389         var _this = _super.call(this, destination) || this;
15390         _this.window = new Subject_1.Subject();
15391         destination.next(_this.window);
15392         return _this;
15393     }
15394     WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15395         this.openWindow();
15396     };
15397     WindowSubscriber.prototype.notifyError = function (error, innerSub) {
15398         this._error(error);
15399     };
15400     WindowSubscriber.prototype.notifyComplete = function (innerSub) {
15401         this._complete();
15402     };
15403     WindowSubscriber.prototype._next = function (value) {
15404         this.window.next(value);
15405     };
15406     WindowSubscriber.prototype._error = function (err) {
15407         this.window.error(err);
15408         this.destination.error(err);
15409     };
15410     WindowSubscriber.prototype._complete = function () {
15411         this.window.complete();
15412         this.destination.complete();
15413     };
15414     WindowSubscriber.prototype._unsubscribe = function () {
15415         this.window = null;
15416     };
15417     WindowSubscriber.prototype.openWindow = function () {
15418         var prevWindow = this.window;
15419         if (prevWindow) {
15420             prevWindow.complete();
15421         }
15422         var destination = this.destination;
15423         var newWindow = this.window = new Subject_1.Subject();
15424         destination.next(newWindow);
15425     };
15426     return WindowSubscriber;
15427 }(OuterSubscriber_1.OuterSubscriber));
15428
15429 },{"../OuterSubscriber":34,"../Subject":37,"../util/subscribeToResult":222}],169:[function(require,module,exports){
15430 "use strict";
15431 var __extends = (this && this.__extends) || (function () {
15432     var extendStatics = function (d, b) {
15433         extendStatics = Object.setPrototypeOf ||
15434             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15435             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15436         return extendStatics(d, b);
15437     }
15438     return function (d, b) {
15439         extendStatics(d, b);
15440         function __() { this.constructor = d; }
15441         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15442     };
15443 })();
15444 Object.defineProperty(exports, "__esModule", { value: true });
15445 var Subscriber_1 = require("../Subscriber");
15446 var Subject_1 = require("../Subject");
15447 function windowCount(windowSize, startWindowEvery) {
15448     if (startWindowEvery === void 0) { startWindowEvery = 0; }
15449     return function windowCountOperatorFunction(source) {
15450         return source.lift(new WindowCountOperator(windowSize, startWindowEvery));
15451     };
15452 }
15453 exports.windowCount = windowCount;
15454 var WindowCountOperator = (function () {
15455     function WindowCountOperator(windowSize, startWindowEvery) {
15456         this.windowSize = windowSize;
15457         this.startWindowEvery = startWindowEvery;
15458     }
15459     WindowCountOperator.prototype.call = function (subscriber, source) {
15460         return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));
15461     };
15462     return WindowCountOperator;
15463 }());
15464 var WindowCountSubscriber = (function (_super) {
15465     __extends(WindowCountSubscriber, _super);
15466     function WindowCountSubscriber(destination, windowSize, startWindowEvery) {
15467         var _this = _super.call(this, destination) || this;
15468         _this.destination = destination;
15469         _this.windowSize = windowSize;
15470         _this.startWindowEvery = startWindowEvery;
15471         _this.windows = [new Subject_1.Subject()];
15472         _this.count = 0;
15473         destination.next(_this.windows[0]);
15474         return _this;
15475     }
15476     WindowCountSubscriber.prototype._next = function (value) {
15477         var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;
15478         var destination = this.destination;
15479         var windowSize = this.windowSize;
15480         var windows = this.windows;
15481         var len = windows.length;
15482         for (var i = 0; i < len && !this.closed; i++) {
15483             windows[i].next(value);
15484         }
15485         var c = this.count - windowSize + 1;
15486         if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {
15487             windows.shift().complete();
15488         }
15489         if (++this.count % startWindowEvery === 0 && !this.closed) {
15490             var window_1 = new Subject_1.Subject();
15491             windows.push(window_1);
15492             destination.next(window_1);
15493         }
15494     };
15495     WindowCountSubscriber.prototype._error = function (err) {
15496         var windows = this.windows;
15497         if (windows) {
15498             while (windows.length > 0 && !this.closed) {
15499                 windows.shift().error(err);
15500             }
15501         }
15502         this.destination.error(err);
15503     };
15504     WindowCountSubscriber.prototype._complete = function () {
15505         var windows = this.windows;
15506         if (windows) {
15507             while (windows.length > 0 && !this.closed) {
15508                 windows.shift().complete();
15509             }
15510         }
15511         this.destination.complete();
15512     };
15513     WindowCountSubscriber.prototype._unsubscribe = function () {
15514         this.count = 0;
15515         this.windows = null;
15516     };
15517     return WindowCountSubscriber;
15518 }(Subscriber_1.Subscriber));
15519
15520 },{"../Subject":37,"../Subscriber":39}],170:[function(require,module,exports){
15521 "use strict";
15522 var __extends = (this && this.__extends) || (function () {
15523     var extendStatics = function (d, b) {
15524         extendStatics = Object.setPrototypeOf ||
15525             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15526             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15527         return extendStatics(d, b);
15528     }
15529     return function (d, b) {
15530         extendStatics(d, b);
15531         function __() { this.constructor = d; }
15532         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15533     };
15534 })();
15535 Object.defineProperty(exports, "__esModule", { value: true });
15536 var Subject_1 = require("../Subject");
15537 var async_1 = require("../scheduler/async");
15538 var Subscriber_1 = require("../Subscriber");
15539 var isNumeric_1 = require("../util/isNumeric");
15540 var isScheduler_1 = require("../util/isScheduler");
15541 function windowTime(windowTimeSpan) {
15542     var scheduler = async_1.async;
15543     var windowCreationInterval = null;
15544     var maxWindowSize = Number.POSITIVE_INFINITY;
15545     if (isScheduler_1.isScheduler(arguments[3])) {
15546         scheduler = arguments[3];
15547     }
15548     if (isScheduler_1.isScheduler(arguments[2])) {
15549         scheduler = arguments[2];
15550     }
15551     else if (isNumeric_1.isNumeric(arguments[2])) {
15552         maxWindowSize = arguments[2];
15553     }
15554     if (isScheduler_1.isScheduler(arguments[1])) {
15555         scheduler = arguments[1];
15556     }
15557     else if (isNumeric_1.isNumeric(arguments[1])) {
15558         windowCreationInterval = arguments[1];
15559     }
15560     return function windowTimeOperatorFunction(source) {
15561         return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));
15562     };
15563 }
15564 exports.windowTime = windowTime;
15565 var WindowTimeOperator = (function () {
15566     function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
15567         this.windowTimeSpan = windowTimeSpan;
15568         this.windowCreationInterval = windowCreationInterval;
15569         this.maxWindowSize = maxWindowSize;
15570         this.scheduler = scheduler;
15571     }
15572     WindowTimeOperator.prototype.call = function (subscriber, source) {
15573         return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler));
15574     };
15575     return WindowTimeOperator;
15576 }());
15577 var CountedSubject = (function (_super) {
15578     __extends(CountedSubject, _super);
15579     function CountedSubject() {
15580         var _this = _super !== null && _super.apply(this, arguments) || this;
15581         _this._numberOfNextedValues = 0;
15582         return _this;
15583     }
15584     CountedSubject.prototype.next = function (value) {
15585         this._numberOfNextedValues++;
15586         _super.prototype.next.call(this, value);
15587     };
15588     Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", {
15589         get: function () {
15590             return this._numberOfNextedValues;
15591         },
15592         enumerable: true,
15593         configurable: true
15594     });
15595     return CountedSubject;
15596 }(Subject_1.Subject));
15597 var WindowTimeSubscriber = (function (_super) {
15598     __extends(WindowTimeSubscriber, _super);
15599     function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
15600         var _this = _super.call(this, destination) || this;
15601         _this.destination = destination;
15602         _this.windowTimeSpan = windowTimeSpan;
15603         _this.windowCreationInterval = windowCreationInterval;
15604         _this.maxWindowSize = maxWindowSize;
15605         _this.scheduler = scheduler;
15606         _this.windows = [];
15607         var window = _this.openWindow();
15608         if (windowCreationInterval !== null && windowCreationInterval >= 0) {
15609             var closeState = { subscriber: _this, window: window, context: null };
15610             var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: _this, scheduler: scheduler };
15611             _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState));
15612             _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState));
15613         }
15614         else {
15615             var timeSpanOnlyState = { subscriber: _this, window: window, windowTimeSpan: windowTimeSpan };
15616             _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));
15617         }
15618         return _this;
15619     }
15620     WindowTimeSubscriber.prototype._next = function (value) {
15621         var windows = this.windows;
15622         var len = windows.length;
15623         for (var i = 0; i < len; i++) {
15624             var window_1 = windows[i];
15625             if (!window_1.closed) {
15626                 window_1.next(value);
15627                 if (window_1.numberOfNextedValues >= this.maxWindowSize) {
15628                     this.closeWindow(window_1);
15629                 }
15630             }
15631         }
15632     };
15633     WindowTimeSubscriber.prototype._error = function (err) {
15634         var windows = this.windows;
15635         while (windows.length > 0) {
15636             windows.shift().error(err);
15637         }
15638         this.destination.error(err);
15639     };
15640     WindowTimeSubscriber.prototype._complete = function () {
15641         var windows = this.windows;
15642         while (windows.length > 0) {
15643             var window_2 = windows.shift();
15644             if (!window_2.closed) {
15645                 window_2.complete();
15646             }
15647         }
15648         this.destination.complete();
15649     };
15650     WindowTimeSubscriber.prototype.openWindow = function () {
15651         var window = new CountedSubject();
15652         this.windows.push(window);
15653         var destination = this.destination;
15654         destination.next(window);
15655         return window;
15656     };
15657     WindowTimeSubscriber.prototype.closeWindow = function (window) {
15658         window.complete();
15659         var windows = this.windows;
15660         windows.splice(windows.indexOf(window), 1);
15661     };
15662     return WindowTimeSubscriber;
15663 }(Subscriber_1.Subscriber));
15664 function dispatchWindowTimeSpanOnly(state) {
15665     var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window;
15666     if (window) {
15667         subscriber.closeWindow(window);
15668     }
15669     state.window = subscriber.openWindow();
15670     this.schedule(state, windowTimeSpan);
15671 }
15672 function dispatchWindowCreation(state) {
15673     var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval;
15674     var window = subscriber.openWindow();
15675     var action = this;
15676     var context = { action: action, subscription: null };
15677     var timeSpanState = { subscriber: subscriber, window: window, context: context };
15678     context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState);
15679     action.add(context.subscription);
15680     action.schedule(state, windowCreationInterval);
15681 }
15682 function dispatchWindowClose(state) {
15683     var subscriber = state.subscriber, window = state.window, context = state.context;
15684     if (context && context.action && context.subscription) {
15685         context.action.remove(context.subscription);
15686     }
15687     subscriber.closeWindow(window);
15688 }
15689
15690 },{"../Subject":37,"../Subscriber":39,"../scheduler/async":188,"../util/isNumeric":209,"../util/isScheduler":213}],171:[function(require,module,exports){
15691 "use strict";
15692 var __extends = (this && this.__extends) || (function () {
15693     var extendStatics = function (d, b) {
15694         extendStatics = Object.setPrototypeOf ||
15695             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15696             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15697         return extendStatics(d, b);
15698     }
15699     return function (d, b) {
15700         extendStatics(d, b);
15701         function __() { this.constructor = d; }
15702         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15703     };
15704 })();
15705 Object.defineProperty(exports, "__esModule", { value: true });
15706 var Subject_1 = require("../Subject");
15707 var Subscription_1 = require("../Subscription");
15708 var tryCatch_1 = require("../util/tryCatch");
15709 var errorObject_1 = require("../util/errorObject");
15710 var OuterSubscriber_1 = require("../OuterSubscriber");
15711 var subscribeToResult_1 = require("../util/subscribeToResult");
15712 function windowToggle(openings, closingSelector) {
15713     return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); };
15714 }
15715 exports.windowToggle = windowToggle;
15716 var WindowToggleOperator = (function () {
15717     function WindowToggleOperator(openings, closingSelector) {
15718         this.openings = openings;
15719         this.closingSelector = closingSelector;
15720     }
15721     WindowToggleOperator.prototype.call = function (subscriber, source) {
15722         return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector));
15723     };
15724     return WindowToggleOperator;
15725 }());
15726 var WindowToggleSubscriber = (function (_super) {
15727     __extends(WindowToggleSubscriber, _super);
15728     function WindowToggleSubscriber(destination, openings, closingSelector) {
15729         var _this = _super.call(this, destination) || this;
15730         _this.openings = openings;
15731         _this.closingSelector = closingSelector;
15732         _this.contexts = [];
15733         _this.add(_this.openSubscription = subscribeToResult_1.subscribeToResult(_this, openings, openings));
15734         return _this;
15735     }
15736     WindowToggleSubscriber.prototype._next = function (value) {
15737         var contexts = this.contexts;
15738         if (contexts) {
15739             var len = contexts.length;
15740             for (var i = 0; i < len; i++) {
15741                 contexts[i].window.next(value);
15742             }
15743         }
15744     };
15745     WindowToggleSubscriber.prototype._error = function (err) {
15746         var contexts = this.contexts;
15747         this.contexts = null;
15748         if (contexts) {
15749             var len = contexts.length;
15750             var index = -1;
15751             while (++index < len) {
15752                 var context_1 = contexts[index];
15753                 context_1.window.error(err);
15754                 context_1.subscription.unsubscribe();
15755             }
15756         }
15757         _super.prototype._error.call(this, err);
15758     };
15759     WindowToggleSubscriber.prototype._complete = function () {
15760         var contexts = this.contexts;
15761         this.contexts = null;
15762         if (contexts) {
15763             var len = contexts.length;
15764             var index = -1;
15765             while (++index < len) {
15766                 var context_2 = contexts[index];
15767                 context_2.window.complete();
15768                 context_2.subscription.unsubscribe();
15769             }
15770         }
15771         _super.prototype._complete.call(this);
15772     };
15773     WindowToggleSubscriber.prototype._unsubscribe = function () {
15774         var contexts = this.contexts;
15775         this.contexts = null;
15776         if (contexts) {
15777             var len = contexts.length;
15778             var index = -1;
15779             while (++index < len) {
15780                 var context_3 = contexts[index];
15781                 context_3.window.unsubscribe();
15782                 context_3.subscription.unsubscribe();
15783             }
15784         }
15785     };
15786     WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15787         if (outerValue === this.openings) {
15788             var closingSelector = this.closingSelector;
15789             var closingNotifier = tryCatch_1.tryCatch(closingSelector)(innerValue);
15790             if (closingNotifier === errorObject_1.errorObject) {
15791                 return this.error(errorObject_1.errorObject.e);
15792             }
15793             else {
15794                 var window_1 = new Subject_1.Subject();
15795                 var subscription = new Subscription_1.Subscription();
15796                 var context_4 = { window: window_1, subscription: subscription };
15797                 this.contexts.push(context_4);
15798                 var innerSubscription = subscribeToResult_1.subscribeToResult(this, closingNotifier, context_4);
15799                 if (innerSubscription.closed) {
15800                     this.closeWindow(this.contexts.length - 1);
15801                 }
15802                 else {
15803                     innerSubscription.context = context_4;
15804                     subscription.add(innerSubscription);
15805                 }
15806                 this.destination.next(window_1);
15807             }
15808         }
15809         else {
15810             this.closeWindow(this.contexts.indexOf(outerValue));
15811         }
15812     };
15813     WindowToggleSubscriber.prototype.notifyError = function (err) {
15814         this.error(err);
15815     };
15816     WindowToggleSubscriber.prototype.notifyComplete = function (inner) {
15817         if (inner !== this.openSubscription) {
15818             this.closeWindow(this.contexts.indexOf(inner.context));
15819         }
15820     };
15821     WindowToggleSubscriber.prototype.closeWindow = function (index) {
15822         if (index === -1) {
15823             return;
15824         }
15825         var contexts = this.contexts;
15826         var context = contexts[index];
15827         var window = context.window, subscription = context.subscription;
15828         contexts.splice(index, 1);
15829         window.complete();
15830         subscription.unsubscribe();
15831     };
15832     return WindowToggleSubscriber;
15833 }(OuterSubscriber_1.OuterSubscriber));
15834
15835 },{"../OuterSubscriber":34,"../Subject":37,"../Subscription":40,"../util/errorObject":200,"../util/subscribeToResult":222,"../util/tryCatch":224}],172:[function(require,module,exports){
15836 "use strict";
15837 var __extends = (this && this.__extends) || (function () {
15838     var extendStatics = function (d, b) {
15839         extendStatics = Object.setPrototypeOf ||
15840             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15841             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15842         return extendStatics(d, b);
15843     }
15844     return function (d, b) {
15845         extendStatics(d, b);
15846         function __() { this.constructor = d; }
15847         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15848     };
15849 })();
15850 Object.defineProperty(exports, "__esModule", { value: true });
15851 var Subject_1 = require("../Subject");
15852 var tryCatch_1 = require("../util/tryCatch");
15853 var errorObject_1 = require("../util/errorObject");
15854 var OuterSubscriber_1 = require("../OuterSubscriber");
15855 var subscribeToResult_1 = require("../util/subscribeToResult");
15856 function windowWhen(closingSelector) {
15857     return function windowWhenOperatorFunction(source) {
15858         return source.lift(new WindowOperator(closingSelector));
15859     };
15860 }
15861 exports.windowWhen = windowWhen;
15862 var WindowOperator = (function () {
15863     function WindowOperator(closingSelector) {
15864         this.closingSelector = closingSelector;
15865     }
15866     WindowOperator.prototype.call = function (subscriber, source) {
15867         return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector));
15868     };
15869     return WindowOperator;
15870 }());
15871 var WindowSubscriber = (function (_super) {
15872     __extends(WindowSubscriber, _super);
15873     function WindowSubscriber(destination, closingSelector) {
15874         var _this = _super.call(this, destination) || this;
15875         _this.destination = destination;
15876         _this.closingSelector = closingSelector;
15877         _this.openWindow();
15878         return _this;
15879     }
15880     WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15881         this.openWindow(innerSub);
15882     };
15883     WindowSubscriber.prototype.notifyError = function (error, innerSub) {
15884         this._error(error);
15885     };
15886     WindowSubscriber.prototype.notifyComplete = function (innerSub) {
15887         this.openWindow(innerSub);
15888     };
15889     WindowSubscriber.prototype._next = function (value) {
15890         this.window.next(value);
15891     };
15892     WindowSubscriber.prototype._error = function (err) {
15893         this.window.error(err);
15894         this.destination.error(err);
15895         this.unsubscribeClosingNotification();
15896     };
15897     WindowSubscriber.prototype._complete = function () {
15898         this.window.complete();
15899         this.destination.complete();
15900         this.unsubscribeClosingNotification();
15901     };
15902     WindowSubscriber.prototype.unsubscribeClosingNotification = function () {
15903         if (this.closingNotification) {
15904             this.closingNotification.unsubscribe();
15905         }
15906     };
15907     WindowSubscriber.prototype.openWindow = function (innerSub) {
15908         if (innerSub === void 0) { innerSub = null; }
15909         if (innerSub) {
15910             this.remove(innerSub);
15911             innerSub.unsubscribe();
15912         }
15913         var prevWindow = this.window;
15914         if (prevWindow) {
15915             prevWindow.complete();
15916         }
15917         var window = this.window = new Subject_1.Subject();
15918         this.destination.next(window);
15919         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
15920         if (closingNotifier === errorObject_1.errorObject) {
15921             var err = errorObject_1.errorObject.e;
15922             this.destination.error(err);
15923             this.window.error(err);
15924         }
15925         else {
15926             this.add(this.closingNotification = subscribeToResult_1.subscribeToResult(this, closingNotifier));
15927         }
15928     };
15929     return WindowSubscriber;
15930 }(OuterSubscriber_1.OuterSubscriber));
15931
15932 },{"../OuterSubscriber":34,"../Subject":37,"../util/errorObject":200,"../util/subscribeToResult":222,"../util/tryCatch":224}],173:[function(require,module,exports){
15933 "use strict";
15934 var __extends = (this && this.__extends) || (function () {
15935     var extendStatics = function (d, b) {
15936         extendStatics = Object.setPrototypeOf ||
15937             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15938             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15939         return extendStatics(d, b);
15940     }
15941     return function (d, b) {
15942         extendStatics(d, b);
15943         function __() { this.constructor = d; }
15944         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15945     };
15946 })();
15947 Object.defineProperty(exports, "__esModule", { value: true });
15948 var OuterSubscriber_1 = require("../OuterSubscriber");
15949 var subscribeToResult_1 = require("../util/subscribeToResult");
15950 function withLatestFrom() {
15951     var args = [];
15952     for (var _i = 0; _i < arguments.length; _i++) {
15953         args[_i] = arguments[_i];
15954     }
15955     return function (source) {
15956         var project;
15957         if (typeof args[args.length - 1] === 'function') {
15958             project = args.pop();
15959         }
15960         var observables = args;
15961         return source.lift(new WithLatestFromOperator(observables, project));
15962     };
15963 }
15964 exports.withLatestFrom = withLatestFrom;
15965 var WithLatestFromOperator = (function () {
15966     function WithLatestFromOperator(observables, project) {
15967         this.observables = observables;
15968         this.project = project;
15969     }
15970     WithLatestFromOperator.prototype.call = function (subscriber, source) {
15971         return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
15972     };
15973     return WithLatestFromOperator;
15974 }());
15975 var WithLatestFromSubscriber = (function (_super) {
15976     __extends(WithLatestFromSubscriber, _super);
15977     function WithLatestFromSubscriber(destination, observables, project) {
15978         var _this = _super.call(this, destination) || this;
15979         _this.observables = observables;
15980         _this.project = project;
15981         _this.toRespond = [];
15982         var len = observables.length;
15983         _this.values = new Array(len);
15984         for (var i = 0; i < len; i++) {
15985             _this.toRespond.push(i);
15986         }
15987         for (var i = 0; i < len; i++) {
15988             var observable = observables[i];
15989             _this.add(subscribeToResult_1.subscribeToResult(_this, observable, observable, i));
15990         }
15991         return _this;
15992     }
15993     WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15994         this.values[outerIndex] = innerValue;
15995         var toRespond = this.toRespond;
15996         if (toRespond.length > 0) {
15997             var found = toRespond.indexOf(outerIndex);
15998             if (found !== -1) {
15999                 toRespond.splice(found, 1);
16000             }
16001         }
16002     };
16003     WithLatestFromSubscriber.prototype.notifyComplete = function () {
16004     };
16005     WithLatestFromSubscriber.prototype._next = function (value) {
16006         if (this.toRespond.length === 0) {
16007             var args = [value].concat(this.values);
16008             if (this.project) {
16009                 this._tryProject(args);
16010             }
16011             else {
16012                 this.destination.next(args);
16013             }
16014         }
16015     };
16016     WithLatestFromSubscriber.prototype._tryProject = function (args) {
16017         var result;
16018         try {
16019             result = this.project.apply(this, args);
16020         }
16021         catch (err) {
16022             this.destination.error(err);
16023             return;
16024         }
16025         this.destination.next(result);
16026     };
16027     return WithLatestFromSubscriber;
16028 }(OuterSubscriber_1.OuterSubscriber));
16029
16030 },{"../OuterSubscriber":34,"../util/subscribeToResult":222}],174:[function(require,module,exports){
16031 "use strict";
16032 Object.defineProperty(exports, "__esModule", { value: true });
16033 var zip_1 = require("../observable/zip");
16034 function zip() {
16035     var observables = [];
16036     for (var _i = 0; _i < arguments.length; _i++) {
16037         observables[_i] = arguments[_i];
16038     }
16039     return function zipOperatorFunction(source) {
16040         return source.lift.call(zip_1.zip.apply(void 0, [source].concat(observables)));
16041     };
16042 }
16043 exports.zip = zip;
16044
16045 },{"../observable/zip":72}],175:[function(require,module,exports){
16046 "use strict";
16047 Object.defineProperty(exports, "__esModule", { value: true });
16048 var zip_1 = require("../observable/zip");
16049 function zipAll(project) {
16050     return function (source) { return source.lift(new zip_1.ZipOperator(project)); };
16051 }
16052 exports.zipAll = zipAll;
16053
16054 },{"../observable/zip":72}],176:[function(require,module,exports){
16055 "use strict";
16056 var __extends = (this && this.__extends) || (function () {
16057     var extendStatics = function (d, b) {
16058         extendStatics = Object.setPrototypeOf ||
16059             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16060             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16061         return extendStatics(d, b);
16062     }
16063     return function (d, b) {
16064         extendStatics(d, b);
16065         function __() { this.constructor = d; }
16066         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16067     };
16068 })();
16069 Object.defineProperty(exports, "__esModule", { value: true });
16070 var Subscription_1 = require("../Subscription");
16071 var Action = (function (_super) {
16072     __extends(Action, _super);
16073     function Action(scheduler, work) {
16074         return _super.call(this) || this;
16075     }
16076     Action.prototype.schedule = function (state, delay) {
16077         if (delay === void 0) { delay = 0; }
16078         return this;
16079     };
16080     return Action;
16081 }(Subscription_1.Subscription));
16082 exports.Action = Action;
16083
16084 },{"../Subscription":40}],177:[function(require,module,exports){
16085 "use strict";
16086 var __extends = (this && this.__extends) || (function () {
16087     var extendStatics = function (d, b) {
16088         extendStatics = Object.setPrototypeOf ||
16089             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16090             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16091         return extendStatics(d, b);
16092     }
16093     return function (d, b) {
16094         extendStatics(d, b);
16095         function __() { this.constructor = d; }
16096         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16097     };
16098 })();
16099 Object.defineProperty(exports, "__esModule", { value: true });
16100 var AsyncAction_1 = require("./AsyncAction");
16101 var AnimationFrameAction = (function (_super) {
16102     __extends(AnimationFrameAction, _super);
16103     function AnimationFrameAction(scheduler, work) {
16104         var _this = _super.call(this, scheduler, work) || this;
16105         _this.scheduler = scheduler;
16106         _this.work = work;
16107         return _this;
16108     }
16109     AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) {
16110         if (delay === void 0) { delay = 0; }
16111         if (delay !== null && delay > 0) {
16112             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
16113         }
16114         scheduler.actions.push(this);
16115         return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function () { return scheduler.flush(null); }));
16116     };
16117     AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
16118         if (delay === void 0) { delay = 0; }
16119         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
16120             return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
16121         }
16122         if (scheduler.actions.length === 0) {
16123             cancelAnimationFrame(id);
16124             scheduler.scheduled = undefined;
16125         }
16126         return undefined;
16127     };
16128     return AnimationFrameAction;
16129 }(AsyncAction_1.AsyncAction));
16130 exports.AnimationFrameAction = AnimationFrameAction;
16131
16132 },{"./AsyncAction":181}],178:[function(require,module,exports){
16133 "use strict";
16134 var __extends = (this && this.__extends) || (function () {
16135     var extendStatics = function (d, b) {
16136         extendStatics = Object.setPrototypeOf ||
16137             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16138             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16139         return extendStatics(d, b);
16140     }
16141     return function (d, b) {
16142         extendStatics(d, b);
16143         function __() { this.constructor = d; }
16144         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16145     };
16146 })();
16147 Object.defineProperty(exports, "__esModule", { value: true });
16148 var AsyncScheduler_1 = require("./AsyncScheduler");
16149 var AnimationFrameScheduler = (function (_super) {
16150     __extends(AnimationFrameScheduler, _super);
16151     function AnimationFrameScheduler() {
16152         return _super !== null && _super.apply(this, arguments) || this;
16153     }
16154     AnimationFrameScheduler.prototype.flush = function (action) {
16155         this.active = true;
16156         this.scheduled = undefined;
16157         var actions = this.actions;
16158         var error;
16159         var index = -1;
16160         var count = actions.length;
16161         action = action || actions.shift();
16162         do {
16163             if (error = action.execute(action.state, action.delay)) {
16164                 break;
16165             }
16166         } while (++index < count && (action = actions.shift()));
16167         this.active = false;
16168         if (error) {
16169             while (++index < count && (action = actions.shift())) {
16170                 action.unsubscribe();
16171             }
16172             throw error;
16173         }
16174     };
16175     return AnimationFrameScheduler;
16176 }(AsyncScheduler_1.AsyncScheduler));
16177 exports.AnimationFrameScheduler = AnimationFrameScheduler;
16178
16179 },{"./AsyncScheduler":182}],179:[function(require,module,exports){
16180 "use strict";
16181 var __extends = (this && this.__extends) || (function () {
16182     var extendStatics = function (d, b) {
16183         extendStatics = Object.setPrototypeOf ||
16184             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16185             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16186         return extendStatics(d, b);
16187     }
16188     return function (d, b) {
16189         extendStatics(d, b);
16190         function __() { this.constructor = d; }
16191         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16192     };
16193 })();
16194 Object.defineProperty(exports, "__esModule", { value: true });
16195 var Immediate_1 = require("../util/Immediate");
16196 var AsyncAction_1 = require("./AsyncAction");
16197 var AsapAction = (function (_super) {
16198     __extends(AsapAction, _super);
16199     function AsapAction(scheduler, work) {
16200         var _this = _super.call(this, scheduler, work) || this;
16201         _this.scheduler = scheduler;
16202         _this.work = work;
16203         return _this;
16204     }
16205     AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) {
16206         if (delay === void 0) { delay = 0; }
16207         if (delay !== null && delay > 0) {
16208             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
16209         }
16210         scheduler.actions.push(this);
16211         return scheduler.scheduled || (scheduler.scheduled = Immediate_1.Immediate.setImmediate(scheduler.flush.bind(scheduler, null)));
16212     };
16213     AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
16214         if (delay === void 0) { delay = 0; }
16215         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
16216             return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
16217         }
16218         if (scheduler.actions.length === 0) {
16219             Immediate_1.Immediate.clearImmediate(id);
16220             scheduler.scheduled = undefined;
16221         }
16222         return undefined;
16223     };
16224     return AsapAction;
16225 }(AsyncAction_1.AsyncAction));
16226 exports.AsapAction = AsapAction;
16227
16228 },{"../util/Immediate":195,"./AsyncAction":181}],180:[function(require,module,exports){
16229 "use strict";
16230 var __extends = (this && this.__extends) || (function () {
16231     var extendStatics = function (d, b) {
16232         extendStatics = Object.setPrototypeOf ||
16233             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16234             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16235         return extendStatics(d, b);
16236     }
16237     return function (d, b) {
16238         extendStatics(d, b);
16239         function __() { this.constructor = d; }
16240         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16241     };
16242 })();
16243 Object.defineProperty(exports, "__esModule", { value: true });
16244 var AsyncScheduler_1 = require("./AsyncScheduler");
16245 var AsapScheduler = (function (_super) {
16246     __extends(AsapScheduler, _super);
16247     function AsapScheduler() {
16248         return _super !== null && _super.apply(this, arguments) || this;
16249     }
16250     AsapScheduler.prototype.flush = function (action) {
16251         this.active = true;
16252         this.scheduled = undefined;
16253         var actions = this.actions;
16254         var error;
16255         var index = -1;
16256         var count = actions.length;
16257         action = action || actions.shift();
16258         do {
16259             if (error = action.execute(action.state, action.delay)) {
16260                 break;
16261             }
16262         } while (++index < count && (action = actions.shift()));
16263         this.active = false;
16264         if (error) {
16265             while (++index < count && (action = actions.shift())) {
16266                 action.unsubscribe();
16267             }
16268             throw error;
16269         }
16270     };
16271     return AsapScheduler;
16272 }(AsyncScheduler_1.AsyncScheduler));
16273 exports.AsapScheduler = AsapScheduler;
16274
16275 },{"./AsyncScheduler":182}],181:[function(require,module,exports){
16276 "use strict";
16277 var __extends = (this && this.__extends) || (function () {
16278     var extendStatics = function (d, b) {
16279         extendStatics = Object.setPrototypeOf ||
16280             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16281             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16282         return extendStatics(d, b);
16283     }
16284     return function (d, b) {
16285         extendStatics(d, b);
16286         function __() { this.constructor = d; }
16287         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16288     };
16289 })();
16290 Object.defineProperty(exports, "__esModule", { value: true });
16291 var Action_1 = require("./Action");
16292 var AsyncAction = (function (_super) {
16293     __extends(AsyncAction, _super);
16294     function AsyncAction(scheduler, work) {
16295         var _this = _super.call(this, scheduler, work) || this;
16296         _this.scheduler = scheduler;
16297         _this.work = work;
16298         _this.pending = false;
16299         return _this;
16300     }
16301     AsyncAction.prototype.schedule = function (state, delay) {
16302         if (delay === void 0) { delay = 0; }
16303         if (this.closed) {
16304             return this;
16305         }
16306         this.state = state;
16307         var id = this.id;
16308         var scheduler = this.scheduler;
16309         if (id != null) {
16310             this.id = this.recycleAsyncId(scheduler, id, delay);
16311         }
16312         this.pending = true;
16313         this.delay = delay;
16314         this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
16315         return this;
16316     };
16317     AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
16318         if (delay === void 0) { delay = 0; }
16319         return setInterval(scheduler.flush.bind(scheduler, this), delay);
16320     };
16321     AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
16322         if (delay === void 0) { delay = 0; }
16323         if (delay !== null && this.delay === delay && this.pending === false) {
16324             return id;
16325         }
16326         clearInterval(id);
16327     };
16328     AsyncAction.prototype.execute = function (state, delay) {
16329         if (this.closed) {
16330             return new Error('executing a cancelled action');
16331         }
16332         this.pending = false;
16333         var error = this._execute(state, delay);
16334         if (error) {
16335             return error;
16336         }
16337         else if (this.pending === false && this.id != null) {
16338             this.id = this.recycleAsyncId(this.scheduler, this.id, null);
16339         }
16340     };
16341     AsyncAction.prototype._execute = function (state, delay) {
16342         var errored = false;
16343         var errorValue = undefined;
16344         try {
16345             this.work(state);
16346         }
16347         catch (e) {
16348             errored = true;
16349             errorValue = !!e && e || new Error(e);
16350         }
16351         if (errored) {
16352             this.unsubscribe();
16353             return errorValue;
16354         }
16355     };
16356     AsyncAction.prototype._unsubscribe = function () {
16357         var id = this.id;
16358         var scheduler = this.scheduler;
16359         var actions = scheduler.actions;
16360         var index = actions.indexOf(this);
16361         this.work = null;
16362         this.state = null;
16363         this.pending = false;
16364         this.scheduler = null;
16365         if (index !== -1) {
16366             actions.splice(index, 1);
16367         }
16368         if (id != null) {
16369             this.id = this.recycleAsyncId(scheduler, id, null);
16370         }
16371         this.delay = null;
16372     };
16373     return AsyncAction;
16374 }(Action_1.Action));
16375 exports.AsyncAction = AsyncAction;
16376
16377 },{"./Action":176}],182:[function(require,module,exports){
16378 "use strict";
16379 var __extends = (this && this.__extends) || (function () {
16380     var extendStatics = function (d, b) {
16381         extendStatics = Object.setPrototypeOf ||
16382             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16383             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16384         return extendStatics(d, b);
16385     }
16386     return function (d, b) {
16387         extendStatics(d, b);
16388         function __() { this.constructor = d; }
16389         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16390     };
16391 })();
16392 Object.defineProperty(exports, "__esModule", { value: true });
16393 var Scheduler_1 = require("../Scheduler");
16394 var AsyncScheduler = (function (_super) {
16395     __extends(AsyncScheduler, _super);
16396     function AsyncScheduler(SchedulerAction, now) {
16397         if (now === void 0) { now = Scheduler_1.Scheduler.now; }
16398         var _this = _super.call(this, SchedulerAction, function () {
16399             if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) {
16400                 return AsyncScheduler.delegate.now();
16401             }
16402             else {
16403                 return now();
16404             }
16405         }) || this;
16406         _this.actions = [];
16407         _this.active = false;
16408         _this.scheduled = undefined;
16409         return _this;
16410     }
16411     AsyncScheduler.prototype.schedule = function (work, delay, state) {
16412         if (delay === void 0) { delay = 0; }
16413         if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
16414             return AsyncScheduler.delegate.schedule(work, delay, state);
16415         }
16416         else {
16417             return _super.prototype.schedule.call(this, work, delay, state);
16418         }
16419     };
16420     AsyncScheduler.prototype.flush = function (action) {
16421         var actions = this.actions;
16422         if (this.active) {
16423             actions.push(action);
16424             return;
16425         }
16426         var error;
16427         this.active = true;
16428         do {
16429             if (error = action.execute(action.state, action.delay)) {
16430                 break;
16431             }
16432         } while (action = actions.shift());
16433         this.active = false;
16434         if (error) {
16435             while (action = actions.shift()) {
16436                 action.unsubscribe();
16437             }
16438             throw error;
16439         }
16440     };
16441     return AsyncScheduler;
16442 }(Scheduler_1.Scheduler));
16443 exports.AsyncScheduler = AsyncScheduler;
16444
16445 },{"../Scheduler":36}],183:[function(require,module,exports){
16446 "use strict";
16447 var __extends = (this && this.__extends) || (function () {
16448     var extendStatics = function (d, b) {
16449         extendStatics = Object.setPrototypeOf ||
16450             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16451             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16452         return extendStatics(d, b);
16453     }
16454     return function (d, b) {
16455         extendStatics(d, b);
16456         function __() { this.constructor = d; }
16457         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16458     };
16459 })();
16460 Object.defineProperty(exports, "__esModule", { value: true });
16461 var AsyncAction_1 = require("./AsyncAction");
16462 var QueueAction = (function (_super) {
16463     __extends(QueueAction, _super);
16464     function QueueAction(scheduler, work) {
16465         var _this = _super.call(this, scheduler, work) || this;
16466         _this.scheduler = scheduler;
16467         _this.work = work;
16468         return _this;
16469     }
16470     QueueAction.prototype.schedule = function (state, delay) {
16471         if (delay === void 0) { delay = 0; }
16472         if (delay > 0) {
16473             return _super.prototype.schedule.call(this, state, delay);
16474         }
16475         this.delay = delay;
16476         this.state = state;
16477         this.scheduler.flush(this);
16478         return this;
16479     };
16480     QueueAction.prototype.execute = function (state, delay) {
16481         return (delay > 0 || this.closed) ?
16482             _super.prototype.execute.call(this, state, delay) :
16483             this._execute(state, delay);
16484     };
16485     QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
16486         if (delay === void 0) { delay = 0; }
16487         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
16488             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
16489         }
16490         return scheduler.flush(this);
16491     };
16492     return QueueAction;
16493 }(AsyncAction_1.AsyncAction));
16494 exports.QueueAction = QueueAction;
16495
16496 },{"./AsyncAction":181}],184:[function(require,module,exports){
16497 "use strict";
16498 var __extends = (this && this.__extends) || (function () {
16499     var extendStatics = function (d, b) {
16500         extendStatics = Object.setPrototypeOf ||
16501             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16502             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16503         return extendStatics(d, b);
16504     }
16505     return function (d, b) {
16506         extendStatics(d, b);
16507         function __() { this.constructor = d; }
16508         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16509     };
16510 })();
16511 Object.defineProperty(exports, "__esModule", { value: true });
16512 var AsyncScheduler_1 = require("./AsyncScheduler");
16513 var QueueScheduler = (function (_super) {
16514     __extends(QueueScheduler, _super);
16515     function QueueScheduler() {
16516         return _super !== null && _super.apply(this, arguments) || this;
16517     }
16518     return QueueScheduler;
16519 }(AsyncScheduler_1.AsyncScheduler));
16520 exports.QueueScheduler = QueueScheduler;
16521
16522 },{"./AsyncScheduler":182}],185:[function(require,module,exports){
16523 "use strict";
16524 var __extends = (this && this.__extends) || (function () {
16525     var extendStatics = function (d, b) {
16526         extendStatics = Object.setPrototypeOf ||
16527             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16528             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16529         return extendStatics(d, b);
16530     }
16531     return function (d, b) {
16532         extendStatics(d, b);
16533         function __() { this.constructor = d; }
16534         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16535     };
16536 })();
16537 Object.defineProperty(exports, "__esModule", { value: true });
16538 var AsyncAction_1 = require("./AsyncAction");
16539 var AsyncScheduler_1 = require("./AsyncScheduler");
16540 var VirtualTimeScheduler = (function (_super) {
16541     __extends(VirtualTimeScheduler, _super);
16542     function VirtualTimeScheduler(SchedulerAction, maxFrames) {
16543         if (SchedulerAction === void 0) { SchedulerAction = VirtualAction; }
16544         if (maxFrames === void 0) { maxFrames = Number.POSITIVE_INFINITY; }
16545         var _this = _super.call(this, SchedulerAction, function () { return _this.frame; }) || this;
16546         _this.maxFrames = maxFrames;
16547         _this.frame = 0;
16548         _this.index = -1;
16549         return _this;
16550     }
16551     VirtualTimeScheduler.prototype.flush = function () {
16552         var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
16553         var error, action;
16554         while ((action = actions.shift()) && (this.frame = action.delay) <= maxFrames) {
16555             if (error = action.execute(action.state, action.delay)) {
16556                 break;
16557             }
16558         }
16559         if (error) {
16560             while (action = actions.shift()) {
16561                 action.unsubscribe();
16562             }
16563             throw error;
16564         }
16565     };
16566     VirtualTimeScheduler.frameTimeFactor = 10;
16567     return VirtualTimeScheduler;
16568 }(AsyncScheduler_1.AsyncScheduler));
16569 exports.VirtualTimeScheduler = VirtualTimeScheduler;
16570 var VirtualAction = (function (_super) {
16571     __extends(VirtualAction, _super);
16572     function VirtualAction(scheduler, work, index) {
16573         if (index === void 0) { index = scheduler.index += 1; }
16574         var _this = _super.call(this, scheduler, work) || this;
16575         _this.scheduler = scheduler;
16576         _this.work = work;
16577         _this.index = index;
16578         _this.active = true;
16579         _this.index = scheduler.index = index;
16580         return _this;
16581     }
16582     VirtualAction.prototype.schedule = function (state, delay) {
16583         if (delay === void 0) { delay = 0; }
16584         if (!this.id) {
16585             return _super.prototype.schedule.call(this, state, delay);
16586         }
16587         this.active = false;
16588         var action = new VirtualAction(this.scheduler, this.work);
16589         this.add(action);
16590         return action.schedule(state, delay);
16591     };
16592     VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
16593         if (delay === void 0) { delay = 0; }
16594         this.delay = scheduler.frame + delay;
16595         var actions = scheduler.actions;
16596         actions.push(this);
16597         actions.sort(VirtualAction.sortActions);
16598         return true;
16599     };
16600     VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
16601         if (delay === void 0) { delay = 0; }
16602         return undefined;
16603     };
16604     VirtualAction.prototype._execute = function (state, delay) {
16605         if (this.active === true) {
16606             return _super.prototype._execute.call(this, state, delay);
16607         }
16608     };
16609     VirtualAction.sortActions = function (a, b) {
16610         if (a.delay === b.delay) {
16611             if (a.index === b.index) {
16612                 return 0;
16613             }
16614             else if (a.index > b.index) {
16615                 return 1;
16616             }
16617             else {
16618                 return -1;
16619             }
16620         }
16621         else if (a.delay > b.delay) {
16622             return 1;
16623         }
16624         else {
16625             return -1;
16626         }
16627     };
16628     return VirtualAction;
16629 }(AsyncAction_1.AsyncAction));
16630 exports.VirtualAction = VirtualAction;
16631
16632 },{"./AsyncAction":181,"./AsyncScheduler":182}],186:[function(require,module,exports){
16633 "use strict";
16634 Object.defineProperty(exports, "__esModule", { value: true });
16635 var AnimationFrameAction_1 = require("./AnimationFrameAction");
16636 var AnimationFrameScheduler_1 = require("./AnimationFrameScheduler");
16637 exports.animationFrame = new AnimationFrameScheduler_1.AnimationFrameScheduler(AnimationFrameAction_1.AnimationFrameAction);
16638
16639 },{"./AnimationFrameAction":177,"./AnimationFrameScheduler":178}],187:[function(require,module,exports){
16640 "use strict";
16641 Object.defineProperty(exports, "__esModule", { value: true });
16642 var AsapAction_1 = require("./AsapAction");
16643 var AsapScheduler_1 = require("./AsapScheduler");
16644 exports.asap = new AsapScheduler_1.AsapScheduler(AsapAction_1.AsapAction);
16645
16646 },{"./AsapAction":179,"./AsapScheduler":180}],188:[function(require,module,exports){
16647 "use strict";
16648 Object.defineProperty(exports, "__esModule", { value: true });
16649 var AsyncAction_1 = require("./AsyncAction");
16650 var AsyncScheduler_1 = require("./AsyncScheduler");
16651 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
16652
16653 },{"./AsyncAction":181,"./AsyncScheduler":182}],189:[function(require,module,exports){
16654 "use strict";
16655 Object.defineProperty(exports, "__esModule", { value: true });
16656 var QueueAction_1 = require("./QueueAction");
16657 var QueueScheduler_1 = require("./QueueScheduler");
16658 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
16659
16660 },{"./QueueAction":183,"./QueueScheduler":184}],190:[function(require,module,exports){
16661 "use strict";
16662 Object.defineProperty(exports, "__esModule", { value: true });
16663 function getSymbolIterator() {
16664     if (typeof Symbol !== 'function' || !Symbol.iterator) {
16665         return '@@iterator';
16666     }
16667     return Symbol.iterator;
16668 }
16669 exports.getSymbolIterator = getSymbolIterator;
16670 exports.iterator = getSymbolIterator();
16671 exports.$$iterator = exports.iterator;
16672
16673 },{}],191:[function(require,module,exports){
16674 "use strict";
16675 Object.defineProperty(exports, "__esModule", { value: true });
16676 exports.observable = typeof Symbol === 'function' && Symbol.observable || '@@observable';
16677
16678 },{}],192:[function(require,module,exports){
16679 "use strict";
16680 Object.defineProperty(exports, "__esModule", { value: true });
16681 exports.rxSubscriber = typeof Symbol === 'function'
16682     ? Symbol('rxSubscriber')
16683     : '@@rxSubscriber_' + Math.random();
16684 exports.$$rxSubscriber = exports.rxSubscriber;
16685
16686 },{}],193:[function(require,module,exports){
16687 "use strict";
16688 Object.defineProperty(exports, "__esModule", { value: true });
16689 function ArgumentOutOfRangeErrorImpl() {
16690     Error.call(this);
16691     this.message = 'argument out of range';
16692     this.name = 'ArgumentOutOfRangeError';
16693     return this;
16694 }
16695 ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);
16696 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;
16697
16698 },{}],194:[function(require,module,exports){
16699 "use strict";
16700 Object.defineProperty(exports, "__esModule", { value: true });
16701 function EmptyErrorImpl() {
16702     Error.call(this);
16703     this.message = 'no elements in sequence';
16704     this.name = 'EmptyError';
16705     return this;
16706 }
16707 EmptyErrorImpl.prototype = Object.create(Error.prototype);
16708 exports.EmptyError = EmptyErrorImpl;
16709
16710 },{}],195:[function(require,module,exports){
16711 "use strict";
16712 Object.defineProperty(exports, "__esModule", { value: true });
16713 var nextHandle = 1;
16714 var tasksByHandle = {};
16715 function runIfPresent(handle) {
16716     var cb = tasksByHandle[handle];
16717     if (cb) {
16718         cb();
16719     }
16720 }
16721 exports.Immediate = {
16722     setImmediate: function (cb) {
16723         var handle = nextHandle++;
16724         tasksByHandle[handle] = cb;
16725         Promise.resolve().then(function () { return runIfPresent(handle); });
16726         return handle;
16727     },
16728     clearImmediate: function (handle) {
16729         delete tasksByHandle[handle];
16730     },
16731 };
16732
16733 },{}],196:[function(require,module,exports){
16734 "use strict";
16735 Object.defineProperty(exports, "__esModule", { value: true });
16736 function ObjectUnsubscribedErrorImpl() {
16737     Error.call(this);
16738     this.message = 'object unsubscribed';
16739     this.name = 'ObjectUnsubscribedError';
16740     return this;
16741 }
16742 ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);
16743 exports.ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;
16744
16745 },{}],197:[function(require,module,exports){
16746 "use strict";
16747 Object.defineProperty(exports, "__esModule", { value: true });
16748 function TimeoutErrorImpl() {
16749     Error.call(this);
16750     this.message = 'Timeout has occurred';
16751     this.name = 'TimeoutError';
16752     return this;
16753 }
16754 TimeoutErrorImpl.prototype = Object.create(Error.prototype);
16755 exports.TimeoutError = TimeoutErrorImpl;
16756
16757 },{}],198:[function(require,module,exports){
16758 "use strict";
16759 Object.defineProperty(exports, "__esModule", { value: true });
16760 function UnsubscriptionErrorImpl(errors) {
16761     Error.call(this);
16762     this.message = errors ?
16763         errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ') : '';
16764     this.name = 'UnsubscriptionError';
16765     this.errors = errors;
16766     return this;
16767 }
16768 UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);
16769 exports.UnsubscriptionError = UnsubscriptionErrorImpl;
16770
16771 },{}],199:[function(require,module,exports){
16772 "use strict";
16773 Object.defineProperty(exports, "__esModule", { value: true });
16774 var Subscriber_1 = require("../Subscriber");
16775 function canReportError(observer) {
16776     while (observer) {
16777         var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
16778         if (closed_1 || isStopped) {
16779             return false;
16780         }
16781         else if (destination && destination instanceof Subscriber_1.Subscriber) {
16782             observer = destination;
16783         }
16784         else {
16785             observer = null;
16786         }
16787     }
16788     return true;
16789 }
16790 exports.canReportError = canReportError;
16791
16792 },{"../Subscriber":39}],200:[function(require,module,exports){
16793 "use strict";
16794 Object.defineProperty(exports, "__esModule", { value: true });
16795 exports.errorObject = { e: {} };
16796
16797 },{}],201:[function(require,module,exports){
16798 "use strict";
16799 Object.defineProperty(exports, "__esModule", { value: true });
16800 function hostReportError(err) {
16801     setTimeout(function () { throw err; });
16802 }
16803 exports.hostReportError = hostReportError;
16804
16805 },{}],202:[function(require,module,exports){
16806 "use strict";
16807 Object.defineProperty(exports, "__esModule", { value: true });
16808 function identity(x) {
16809     return x;
16810 }
16811 exports.identity = identity;
16812
16813 },{}],203:[function(require,module,exports){
16814 "use strict";
16815 Object.defineProperty(exports, "__esModule", { value: true });
16816 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
16817
16818 },{}],204:[function(require,module,exports){
16819 "use strict";
16820 Object.defineProperty(exports, "__esModule", { value: true });
16821 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
16822
16823 },{}],205:[function(require,module,exports){
16824 "use strict";
16825 Object.defineProperty(exports, "__esModule", { value: true });
16826 function isDate(value) {
16827     return value instanceof Date && !isNaN(+value);
16828 }
16829 exports.isDate = isDate;
16830
16831 },{}],206:[function(require,module,exports){
16832 "use strict";
16833 Object.defineProperty(exports, "__esModule", { value: true });
16834 function isFunction(x) {
16835     return typeof x === 'function';
16836 }
16837 exports.isFunction = isFunction;
16838
16839 },{}],207:[function(require,module,exports){
16840 "use strict";
16841 Object.defineProperty(exports, "__esModule", { value: true });
16842 var observable_1 = require("../symbol/observable");
16843 function isInteropObservable(input) {
16844     return input && typeof input[observable_1.observable] === 'function';
16845 }
16846 exports.isInteropObservable = isInteropObservable;
16847
16848 },{"../symbol/observable":191}],208:[function(require,module,exports){
16849 "use strict";
16850 Object.defineProperty(exports, "__esModule", { value: true });
16851 var iterator_1 = require("../symbol/iterator");
16852 function isIterable(input) {
16853     return input && typeof input[iterator_1.iterator] === 'function';
16854 }
16855 exports.isIterable = isIterable;
16856
16857 },{"../symbol/iterator":190}],209:[function(require,module,exports){
16858 "use strict";
16859 Object.defineProperty(exports, "__esModule", { value: true });
16860 var isArray_1 = require("./isArray");
16861 function isNumeric(val) {
16862     return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
16863 }
16864 exports.isNumeric = isNumeric;
16865
16866 },{"./isArray":203}],210:[function(require,module,exports){
16867 "use strict";
16868 Object.defineProperty(exports, "__esModule", { value: true });
16869 function isObject(x) {
16870     return x != null && typeof x === 'object';
16871 }
16872 exports.isObject = isObject;
16873
16874 },{}],211:[function(require,module,exports){
16875 "use strict";
16876 Object.defineProperty(exports, "__esModule", { value: true });
16877 var Observable_1 = require("../Observable");
16878 function isObservable(obj) {
16879     return !!obj && (obj instanceof Observable_1.Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));
16880 }
16881 exports.isObservable = isObservable;
16882
16883 },{"../Observable":32}],212:[function(require,module,exports){
16884 "use strict";
16885 Object.defineProperty(exports, "__esModule", { value: true });
16886 function isPromise(value) {
16887     return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
16888 }
16889 exports.isPromise = isPromise;
16890
16891 },{}],213:[function(require,module,exports){
16892 "use strict";
16893 Object.defineProperty(exports, "__esModule", { value: true });
16894 function isScheduler(value) {
16895     return value && typeof value.schedule === 'function';
16896 }
16897 exports.isScheduler = isScheduler;
16898
16899 },{}],214:[function(require,module,exports){
16900 "use strict";
16901 Object.defineProperty(exports, "__esModule", { value: true });
16902 function noop() { }
16903 exports.noop = noop;
16904
16905 },{}],215:[function(require,module,exports){
16906 "use strict";
16907 Object.defineProperty(exports, "__esModule", { value: true });
16908 function not(pred, thisArg) {
16909     function notPred() {
16910         return !(notPred.pred.apply(notPred.thisArg, arguments));
16911     }
16912     notPred.pred = pred;
16913     notPred.thisArg = thisArg;
16914     return notPred;
16915 }
16916 exports.not = not;
16917
16918 },{}],216:[function(require,module,exports){
16919 "use strict";
16920 Object.defineProperty(exports, "__esModule", { value: true });
16921 var noop_1 = require("./noop");
16922 function pipe() {
16923     var fns = [];
16924     for (var _i = 0; _i < arguments.length; _i++) {
16925         fns[_i] = arguments[_i];
16926     }
16927     return pipeFromArray(fns);
16928 }
16929 exports.pipe = pipe;
16930 function pipeFromArray(fns) {
16931     if (!fns) {
16932         return noop_1.noop;
16933     }
16934     if (fns.length === 1) {
16935         return fns[0];
16936     }
16937     return function piped(input) {
16938         return fns.reduce(function (prev, fn) { return fn(prev); }, input);
16939     };
16940 }
16941 exports.pipeFromArray = pipeFromArray;
16942
16943 },{"./noop":214}],217:[function(require,module,exports){
16944 "use strict";
16945 Object.defineProperty(exports, "__esModule", { value: true });
16946 var Observable_1 = require("../Observable");
16947 var subscribeToArray_1 = require("./subscribeToArray");
16948 var subscribeToPromise_1 = require("./subscribeToPromise");
16949 var subscribeToIterable_1 = require("./subscribeToIterable");
16950 var subscribeToObservable_1 = require("./subscribeToObservable");
16951 var isArrayLike_1 = require("./isArrayLike");
16952 var isPromise_1 = require("./isPromise");
16953 var isObject_1 = require("./isObject");
16954 var iterator_1 = require("../symbol/iterator");
16955 var observable_1 = require("../symbol/observable");
16956 exports.subscribeTo = function (result) {
16957     if (result instanceof Observable_1.Observable) {
16958         return function (subscriber) {
16959             if (result._isScalar) {
16960                 subscriber.next(result.value);
16961                 subscriber.complete();
16962                 return undefined;
16963             }
16964             else {
16965                 return result.subscribe(subscriber);
16966             }
16967         };
16968     }
16969     else if (result && typeof result[observable_1.observable] === 'function') {
16970         return subscribeToObservable_1.subscribeToObservable(result);
16971     }
16972     else if (isArrayLike_1.isArrayLike(result)) {
16973         return subscribeToArray_1.subscribeToArray(result);
16974     }
16975     else if (isPromise_1.isPromise(result)) {
16976         return subscribeToPromise_1.subscribeToPromise(result);
16977     }
16978     else if (result && typeof result[iterator_1.iterator] === 'function') {
16979         return subscribeToIterable_1.subscribeToIterable(result);
16980     }
16981     else {
16982         var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
16983         var msg = "You provided " + value + " where a stream was expected."
16984             + ' You can provide an Observable, Promise, Array, or Iterable.';
16985         throw new TypeError(msg);
16986     }
16987 };
16988
16989 },{"../Observable":32,"../symbol/iterator":190,"../symbol/observable":191,"./isArrayLike":204,"./isObject":210,"./isPromise":212,"./subscribeToArray":218,"./subscribeToIterable":219,"./subscribeToObservable":220,"./subscribeToPromise":221}],218:[function(require,module,exports){
16990 "use strict";
16991 Object.defineProperty(exports, "__esModule", { value: true });
16992 exports.subscribeToArray = function (array) { return function (subscriber) {
16993     for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) {
16994         subscriber.next(array[i]);
16995     }
16996     if (!subscriber.closed) {
16997         subscriber.complete();
16998     }
16999 }; };
17000
17001 },{}],219:[function(require,module,exports){
17002 "use strict";
17003 Object.defineProperty(exports, "__esModule", { value: true });
17004 var iterator_1 = require("../symbol/iterator");
17005 exports.subscribeToIterable = function (iterable) { return function (subscriber) {
17006     var iterator = iterable[iterator_1.iterator]();
17007     do {
17008         var item = iterator.next();
17009         if (item.done) {
17010             subscriber.complete();
17011             break;
17012         }
17013         subscriber.next(item.value);
17014         if (subscriber.closed) {
17015             break;
17016         }
17017     } while (true);
17018     if (typeof iterator.return === 'function') {
17019         subscriber.add(function () {
17020             if (iterator.return) {
17021                 iterator.return();
17022             }
17023         });
17024     }
17025     return subscriber;
17026 }; };
17027
17028 },{"../symbol/iterator":190}],220:[function(require,module,exports){
17029 "use strict";
17030 Object.defineProperty(exports, "__esModule", { value: true });
17031 var observable_1 = require("../symbol/observable");
17032 exports.subscribeToObservable = function (obj) { return function (subscriber) {
17033     var obs = obj[observable_1.observable]();
17034     if (typeof obs.subscribe !== 'function') {
17035         throw new TypeError('Provided object does not correctly implement Symbol.observable');
17036     }
17037     else {
17038         return obs.subscribe(subscriber);
17039     }
17040 }; };
17041
17042 },{"../symbol/observable":191}],221:[function(require,module,exports){
17043 "use strict";
17044 Object.defineProperty(exports, "__esModule", { value: true });
17045 var hostReportError_1 = require("./hostReportError");
17046 exports.subscribeToPromise = function (promise) { return function (subscriber) {
17047     promise.then(function (value) {
17048         if (!subscriber.closed) {
17049             subscriber.next(value);
17050             subscriber.complete();
17051         }
17052     }, function (err) { return subscriber.error(err); })
17053         .then(null, hostReportError_1.hostReportError);
17054     return subscriber;
17055 }; };
17056
17057 },{"./hostReportError":201}],222:[function(require,module,exports){
17058 "use strict";
17059 Object.defineProperty(exports, "__esModule", { value: true });
17060 var InnerSubscriber_1 = require("../InnerSubscriber");
17061 var subscribeTo_1 = require("./subscribeTo");
17062 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) {
17063     if (destination === void 0) { destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex); }
17064     if (destination.closed) {
17065         return;
17066     }
17067     return subscribeTo_1.subscribeTo(result)(destination);
17068 }
17069 exports.subscribeToResult = subscribeToResult;
17070
17071 },{"../InnerSubscriber":30,"./subscribeTo":217}],223:[function(require,module,exports){
17072 "use strict";
17073 Object.defineProperty(exports, "__esModule", { value: true });
17074 var Subscriber_1 = require("../Subscriber");
17075 var rxSubscriber_1 = require("../symbol/rxSubscriber");
17076 var Observer_1 = require("../Observer");
17077 function toSubscriber(nextOrObserver, error, complete) {
17078     if (nextOrObserver) {
17079         if (nextOrObserver instanceof Subscriber_1.Subscriber) {
17080             return nextOrObserver;
17081         }
17082         if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
17083             return nextOrObserver[rxSubscriber_1.rxSubscriber]();
17084         }
17085     }
17086     if (!nextOrObserver && !error && !complete) {
17087         return new Subscriber_1.Subscriber(Observer_1.empty);
17088     }
17089     return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
17090 }
17091 exports.toSubscriber = toSubscriber;
17092
17093 },{"../Observer":33,"../Subscriber":39,"../symbol/rxSubscriber":192}],224:[function(require,module,exports){
17094 "use strict";
17095 Object.defineProperty(exports, "__esModule", { value: true });
17096 var errorObject_1 = require("./errorObject");
17097 var tryCatchTarget;
17098 function tryCatcher() {
17099     try {
17100         return tryCatchTarget.apply(this, arguments);
17101     }
17102     catch (e) {
17103         errorObject_1.errorObject.e = e;
17104         return errorObject_1.errorObject;
17105     }
17106 }
17107 function tryCatch(fn) {
17108     tryCatchTarget = fn;
17109     return tryCatcher;
17110 }
17111 exports.tryCatch = tryCatch;
17112
17113 },{"./errorObject":200}],225:[function(require,module,exports){
17114 "use strict";
17115 Object.defineProperty(exports, "__esModule", { value: true });
17116 var audit_1 = require("../internal/operators/audit");
17117 exports.audit = audit_1.audit;
17118 var auditTime_1 = require("../internal/operators/auditTime");
17119 exports.auditTime = auditTime_1.auditTime;
17120 var buffer_1 = require("../internal/operators/buffer");
17121 exports.buffer = buffer_1.buffer;
17122 var bufferCount_1 = require("../internal/operators/bufferCount");
17123 exports.bufferCount = bufferCount_1.bufferCount;
17124 var bufferTime_1 = require("../internal/operators/bufferTime");
17125 exports.bufferTime = bufferTime_1.bufferTime;
17126 var bufferToggle_1 = require("../internal/operators/bufferToggle");
17127 exports.bufferToggle = bufferToggle_1.bufferToggle;
17128 var bufferWhen_1 = require("../internal/operators/bufferWhen");
17129 exports.bufferWhen = bufferWhen_1.bufferWhen;
17130 var catchError_1 = require("../internal/operators/catchError");
17131 exports.catchError = catchError_1.catchError;
17132 var combineAll_1 = require("../internal/operators/combineAll");
17133 exports.combineAll = combineAll_1.combineAll;
17134 var combineLatest_1 = require("../internal/operators/combineLatest");
17135 exports.combineLatest = combineLatest_1.combineLatest;
17136 var concat_1 = require("../internal/operators/concat");
17137 exports.concat = concat_1.concat;
17138 var concatAll_1 = require("../internal/operators/concatAll");
17139 exports.concatAll = concatAll_1.concatAll;
17140 var concatMap_1 = require("../internal/operators/concatMap");
17141 exports.concatMap = concatMap_1.concatMap;
17142 var concatMapTo_1 = require("../internal/operators/concatMapTo");
17143 exports.concatMapTo = concatMapTo_1.concatMapTo;
17144 var count_1 = require("../internal/operators/count");
17145 exports.count = count_1.count;
17146 var debounce_1 = require("../internal/operators/debounce");
17147 exports.debounce = debounce_1.debounce;
17148 var debounceTime_1 = require("../internal/operators/debounceTime");
17149 exports.debounceTime = debounceTime_1.debounceTime;
17150 var defaultIfEmpty_1 = require("../internal/operators/defaultIfEmpty");
17151 exports.defaultIfEmpty = defaultIfEmpty_1.defaultIfEmpty;
17152 var delay_1 = require("../internal/operators/delay");
17153 exports.delay = delay_1.delay;
17154 var delayWhen_1 = require("../internal/operators/delayWhen");
17155 exports.delayWhen = delayWhen_1.delayWhen;
17156 var dematerialize_1 = require("../internal/operators/dematerialize");
17157 exports.dematerialize = dematerialize_1.dematerialize;
17158 var distinct_1 = require("../internal/operators/distinct");
17159 exports.distinct = distinct_1.distinct;
17160 var distinctUntilChanged_1 = require("../internal/operators/distinctUntilChanged");
17161 exports.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
17162 var distinctUntilKeyChanged_1 = require("../internal/operators/distinctUntilKeyChanged");
17163 exports.distinctUntilKeyChanged = distinctUntilKeyChanged_1.distinctUntilKeyChanged;
17164 var elementAt_1 = require("../internal/operators/elementAt");
17165 exports.elementAt = elementAt_1.elementAt;
17166 var endWith_1 = require("../internal/operators/endWith");
17167 exports.endWith = endWith_1.endWith;
17168 var every_1 = require("../internal/operators/every");
17169 exports.every = every_1.every;
17170 var exhaust_1 = require("../internal/operators/exhaust");
17171 exports.exhaust = exhaust_1.exhaust;
17172 var exhaustMap_1 = require("../internal/operators/exhaustMap");
17173 exports.exhaustMap = exhaustMap_1.exhaustMap;
17174 var expand_1 = require("../internal/operators/expand");
17175 exports.expand = expand_1.expand;
17176 var filter_1 = require("../internal/operators/filter");
17177 exports.filter = filter_1.filter;
17178 var finalize_1 = require("../internal/operators/finalize");
17179 exports.finalize = finalize_1.finalize;
17180 var find_1 = require("../internal/operators/find");
17181 exports.find = find_1.find;
17182 var findIndex_1 = require("../internal/operators/findIndex");
17183 exports.findIndex = findIndex_1.findIndex;
17184 var first_1 = require("../internal/operators/first");
17185 exports.first = first_1.first;
17186 var groupBy_1 = require("../internal/operators/groupBy");
17187 exports.groupBy = groupBy_1.groupBy;
17188 var ignoreElements_1 = require("../internal/operators/ignoreElements");
17189 exports.ignoreElements = ignoreElements_1.ignoreElements;
17190 var isEmpty_1 = require("../internal/operators/isEmpty");
17191 exports.isEmpty = isEmpty_1.isEmpty;
17192 var last_1 = require("../internal/operators/last");
17193 exports.last = last_1.last;
17194 var map_1 = require("../internal/operators/map");
17195 exports.map = map_1.map;
17196 var mapTo_1 = require("../internal/operators/mapTo");
17197 exports.mapTo = mapTo_1.mapTo;
17198 var materialize_1 = require("../internal/operators/materialize");
17199 exports.materialize = materialize_1.materialize;
17200 var max_1 = require("../internal/operators/max");
17201 exports.max = max_1.max;
17202 var merge_1 = require("../internal/operators/merge");
17203 exports.merge = merge_1.merge;
17204 var mergeAll_1 = require("../internal/operators/mergeAll");
17205 exports.mergeAll = mergeAll_1.mergeAll;
17206 var mergeMap_1 = require("../internal/operators/mergeMap");
17207 exports.mergeMap = mergeMap_1.mergeMap;
17208 var mergeMap_2 = require("../internal/operators/mergeMap");
17209 exports.flatMap = mergeMap_2.mergeMap;
17210 var mergeMapTo_1 = require("../internal/operators/mergeMapTo");
17211 exports.mergeMapTo = mergeMapTo_1.mergeMapTo;
17212 var mergeScan_1 = require("../internal/operators/mergeScan");
17213 exports.mergeScan = mergeScan_1.mergeScan;
17214 var min_1 = require("../internal/operators/min");
17215 exports.min = min_1.min;
17216 var multicast_1 = require("../internal/operators/multicast");
17217 exports.multicast = multicast_1.multicast;
17218 var observeOn_1 = require("../internal/operators/observeOn");
17219 exports.observeOn = observeOn_1.observeOn;
17220 var onErrorResumeNext_1 = require("../internal/operators/onErrorResumeNext");
17221 exports.onErrorResumeNext = onErrorResumeNext_1.onErrorResumeNext;
17222 var pairwise_1 = require("../internal/operators/pairwise");
17223 exports.pairwise = pairwise_1.pairwise;
17224 var partition_1 = require("../internal/operators/partition");
17225 exports.partition = partition_1.partition;
17226 var pluck_1 = require("../internal/operators/pluck");
17227 exports.pluck = pluck_1.pluck;
17228 var publish_1 = require("../internal/operators/publish");
17229 exports.publish = publish_1.publish;
17230 var publishBehavior_1 = require("../internal/operators/publishBehavior");
17231 exports.publishBehavior = publishBehavior_1.publishBehavior;
17232 var publishLast_1 = require("../internal/operators/publishLast");
17233 exports.publishLast = publishLast_1.publishLast;
17234 var publishReplay_1 = require("../internal/operators/publishReplay");
17235 exports.publishReplay = publishReplay_1.publishReplay;
17236 var race_1 = require("../internal/operators/race");
17237 exports.race = race_1.race;
17238 var reduce_1 = require("../internal/operators/reduce");
17239 exports.reduce = reduce_1.reduce;
17240 var repeat_1 = require("../internal/operators/repeat");
17241 exports.repeat = repeat_1.repeat;
17242 var repeatWhen_1 = require("../internal/operators/repeatWhen");
17243 exports.repeatWhen = repeatWhen_1.repeatWhen;
17244 var retry_1 = require("../internal/operators/retry");
17245 exports.retry = retry_1.retry;
17246 var retryWhen_1 = require("../internal/operators/retryWhen");
17247 exports.retryWhen = retryWhen_1.retryWhen;
17248 var refCount_1 = require("../internal/operators/refCount");
17249 exports.refCount = refCount_1.refCount;
17250 var sample_1 = require("../internal/operators/sample");
17251 exports.sample = sample_1.sample;
17252 var sampleTime_1 = require("../internal/operators/sampleTime");
17253 exports.sampleTime = sampleTime_1.sampleTime;
17254 var scan_1 = require("../internal/operators/scan");
17255 exports.scan = scan_1.scan;
17256 var sequenceEqual_1 = require("../internal/operators/sequenceEqual");
17257 exports.sequenceEqual = sequenceEqual_1.sequenceEqual;
17258 var share_1 = require("../internal/operators/share");
17259 exports.share = share_1.share;
17260 var shareReplay_1 = require("../internal/operators/shareReplay");
17261 exports.shareReplay = shareReplay_1.shareReplay;
17262 var single_1 = require("../internal/operators/single");
17263 exports.single = single_1.single;
17264 var skip_1 = require("../internal/operators/skip");
17265 exports.skip = skip_1.skip;
17266 var skipLast_1 = require("../internal/operators/skipLast");
17267 exports.skipLast = skipLast_1.skipLast;
17268 var skipUntil_1 = require("../internal/operators/skipUntil");
17269 exports.skipUntil = skipUntil_1.skipUntil;
17270 var skipWhile_1 = require("../internal/operators/skipWhile");
17271 exports.skipWhile = skipWhile_1.skipWhile;
17272 var startWith_1 = require("../internal/operators/startWith");
17273 exports.startWith = startWith_1.startWith;
17274 var subscribeOn_1 = require("../internal/operators/subscribeOn");
17275 exports.subscribeOn = subscribeOn_1.subscribeOn;
17276 var switchAll_1 = require("../internal/operators/switchAll");
17277 exports.switchAll = switchAll_1.switchAll;
17278 var switchMap_1 = require("../internal/operators/switchMap");
17279 exports.switchMap = switchMap_1.switchMap;
17280 var switchMapTo_1 = require("../internal/operators/switchMapTo");
17281 exports.switchMapTo = switchMapTo_1.switchMapTo;
17282 var take_1 = require("../internal/operators/take");
17283 exports.take = take_1.take;
17284 var takeLast_1 = require("../internal/operators/takeLast");
17285 exports.takeLast = takeLast_1.takeLast;
17286 var takeUntil_1 = require("../internal/operators/takeUntil");
17287 exports.takeUntil = takeUntil_1.takeUntil;
17288 var takeWhile_1 = require("../internal/operators/takeWhile");
17289 exports.takeWhile = takeWhile_1.takeWhile;
17290 var tap_1 = require("../internal/operators/tap");
17291 exports.tap = tap_1.tap;
17292 var throttle_1 = require("../internal/operators/throttle");
17293 exports.throttle = throttle_1.throttle;
17294 var throttleTime_1 = require("../internal/operators/throttleTime");
17295 exports.throttleTime = throttleTime_1.throttleTime;
17296 var throwIfEmpty_1 = require("../internal/operators/throwIfEmpty");
17297 exports.throwIfEmpty = throwIfEmpty_1.throwIfEmpty;
17298 var timeInterval_1 = require("../internal/operators/timeInterval");
17299 exports.timeInterval = timeInterval_1.timeInterval;
17300 var timeout_1 = require("../internal/operators/timeout");
17301 exports.timeout = timeout_1.timeout;
17302 var timeoutWith_1 = require("../internal/operators/timeoutWith");
17303 exports.timeoutWith = timeoutWith_1.timeoutWith;
17304 var timestamp_1 = require("../internal/operators/timestamp");
17305 exports.timestamp = timestamp_1.timestamp;
17306 var toArray_1 = require("../internal/operators/toArray");
17307 exports.toArray = toArray_1.toArray;
17308 var window_1 = require("../internal/operators/window");
17309 exports.window = window_1.window;
17310 var windowCount_1 = require("../internal/operators/windowCount");
17311 exports.windowCount = windowCount_1.windowCount;
17312 var windowTime_1 = require("../internal/operators/windowTime");
17313 exports.windowTime = windowTime_1.windowTime;
17314 var windowToggle_1 = require("../internal/operators/windowToggle");
17315 exports.windowToggle = windowToggle_1.windowToggle;
17316 var windowWhen_1 = require("../internal/operators/windowWhen");
17317 exports.windowWhen = windowWhen_1.windowWhen;
17318 var withLatestFrom_1 = require("../internal/operators/withLatestFrom");
17319 exports.withLatestFrom = withLatestFrom_1.withLatestFrom;
17320 var zip_1 = require("../internal/operators/zip");
17321 exports.zip = zip_1.zip;
17322 var zipAll_1 = require("../internal/operators/zipAll");
17323 exports.zipAll = zipAll_1.zipAll;
17324
17325 },{"../internal/operators/audit":73,"../internal/operators/auditTime":74,"../internal/operators/buffer":75,"../internal/operators/bufferCount":76,"../internal/operators/bufferTime":77,"../internal/operators/bufferToggle":78,"../internal/operators/bufferWhen":79,"../internal/operators/catchError":80,"../internal/operators/combineAll":81,"../internal/operators/combineLatest":82,"../internal/operators/concat":83,"../internal/operators/concatAll":84,"../internal/operators/concatMap":85,"../internal/operators/concatMapTo":86,"../internal/operators/count":87,"../internal/operators/debounce":88,"../internal/operators/debounceTime":89,"../internal/operators/defaultIfEmpty":90,"../internal/operators/delay":91,"../internal/operators/delayWhen":92,"../internal/operators/dematerialize":93,"../internal/operators/distinct":94,"../internal/operators/distinctUntilChanged":95,"../internal/operators/distinctUntilKeyChanged":96,"../internal/operators/elementAt":97,"../internal/operators/endWith":98,"../internal/operators/every":99,"../internal/operators/exhaust":100,"../internal/operators/exhaustMap":101,"../internal/operators/expand":102,"../internal/operators/filter":103,"../internal/operators/finalize":104,"../internal/operators/find":105,"../internal/operators/findIndex":106,"../internal/operators/first":107,"../internal/operators/groupBy":108,"../internal/operators/ignoreElements":109,"../internal/operators/isEmpty":110,"../internal/operators/last":111,"../internal/operators/map":112,"../internal/operators/mapTo":113,"../internal/operators/materialize":114,"../internal/operators/max":115,"../internal/operators/merge":116,"../internal/operators/mergeAll":117,"../internal/operators/mergeMap":118,"../internal/operators/mergeMapTo":119,"../internal/operators/mergeScan":120,"../internal/operators/min":121,"../internal/operators/multicast":122,"../internal/operators/observeOn":123,"../internal/operators/onErrorResumeNext":124,"../internal/operators/pairwise":125,"../internal/operators/partition":126,"../internal/operators/pluck":127,"../internal/operators/publish":128,"../internal/operators/publishBehavior":129,"../internal/operators/publishLast":130,"../internal/operators/publishReplay":131,"../internal/operators/race":132,"../internal/operators/reduce":133,"../internal/operators/refCount":134,"../internal/operators/repeat":135,"../internal/operators/repeatWhen":136,"../internal/operators/retry":137,"../internal/operators/retryWhen":138,"../internal/operators/sample":139,"../internal/operators/sampleTime":140,"../internal/operators/scan":141,"../internal/operators/sequenceEqual":142,"../internal/operators/share":143,"../internal/operators/shareReplay":144,"../internal/operators/single":145,"../internal/operators/skip":146,"../internal/operators/skipLast":147,"../internal/operators/skipUntil":148,"../internal/operators/skipWhile":149,"../internal/operators/startWith":150,"../internal/operators/subscribeOn":151,"../internal/operators/switchAll":152,"../internal/operators/switchMap":153,"../internal/operators/switchMapTo":154,"../internal/operators/take":155,"../internal/operators/takeLast":156,"../internal/operators/takeUntil":157,"../internal/operators/takeWhile":158,"../internal/operators/tap":159,"../internal/operators/throttle":160,"../internal/operators/throttleTime":161,"../internal/operators/throwIfEmpty":162,"../internal/operators/timeInterval":163,"../internal/operators/timeout":164,"../internal/operators/timeoutWith":165,"../internal/operators/timestamp":166,"../internal/operators/toArray":167,"../internal/operators/window":168,"../internal/operators/windowCount":169,"../internal/operators/windowTime":170,"../internal/operators/windowToggle":171,"../internal/operators/windowWhen":172,"../internal/operators/withLatestFrom":173,"../internal/operators/zip":174,"../internal/operators/zipAll":175}],226:[function(require,module,exports){
17326 // threejs.org/license
17327 (function(l,ya){"object"===typeof exports&&"undefined"!==typeof module?ya(exports):"function"===typeof define&&define.amd?define(["exports"],ya):ya(l.THREE={})})(this,function(l){function ya(){}function z(a,b){this.x=a||0;this.y=b||0}function I(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function fa(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function p(a,
17328 b,c){this.x=a||0;this.y=b||0;this.z=c||0}function ra(){this.elements=[1,0,0,0,1,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function T(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:Ef++});this.uuid=H.generateUUID();this.name="";this.image=void 0!==a?a:T.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:T.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=void 0!==d?d:1001;this.magFilter=void 0!==
17329 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 z(0,0);this.repeat=new z(1,1);this.center=new z(0,0);this.rotation=0;this.matrixAutoUpdate=!0;this.matrix=new ra;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 V(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function fb(a,
17330 b,c){this.width=a;this.height=b;this.scissor=new V(0,0,a,b);this.scissorTest=!1;this.viewport=new V(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new T(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.texture.generateMipmaps=void 0!==c.generateMipmaps?c.generateMipmaps:!0;this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?
17331 c.depthTexture:null}function Gb(a,b,c){fb.call(this,a,b,c);this.activeMipMapLevel=this.activeCubeFace=0}function gb(a,b,c,d,e,f,g,h,k,m,q,n){T.call(this,null,f,g,h,k,m,d,e,q,n);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==m?m:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function Sa(a,b){this.min=void 0!==a?a:new p(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new p(-Infinity,-Infinity,-Infinity)}function Da(a,b){this.center=void 0!==
17332 a?a:new p;this.radius=void 0!==b?b:0}function Ma(a,b){this.normal=void 0!==a?a:new p(1,0,0);this.constant=void 0!==b?b:0}function md(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 G(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function Qd(){function a(e,f){!1!==c&&(d(e,f),b.requestAnimationFrame(a))}var b=null,c=!1,d=null;return{start:function(){!0!==c&&null!==d&&(b.requestAnimationFrame(a),
17333 c=!0)},stop:function(){c=!1},setAnimationLoop:function(a){d=a},setContext:function(a){b=a}}}function Ff(a){function b(b,c){var d=b.array,e=b.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW,h=a.createBuffer();a.bindBuffer(c,h);a.bufferData(c,d,e);b.onUploadCallback();c=a.FLOAT;d instanceof Float32Array?c=a.FLOAT:d instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):d instanceof Uint16Array?c=a.UNSIGNED_SHORT:d instanceof Int16Array?c=a.SHORT:d instanceof
17334 Uint32Array?c=a.UNSIGNED_INT:d instanceof Int32Array?c=a.INT:d instanceof Int8Array?c=a.BYTE:d instanceof Uint8Array&&(c=a.UNSIGNED_BYTE);return{buffer:h,type:c,bytesPerElement:d.BYTES_PER_ELEMENT,version:b.version}}var c=new WeakMap;return{get:function(a){a.isInterleavedBufferAttribute&&(a=a.data);return c.get(a)},remove:function(b){b.isInterleavedBufferAttribute&&(b=b.data);var d=c.get(b);d&&(a.deleteBuffer(d.buffer),c.delete(b))},update:function(d,e){d.isInterleavedBufferAttribute&&(d=d.data);
17335 var f=c.get(d);if(void 0===f)c.set(d,b(d,e));else if(f.version<d.version){var g=d,h=g.array,k=g.updateRange;a.bindBuffer(e,f.buffer);!1===g.dynamic?a.bufferData(e,h,a.STATIC_DRAW):-1===k.count?a.bufferSubData(e,0,h):0===k.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):(a.bufferSubData(e,k.offset*h.BYTES_PER_ELEMENT,h.subarray(k.offset,k.offset+k.count)),k.count=
17336 -1);f.version=d.version}}}}function hb(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||hb.DefaultOrder}function Rd(){this.mask=1}function D(){Object.defineProperty(this,"id",{value:Gf++});this.uuid=H.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=D.DefaultUp.clone();var a=new p,b=new hb,c=new fa,d=new p(1,1,1);b.onChange(function(){c.setFromEuler(b,!1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,
17337 {position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new I},normalMatrix:{value:new ra}});this.matrix=new I;this.matrixWorld=new I;this.matrixAutoUpdate=D.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Rd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=0;this.userData={}}function Na(){D.call(this);this.type="Camera";this.matrixWorldInverse=
17338 new I;this.projectionMatrix=new I}function Hb(a,b,c,d,e,f){Na.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function Ta(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new p;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?e:new G;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function R(){Object.defineProperty(this,
17339 "id",{value:Hf+=2});this.uuid=H.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 Q(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
17340 this.name="";this.array=a;this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===c;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.version=0}function oc(a,b,c){Q.call(this,new Int8Array(a),b,c)}function pc(a,b,c){Q.call(this,new Uint8Array(a),b,c)}function qc(a,b,c){Q.call(this,new Uint8ClampedArray(a),b,c)}function rc(a,b,c){Q.call(this,new Int16Array(a),b,c)}function ib(a,b,c){Q.call(this,new Uint16Array(a),b,c)}function sc(a,b,c){Q.call(this,new Int32Array(a),b,c)}function jb(a,
17341 b,c){Q.call(this,new Uint32Array(a),b,c)}function A(a,b,c){Q.call(this,new Float32Array(a),b,c)}function tc(a,b,c){Q.call(this,new Float64Array(a),b,c)}function Ee(){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 Fe(a){if(0===a.length)return-Infinity;
17342 for(var b=a[0],c=1,d=a.length;c<d;++c)a[c]>b&&(b=a[c]);return b}function C(){Object.defineProperty(this,"id",{value:If+=2});this.uuid=H.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};this.userData={}}function Ib(a,b,c,d,e,f){R.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,
17343 depthSegments:f};this.fromBufferGeometry(new kb(a,b,c,d,e,f));this.mergeVertices()}function kb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,l,N,O,Jf){var r=f/N,v=g/O,P=f/2,y=g/2,w=l/2;g=N+1;var E=O+1,x=f=0,B,z,A=new p;for(z=0;z<E;z++){var D=z*v-y;for(B=0;B<g;B++)A[a]=(B*r-P)*d,A[b]=D*e,A[c]=w,m.push(A.x,A.y,A.z),A[a]=0,A[b]=0,A[c]=0<l?1:-1,q.push(A.x,A.y,A.z),n.push(B/N),n.push(1-z/O),f+=1}for(z=0;z<O;z++)for(B=0;B<N;B++)a=t+B+g*(z+1),b=t+(B+1)+g*(z+1),c=t+(B+1)+g*z,k.push(t+B+g*z,a,c),k.push(a,b,c),x+=
17344 6;h.addGroup(u,x,Jf);u+=x;t+=f}C.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};var h=this;a=a||1;b=b||1;c=c||1;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=[],m=[],q=[],n=[],t=0,u=0;g("z","y","x",-1,-1,c,b,a,f,e,0);g("z","y","x",1,-1,c,b,-a,f,e,1);g("x","z","y",1,1,a,c,b,d,f,2);g("x","z","y",1,-1,a,c,-b,d,f,3);g("x","y","z",1,-1,a,b,c,d,e,4);g("x","y","z",-1,-1,a,b,-c,d,e,5);this.setIndex(k);this.addAttribute("position",
17345 new A(m,3));this.addAttribute("normal",new A(q,3));this.addAttribute("uv",new A(n,2))}function uc(a,b,c,d){R.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new lb(a,b,c,d));this.mergeVertices()}function lb(a,b,c,d){C.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};a=a||1;b=b||1;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=
17346 b/d,q=[],n=[],t=[],u=[];for(a=0;a<h;a++){var r=a*m-f;for(b=0;b<g;b++)n.push(b*k-e,-r,0),t.push(0,0,1),u.push(b/c),u.push(1-a/d)}for(a=0;a<d;a++)for(b=0;b<c;b++)e=b+g*(a+1),f=b+1+g*(a+1),h=b+1+g*a,q.push(b+g*a,e,h),q.push(e,f,h);this.setIndex(q);this.addAttribute("position",new A(n,3));this.addAttribute("normal",new A(t,3));this.addAttribute("uv",new A(u,2))}function J(){Object.defineProperty(this,"id",{value:Kf++});this.uuid=H.generateUUID();this.name="";this.type="Material";this.lights=this.fog=
17347 !0;this.blending=1;this.side=0;this.flatShading=!1;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.shadowSide=null;this.colorWrite=!0;this.precision=null;this.polygonOffset=!1;this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.dithering=!1;
17348 this.alphaTest=0;this.premultipliedAlpha=!1;this.overdraw=0;this.visible=!0;this.userData={};this.needsUpdate=!0}function da(a){J.call(this);this.type="MeshBasicMaterial";this.color=new G(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=
17349 this.morphTargets=this.skinning=!1;this.setValues(a)}function ta(a){J.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=this.morphTargets=this.skinning=this.clipping=this.lights=this.fog=!1;this.extensions=
17350 {derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=void 0;this.uniformsNeedUpdate=!1;void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(a))}function mb(a,b){this.origin=void 0!==a?a:new p;this.direction=void 0!==b?b:new p}function ja(a,b,c){this.a=void 0!==a?a:new p;this.b=void 0!==b?b:new p;this.c=
17351 void 0!==c?c:new p}function la(a,b){D.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new C;this.material=void 0!==b?b:new da({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Lf(a,b,c,d){function e(a,c){b.buffers.color.setClear(a.r,a.g,a.b,c,d)}var f=new G(0),g=0,h,k,m;return{getClearColor:function(){return f},setClearColor:function(a,b){f.set(a);g=void 0!==b?b:1;e(f,g)},getClearAlpha:function(){return g},setClearAlpha:function(a){g=a;e(f,g)},render:function(b,
17352 d,t,u){d=d.background;null===d?e(f,g):d&&d.isColor&&(e(d,1),u=!0);(a.autoClear||u)&&a.clear(a.autoClearColor,a.autoClearDepth,a.autoClearStencil);d&&d.isCubeTexture?(void 0===m&&(m=new la(new kb(1,1,1),new ta({uniforms:nb.cube.uniforms,vertexShader:nb.cube.vertexShader,fragmentShader:nb.cube.fragmentShader,side:1,depthTest:!0,depthWrite:!1,fog:!1})),m.geometry.removeAttribute("normal"),m.geometry.removeAttribute("uv"),m.onBeforeRender=function(a,b,c){this.matrixWorld.copyPosition(c.matrixWorld)},
17353 c.update(m)),m.material.uniforms.tCube.value=d,b.push(m,m.geometry,m.material,0,null)):d&&d.isTexture&&(void 0===h&&(h=new Hb(-1,1,1,-1,0,1),k=new la(new lb(2,2),new da({depthTest:!1,depthWrite:!1,fog:!1})),c.update(k)),k.material.map=d,a.renderBufferDirect(h,null,k.geometry,k.material,k,null))}}}function Mf(a,b,c,d){var e;this.setMode=function(a){e=a};this.render=function(b,d){a.drawArrays(e,b,d);c.update(d,e)};this.renderInstances=function(f,g,h){if(d.isWebGL2)var k=a;else if(k=b.get("ANGLE_instanced_arrays"),
17354 null===k){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}k[d.isWebGL2?"drawArraysInstanced":"drawArraysInstancedANGLE"](e,g,h,f.maxInstancedCount);c.update(h,e,f.maxInstancedCount)}}function Nf(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"===
17355 b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.MEDIUM_FLOAT).precision?"mediump":"lowp"}var e,f="undefined"!==typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext,g=void 0!==c.precision?c.precision:"highp",h=d(g);h!==g&&(console.warn("THREE.WebGLRenderer:",g,"not supported, using",h,"instead."),g=h);c=!0===c.logarithmicDepthBuffer;h=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS);var k=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
17356 m=a.getParameter(a.MAX_TEXTURE_SIZE),q=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),n=a.getParameter(a.MAX_VERTEX_ATTRIBS),t=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),u=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<k,y=f||!!b.get("OES_texture_float");return{isWebGL2:f,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,
17357 precision:g,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:k,maxTextureSize:m,maxCubemapSize:q,maxAttributes:n,maxVertexUniforms:t,maxVaryings:u,maxFragmentUniforms:r,vertexTextures:l,floatFragmentTextures:y,floatVertexTextures:l&&y}}function Of(){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===
17358 g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new Ma,k=new ra,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=
17359 function(c,h,k,u,r,l){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var n=4*k,q=r.clippingState||null;m.value=q;q=b(c,u,n,l);for(c=0;c!==n;++c)q[c]=d[c];r.clippingState=q;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Pf(a){var b={};return{get:function(c){if(void 0!==b[c])return b[c];switch(c){case "WEBGL_depth_texture":var d=a.getExtension("WEBGL_depth_texture")||a.getExtension("MOZ_WEBGL_depth_texture")||a.getExtension("WEBKIT_WEBGL_depth_texture");break;
17360 case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case "WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");
17361 break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function Qf(a,b,c){function d(a){var h=a.target;a=e[h.id];null!==a.index&&b.remove(a.index);for(var g in a.attributes)b.remove(a.attributes[g]);h.removeEventListener("dispose",d);delete e[h.id];if(g=f[a.id])b.remove(g),delete f[a.id];c.memory.geometries--}var e={},f={};return{get:function(a,b){var f=e[b.id];if(f)return f;b.addEventListener("dispose",d);b.isBufferGeometry?
17362 f=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new C).setFromObject(a)),f=b._bufferGeometry);e[b.id]=f;c.memory.geometries++;return f},update:function(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f],a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c){d=c[f];e=0;for(var g=d.length;e<g;e++)b.update(d[e],a.ARRAY_BUFFER)}},getWireframeAttribute:function(c){var d=f[c.id];if(d)return d;d=[];var e=c.index,g=c.attributes;if(null!==
17363 e){e=e.array;g=0;for(var q=e.length;g<q;g+=3){var n=e[g+0],t=e[g+1],u=e[g+2];d.push(n,t,t,u,u,n)}}else for(e=g.position.array,g=0,q=e.length/3-1;g<q;g+=3)n=g+0,t=g+1,u=g+2,d.push(n,t,t,u,u,n);d=new (65535<Fe(d)?jb:ib)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=d}}}function Rf(a,b,c,d){var e,f,g;this.setMode=function(a){e=a};this.setIndex=function(a){f=a.type;g=a.bytesPerElement};this.render=function(b,d){a.drawElements(e,d,f,b*g);c.update(d,e)};this.renderInstances=function(h,k,m){if(d.isWebGL2)var q=
17364 a;else if(q=b.get("ANGLE_instanced_arrays"),null===q){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}q[d.isWebGL2?"drawElementsInstanced":"drawElementsInstancedANGLE"](e,m,f,k*g,h.maxInstancedCount);c.update(m,e,h.maxInstancedCount)}}function Sf(a){var b={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:b,programs:null,autoReset:!0,reset:function(){b.frame++;
17365 b.calls=0;b.triangles=0;b.points=0;b.lines=0},update:function(c,d,e){e=e||1;b.calls++;switch(d){case a.TRIANGLES:b.triangles+=c/3*e;break;case a.TRIANGLE_STRIP:case a.TRIANGLE_FAN:b.triangles+=e*(c-2);break;case a.LINES:b.lines+=c/2*e;break;case a.LINE_STRIP:b.lines+=e*(c-1);break;case a.LINE_LOOP:b.lines+=e*c;break;case a.POINTS:b.points+=e*c;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",d)}}}}function Tf(a,b){return Math.abs(b[1])-Math.abs(a[1])}function Uf(a){var b={},c=new Float32Array(8);
17366 return{update:function(d,e,f,g){var h=d.morphTargetInfluences,k=h.length;d=b[e.id];if(void 0===d){d=[];for(var m=0;m<k;m++)d[m]=[m,0];b[e.id]=d}var q=f.morphTargets&&e.morphAttributes.position;f=f.morphNormals&&e.morphAttributes.normal;for(m=0;m<k;m++){var n=d[m];0!==n[1]&&(q&&e.removeAttribute("morphTarget"+m),f&&e.removeAttribute("morphNormal"+m))}for(m=0;m<k;m++)n=d[m],n[0]=m,n[1]=h[m];d.sort(Tf);for(m=0;8>m;m++){if(n=d[m])if(h=n[0],k=n[1]){q&&e.addAttribute("morphTarget"+m,q[h]);f&&e.addAttribute("morphNormal"+
17367 m,f[h]);c[m]=k;continue}c[m]=0}g.getUniforms().setValue(a,"morphTargetInfluences",c)}}}function Vf(a,b){var c={};return{update:function(d){var e=b.render.frame,f=d.geometry,g=a.get(d,f);c[g.id]!==e&&(f.isGeometry&&g.updateFromObject(d),a.update(g),c[g.id]=e);return g},dispose:function(){c={}}}}function Ua(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];T.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,m);this.flipY=!1}function Jb(a,b,c){var d=a[0];if(0>=d||0<d)return a;var e=b*c,f=Ge[e];void 0===f&&(f=new Float32Array(e),
17368 Ge[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 ea(a,b){if(a.length!==b.length)return!1;for(var c=0,d=a.length;c<d;c++)if(a[c]!==b[c])return!1;return!0}function qa(a,b){for(var c=0,d=b.length;c<d;c++)a[c]=b[c]}function He(a,b){var c=Ie[b];void 0===c&&(c=new Int32Array(b),Ie[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function Wf(a,b){var c=this.cache;c[0]!==b&&(a.uniform1f(this.addr,b),c[0]=b)}function Xf(a,b){var c=this.cache;c[0]!==
17369 b&&(a.uniform1i(this.addr,b),c[0]=b)}function Yf(a,b){var c=this.cache;if(void 0!==b.x){if(c[0]!==b.x||c[1]!==b.y)a.uniform2f(this.addr,b.x,b.y),c[0]=b.x,c[1]=b.y}else ea(c,b)||(a.uniform2fv(this.addr,b),qa(c,b))}function Zf(a,b){var c=this.cache;if(void 0!==b.x){if(c[0]!==b.x||c[1]!==b.y||c[2]!==b.z)a.uniform3f(this.addr,b.x,b.y,b.z),c[0]=b.x,c[1]=b.y,c[2]=b.z}else if(void 0!==b.r){if(c[0]!==b.r||c[1]!==b.g||c[2]!==b.b)a.uniform3f(this.addr,b.r,b.g,b.b),c[0]=b.r,c[1]=b.g,c[2]=b.b}else ea(c,b)||(a.uniform3fv(this.addr,
17370 b),qa(c,b))}function $f(a,b){var c=this.cache;if(void 0!==b.x){if(c[0]!==b.x||c[1]!==b.y||c[2]!==b.z||c[3]!==b.w)a.uniform4f(this.addr,b.x,b.y,b.z,b.w),c[0]=b.x,c[1]=b.y,c[2]=b.z,c[3]=b.w}else ea(c,b)||(a.uniform4fv(this.addr,b),qa(c,b))}function ag(a,b){var c=this.cache,d=b.elements;void 0===d?ea(c,b)||(a.uniformMatrix2fv(this.addr,!1,b),qa(c,b)):ea(c,d)||(Je.set(d),a.uniformMatrix2fv(this.addr,!1,Je),qa(c,d))}function bg(a,b){var c=this.cache,d=b.elements;void 0===d?ea(c,b)||(a.uniformMatrix3fv(this.addr,
17371 !1,b),qa(c,b)):ea(c,d)||(Ke.set(d),a.uniformMatrix3fv(this.addr,!1,Ke),qa(c,d))}function cg(a,b){var c=this.cache,d=b.elements;void 0===d?ea(c,b)||(a.uniformMatrix4fv(this.addr,!1,b),qa(c,b)):ea(c,d)||(Le.set(d),a.uniformMatrix4fv(this.addr,!1,Le),qa(c,d))}function dg(a,b,c){var d=this.cache,e=c.allocTextureUnit();d[0]!==e&&(a.uniform1i(this.addr,e),d[0]=e);c.setTexture2D(b||Me,e)}function eg(a,b,c){var d=this.cache,e=c.allocTextureUnit();d[0]!==e&&(a.uniform1i(this.addr,e),d[0]=e);c.setTextureCube(b||
17372 Ne,e)}function Oe(a,b){var c=this.cache;ea(c,b)||(a.uniform2iv(this.addr,b),qa(c,b))}function Pe(a,b){var c=this.cache;ea(c,b)||(a.uniform3iv(this.addr,b),qa(c,b))}function Qe(a,b){var c=this.cache;ea(c,b)||(a.uniform4iv(this.addr,b),qa(c,b))}function fg(a){switch(a){case 5126:return Wf;case 35664:return Yf;case 35665:return Zf;case 35666:return $f;case 35674:return ag;case 35675:return bg;case 35676:return cg;case 35678:case 36198:return dg;case 35680:return eg;case 5124:case 35670:return Xf;case 35667:case 35671:return Oe;
17373 case 35668:case 35672:return Pe;case 35669:case 35673:return Qe}}function gg(a,b){var c=this.cache;ea(c,b)||(a.uniform1fv(this.addr,b),qa(c,b))}function hg(a,b){var c=this.cache;ea(c,b)||(a.uniform1iv(this.addr,b),qa(c,b))}function ig(a,b){var c=this.cache;b=Jb(b,this.size,2);ea(c,b)||(a.uniform2fv(this.addr,b),this.updateCache(b))}function jg(a,b){var c=this.cache;b=Jb(b,this.size,3);ea(c,b)||(a.uniform3fv(this.addr,b),this.updateCache(b))}function kg(a,b){var c=this.cache;b=Jb(b,this.size,4);ea(c,
17374 b)||(a.uniform4fv(this.addr,b),this.updateCache(b))}function lg(a,b){var c=this.cache;b=Jb(b,this.size,4);ea(c,b)||(a.uniformMatrix2fv(this.addr,!1,b),this.updateCache(b))}function mg(a,b){var c=this.cache;b=Jb(b,this.size,9);ea(c,b)||(a.uniformMatrix3fv(this.addr,!1,b),this.updateCache(b))}function ng(a,b){var c=this.cache;b=Jb(b,this.size,16);ea(c,b)||(a.uniformMatrix4fv(this.addr,!1,b),this.updateCache(b))}function og(a,b,c){var d=this.cache,e=b.length,f=He(c,e);!1===ea(d,f)&&(a.uniform1iv(this.addr,
17375 f),qa(d,f));for(a=0;a!==e;++a)c.setTexture2D(b[a]||Me,f[a])}function pg(a,b,c){var d=this.cache,e=b.length,f=He(c,e);!1===ea(d,f)&&(a.uniform1iv(this.addr,f),qa(d,f));for(a=0;a!==e;++a)c.setTextureCube(b[a]||Ne,f[a])}function qg(a){switch(a){case 5126:return gg;case 35664:return ig;case 35665:return jg;case 35666:return kg;case 35674:return lg;case 35675:return mg;case 35676:return ng;case 35678:return og;case 35680:return pg;case 5124:case 35670:return hg;case 35667:case 35671:return Oe;case 35668:case 35672:return Pe;
17376 case 35669:case 35673:return Qe}}function rg(a,b,c){this.id=a;this.addr=c;this.cache=[];this.setValue=fg(b.type)}function Re(a,b,c){this.id=a;this.addr=c;this.cache=[];this.size=b.size;this.setValue=qg(b.type)}function Se(a){this.id=a;this.seq=[];this.map={}}function Za(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(Vd.lastIndex=0;;){var m=
17377 Vd.exec(h),q=Vd.lastIndex,n=m[1],t=m[3];"]"===m[2]&&(n|=0);if(void 0===t||"["===t&&q+2===k){h=g;e=void 0===t?new rg(n,e,f):new Re(n,e,f);h.seq.push(e);h.map[e.id]=e;break}else t=g.map[n],void 0===t&&(t=new Se(n),n=g,g=t,n.seq.push(g),n.map[g.id]=g),g=t}}}function sg(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Te(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.");
17378 ""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),sg(c));return d}function Ue(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: "+
17379 a);}}function Wd(a,b){b=Ue(b);return"vec4 "+a+"( vec4 value ) { return "+b[0]+"ToLinear"+b[1]+"; }"}function tg(a,b){b=Ue(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+b[0]+b[1]+"; }"}function ug(a,b){switch(b){case 1:b="Linear";break;case 2:b="Reinhard";break;case 3:b="Uncharted2";break;case 4:b="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+b);}return"vec3 "+a+"( vec3 color ) { return "+b+"ToneMapping( color ); }"}function vg(a,b,c){a=a||{};return[a.derivatives||
17380 b.envMapCubeUV||b.bumpMap||b.normalMap&&!b.objectSpaceNormalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(vc).join("\n")}function wg(a){var b=[],c;for(c in a){var d=
17381 a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function vc(a){return""!==a}function Ve(a,b){return a.replace(/NUM_DIR_LIGHTS/g,b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,b.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function We(a,b){return a.replace(/NUM_CLIPPING_PLANES/g,b.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,b.numClippingPlanes-b.numClipIntersection)}function Xd(a){return a.replace(/^[ \t]*#include +<([\w\d./]+)>/gm,
17382 function(a,c){a=S[c];if(void 0===a)throw Error("Can not resolve #include <"+c+">");return Xd(a)})}function Xe(a){return a.replace(/#pragma unroll_loop[\s]+?for \( int i = (\d+); i < (\d+); i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function xg(a,b,c,d,e,f,g){var h=a.context,k=d.defines,m=e.vertexShader,q=e.fragmentShader,n="SHADOWMAP_TYPE_BASIC";1===f.shadowMapType?n="SHADOWMAP_TYPE_PCF":2===f.shadowMapType&&
17383 (n="SHADOWMAP_TYPE_PCF_SOFT");var t="ENVMAP_TYPE_CUBE",u="ENVMAP_MODE_REFLECTION",r="ENVMAP_BLENDING_MULTIPLY";if(f.envMap){switch(d.envMap.mapping){case 301:case 302:t="ENVMAP_TYPE_CUBE";break;case 306:case 307:t="ENVMAP_TYPE_CUBE_UV";break;case 303:case 304:t="ENVMAP_TYPE_EQUIREC";break;case 305:t="ENVMAP_TYPE_SPHERE"}switch(d.envMap.mapping){case 302:case 304:u="ENVMAP_MODE_REFRACTION"}switch(d.combine){case 0:r="ENVMAP_BLENDING_MULTIPLY";break;case 1:r="ENVMAP_BLENDING_MIX";break;case 2:r="ENVMAP_BLENDING_ADD"}}var l=
17384 0<a.gammaFactor?a.gammaFactor:1,y=g.isWebGL2?"":vg(d.extensions,f,b),p=wg(k),w=h.createProgram();d.isRawShaderMaterial?(k=[p].filter(vc).join("\n"),0<k.length&&(k+="\n"),b=[y,p].filter(vc).join("\n"),0<b.length&&(b+="\n")):(k=["precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,p,f.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+l,"#define MAX_BONES "+f.maxBones,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":
17385 "",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+u:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":"",f.normalMap?"#define USE_NORMALMAP":"",f.normalMap&&f.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",f.displacementMap&&f.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":
17386 "",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.flatShading?"#define FLAT_SHADED":"",f.skinning?"#define USE_SKINNING":"",f.useVertexTexture?"#define BONE_TEXTURE":"",f.morphTargets?"#define USE_MORPHTARGETS":"",f.morphNormals&&!1===f.flatShading?"#define USE_MORPHNORMALS":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"",f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+
17387 n:"",f.sizeAttenuation?"#define USE_SIZEATTENUATION":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&(g.isWebGL2||b.get("EXT_frag_depth"))?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;",
17388 "#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif",
17389 "#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(vc).join("\n"),b=[y,"precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,p,f.alphaTest?"#define ALPHATEST "+f.alphaTest+(f.alphaTest%1?"":".0"):"","#define GAMMA_FACTOR "+l,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+t:"",f.envMap?"#define "+
17390 u:"",f.envMap?"#define "+r:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":"",f.normalMap?"#define USE_NORMALMAP":"",f.normalMap&&f.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":"",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.gradientMap?
17391 "#define USE_GRADIENTMAP":"",f.flatShading?"#define FLAT_SHADED":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"",f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+n:"",f.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",f.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&(g.isWebGL2||b.get("EXT_frag_depth"))?"#define USE_LOGDEPTHBUF_EXT":"",f.envMap&&
17392 (g.isWebGL2||b.get("EXT_shader_texture_lod"))?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==f.toneMapping?"#define TONE_MAPPING":"",0!==f.toneMapping?S.tonemapping_pars_fragment:"",0!==f.toneMapping?ug("toneMapping",f.toneMapping):"",f.dithering?"#define DITHERING":"",f.outputEncoding||f.mapEncoding||f.envMapEncoding||f.emissiveMapEncoding?S.encodings_pars_fragment:"",f.mapEncoding?Wd("mapTexelToLinear",f.mapEncoding):"",f.envMapEncoding?Wd("envMapTexelToLinear",
17393 f.envMapEncoding):"",f.emissiveMapEncoding?Wd("emissiveMapTexelToLinear",f.emissiveMapEncoding):"",f.outputEncoding?tg("linearToOutputTexel",f.outputEncoding):"",f.depthPacking?"#define DEPTH_PACKING "+d.depthPacking:"","\n"].filter(vc).join("\n"));m=Xd(m);m=Ve(m,f);m=We(m,f);q=Xd(q);q=Ve(q,f);q=We(q,f);m=Xe(m);q=Xe(q);g.isWebGL2&&!d.isRawShaderMaterial&&(g=!1,n=/^\s*#version\s+300\s+es\s*\n/,d.isShaderMaterial&&null!==m.match(n)&&null!==q.match(n)&&(g=!0,m=m.replace(n,""),q=q.replace(n,"")),k="#version 300 es\n\n#define attribute in\n#define varying out\n#define texture2D texture\n"+
17394 k,b=["#version 300 es\n\n#define varying in",g?"":"out highp vec4 pc_fragColor;",g?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth\n#define texture2D texture\n#define textureCube texture\n#define texture2DProj textureProj\n#define texture2DLodEXT textureLod\n#define texture2DProjLodEXT textureProjLod\n#define textureCubeLodEXT textureLod\n#define texture2DGradEXT textureGrad\n#define texture2DProjGradEXT textureProjGrad\n#define textureCubeGradEXT textureGrad"].join("\n")+
17395 "\n"+b);q=b+q;m=Te(h,h.VERTEX_SHADER,k+m);q=Te(h,h.FRAGMENT_SHADER,q);h.attachShader(w,m);h.attachShader(w,q);void 0!==d.index0AttributeName?h.bindAttribLocation(w,0,d.index0AttributeName):!0===f.morphTargets&&h.bindAttribLocation(w,0,"position");h.linkProgram(w);f=h.getProgramInfoLog(w).trim();g=h.getShaderInfoLog(m).trim();n=h.getShaderInfoLog(q).trim();u=t=!0;if(!1===h.getProgramParameter(w,h.LINK_STATUS))t=!1,console.error("THREE.WebGLProgram: shader error: ",h.getError(),"gl.VALIDATE_STATUS",
17396 h.getProgramParameter(w,h.VALIDATE_STATUS),"gl.getProgramInfoLog",f,g,n);else if(""!==f)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",f);else if(""===g||""===n)u=!1;u&&(this.diagnostics={runnable:t,material:d,programLog:f,vertexShader:{log:g,prefix:k},fragmentShader:{log:n,prefix:b}});h.deleteShader(m);h.deleteShader(q);var B;this.getUniforms=function(){void 0===B&&(B=new Za(h,w,a));return B};var E;this.getAttributes=function(){if(void 0===E){for(var a={},b=h.getProgramParameter(w,h.ACTIVE_ATTRIBUTES),
17397 c=0;c<b;c++){var d=h.getActiveAttrib(w,c).name;a[d]=h.getAttribLocation(w,d)}E=a}return E};this.destroy=function(){h.deleteProgram(w);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.name=e.name;this.id=yg++;this.code=c;this.usedTimes=1;this.program=
17398 w;this.vertexShader=m;this.fragmentShader=q;return this}function zg(a,b,c){function d(a,b){if(a)a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=a.texture.encoding);else var c=3E3;3E3===c&&b&&(c=3007);return c}var e=[],f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",
17399 MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"},g="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap objectSpaceNormalMap displacementMap specularMap roughnessMap metalnessMap gradientMap alphaMap combine vertexColors fog useFog fogExp flatShading sizeAttenuation logarithmicDepthBuffer skinning maxBones useVertexTexture morphTargets morphNormals maxMorphTargets maxMorphNormals premultipliedAlpha numDirLights numPointLights numSpotLights numHemiLights numRectAreaLights shadowMapEnabled shadowMapType toneMapping physicallyCorrectLights alphaTest doubleSided flipSided numClippingPlanes numClipIntersection depthPacking dithering".split(" ");
17400 this.getParameters=function(b,e,g,q,n,t,u){var h=f[b.type];if(u.isSkinnedMesh){var k=u.skeleton.bones;if(c.floatVertexTextures)k=1024;else{var m=Math.min(Math.floor((c.maxVertexUniforms-20)/4),k.length);m<k.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+k.length+" bones. This GPU supports "+m+"."),k=0):k=m}}else k=0;m=c.precision;null!==b.precision&&(m=c.getMaxPrecision(b.precision),m!==b.precision&&console.warn("THREE.WebGLProgram.getParameters:",b.precision,"not supported, using",m,"instead."));
17401 var l=a.getRenderTarget();return{shaderID:h,precision:m,supportsVertexTextures:c.vertexTextures,outputEncoding:d(l?l.texture:null,a.gammaOutput),map:!!b.map,mapEncoding:d(b.map,a.gammaInput),envMap:!!b.envMap,envMapMode:b.envMap&&b.envMap.mapping,envMapEncoding:d(b.envMap,a.gammaInput),envMapCubeUV:!!b.envMap&&(306===b.envMap.mapping||307===b.envMap.mapping),lightMap:!!b.lightMap,aoMap:!!b.aoMap,emissiveMap:!!b.emissiveMap,emissiveMapEncoding:d(b.emissiveMap,a.gammaInput),bumpMap:!!b.bumpMap,normalMap:!!b.normalMap,
17402 objectSpaceNormalMap:1===b.normalMapType,displacementMap:!!b.displacementMap,roughnessMap:!!b.roughnessMap,metalnessMap:!!b.metalnessMap,specularMap:!!b.specularMap,alphaMap:!!b.alphaMap,gradientMap:!!b.gradientMap,combine:b.combine,vertexColors:b.vertexColors,fog:!!q,useFog:b.fog,fogExp:q&&q.isFogExp2,flatShading:b.flatShading,sizeAttenuation:b.sizeAttenuation,logarithmicDepthBuffer:c.logarithmicDepthBuffer,skinning:b.skinning&&0<k,maxBones:k,useVertexTexture:c.floatVertexTextures,morphTargets:b.morphTargets,
17403 morphNormals:b.morphNormals,maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:e.directional.length,numPointLights:e.point.length,numSpotLights:e.spot.length,numRectAreaLights:e.rectArea.length,numHemiLights:e.hemi.length,numClippingPlanes:n,numClipIntersection:t,dithering:b.dithering,shadowMapEnabled:a.shadowMap.enabled&&u.receiveShadow&&0<g.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:b.premultipliedAlpha,
17404 alphaTest:b.alphaTest,doubleSided:2===b.side,flipSided:1===b.side,depthPacking:void 0!==b.depthPacking?b.depthPacking:!1}};this.getProgramCode=function(b,c){var d=[];c.shaderID?d.push(c.shaderID):(d.push(b.fragmentShader),d.push(b.vertexShader));if(void 0!==b.defines)for(var e in b.defines)d.push(e),d.push(b.defines[e]);for(e=0;e<g.length;e++)d.push(c[g[e]]);d.push(b.onBeforeCompile.toString());d.push(a.gammaOutput);return d.join()};this.acquireProgram=function(d,f,g,q){for(var h,k=0,m=e.length;k<
17405 m;k++){var r=e[k];if(r.code===q){h=r;++h.usedTimes;break}}void 0===h&&(h=new xg(a,b,q,d,f,g,c),e.push(h));return h};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=e.indexOf(a);e[b]=e[e.length-1];e.pop();a.destroy()}};this.programs=e}function Ag(){var a=new WeakMap;return{get:function(b){var c=a.get(b);void 0===c&&(c={},a.set(b,c));return c},remove:function(b){a.delete(b)},update:function(b,c,d){a.get(b)[c]=d},dispose:function(){a=new WeakMap}}}function Bg(a,b){return a.renderOrder!==
17406 b.renderOrder?a.renderOrder-b.renderOrder:a.program&&b.program&&a.program!==b.program?a.program.id-b.program.id:a.material.id!==b.material.id?a.material.id-b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Cg(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Dg(){var a=[],b=0,c=[],d=[];return{opaque:c,transparent:d,init:function(){b=0;c.length=0;d.length=0},push:function(e,f,g,h,k){var m=a[b];void 0===m?(m={id:e.id,object:e,geometry:f,material:g,
17407 program:g.program,renderOrder:e.renderOrder,z:h,group:k},a[b]=m):(m.id=e.id,m.object=e,m.geometry=f,m.material=g,m.program=g.program,m.renderOrder=e.renderOrder,m.z=h,m.group=k);(!0===g.transparent?d:c).push(m);b++},sort:function(){1<c.length&&c.sort(Bg);1<d.length&&d.sort(Cg)}}}function Eg(){var a={};return{get:function(b,c){b=b.id+","+c.id;c=a[b];void 0===c&&(c=new Dg,a[b]=c);return c},dispose:function(){a={}}}}function Fg(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];switch(b.type){case "DirectionalLight":var c=
17408 {direction:new p,color:new G,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new z};break;case "SpotLight":c={position:new p,direction:new p,color:new G,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new z};break;case "PointLight":c={position:new p,color:new G,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new z,shadowCameraNear:1,shadowCameraFar:1E3};break;case "HemisphereLight":c={direction:new p,skyColor:new G,groundColor:new G};
17409 break;case "RectAreaLight":c={color:new G,position:new p,halfWidth:new p,halfHeight:new p}}return a[b.id]=c}}}function Gg(){var a=new Fg,b={id:Hg++,hash:{stateID:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,shadowsLength:-1},ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]},c=new p,d=new I,e=new I;return{setup:function(f,
17410 g,h){var k=0,m=0,q=0,n=0,t=0,u=0,r=0,l=0;h=h.matrixWorldInverse;for(var y=0,p=f.length;y<p;y++){var w=f[y],B=w.color,E=w.intensity,P=w.distance,N=w.shadow&&w.shadow.map?w.shadow.map.texture:null;if(w.isAmbientLight)k+=B.r*E,m+=B.g*E,q+=B.b*E;else if(w.isDirectionalLight){var O=a.get(w);O.color.copy(w.color).multiplyScalar(w.intensity);O.direction.setFromMatrixPosition(w.matrixWorld);c.setFromMatrixPosition(w.target.matrixWorld);O.direction.sub(c);O.direction.transformDirection(h);if(O.shadow=w.castShadow)B=
17411 w.shadow,O.shadowBias=B.bias,O.shadowRadius=B.radius,O.shadowMapSize=B.mapSize;b.directionalShadowMap[n]=N;b.directionalShadowMatrix[n]=w.shadow.matrix;b.directional[n]=O;n++}else if(w.isSpotLight){O=a.get(w);O.position.setFromMatrixPosition(w.matrixWorld);O.position.applyMatrix4(h);O.color.copy(B).multiplyScalar(E);O.distance=P;O.direction.setFromMatrixPosition(w.matrixWorld);c.setFromMatrixPosition(w.target.matrixWorld);O.direction.sub(c);O.direction.transformDirection(h);O.coneCos=Math.cos(w.angle);
17412 O.penumbraCos=Math.cos(w.angle*(1-w.penumbra));O.decay=0===w.distance?0:w.decay;if(O.shadow=w.castShadow)B=w.shadow,O.shadowBias=B.bias,O.shadowRadius=B.radius,O.shadowMapSize=B.mapSize;b.spotShadowMap[u]=N;b.spotShadowMatrix[u]=w.shadow.matrix;b.spot[u]=O;u++}else if(w.isRectAreaLight)O=a.get(w),O.color.copy(B).multiplyScalar(E),O.position.setFromMatrixPosition(w.matrixWorld),O.position.applyMatrix4(h),e.identity(),d.copy(w.matrixWorld),d.premultiply(h),e.extractRotation(d),O.halfWidth.set(.5*w.width,
17413 0,0),O.halfHeight.set(0,.5*w.height,0),O.halfWidth.applyMatrix4(e),O.halfHeight.applyMatrix4(e),b.rectArea[r]=O,r++;else if(w.isPointLight){O=a.get(w);O.position.setFromMatrixPosition(w.matrixWorld);O.position.applyMatrix4(h);O.color.copy(w.color).multiplyScalar(w.intensity);O.distance=w.distance;O.decay=0===w.distance?0:w.decay;if(O.shadow=w.castShadow)B=w.shadow,O.shadowBias=B.bias,O.shadowRadius=B.radius,O.shadowMapSize=B.mapSize,O.shadowCameraNear=B.camera.near,O.shadowCameraFar=B.camera.far;
17414 b.pointShadowMap[t]=N;b.pointShadowMatrix[t]=w.shadow.matrix;b.point[t]=O;t++}else w.isHemisphereLight&&(O=a.get(w),O.direction.setFromMatrixPosition(w.matrixWorld),O.direction.transformDirection(h),O.direction.normalize(),O.skyColor.copy(w.color).multiplyScalar(E),O.groundColor.copy(w.groundColor).multiplyScalar(E),b.hemi[l]=O,l++)}b.ambient[0]=k;b.ambient[1]=m;b.ambient[2]=q;b.directional.length=n;b.spot.length=u;b.rectArea.length=r;b.point.length=t;b.hemi.length=l;b.hash.stateID=b.id;b.hash.directionalLength=
17415 n;b.hash.pointLength=t;b.hash.spotLength=u;b.hash.rectAreaLength=r;b.hash.hemiLength=l;b.hash.shadowsLength=g.length},state:b}}function Ye(){var a=new Gg,b=[],c=[];return{init:function(){b.length=0;c.length=0},state:{lightsArray:b,shadowsArray:c,lights:a},setupLights:function(d){a.setup(b,c,d)},pushLight:function(a){b.push(a)},pushShadow:function(a){c.push(a)}}}function Ig(){var a={};return{get:function(b,c){if(void 0===a[b.id]){var d=new Ye;a[b.id]={};a[b.id][c.id]=d}else void 0===a[b.id][c.id]?
17416 (d=new Ye,a[b.id][c.id]=d):d=a[b.id][c.id];return d},dispose:function(){a={}}}}function $a(a){J.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=this.skinning=!1;this.displacementMap=this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.lights=this.fog=!1;this.setValues(a)}function ab(a){J.call(this);this.type="MeshDistanceMaterial";this.referencePosition=new p;this.nearDistance=1;this.farDistance=
17417 1E3;this.morphTargets=this.skinning=!1;this.displacementMap=this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.lights=this.fog=!1;this.setValues(a)}function Ze(a,b,c){function d(b,c,d,e,f,g){var h=b.geometry;var k=n;var m=b.customDepthMaterial;d&&(k=t,m=b.customDistanceMaterial);m?k=m:(m=!1,c.morphTargets&&(h&&h.isBufferGeometry?m=h.morphAttributes&&h.morphAttributes.position&&0<h.morphAttributes.position.length:h&&h.isGeometry&&(m=h.morphTargets&&0<h.morphTargets.length)),
17418 b.isSkinnedMesh&&!1===c.skinning&&console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",b),b=b.isSkinnedMesh&&c.skinning,h=0,m&&(h|=1),b&&(h|=2),k=k[h]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(h=k.uuid,m=c.uuid,b=u[h],void 0===b&&(b={},u[h]=b),h=b[m],void 0===h&&(h=k.clone(),b[m]=h),k=h);k.visible=c.visible;k.wireframe=c.wireframe;k.side=null!=c.shadowSide?c.shadowSide:r[c.side];k.clipShadows=c.clipShadows;k.clippingPlanes=c.clippingPlanes;
17419 k.clipIntersection=c.clipIntersection;k.wireframeLinewidth=c.wireframeLinewidth;k.linewidth=c.linewidth;d&&k.isMeshDistanceMaterial&&(k.referencePosition.copy(e),k.nearDistance=f,k.farDistance=g);return k}function e(c,g,h,k){if(!1!==c.visible){if(c.layers.test(g.layers)&&(c.isMesh||c.isLine||c.isPoints)&&c.castShadow&&(!c.frustumCulled||f.intersectsObject(c))){c.modelViewMatrix.multiplyMatrices(h.matrixWorldInverse,c.matrixWorld);var m=b.update(c),n=c.material;if(Array.isArray(n))for(var t=m.groups,
17420 u=0,r=t.length;u<r;u++){var l=t[u],P=n[l.materialIndex];P&&P.visible&&(P=d(c,P,k,q,h.near,h.far),a.renderBufferDirect(h,null,m,P,c,l))}else n.visible&&(P=d(c,n,k,q,h.near,h.far),a.renderBufferDirect(h,null,m,P,c,null))}c=c.children;m=0;for(n=c.length;m<n;m++)e(c[m],g,h,k)}}var f=new md,g=new I,h=new z,k=new z(c,c),m=new p,q=new p,n=Array(4),t=Array(4),u={},r={0:1,1:0,2:2},l=[new p(1,0,0),new p(-1,0,0),new p(0,0,1),new p(0,0,-1),new p(0,1,0),new p(0,-1,0)],y=[new p(0,1,0),new p(0,1,0),new p(0,1,0),
17421 new p(0,1,0),new p(0,0,1),new p(0,0,-1)],x=[new V,new V,new V,new V,new V,new V];for(c=0;4!==c;++c){var w=0!==(c&1),B=0!==(c&2),E=new $a({depthPacking:3201,morphTargets:w,skinning:B});n[c]=E;w=new ab({morphTargets:w,skinning:B});t[c]=w}var P=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.render=function(b,c,d){if(!1!==P.enabled&&(!1!==P.autoUpdate||!1!==P.needsUpdate)&&0!==b.length){var n=a.state;n.disable(a.context.BLEND);n.buffers.color.setClear(1,1,1,1);n.buffers.depth.setTest(!0);
17422 n.setScissorTest(!1);for(var t,u=0,r=b.length;u<r;u++){var v=b[u];t=v.shadow;var p=v&&v.isPointLight;if(void 0===t)console.warn("THREE.WebGLShadowMap:",v,"has no shadow.");else{var w=t.camera;h.copy(t.mapSize);h.min(k);if(p){var N=h.x,E=h.y;x[0].set(2*N,E,N,E);x[1].set(0,E,N,E);x[2].set(3*N,E,N,E);x[3].set(N,E,N,E);x[4].set(3*N,0,N,E);x[5].set(N,0,N,E);h.x*=4;h.y*=2}null===t.map&&(t.map=new fb(h.x,h.y,{minFilter:1003,magFilter:1003,format:1023}),t.map.texture.name=v.name+".shadowMap",w.updateProjectionMatrix());
17423 t.isSpotLightShadow&&t.update(v);N=t.map;E=t.matrix;q.setFromMatrixPosition(v.matrixWorld);w.position.copy(q);p?(t=6,E.makeTranslation(-q.x,-q.y,-q.z)):(t=1,m.setFromMatrixPosition(v.target.matrixWorld),w.lookAt(m),w.updateMatrixWorld(),E.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),E.multiply(w.projectionMatrix),E.multiply(w.matrixWorldInverse));a.setRenderTarget(N);a.clear();for(v=0;v<t;v++)p&&(m.copy(w.position),m.add(l[v]),w.up.copy(y[v]),w.lookAt(m),w.updateMatrixWorld(),n.viewport(x[v])),g.multiplyMatrices(w.projectionMatrix,
17424 w.matrixWorldInverse),f.setFromMatrix(g),e(c,d,w,p)}}P.needsUpdate=!1}}}function Jg(a,b,c,d){function e(b,c,d){var e=new Uint8Array(4),f=a.createTexture();a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b<d;b++)a.texImage2D(c+b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function f(c,e){x[c]=1;0===w[c]&&(a.enableVertexAttribArray(c),w[c]=1);B[c]!==e&&((d.isWebGL2?a:b.get("ANGLE_instanced_arrays"))[d.isWebGL2?"vertexAttribDivisor":
17425 "vertexAttribDivisorANGLE"](c,e),B[c]=e)}function g(b){!0!==E[b]&&(a.enable(b),E[b]=!0)}function h(b){!1!==E[b]&&(a.disable(b),E[b]=!1)}function k(b,d,e,f,k,m,n,q){0!==b?g(a.BLEND):h(a.BLEND);if(5!==b){if(b!==O||q!==C)switch(b){case 2:q?(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));break;case 3:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,
17426 a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR));break;case 4:q?(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));break;default:q?(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,
17427 a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA))}D=A=Ud=Td=Sd=z=null}else{k=k||d;m=m||e;n=n||f;if(d!==z||k!==Ud)a.blendEquationSeparate(c.convert(d),c.convert(k)),z=d,Ud=k;if(e!==Sd||f!==Td||m!==A||n!==D)a.blendFuncSeparate(c.convert(e),c.convert(f),c.convert(m),c.convert(n)),Sd=e,Td=f,A=m,D=n}O=b;C=q}function m(b){G!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),G=b)}function q(b){0!==b?(g(a.CULL_FACE),b!==K&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):h(a.CULL_FACE);
17428 K=b}function n(b,c,d){if(b){if(g(a.POLYGON_OFFSET_FILL),R!==c||I!==d)a.polygonOffset(c,d),R=c,I=d}else h(a.POLYGON_OFFSET_FILL)}function t(b){void 0===b&&(b=a.TEXTURE0+J-1);Q!==b&&(a.activeTexture(b),Q=b)}var u=new function(){var b=!1,c=new V,d=null,e=new V(0,0,0,0);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;
17429 d=null;e.set(-1,0,0,0)}}},r=new function(){var b=!1,c=null,d=null,e=null;return{setTest:function(b){b?g(a.DEPTH_TEST):h(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);break;case 7:a.depthFunc(a.NOTEQUAL);
17430 break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){e!==b&&(a.clearDepth(b),e=b)},reset:function(){b=!1;e=d=c=null}}},l=new function(){var b=!1,c=null,d=null,e=null,f=null,k=null,m=null,n=null,q=null;return{setTest:function(b){b?g(a.STENCIL_TEST):h(a.STENCIL_TEST)},setMask:function(d){c===d||b||(a.stencilMask(d),c=d)},setFunc:function(b,c,g){if(d!==b||e!==c||f!==g)a.stencilFunc(b,c,g),d=b,e=c,f=g},setOp:function(b,c,d){if(k!==b||m!==
17431 c||n!==d)a.stencilOp(b,c,d),k=b,m=c,n=d},setLocked:function(a){b=a},setClear:function(b){q!==b&&(a.clearStencil(b),q=b)},reset:function(){b=!1;q=n=m=k=f=e=d=c=null}}},p=a.getParameter(a.MAX_VERTEX_ATTRIBS),x=new Uint8Array(p),w=new Uint8Array(p),B=new Uint8Array(p),E={},P=null,N=null,O=null,z=null,Sd=null,Td=null,Ud=null,A=null,D=null,C=!1,G=null,K=null,L=null,R=null,I=null,J=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS),H=!1;p=0;p=a.getParameter(a.VERSION);-1!==p.indexOf("WebGL")?(p=parseFloat(/^WebGL ([0-9])/.exec(p)[1]),
17432 H=1<=p):-1!==p.indexOf("OpenGL ES")&&(p=parseFloat(/^OpenGL ES ([0-9])/.exec(p)[1]),H=2<=p);var Q=null,S={},Y=new V,W=new V,M={};M[a.TEXTURE_2D]=e(a.TEXTURE_2D,a.TEXTURE_2D,1);M[a.TEXTURE_CUBE_MAP]=e(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);u.setClear(0,0,0,1);r.setClear(1);l.setClear(0);g(a.DEPTH_TEST);r.setFunc(3);m(!1);q(1);g(a.CULL_FACE);g(a.BLEND);k(1);return{buffers:{color:u,depth:r,stencil:l},initAttributes:function(){for(var a=0,b=x.length;a<b;a++)x[a]=0},enableAttribute:function(a){f(a,
17433 0)},enableAttributeAndDivisor:f,disableUnusedAttributes:function(){for(var b=0,c=w.length;b!==c;++b)w[b]!==x[b]&&(a.disableVertexAttribArray(b),w[b]=0)},enable:g,disable:h,getCompressedTextureFormats:function(){if(null===P&&(P=[],b.get("WEBGL_compressed_texture_pvrtc")||b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")||b.get("WEBGL_compressed_texture_astc")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)P.push(c[d]);return P},useProgram:function(b){return N!==
17434 b?(a.useProgram(b),N=b,!0):!1},setBlending:k,setMaterial:function(b,c){2===b.side?h(a.CULL_FACE):g(a.CULL_FACE);var d=1===b.side;c&&(d=!d);m(d);1===b.blending&&!1===b.transparent?k(0):k(b.blending,b.blendEquation,b.blendSrc,b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha);r.setFunc(b.depthFunc);r.setTest(b.depthTest);r.setMask(b.depthWrite);u.setMask(b.colorWrite);n(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:m,setCullFace:q,setLineWidth:function(b){b!==
17435 L&&(H&&a.lineWidth(b),L=b)},setPolygonOffset:n,setScissorTest:function(b){b?g(a.SCISSOR_TEST):h(a.SCISSOR_TEST)},activeTexture:t,bindTexture:function(b,c){null===Q&&t();var d=S[Q];void 0===d&&(d={type:void 0,texture:void 0},S[Q]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||M[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,arguments)}catch(U){console.error("THREE.WebGLState:",U)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(U){console.error("THREE.WebGLState:",
17436 U)}},scissor:function(b){!1===Y.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),Y.copy(b))},viewport:function(b){!1===W.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),W.copy(b))},reset:function(){for(var b=0;b<w.length;b++)1===w[b]&&(a.disableVertexAttribArray(b),w[b]=0);E={};Q=P=null;S={};K=G=O=N=null;u.reset();r.reset();l.reset()}}}function Kg(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){if("data"in a){console.warn("THREE.WebGLRenderer: image in DataTexture is too big ("+a.width+"x"+a.height+").");
17437 return}b/=Math.max(a.width,a.height);var c=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");c.width=Math.floor(a.width*b);c.height=Math.floor(a.height*b);c.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,c.width,c.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+c.width+"x"+c.height);return c}return a}function k(a){return H.isPowerOfTwo(a.width)&&H.isPowerOfTwo(a.height)}function m(a,b){return a.generateMipmaps&&b&&1003!==
17438 a.minFilter&&1006!==a.minFilter}function q(b,c,e,f){a.generateMipmap(b);d.get(c).__maxMipLevel=Math.log(Math.max(e,f))*Math.LOG2E}function n(b,c){if(!e.isWebGL2)return b;if(b===a.RGB){if(c===a.FLOAT)return a.RGB32F;if(c===a.HALF_FLOAT)return a.RGB16F;if(c===a.UNSIGNED_BYTE)return a.RGB8}if(b===a.RGBA){if(c===a.FLOAT)return a.RGBA32F;if(c===a.HALF_FLOAT)return a.RGBA16F;if(c===a.UNSIGNED_BYTE)return a.RGBA8}return b}function t(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function u(b){b=
17439 b.target;b.removeEventListener("dispose",u);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}b.isVideoTexture&&delete B[b.id];g.memory.textures--}function r(b){b=b.target;b.removeEventListener("dispose",r);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=
17440 0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.memory.textures--}function l(b,t){var r=d.get(b);if(b.isVideoTexture){var l=b.id,v=g.render.frame;B[l]!==v&&(B[l]=v,b.update())}if(0<b.version&&r.__version!==b.version)if(l=b.image,void 0===l)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined");
17441 else if(!1===l.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{void 0===r.__webglInit&&(r.__webglInit=!0,b.addEventListener("dispose",u),r.__webglTexture=a.createTexture(),g.memory.textures++);c.activeTexture(a.TEXTURE0+t);c.bindTexture(a.TEXTURE_2D,r.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);t=h(b.image,e.maxTextureSize);
17442 (e.isWebGL2?0:1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(t)&&(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof ImageBitmap)&&(void 0===E&&(E=document.createElementNS("http://www.w3.org/1999/xhtml","canvas")),E.width=H.floorPowerOfTwo(t.width),E.height=H.floorPowerOfTwo(t.height),E.getContext("2d").drawImage(t,0,0,E.width,E.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+t.width+"x"+t.height+"). Resized to "+E.width+
17443 "x"+E.height),t=E);l=k(t);v=f.convert(b.format);var w=f.convert(b.type),y=n(v,w);p(a.TEXTURE_2D,b,l);var P=b.mipmaps;if(b.isDepthTexture){y=a.DEPTH_COMPONENT;if(1015===b.type){if(!e.isWebGL2)throw Error("Float Depth Texture only supported in WebGL2.0");y=a.DEPTH_COMPONENT32F}else e.isWebGL2&&(y=a.DEPTH_COMPONENT16);1026===b.format&&y===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),b.type=
17444 1012,w=f.convert(b.type));1027===b.format&&(y=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,w=f.convert(b.type)));c.texImage2D(a.TEXTURE_2D,0,y,t.width,t.height,0,v,w,null)}else if(b.isDataTexture)if(0<P.length&&l){for(var N=0,x=P.length;N<x;N++){var z=P[N];c.texImage2D(a.TEXTURE_2D,N,y,z.width,z.height,0,v,w,z.data)}b.generateMipmaps=!1;r.__maxMipLevel=P.length-1}else c.texImage2D(a.TEXTURE_2D,0,y,t.width,
17445 t.height,0,v,w,t.data),r.__maxMipLevel=0;else if(b.isCompressedTexture){N=0;for(x=P.length;N<x;N++)z=P[N],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(v)?c.compressedTexImage2D(a.TEXTURE_2D,N,y,z.width,z.height,0,z.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):c.texImage2D(a.TEXTURE_2D,N,y,z.width,z.height,0,v,w,z.data);r.__maxMipLevel=P.length-1}else if(0<P.length&&l){N=0;for(x=P.length;N<x;N++)z=
17446 P[N],c.texImage2D(a.TEXTURE_2D,N,y,v,w,z);b.generateMipmaps=!1;r.__maxMipLevel=P.length-1}else c.texImage2D(a.TEXTURE_2D,0,y,v,w,t),r.__maxMipLevel=0;m(b,l)&&q(a.TEXTURE_2D,b,t.width,t.height);r.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}c.activeTexture(a.TEXTURE0+t);c.bindTexture(a.TEXTURE_2D,r.__webglTexture)}function p(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f.convert(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,f.convert(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f.convert(g.magFilter)),
17447 a.texParameteri(c,a.TEXTURE_MIN_FILTER,f.convert(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),1001===g.wrapS&&1001===g.wrapT||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),a.texParameteri(c,a.TEXTURE_MAG_FILTER,t(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,t(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."));
17448 !(h=b.get("EXT_texture_filter_anisotropic"))||1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===(e.isWebGL2||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 x(b,e,g,h){var k=f.convert(e.texture.format),m=f.convert(e.texture.type),q=n(k,m);c.texImage2D(h,0,q,e.width,e.height,0,k,m,null);
17449 a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function w(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,
17450 a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var B={},E;this.setTexture2D=l;this.setTextureCube=function(b,t){var r=d.get(b);if(6===b.image.length)if(0<b.version&&r.__version!==b.version){r.__image__webglTextureCube||(b.addEventListener("dispose",u),r.__image__webglTextureCube=a.createTexture(),g.memory.textures++);c.activeTexture(a.TEXTURE0+t);c.bindTexture(a.TEXTURE_CUBE_MAP,r.__image__webglTextureCube);
17451 a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);t=b&&b.isCompressedTexture;for(var l=b.image[0]&&b.image[0].isDataTexture,v=[],w=0;6>w;w++)v[w]=t||l?l?b.image[w].image:b.image[w]:h(b.image[w],e.maxCubemapSize);var y=v[0],E=k(y),P=f.convert(b.format),x=f.convert(b.type),N=n(P,x);p(a.TEXTURE_CUBE_MAP,b,E);for(w=0;6>w;w++)if(t)for(var B,z=v[w].mipmaps,A=0,D=z.length;A<D;A++)B=z[A],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(P)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+
17452 w,A,N,B.width,B.height,0,B.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,A,N,B.width,B.height,0,P,x,B.data);else l?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,0,N,v[w].width,v[w].height,0,P,x,v[w].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,0,N,P,x,v[w]);r.__maxMipLevel=t?z.length-1:0;m(b,E)&&q(a.TEXTURE_CUBE_MAP,b,y.width,y.height);r.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+
17453 t),c.bindTexture(a.TEXTURE_CUBE_MAP,r.__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",r);f.__webglTexture=a.createTexture();g.memory.textures++;var h=!0===b.isWebGLRenderTargetCube,n=k(b);if(h){e.__webglFramebuffer=[];for(var t=0;6>t;t++)e.__webglFramebuffer[t]=a.createFramebuffer()}else e.__webglFramebuffer=
17454 a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);p(a.TEXTURE_CUBE_MAP,b.texture,n);for(t=0;6>t;t++)x(e.__webglFramebuffer[t],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+t);m(b.texture,n)&&q(a.TEXTURE_CUBE_MAP,b.texture,b.width,b.height);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),p(a.TEXTURE_2D,b.texture,n),x(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),m(b.texture,n)&&q(a.TEXTURE_2D,b.texture,b.width,b.height),
17455 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&&
17456 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);l(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");
17457 }else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),w(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),w(e.__webglDepthbuffer,b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=k(b);if(m(e,f)){f=b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D;var g=d.get(e).__webglTexture;
17458 c.bindTexture(f,g);q(f,e,b.width,b.height);c.bindTexture(f,null)}}}function $e(a,b,c){return{convert:function(d){if(1E3===d)return a.REPEAT;if(1001===d)return a.CLAMP_TO_EDGE;if(1002===d)return a.MIRRORED_REPEAT;if(1003===d)return a.NEAREST;if(1004===d)return a.NEAREST_MIPMAP_NEAREST;if(1005===d)return a.NEAREST_MIPMAP_LINEAR;if(1006===d)return a.LINEAR;if(1007===d)return a.LINEAR_MIPMAP_NEAREST;if(1008===d)return a.LINEAR_MIPMAP_LINEAR;if(1009===d)return a.UNSIGNED_BYTE;if(1017===d)return a.UNSIGNED_SHORT_4_4_4_4;
17459 if(1018===d)return a.UNSIGNED_SHORT_5_5_5_1;if(1019===d)return a.UNSIGNED_SHORT_5_6_5;if(1010===d)return a.BYTE;if(1011===d)return a.SHORT;if(1012===d)return a.UNSIGNED_SHORT;if(1013===d)return a.INT;if(1014===d)return a.UNSIGNED_INT;if(1015===d)return a.FLOAT;if(1016===d){if(c.isWebGL2)return a.HALF_FLOAT;var e=b.get("OES_texture_half_float");if(null!==e)return e.HALF_FLOAT_OES}if(1021===d)return a.ALPHA;if(1022===d)return a.RGB;if(1023===d)return a.RGBA;if(1024===d)return a.LUMINANCE;if(1025===
17460 d)return a.LUMINANCE_ALPHA;if(1026===d)return a.DEPTH_COMPONENT;if(1027===d)return a.DEPTH_STENCIL;if(100===d)return a.FUNC_ADD;if(101===d)return a.FUNC_SUBTRACT;if(102===d)return a.FUNC_REVERSE_SUBTRACT;if(200===d)return a.ZERO;if(201===d)return a.ONE;if(202===d)return a.SRC_COLOR;if(203===d)return a.ONE_MINUS_SRC_COLOR;if(204===d)return a.SRC_ALPHA;if(205===d)return a.ONE_MINUS_SRC_ALPHA;if(206===d)return a.DST_ALPHA;if(207===d)return a.ONE_MINUS_DST_ALPHA;if(208===d)return a.DST_COLOR;if(209===
17461 d)return a.ONE_MINUS_DST_COLOR;if(210===d)return a.SRC_ALPHA_SATURATE;if(33776===d||33777===d||33778===d||33779===d)if(e=b.get("WEBGL_compressed_texture_s3tc"),null!==e){if(33776===d)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===d)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===d)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===d)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===d||35841===d||35842===d||35843===d)if(e=b.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(35840===d)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
17462 if(35841===d)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===d)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===d)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===d&&(e=b.get("WEBGL_compressed_texture_etc1"),null!==e))return e.COMPRESSED_RGB_ETC1_WEBGL;if(37808===d||37809===d||37810===d||37811===d||37812===d||37813===d||37814===d||37815===d||37816===d||37817===d||37818===d||37819===d||37820===d||37821===d)if(e=b.get("WEBGL_compressed_texture_astc"),null!==e)return d;if(103===d||104===
17463 d){if(c.isWebGL2){if(103===d)return a.MIN;if(104===d)return a.MAX}e=b.get("EXT_blend_minmax");if(null!==e){if(103===d)return e.MIN_EXT;if(104===d)return e.MAX_EXT}}if(1020===d){if(c.isWebGL2)return a.UNSIGNED_INT_24_8;e=b.get("WEBGL_depth_texture");if(null!==e)return e.UNSIGNED_INT_24_8_WEBGL}return 0}}}function Kb(){D.call(this);this.type="Group"}function Z(a,b,c,d){Na.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;
17464 this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}function yc(a){Z.call(this);this.cameras=a||[]}function af(a){function b(){return null!==e&&!0===e.isPresenting}function c(){if(b()){var c=e.getEyeParameters("left"),f=c.renderWidth;c=c.renderHeight;x=a.getPixelRatio();y=a.getSize();a.setDrawingBufferSize(2*f,c,1);B.start()}else d.enabled&&(a.setDrawingBufferSize(y.width,y.height,x),B.stop())}var d=this,e=null,f=null,g=null,h=
17465 [],k=new I,m=new I;"undefined"!==typeof window&&"VRFrameData"in window&&(f=new window.VRFrameData,window.addEventListener("vrdisplaypresentchange",c,!1));var q=new I,n=new fa,t=new p,u=new Z;u.bounds=new V(0,0,.5,1);u.layers.enable(1);var r=new Z;r.bounds=new V(.5,0,.5,1);r.layers.enable(2);var l=new yc([u,r]);l.layers.enable(1);l.layers.enable(2);var y,x,w=[];this.enabled=!1;this.userHeight=1.6;this.getController=function(a){var b=h[a];void 0===b&&(b=new Kb,b.matrixAutoUpdate=!1,b.visible=!1,h[a]=
17466 b);return b};this.getDevice=function(){return e};this.setDevice=function(a){void 0!==a&&(e=a);B.setContext(a)};this.setPoseTarget=function(a){void 0!==a&&(g=a)};this.getCamera=function(a){if(null===e)return a.position.set(0,d.userHeight,0),a;e.depthNear=a.near;e.depthFar=a.far;e.getFrameData(f);var b=e.stageParameters;b?k.fromArray(b.sittingToStandingTransform):k.makeTranslation(0,d.userHeight,0);b=f.pose;var c=null!==g?g:a;c.matrix.copy(k);c.matrix.decompose(c.position,c.quaternion,c.scale);null!==
17467 b.orientation&&(n.fromArray(b.orientation),c.quaternion.multiply(n));null!==b.position&&(n.setFromRotationMatrix(k),t.fromArray(b.position),t.applyQuaternion(n),c.position.add(t));c.updateMatrixWorld();if(!1===e.isPresenting)return a;u.near=a.near;r.near=a.near;u.far=a.far;r.far=a.far;l.matrixWorld.copy(a.matrixWorld);l.matrixWorldInverse.copy(a.matrixWorldInverse);u.matrixWorldInverse.fromArray(f.leftViewMatrix);r.matrixWorldInverse.fromArray(f.rightViewMatrix);m.getInverse(k);u.matrixWorldInverse.multiply(m);
17468 r.matrixWorldInverse.multiply(m);a=c.parent;null!==a&&(q.getInverse(a.matrixWorld),u.matrixWorldInverse.multiply(q),r.matrixWorldInverse.multiply(q));u.matrixWorld.getInverse(u.matrixWorldInverse);r.matrixWorld.getInverse(r.matrixWorldInverse);u.projectionMatrix.fromArray(f.leftProjectionMatrix);r.projectionMatrix.fromArray(f.rightProjectionMatrix);l.projectionMatrix.copy(u.projectionMatrix);a=e.getLayers();a.length&&(a=a[0],null!==a.leftBounds&&4===a.leftBounds.length&&u.bounds.fromArray(a.leftBounds),
17469 null!==a.rightBounds&&4===a.rightBounds.length&&r.bounds.fromArray(a.rightBounds));a:for(a=0;a<h.length;a++){b=h[a];b:{c=a;for(var v=navigator.getGamepads&&navigator.getGamepads(),p=0,y=0,x=v.length;p<x;p++){var E=v[p];if(E&&("Daydream Controller"===E.id||"Gear VR Controller"===E.id||"Oculus Go Controller"===E.id||"OpenVR Gamepad"===E.id||E.id.startsWith("Oculus Touch")||E.id.startsWith("Spatial Controller"))){if(y===c){c=E;break b}y++}}c=void 0}if(void 0!==c&&void 0!==c.pose){if(null===c.pose)break a;
17470 v=c.pose;!1===v.hasPosition&&b.position.set(.2,-.6,-.05);null!==v.position&&b.position.fromArray(v.position);null!==v.orientation&&b.quaternion.fromArray(v.orientation);b.matrix.compose(b.position,b.quaternion,b.scale);b.matrix.premultiply(k);b.matrix.decompose(b.position,b.quaternion,b.scale);b.matrixWorldNeedsUpdate=!0;b.visible=!0;v="Daydream Controller"===c.id?0:1;w[a]!==c.buttons[v].pressed&&(w[a]=c.buttons[v].pressed,!0===w[a]?b.dispatchEvent({type:"selectstart"}):(b.dispatchEvent({type:"selectend"}),
17471 b.dispatchEvent({type:"select"})))}else b.visible=!1}return l};this.getStandingMatrix=function(){return k};this.isPresenting=b;var B=new Qd;this.setAnimationLoop=function(a){B.setAnimationLoop(a)};this.submitFrame=function(){b()&&e.submitFrame()};this.dispose=function(){"undefined"!==typeof window&&window.removeEventListener("vrdisplaypresentchange",c)}}function Lg(a){function b(){return null!==h&&null!==k}function c(a){var b=q[n.indexOf(a.inputSource)];b&&b.dispatchEvent({type:a.type})}function d(){a.setFramebuffer(null);
17472 p.stop()}function e(a,b){null===b?a.matrixWorld.copy(a.matrix):a.matrixWorld.multiplyMatrices(b.matrixWorld,a.matrix);a.matrixWorldInverse.getInverse(a.matrixWorld)}var f=a.context,g=null,h=null,k=null,m=null,q=[],n=[],t=new Z;t.layers.enable(1);t.viewport=new V;var u=new Z;u.layers.enable(2);u.viewport=new V;var r=new yc([t,u]);r.layers.enable(1);r.layers.enable(2);this.enabled=!1;this.getController=function(a){var b=q[a];void 0===b&&(b=new Kb,b.matrixAutoUpdate=!1,b.visible=!1,q[a]=b);return b};
17473 this.getDevice=function(){return g};this.setDevice=function(a){void 0!==a&&(g=a);a instanceof XRDevice&&f.setCompatibleXRDevice(a)};this.setSession=function(b,e){h=b;null!==h&&(h.addEventListener("select",c),h.addEventListener("selectstart",c),h.addEventListener("selectend",c),h.addEventListener("end",d),h.baseLayer=new XRWebGLLayer(h,f),h.requestFrameOfReference(e.frameOfReferenceType).then(function(b){k=b;a.setFramebuffer(h.baseLayer.framebuffer);p.setContext(h);p.start()}),n=h.getInputSources(),
17474 h.addEventListener("inputsourceschange",function(){n=h.getInputSources();console.log(n)}))};this.getCamera=function(a){if(b()){var c=a.parent,d=r.cameras;e(r,c);for(var f=0;f<d.length;f++)e(d[f],c);a.matrixWorld.copy(r.matrixWorld);a=a.children;f=0;for(c=a.length;f<c;f++)a[f].updateMatrixWorld(!0);return r}return a};this.isPresenting=b;var l=null,p=new Qd;p.setAnimationLoop(function(a,b){m=b.getDevicePose(k);if(null!==m)for(var c=h.baseLayer,d=b.views,e=0;e<d.length;e++){var f=d[e],g=c.getViewport(f),
17475 t=m.getViewMatrix(f),u=r.cameras[e];u.matrix.fromArray(t).getInverse(u.matrix);u.projectionMatrix.fromArray(f.projectionMatrix);u.viewport.set(g.x,g.y,g.width,g.height);0===e&&(r.matrix.copy(u.matrix),r.projectionMatrix.copy(u.projectionMatrix))}for(e=0;e<q.length;e++){c=q[e];if(d=n[e])if(d=b.getInputPose(d,k),null!==d){c.matrix.elements=d.pointerMatrix;c.matrix.decompose(c.position,c.rotation,c.scale);c.visible=!0;continue}c.visible=!1}l&&l(a)});this.setAnimationLoop=function(a){l=a};this.dispose=
17476 function(){};this.getStandingMatrix=function(){console.warn("THREE.WebXRManager: getStandingMatrix() is no longer needed.");return new THREE.Matrix4};this.submitFrame=function(){}}function Zd(a){var b;function c(){ha=new Pf(F);ua=new Nf(F,ha,a);ua.isWebGL2||(ha.get("WEBGL_depth_texture"),ha.get("OES_texture_float"),ha.get("OES_texture_half_float"),ha.get("OES_texture_half_float_linear"),ha.get("OES_standard_derivatives"),ha.get("OES_element_index_uint"),ha.get("ANGLE_instanced_arrays"));ha.get("OES_texture_float_linear");
17477 da=new $e(F,ha,ua);ba=new Jg(F,ha,da,ua);ba.scissor(wc.copy(fa).multiplyScalar(U));ba.viewport(T.copy(od).multiplyScalar(U));ca=new Sf(F);Ba=new Ag;ia=new Kg(F,ha,ba,Ba,ua,da,ca);pa=new Ff(F);ra=new Qf(F,pa,ca);ma=new Vf(ra,ca);va=new Uf(F);la=new zg(C,ha,ua);sa=new Eg;na=new Ig;ka=new Lf(C,ba,ma,N);xa=new Mf(F,ha,ca,ua);ya=new Rf(F,ha,ca,ua);ca.programs=la.programs;C.context=F;C.capabilities=ua;C.extensions=ha;C.properties=Ba;C.renderLists=sa;C.state=ba;C.info=ca}function d(a){a.preventDefault();
17478 console.log("THREE.WebGLRenderer: Context Lost.");G=!0}function e(){console.log("THREE.WebGLRenderer: Context Restored.");G=!1;c()}function f(a){a=a.target;a.removeEventListener("dispose",f);g(a);Ba.remove(a)}function g(a){var b=Ba.get(a).program;a.program=void 0;void 0!==b&&la.releaseProgram(b)}function h(a,b){a.render(function(a){C.renderBufferImmediate(a,b)})}function k(a,b,c){if(!1!==a.visible){if(a.layers.test(b.layers))if(a.isLight)D.pushLight(a),a.castShadow&&D.pushShadow(a);else if(a.isSprite){if(!a.frustumCulled||
17479 oa.intersectsSprite(a)){c&&bb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(xc);var d=ma.update(a),e=a.material;A.push(a,d,e,bb.z,null)}}else if(a.isImmediateRenderObject)c&&bb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(xc),A.push(a,null,a.material,bb.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||oa.intersectsObject(a))if(c&&bb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(xc),d=ma.update(a),e=a.material,Array.isArray(e))for(var f=
17480 d.groups,g=0,h=f.length;g<h;g++){var m=f[g],n=e[m.materialIndex];n&&n.visible&&A.push(a,d,n,bb.z,m)}else e.visible&&A.push(a,d,e,bb.z,null);a=a.children;g=0;for(h=a.length;g<h;g++)k(a[g],b,c)}}function m(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,k=g.geometry,m=void 0===d?g.material:d;g=g.group;if(c.isArrayCamera){W=c;for(var n=c.cameras,t=0,u=n.length;t<u;t++){var l=n[t];if(h.layers.test(l.layers)){if("viewport"in l)ba.viewport(T.copy(l.viewport));else{var r=l.bounds;ba.viewport(T.set(r.x*
17481 Z,r.y*M,r.z*Z,r.w*M).multiplyScalar(U))}q(h,b,l,k,m,g)}}}else W=null,q(h,b,c,k,m,g)}}function q(a,c,d,e,f,g){a.onBeforeRender(C,c,d,e,f,g);D=na.get(c,W||d);a.modelViewMatrix.multiplyMatrices(d.matrixWorldInverse,a.matrixWorld);a.normalMatrix.getNormalMatrix(a.modelViewMatrix);if(a.isImmediateRenderObject){ba.setMaterial(f);var k=t(d,c.fog,f,a);S=b=null;nd=!1;h(a,k)}else C.renderBufferDirect(d,c.fog,e,f,a,g);a.onAfterRender(C,c,d,e,f,g);D=na.get(c,W||d)}function n(a,b,c){var d=Ba.get(a),e=D.state.lights,
17482 h=d.lightsHash,k=e.state.hash;c=la.getParameters(a,e.state,D.state.shadowsArray,b,aa.numPlanes,aa.numIntersection,c);var m=la.getProgramCode(a,c),n=d.program,q=!0;if(void 0===n)a.addEventListener("dispose",f);else if(n.code!==m)g(a);else{if(h.stateID!==k.stateID||h.directionalLength!==k.directionalLength||h.pointLength!==k.pointLength||h.spotLength!==k.spotLength||h.rectAreaLength!==k.rectAreaLength||h.hemiLength!==k.hemiLength||h.shadowsLength!==k.shadowsLength)h.stateID=k.stateID,h.directionalLength=
17483 k.directionalLength,h.pointLength=k.pointLength,h.spotLength=k.spotLength,h.rectAreaLength=k.rectAreaLength,h.hemiLength=k.hemiLength,h.shadowsLength=k.shadowsLength;else if(void 0!==c.shaderID)return;q=!1}q&&(c.shaderID?(m=nb[c.shaderID],d.shader={name:a.type,uniforms:Aa.clone(m.uniforms),vertexShader:m.vertexShader,fragmentShader:m.fragmentShader}):d.shader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader},a.onBeforeCompile(d.shader,C),m=la.getProgramCode(a,
17484 c),n=la.acquireProgram(a,d.shader,c,m),d.program=n,a.program=n);c=n.getAttributes();if(a.morphTargets)for(m=a.numSupportedMorphTargets=0;m<C.maxMorphTargets;m++)0<=c["morphTarget"+m]&&a.numSupportedMorphTargets++;if(a.morphNormals)for(m=a.numSupportedMorphNormals=0;m<C.maxMorphNormals;m++)0<=c["morphNormal"+m]&&a.numSupportedMorphNormals++;c=d.shader.uniforms;if(!a.isShaderMaterial&&!a.isRawShaderMaterial||!0===a.clipping)d.numClippingPlanes=aa.numPlanes,d.numIntersection=aa.numIntersection,c.clippingPlanes=
17485 aa.uniform;d.fog=b;void 0===h&&(d.lightsHash=h={});h.stateID=k.stateID;h.directionalLength=k.directionalLength;h.pointLength=k.pointLength;h.spotLength=k.spotLength;h.rectAreaLength=k.rectAreaLength;h.hemiLength=k.hemiLength;h.shadowsLength=k.shadowsLength;a.lights&&(c.ambientLightColor.value=e.state.ambient,c.directionalLights.value=e.state.directional,c.spotLights.value=e.state.spot,c.rectAreaLights.value=e.state.rectArea,c.pointLights.value=e.state.point,c.hemisphereLights.value=e.state.hemi,c.directionalShadowMap.value=
17486 e.state.directionalShadowMap,c.directionalShadowMatrix.value=e.state.directionalShadowMatrix,c.spotShadowMap.value=e.state.spotShadowMap,c.spotShadowMatrix.value=e.state.spotShadowMatrix,c.pointShadowMap.value=e.state.pointShadowMap,c.pointShadowMatrix.value=e.state.pointShadowMatrix);a=d.program.getUniforms();a=Za.seqWithValue(a.seq,c);d.uniformsList=a}function t(a,b,c,d){X=0;var e=Ba.get(c),f=e.lightsHash,g=D.state.lights.state.hash;pd&&(Yd||a!==Y)&&aa.setState(c.clippingPlanes,c.clipIntersection,
17487 c.clipShadows,a,e,a===Y&&c.id===J);!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:!c.lights||f.stateID===g.stateID&&f.directionalLength===g.directionalLength&&f.pointLength===g.pointLength&&f.spotLength===g.spotLength&&f.rectAreaLength===g.rectAreaLength&&f.hemiLength===g.hemiLength&&f.shadowsLength===g.shadowsLength?void 0===e.numClippingPlanes||e.numClippingPlanes===aa.numPlanes&&e.numIntersection===aa.numIntersection||(c.needsUpdate=!0):c.needsUpdate=
17488 !0);c.needsUpdate&&(n(c,b,d),c.needsUpdate=!1);var h=!1,k=!1,m=!1;f=e.program;g=f.getUniforms();var q=e.shader.uniforms;ba.useProgram(f.program)&&(m=k=h=!0);c.id!==J&&(J=c.id,k=!0);if(h||a!==Y){g.setValue(F,"projectionMatrix",a.projectionMatrix);ua.logarithmicDepthBuffer&&g.setValue(F,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));Y!==(W||a)&&(Y=W||a,m=k=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)h=g.map.cameraPosition,void 0!==h&&h.setValue(F,bb.setFromMatrixPosition(a.matrixWorld));
17489 (c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&g.setValue(F,"viewMatrix",a.matrixWorldInverse)}if(c.skinning&&(g.setOptional(F,d,"bindMatrix"),g.setOptional(F,d,"bindMatrixInverse"),a=d.skeleton))if(h=a.bones,ua.floatVertexTextures){if(void 0===a.boneTexture){h=Math.sqrt(4*h.length);h=H.ceilPowerOfTwo(h);h=Math.max(h,4);var t=new Float32Array(h*h*4);t.set(a.boneMatrices);var v=new gb(t,h,h,1023,1015);v.needsUpdate=
17490 !0;a.boneMatrices=t;a.boneTexture=v;a.boneTextureSize=h}g.setValue(F,"boneTexture",a.boneTexture);g.setValue(F,"boneTextureSize",a.boneTextureSize)}else g.setOptional(F,a,"boneMatrices");k&&(g.setValue(F,"toneMappingExposure",C.toneMappingExposure),g.setValue(F,"toneMappingWhitePoint",C.toneMappingWhitePoint),c.lights&&(k=m,q.ambientLightColor.needsUpdate=k,q.directionalLights.needsUpdate=k,q.pointLights.needsUpdate=k,q.spotLights.needsUpdate=k,q.rectAreaLights.needsUpdate=k,q.hemisphereLights.needsUpdate=
17491 k),b&&c.fog&&(q.fogColor.value=b.color,b.isFog?(q.fogNear.value=b.near,q.fogFar.value=b.far):b.isFogExp2&&(q.fogDensity.value=b.density)),c.isMeshBasicMaterial?u(q,c):c.isMeshLambertMaterial?(u(q,c),c.emissiveMap&&(q.emissiveMap.value=c.emissiveMap)):c.isMeshPhongMaterial?(u(q,c),c.isMeshToonMaterial?(r(q,c),c.gradientMap&&(q.gradientMap.value=c.gradientMap)):r(q,c)):c.isMeshStandardMaterial?(u(q,c),c.isMeshPhysicalMaterial?(l(q,c),q.reflectivity.value=c.reflectivity,q.clearCoat.value=c.clearCoat,
17492 q.clearCoatRoughness.value=c.clearCoatRoughness):l(q,c)):c.isMeshDepthMaterial?(u(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isMeshDistanceMaterial?(u(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias),q.referencePosition.value.copy(c.referencePosition),q.nearDistance.value=c.nearDistance,
17493 q.farDistance.value=c.farDistance):c.isMeshNormalMaterial?(u(q,c),c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale,1===c.side&&(q.bumpScale.value*=-1)),c.normalMap&&(q.normalMap.value=c.normalMap,q.normalScale.value.copy(c.normalScale),1===c.side&&q.normalScale.value.negate()),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isLineBasicMaterial?(q.diffuse.value=c.color,q.opacity.value=
17494 c.opacity,c.isLineDashedMaterial&&(q.dashSize.value=c.dashSize,q.totalSize.value=c.dashSize+c.gapSize,q.scale.value=c.scale)):c.isPointsMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,q.size.value=c.size*U,q.scale.value=.5*M,q.map.value=c.map,null!==c.map&&(!0===c.map.matrixAutoUpdate&&c.map.updateMatrix(),q.uvTransform.value.copy(c.map.matrix))):c.isSpriteMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,q.rotation.value=c.rotation,q.map.value=c.map,null!==c.map&&(!0===c.map.matrixAutoUpdate&&
17495 c.map.updateMatrix(),q.uvTransform.value.copy(c.map.matrix))):c.isShadowMaterial&&(q.color.value=c.color,q.opacity.value=c.opacity),void 0!==q.ltc_1&&(q.ltc_1.value=K.LTC_1),void 0!==q.ltc_2&&(q.ltc_2.value=K.LTC_2),Za.upload(F,e.uniformsList,q,C));c.isShaderMaterial&&!0===c.uniformsNeedUpdate&&(Za.upload(F,e.uniformsList,q,C),c.uniformsNeedUpdate=!1);c.isSpriteMaterial&&g.setValue(F,"center",d.center);g.setValue(F,"modelViewMatrix",d.modelViewMatrix);g.setValue(F,"normalMatrix",d.normalMatrix);g.setValue(F,
17496 "modelMatrix",d.matrixWorld);return f}function u(a,b){a.opacity.value=b.opacity;b.color&&(a.diffuse.value=b.color);b.emissive&&a.emissive.value.copy(b.emissive).multiplyScalar(b.emissiveIntensity);b.map&&(a.map.value=b.map);b.alphaMap&&(a.alphaMap.value=b.alphaMap);b.specularMap&&(a.specularMap.value=b.specularMap);b.envMap&&(a.envMap.value=b.envMap,a.flipEnvMap.value=b.envMap&&b.envMap.isCubeTexture?-1:1,a.reflectivity.value=b.reflectivity,a.refractionRatio.value=b.refractionRatio,a.maxMipLevel.value=
17497 Ba.get(b.envMap).__maxMipLevel);b.lightMap&&(a.lightMap.value=b.lightMap,a.lightMapIntensity.value=b.lightMapIntensity);b.aoMap&&(a.aoMap.value=b.aoMap,a.aoMapIntensity.value=b.aoMapIntensity);if(b.map)var c=b.map;else b.specularMap?c=b.specularMap:b.displacementMap?c=b.displacementMap:b.normalMap?c=b.normalMap:b.bumpMap?c=b.bumpMap:b.roughnessMap?c=b.roughnessMap:b.metalnessMap?c=b.metalnessMap:b.alphaMap?c=b.alphaMap:b.emissiveMap&&(c=b.emissiveMap);void 0!==c&&(c.isWebGLRenderTarget&&(c=c.texture),
17498 !0===c.matrixAutoUpdate&&c.updateMatrix(),a.uvTransform.value.copy(c.matrix))}function r(a,b){a.specular.value=b.specular;a.shininess.value=Math.max(b.shininess,1E-4);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale,1===b.side&&(a.bumpScale.value*=-1));b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale),1===b.side&&a.normalScale.value.negate());b.displacementMap&&(a.displacementMap.value=b.displacementMap,
17499 a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function l(a,b){a.roughness.value=b.roughness;a.metalness.value=b.metalness;b.roughnessMap&&(a.roughnessMap.value=b.roughnessMap);b.metalnessMap&&(a.metalnessMap.value=b.metalnessMap);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale,1===b.side&&(a.bumpScale.value*=-1));b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale),
17500 1===b.side&&a.normalScale.value.negate());b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}console.log("THREE.WebGLRenderer","95");a=a||{};var y=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),x=void 0!==a.context?a.context:null,w=void 0!==a.alpha?a.alpha:!1,B=void 0!==a.depth?a.depth:!0,E=void 0!==
17501 a.stencil?a.stencil:!0,P=void 0!==a.antialias?a.antialias:!1,N=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,O=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,z=void 0!==a.powerPreference?a.powerPreference:"default",A=null,D=null;this.domElement=y;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=
17502 !1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var C=this,G=!1,L=null,R=null,Q=null,J=-1;var S=b=null;var nd=!1;var Y=null,W=null,T=new V,wc=new V,ea=null,X=0,Z=y.width,M=y.height,U=1,od=new V(0,0,Z,M),fa=new V(0,0,Z,M),qa=!1,oa=new md,aa=new Of,pd=!1,Yd=!1,xc=new I,bb=new p;try{w={alpha:w,depth:B,stencil:E,antialias:P,premultipliedAlpha:N,preserveDrawingBuffer:O,powerPreference:z};y.addEventListener("webglcontextlost",d,!1);
17503 y.addEventListener("webglcontextrestored",e,!1);var F=x||y.getContext("webgl",w)||y.getContext("experimental-webgl",w);if(null===F){if(null!==y.getContext("webgl"))throw Error("Error creating WebGL context with your selected attributes.");throw Error("Error creating WebGL context.");}void 0===F.getShaderPrecisionFormat&&(F.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(Mg){console.error("THREE.WebGLRenderer: "+Mg.message)}var ha,ua,ba,ca,Ba,ia,pa,ra,ma,la,sa,
17504 na,ka,va,xa,ya,da;c();var ja="xr"in navigator?new Lg(C):new af(C);this.vr=ja;var za=new Ze(C,ma,ua.maxTextureSize);this.shadowMap=za;this.getContext=function(){return F};this.getContextAttributes=function(){return F.getContextAttributes()};this.forceContextLoss=function(){var a=ha.get("WEBGL_lose_context");a&&a.loseContext()};this.forceContextRestore=function(){var a=ha.get("WEBGL_lose_context");a&&a.restoreContext()};this.getPixelRatio=function(){return U};this.setPixelRatio=function(a){void 0!==
17505 a&&(U=a,this.setSize(Z,M,!1))};this.getSize=function(){return{width:Z,height:M}};this.setSize=function(a,b,c){ja.isPresenting()?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(Z=a,M=b,y.width=a*U,y.height=b*U,!1!==c&&(y.style.width=a+"px",y.style.height=b+"px"),this.setViewport(0,0,a,b))};this.getDrawingBufferSize=function(){return{width:Z*U,height:M*U}};this.setDrawingBufferSize=function(a,b,c){Z=a;M=b;U=c;y.width=a*c;y.height=b*c;this.setViewport(0,0,a,b)};
17506 this.getCurrentViewport=function(){return T};this.setViewport=function(a,b,c,d){od.set(a,M-b-d,c,d);ba.viewport(T.copy(od).multiplyScalar(U))};this.setScissor=function(a,b,c,d){fa.set(a,M-b-d,c,d);ba.scissor(wc.copy(fa).multiplyScalar(U))};this.setScissorTest=function(a){ba.setScissorTest(qa=a)};this.getClearColor=function(){return ka.getClearColor()};this.setClearColor=function(){ka.setClearColor.apply(ka,arguments)};this.getClearAlpha=function(){return ka.getClearAlpha()};this.setClearAlpha=function(){ka.setClearAlpha.apply(ka,
17507 arguments)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=F.COLOR_BUFFER_BIT;if(void 0===b||b)d|=F.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=F.STENCIL_BUFFER_BIT;F.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);this.clear(b,c,d)};this.dispose=function(){y.removeEventListener("webglcontextlost",d,!1);y.removeEventListener("webglcontextrestored",
17508 e,!1);sa.dispose();na.dispose();Ba.dispose();ma.dispose();ja.dispose();ta.stop()};this.renderBufferImmediate=function(a,b){ba.initAttributes();var c=Ba.get(a);a.hasPositions&&!c.position&&(c.position=F.createBuffer());a.hasNormals&&!c.normal&&(c.normal=F.createBuffer());a.hasUvs&&!c.uv&&(c.uv=F.createBuffer());a.hasColors&&!c.color&&(c.color=F.createBuffer());b=b.getAttributes();a.hasPositions&&(F.bindBuffer(F.ARRAY_BUFFER,c.position),F.bufferData(F.ARRAY_BUFFER,a.positionArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.position),
17509 F.vertexAttribPointer(b.position,3,F.FLOAT,!1,0,0));a.hasNormals&&(F.bindBuffer(F.ARRAY_BUFFER,c.normal),F.bufferData(F.ARRAY_BUFFER,a.normalArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.normal),F.vertexAttribPointer(b.normal,3,F.FLOAT,!1,0,0));a.hasUvs&&(F.bindBuffer(F.ARRAY_BUFFER,c.uv),F.bufferData(F.ARRAY_BUFFER,a.uvArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.uv),F.vertexAttribPointer(b.uv,2,F.FLOAT,!1,0,0));a.hasColors&&(F.bindBuffer(F.ARRAY_BUFFER,c.color),F.bufferData(F.ARRAY_BUFFER,a.colorArray,
17510 F.DYNAMIC_DRAW),ba.enableAttribute(b.color),F.vertexAttribPointer(b.color,3,F.FLOAT,!1,0,0));ba.disableUnusedAttributes();F.drawArrays(F.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,c,d,e,f,g){var h=f.isMesh&&0>f.normalMatrix.determinant();ba.setMaterial(e,h);var k=t(a,c,e,f),m=!1;if(b!==d.id||S!==k.id||nd!==(!0===e.wireframe))b=d.id,S=k.id,nd=!0===e.wireframe,m=!0;f.morphTargetInfluences&&(va.update(f,d,e,k),m=!0);h=d.index;var q=d.attributes.position;c=1;!0===e.wireframe&&
17511 (h=ra.getWireframeAttribute(d),c=2);a=xa;if(null!==h){var n=pa.get(h);a=ya;a.setIndex(n)}if(m){if(d&&d.isInstancedBufferGeometry&!ua.isWebGL2&&null===ha.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{ba.initAttributes();m=d.attributes;k=k.getAttributes();var u=e.defaultAttributeValues;for(N in k){var l=k[N];if(0<=l){var r=m[N];if(void 0!==r){var v=r.normalized,
17512 p=r.itemSize,w=pa.get(r);if(void 0!==w){var y=w.buffer,E=w.type;w=w.bytesPerElement;if(r.isInterleavedBufferAttribute){var x=r.data,B=x.stride;r=r.offset;x&&x.isInstancedInterleavedBuffer?(ba.enableAttributeAndDivisor(l,x.meshPerAttribute),void 0===d.maxInstancedCount&&(d.maxInstancedCount=x.meshPerAttribute*x.count)):ba.enableAttribute(l);F.bindBuffer(F.ARRAY_BUFFER,y);F.vertexAttribPointer(l,p,E,v,B*w,r*w)}else r.isInstancedBufferAttribute?(ba.enableAttributeAndDivisor(l,r.meshPerAttribute),void 0===
17513 d.maxInstancedCount&&(d.maxInstancedCount=r.meshPerAttribute*r.count)):ba.enableAttribute(l),F.bindBuffer(F.ARRAY_BUFFER,y),F.vertexAttribPointer(l,p,E,v,0,0)}}else if(void 0!==u&&(v=u[N],void 0!==v))switch(v.length){case 2:F.vertexAttrib2fv(l,v);break;case 3:F.vertexAttrib3fv(l,v);break;case 4:F.vertexAttrib4fv(l,v);break;default:F.vertexAttrib1fv(l,v)}}}ba.disableUnusedAttributes()}null!==h&&F.bindBuffer(F.ELEMENT_ARRAY_BUFFER,n.buffer)}n=Infinity;null!==h?n=h.count:void 0!==q&&(n=q.count);h=d.drawRange.start*
17514 c;q=null!==g?g.start*c:0;var N=Math.max(h,q);g=Math.max(0,Math.min(n,h+d.drawRange.count*c,q+(null!==g?g.count*c:Infinity))-1-N+1);if(0!==g){if(f.isMesh)if(!0===e.wireframe)ba.setLineWidth(e.wireframeLinewidth*(null===R?U:1)),a.setMode(F.LINES);else switch(f.drawMode){case 0:a.setMode(F.TRIANGLES);break;case 1:a.setMode(F.TRIANGLE_STRIP);break;case 2:a.setMode(F.TRIANGLE_FAN)}else f.isLine?(e=e.linewidth,void 0===e&&(e=1),ba.setLineWidth(e*(null===R?U:1)),f.isLineSegments?a.setMode(F.LINES):f.isLineLoop?
17515 a.setMode(F.LINE_LOOP):a.setMode(F.LINE_STRIP)):f.isPoints?a.setMode(F.POINTS):f.isSprite&&a.setMode(F.TRIANGLES);d&&d.isInstancedBufferGeometry?0<d.maxInstancedCount&&a.renderInstances(d,N,g):a.render(N,g)}};this.compile=function(a,b){D=na.get(a,b);D.init();a.traverse(function(a){a.isLight&&(D.pushLight(a),a.castShadow&&D.pushShadow(a))});D.setupLights(b);a.traverse(function(b){if(b.material)if(Array.isArray(b.material))for(var c=0;c<b.material.length;c++)n(b.material[c],a.fog,b);else n(b.material,
17516 a.fog,b)})};var wa=null,ta=new Qd;ta.setAnimationLoop(function(a){ja.isPresenting()||wa&&wa(a)});"undefined"!==typeof window&&ta.setContext(window);this.setAnimationLoop=function(a){wa=a;ja.setAnimationLoop(a);ta.start()};this.render=function(a,c,d,e){if(!c||!c.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");else if(!G){S=b=null;nd=!1;J=-1;Y=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===c.parent&&c.updateMatrixWorld();ja.enabled&&(c=ja.getCamera(c));
17517 D=na.get(a,c);D.init();a.onBeforeRender(C,a,c,d);xc.multiplyMatrices(c.projectionMatrix,c.matrixWorldInverse);oa.setFromMatrix(xc);Yd=this.localClippingEnabled;pd=aa.init(this.clippingPlanes,Yd,c);A=sa.get(a,c);A.init();k(a,c,C.sortObjects);!0===C.sortObjects&&A.sort();pd&&aa.beginShadows();za.render(D.state.shadowsArray,a,c);D.setupLights(c);pd&&aa.endShadows();this.info.autoReset&&this.info.reset();void 0===d&&(d=null);this.setRenderTarget(d);ka.render(A,a,c,e);e=A.opaque;var f=A.transparent;if(a.overrideMaterial){var g=
17518 a.overrideMaterial;e.length&&m(e,a,c,g);f.length&&m(f,a,c,g)}else e.length&&m(e,a,c),f.length&&m(f,a,c);d&&ia.updateRenderTargetMipmap(d);ba.buffers.depth.setTest(!0);ba.buffers.depth.setMask(!0);ba.buffers.color.setMask(!0);ba.setPolygonOffset(!1);a.onAfterRender(C,a,c);ja.enabled&&ja.submitFrame();D=A=null}};this.allocTextureUnit=function(){var a=X;a>=ua.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+ua.maxTextures);X+=1;return a};
17519 this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);ia.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);ia.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&
17520 b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?ia.setTextureCube(b,c):ia.setTextureCubeDynamic(b,c)}}();this.setFramebuffer=function(a){L=a};this.getRenderTarget=function(){return R};this.setRenderTarget=function(a){(R=a)&&void 0===Ba.get(a).__webglFramebuffer&&ia.setupRenderTarget(a);var b=L,c=!1;a?(b=
17521 Ba.get(a).__webglFramebuffer,a.isWebGLRenderTargetCube&&(b=b[a.activeCubeFace],c=!0),T.copy(a.viewport),wc.copy(a.scissor),ea=a.scissorTest):(T.copy(od).multiplyScalar(U),wc.copy(fa).multiplyScalar(U),ea=qa);Q!==b&&(F.bindFramebuffer(F.FRAMEBUFFER,b),Q=b);ba.viewport(T);ba.scissor(wc);ba.setScissorTest(ea);c&&(c=Ba.get(a.texture),F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,c.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=
17522 function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=Ba.get(a).__webglFramebuffer;if(g){var h=!1;g!==Q&&(F.bindFramebuffer(F.FRAMEBUFFER,g),h=!0);try{var k=a.texture,m=k.format,q=k.type;1023!==m&&da.convert(m)!==F.getParameter(F.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===q||da.convert(q)===F.getParameter(F.IMPLEMENTATION_COLOR_READ_TYPE)||1015===q&&(ua.isWebGL2||ha.get("OES_texture_float")||
17523 ha.get("WEBGL_color_buffer_float"))||1016===q&&(ua.isWebGL2?ha.get("EXT_color_buffer_float"):ha.get("EXT_color_buffer_half_float"))?F.checkFramebufferStatus(F.FRAMEBUFFER)===F.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&F.readPixels(b,c,d,e,da.convert(m),da.convert(q),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&&
17524 F.bindFramebuffer(F.FRAMEBUFFER,Q)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")};this.copyFramebufferToTexture=function(a,b,c){var d=b.image.width,e=b.image.height,f=da.convert(b.format);this.setTexture2D(b,0);F.copyTexImage2D(F.TEXTURE_2D,c||0,f,a.x,a.y,d,e,0)};this.copyTextureToTexture=function(a,b,c,d){var e=b.image.width,f=b.image.height,g=da.convert(c.format),h=da.convert(c.type);this.setTexture2D(c,0);b.isDataTexture?F.texSubImage2D(F.TEXTURE_2D,
17525 d||0,a.x,a.y,e,f,g,h,b.image.data):F.texSubImage2D(F.TEXTURE_2D,d||0,a.x,a.y,g,h,b.image)}}function Lb(a,b){this.name="";this.color=new G(a);this.density=void 0!==b?b:2.5E-4}function Mb(a,b,c){this.name="";this.color=new G(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function qd(){D.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function ob(a,b){this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange=
17526 {offset:0,count:-1};this.version=0}function zc(a,b,c,d){this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function cb(a){J.call(this);this.type="SpriteMaterial";this.color=new G(16777215);this.map=null;this.rotation=0;this.lights=!1;this.transparent=!0;this.setValues(a)}function Ac(a){D.call(this);this.type="Sprite";if(void 0===Nb){Nb=new C;var b=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]);b=new ob(b,5);Nb.setIndex([0,1,2,0,2,3]);Nb.addAttribute("position",
17527 new zc(b,3,0,!1));Nb.addAttribute("uv",new zc(b,2,3,!1))}this.geometry=Nb;this.material=void 0!==a?a:new cb;this.center=new z(.5,.5)}function Bc(){D.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Cc(a,b){a=a||[];this.bones=a.slice(0);this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else for(console.warn("THREE.Skeleton boneInverses is the wrong length."),
17528 this.boneInverses=[],a=0,b=this.bones.length;a<b;a++)this.boneInverses.push(new I)}function rd(){D.call(this);this.type="Bone"}function sd(a,b){la.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new I;this.bindMatrixInverse=new I;a=this.initBones();a=new Cc(a);this.bind(a,this.matrixWorld);this.normalizeSkinWeights()}function Y(a){J.call(this);this.type="LineBasicMaterial";this.color=new G(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;
17529 this.setValues(a)}function sa(a,b,c){1===c&&console.error("THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.");D.call(this);this.type="Line";this.geometry=void 0!==a?a:new C;this.material=void 0!==b?b:new Y({color:16777215*Math.random()})}function W(a,b){sa.call(this,a,b);this.type="LineSegments"}function td(a,b){sa.call(this,a,b);this.type="LineLoop"}function Ea(a){J.call(this);this.type="PointsMaterial";this.color=new G(16777215);this.map=null;this.size=
17530 1;this.sizeAttenuation=!0;this.lights=this.morphTargets=!1;this.setValues(a)}function Ob(a,b){D.call(this);this.type="Points";this.geometry=void 0!==a?a:new C;this.material=void 0!==b?b:new Ea({color:16777215*Math.random()})}function $d(a,b,c,d,e,f,g,h,k){T.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1}function Pb(a,b,c,d,e,f,g,h,k,m,q,n){T.call(this,null,f,g,h,k,m,d,e,q,n);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function Dc(a,b,c,d,e,f,g,h,k){T.call(this,
17531 a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Ec(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===m&&(c=1012);void 0===c&&1027===m&&(c=1020);T.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 Qb(a){C.call(this);this.type="WireframeGeometry";var b=
17532 [],c,d,e,f=[0,0],g={},h=["a","b","c"];if(a&&a.isGeometry){var k=a.faces;var m=0;for(d=k.length;m<d;m++){var q=k[m];for(c=0;3>c;c++){var n=q[h[c]];var t=q[h[(c+1)%3]];f[0]=Math.min(n,t);f[1]=Math.max(n,t);n=f[0]+","+f[1];void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]})}}for(n in g)m=g[n],h=a.vertices[m.index1],b.push(h.x,h.y,h.z),h=a.vertices[m.index2],b.push(h.x,h.y,h.z)}else if(a&&a.isBufferGeometry)if(h=new p,null!==a.index){k=a.attributes.position;q=a.index;var u=a.groups;0===u.length&&(u=[{start:0,
17533 count:q.count,materialIndex:0}]);a=0;for(e=u.length;a<e;++a)for(m=u[a],c=m.start,d=m.count,m=c,d=c+d;m<d;m+=3)for(c=0;3>c;c++)n=q.getX(m+c),t=q.getX(m+(c+1)%3),f[0]=Math.min(n,t),f[1]=Math.max(n,t),n=f[0]+","+f[1],void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]});for(n in g)m=g[n],h.fromBufferAttribute(k,m.index1),b.push(h.x,h.y,h.z),h.fromBufferAttribute(k,m.index2),b.push(h.x,h.y,h.z)}else for(k=a.attributes.position,m=0,d=k.count/3;m<d;m++)for(c=0;3>c;c++)g=3*m+c,h.fromBufferAttribute(k,g),b.push(h.x,
17534 h.y,h.z),g=3*m+(c+1)%3,h.fromBufferAttribute(k,g),b.push(h.x,h.y,h.z);this.addAttribute("position",new A(b,3))}function Fc(a,b,c){R.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Rb(a,b,c));this.mergeVertices()}function Rb(a,b,c){C.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=new p,k=new p,m=new p,q=new p,n=new p,t,u;3>a.length&&console.error("THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.");
17535 var r=b+1;for(t=0;t<=c;t++){var l=t/c;for(u=0;u<=b;u++){var y=u/b;a(y,l,k);e.push(k.x,k.y,k.z);0<=y-1E-5?(a(y-1E-5,l,m),q.subVectors(k,m)):(a(y+1E-5,l,m),q.subVectors(m,k));0<=l-1E-5?(a(y,l-1E-5,m),n.subVectors(k,m)):(a(y,l+1E-5,m),n.subVectors(m,k));h.crossVectors(q,n).normalize();f.push(h.x,h.y,h.z);g.push(y,l)}}for(t=0;t<c;t++)for(u=0;u<b;u++)a=t*r+u+1,h=(t+1)*r+u+1,k=(t+1)*r+u,d.push(t*r+u,a,k),d.push(a,h,k);this.setIndex(d);this.addAttribute("position",new A(e,3));this.addAttribute("normal",
17536 new A(f,3));this.addAttribute("uv",new A(g,2))}function Gc(a,b,c,d){R.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new na(a,b,c,d));this.mergeVertices()}function na(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){b*=3;c.x=a[b+0];c.y=a[b+1];c.z=a[b+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)}C.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:a,
17537 indices:b,radius:c,detail:d};c=c||1;d=d||0;var h=[],k=[];(function(a){for(var c=new p,d=new p,g=new p,h=0;h<b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var k,m,l=c,x=d,w=g,B=Math.pow(2,a),E=[];for(m=0;m<=B;m++){E[m]=[];var P=l.clone().lerp(w,m/B),N=x.clone().lerp(w,m/B),O=B-m;for(k=0;k<=O;k++)E[m][k]=0===k&&m===B?P:P.clone().lerp(N,k/O)}for(m=0;m<B;m++)for(k=0;k<2*(B-m)-1;k++)l=Math.floor(k/2),0===k%2?(e(E[m][l+1]),e(E[m+1][l]),e(E[m][l])):(e(E[m][l+1]),e(E[m+1][l+1]),e(E[m+1][l]))}})(d);(function(a){for(var b=
17538 new p,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 p,b=0;b<h.length;b+=3)a.x=h[b+0],a.y=h[b+1],a.z=h[b+2],k.push(Math.atan2(a.z,-a.x)/2/Math.PI+.5,1-(Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))/Math.PI+.5));a=new p;b=new p;for(var c=new p,d=new p,e=new z,f=new z,l=new z,y=0,x=0;y<h.length;y+=9,x+=6){a.set(h[y+0],h[y+1],h[y+2]);b.set(h[y+3],h[y+4],h[y+5]);c.set(h[y+6],h[y+7],h[y+8]);e.set(k[x+0],
17539 k[x+1]);f.set(k[x+2],k[x+3]);l.set(k[x+4],k[x+5]);d.copy(a).add(b).add(c).divideScalar(3);var w=Math.atan2(d.z,-d.x);g(e,x+0,a,w);g(f,x+2,b,w);g(l,x+4,c,w)}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 A(h,3));this.addAttribute("normal",new A(h.slice(),3));this.addAttribute("uv",new A(k,2));0===d?this.computeVertexNormals():this.normalizeNormals()}function Hc(a,
17540 b){R.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Sb(a,b));this.mergeVertices()}function Sb(a,b){na.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Ic(a,b){R.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new pb(a,b));this.mergeVertices()}function pb(a,b){na.call(this,[1,0,0,
17541 -1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Jc(a,b){R.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Tb(a,b));this.mergeVertices()}function Tb(a,b){var c=(1+Math.sqrt(5))/2;na.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,
17542 11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Kc(a,b){R.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ub(a,b));this.mergeVertices()}function Ub(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;na.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,
17543 0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Lc(a,b,c,d,e,f){R.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,
17544 closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Vb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Vb(a,b,c,d,e){function f(e){q=a.getPointAt(e/b,q);var f=g.normals[e];e=g.binormals[e];for(t=0;t<=d;t++){var m=t/d*Math.PI*2,n=Math.sin(m);m=-Math.cos(m);k.x=m*f.x+n*e.x;k.y=m*f.y+n*e.y;k.z=m*f.z+n*e.z;k.normalize();r.push(k.x,k.y,k.z);h.x=q.x+c*k.x;h.y=q.y+c*k.y;h.z=
17545 q.z+c*k.z;l.push(h.x,h.y,h.z)}}C.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new p,k=new p,m=new z,q=new p,n,t,l=[],r=[],v=[],y=[];for(n=0;n<b;n++)f(n);f(!1===e?b:0);for(n=0;n<=b;n++)for(t=0;t<=d;t++)m.x=n/b,m.y=t/d,v.push(m.x,m.y);(function(){for(t=1;t<=b;t++)for(n=1;n<=d;n++){var a=
17546 (d+1)*t+(n-1),c=(d+1)*t+n,e=(d+1)*(t-1)+n;y.push((d+1)*(t-1)+(n-1),a,e);y.push(a,c,e)}})();this.setIndex(y);this.addAttribute("position",new A(l,3));this.addAttribute("normal",new A(r,3));this.addAttribute("uv",new A(v,2))}function Mc(a,b,c,d,e,f,g){R.call(this);this.type="TorusKnotGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};void 0!==g&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");this.fromBufferGeometry(new Wb(a,
17547 b,c,d,e,f));this.mergeVertices()}function Wb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);b=c/b*a;c=Math.cos(b);e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}C.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||1;b=b||.4;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=[],k=[],m=[],q=[],n,t=new p,l=new p,r=new p,v=new p,y=new p,x=new p,w=new p;for(n=0;n<=c;++n){var B=n/c*e*Math.PI*2;
17548 g(B,e,f,a,r);g(B+.01,e,f,a,v);x.subVectors(v,r);w.addVectors(v,r);y.crossVectors(x,w);w.crossVectors(y,x);y.normalize();w.normalize();for(B=0;B<=d;++B){var E=B/d*Math.PI*2,P=-b*Math.cos(E);E=b*Math.sin(E);t.x=r.x+(P*w.x+E*y.x);t.y=r.y+(P*w.y+E*y.y);t.z=r.z+(P*w.z+E*y.z);k.push(t.x,t.y,t.z);l.subVectors(t,r).normalize();m.push(l.x,l.y,l.z);q.push(n/c);q.push(B/d)}}for(B=1;B<=c;B++)for(n=1;n<=d;n++)a=(d+1)*B+(n-1),b=(d+1)*B+n,e=(d+1)*(B-1)+n,h.push((d+1)*(B-1)+(n-1),a,e),h.push(a,b,e);this.setIndex(h);
17549 this.addAttribute("position",new A(k,3));this.addAttribute("normal",new A(m,3));this.addAttribute("uv",new A(q,2))}function Nc(a,b,c,d,e){R.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Xb(a,b,c,d,e));this.mergeVertices()}function Xb(a,b,c,d,e){C.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||1;b=b||.4;c=Math.floor(c)||8;d=Math.floor(d)||
17550 6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],m=new p,q=new p,n=new p,t,l;for(t=0;t<=c;t++)for(l=0;l<=d;l++){var r=l/d*e,v=t/c*Math.PI*2;q.x=(a+b*Math.cos(v))*Math.cos(r);q.y=(a+b*Math.cos(v))*Math.sin(r);q.z=b*Math.sin(v);g.push(q.x,q.y,q.z);m.x=a*Math.cos(r);m.y=a*Math.sin(r);n.subVectors(q,m).normalize();h.push(n.x,n.y,n.z);k.push(l/d);k.push(t/c)}for(t=1;t<=c;t++)for(l=1;l<=d;l++)a=(d+1)*(t-1)+l-1,b=(d+1)*(t-1)+l,e=(d+1)*t+l,f.push((d+1)*t+l-1,a,e),f.push(a,b,e);this.setIndex(f);this.addAttribute("position",
17551 new A(g,3));this.addAttribute("normal",new A(h,3));this.addAttribute("uv",new A(k,2))}function bf(a,b,c,d,e){for(var f,g=0,h=b,k=c-d;h<c;h+=d)g+=(a[k]-a[h])*(a[h+1]+a[k+1]),k=h;if(e===0<g)for(e=b;e<c;e+=d)f=cf(e,a[e],a[e+1],f);else for(e=c-d;e>=b;e-=d)f=cf(e,a[e],a[e+1],f);f&&qb(f,f.next)&&(Oc(f),f=f.next);return f}function Pc(a,b){if(!a)return a;b||(b=a);do{var c=!1;if(a.steiner||!qb(a,a.next)&&0!==ma(a.prev,a,a.next))a=a.next;else{Oc(a);a=b=a.prev;if(a===a.next)break;c=!0}}while(c||a!==b);return b}
17552 function Qc(a,b,c,d,e,f,g){if(a){if(!g&&f){var h=a,k=h;do null===k.z&&(k.z=ae(k.x,k.y,d,e,f)),k.prevZ=k.prev,k=k.nextZ=k.next;while(k!==h);k.prevZ.nextZ=null;k.prevZ=null;h=k;var m,q,n,t,l=1;do{k=h;var r=h=null;for(q=0;k;){q++;var v=k;for(m=n=0;m<l&&(n++,v=v.nextZ,v);m++);for(t=l;0<n||0<t&&v;)0!==n&&(0===t||!v||k.z<=v.z)?(m=k,k=k.nextZ,n--):(m=v,v=v.nextZ,t--),r?r.nextZ=m:h=m,m.prevZ=r,r=m;k=v}r.nextZ=null;l*=2}while(1<q)}for(h=a;a.prev!==a.next;){k=a.prev;v=a.next;if(f)a:{r=a;t=d;var p=e,x=f;q=r.prev;
17553 n=r;l=r.next;if(0<=ma(q,n,l))r=!1;else{var w=q.x>n.x?q.x>l.x?q.x:l.x:n.x>l.x?n.x:l.x,B=q.y>n.y?q.y>l.y?q.y:l.y:n.y>l.y?n.y:l.y;m=ae(q.x<n.x?q.x<l.x?q.x:l.x:n.x<l.x?n.x:l.x,q.y<n.y?q.y<l.y?q.y:l.y:n.y<l.y?n.y:l.y,t,p,x);t=ae(w,B,t,p,x);for(p=r.nextZ;p&&p.z<=t;){if(p!==r.prev&&p!==r.next&&ud(q.x,q.y,n.x,n.y,l.x,l.y,p.x,p.y)&&0<=ma(p.prev,p,p.next)){r=!1;break a}p=p.nextZ}for(p=r.prevZ;p&&p.z>=m;){if(p!==r.prev&&p!==r.next&&ud(q.x,q.y,n.x,n.y,l.x,l.y,p.x,p.y)&&0<=ma(p.prev,p,p.next)){r=!1;break a}p=
17554 p.prevZ}r=!0}}else a:if(r=a,q=r.prev,n=r,l=r.next,0<=ma(q,n,l))r=!1;else{for(m=r.next.next;m!==r.prev;){if(ud(q.x,q.y,n.x,n.y,l.x,l.y,m.x,m.y)&&0<=ma(m.prev,m,m.next)){r=!1;break a}m=m.next}r=!0}if(r)b.push(k.i/c),b.push(a.i/c),b.push(v.i/c),Oc(a),h=a=v.next;else if(a=v,a===h){if(!g)Qc(Pc(a),b,c,d,e,f,1);else if(1===g){g=b;h=c;k=a;do v=k.prev,r=k.next.next,!qb(v,r)&&df(v,k,k.next,r)&&Rc(v,r)&&Rc(r,v)&&(g.push(v.i/h),g.push(k.i/h),g.push(r.i/h),Oc(k),Oc(k.next),k=a=r),k=k.next;while(k!==a);a=k;Qc(a,
17555 b,c,d,e,f,2)}else if(2===g)a:{g=a;do{for(h=g.next.next;h!==g.prev;){if(k=g.i!==h.i){k=g;v=h;if(r=k.next.i!==v.i&&k.prev.i!==v.i){b:{r=k;do{if(r.i!==k.i&&r.next.i!==k.i&&r.i!==v.i&&r.next.i!==v.i&&df(r,r.next,k,v)){r=!0;break b}r=r.next}while(r!==k);r=!1}r=!r}if(r=r&&Rc(k,v)&&Rc(v,k)){r=k;q=!1;n=(k.x+v.x)/2;v=(k.y+v.y)/2;do r.y>v!==r.next.y>v&&r.next.y!==r.y&&n<(r.next.x-r.x)*(v-r.y)/(r.next.y-r.y)+r.x&&(q=!q),r=r.next;while(r!==k);r=q}k=r}if(k){a=ef(g,h);g=Pc(g,g.next);a=Pc(a,a.next);Qc(g,b,c,d,e,
17556 f);Qc(a,b,c,d,e,f);break a}h=h.next}g=g.next}while(g!==a)}break}}}}function Ng(a,b){return a.x-b.x}function Og(a,b){var c=b,d=a.x,e=a.y,f=-Infinity;do{if(e<=c.y&&e>=c.next.y&&c.next.y!==c.y){var g=c.x+(e-c.y)*(c.next.x-c.x)/(c.next.y-c.y);if(g<=d&&g>f){f=g;if(g===d){if(e===c.y)return c;if(e===c.next.y)return c.next}var h=c.x<c.next.x?c:c.next}}c=c.next}while(c!==b);if(!h)return null;if(d===f)return h.prev;b=h;g=h.x;var k=h.y,m=Infinity;for(c=h.next;c!==b;){if(d>=c.x&&c.x>=g&&d!==c.x&&ud(e<k?d:f,e,
17557 g,k,e<k?f:d,e,c.x,c.y)){var q=Math.abs(e-c.y)/(d-c.x);(q<m||q===m&&c.x>h.x)&&Rc(c,a)&&(h=c,m=q)}c=c.next}return h}function ae(a,b,c,d,e){a=32767*(a-c)*e;b=32767*(b-d)*e;a=(a|a<<8)&16711935;a=(a|a<<4)&252645135;a=(a|a<<2)&858993459;b=(b|b<<8)&16711935;b=(b|b<<4)&252645135;b=(b|b<<2)&858993459;return(a|a<<1)&1431655765|((b|b<<1)&1431655765)<<1}function Pg(a){var b=a,c=a;do b.x<c.x&&(c=b),b=b.next;while(b!==a);return c}function ud(a,b,c,d,e,f,g,h){return 0<=(e-g)*(b-h)-(a-g)*(f-h)&&0<=(a-g)*(d-h)-(c-
17558 g)*(b-h)&&0<=(c-g)*(f-h)-(e-g)*(d-h)}function ma(a,b,c){return(b.y-a.y)*(c.x-b.x)-(b.x-a.x)*(c.y-b.y)}function qb(a,b){return a.x===b.x&&a.y===b.y}function df(a,b,c,d){return qb(a,b)&&qb(c,d)||qb(a,d)&&qb(c,b)?!0:0<ma(a,b,c)!==0<ma(a,b,d)&&0<ma(c,d,a)!==0<ma(c,d,b)}function Rc(a,b){return 0>ma(a.prev,a,a.next)?0<=ma(a,b,a.next)&&0<=ma(a,a.prev,b):0>ma(a,b,a.prev)||0>ma(a,a.next,b)}function ef(a,b){var c=new be(a.i,a.x,a.y),d=new be(b.i,b.x,b.y),e=a.next,f=b.prev;a.next=b;b.prev=a;c.next=e;e.prev=
17559 c;d.next=c;c.prev=d;f.next=d;d.prev=f;return d}function cf(a,b,c,d){a=new be(a,b,c);d?(a.next=d.next,a.prev=d,d.next.prev=a,d.next=a):(a.prev=a,a.next=a);return a}function Oc(a){a.next.prev=a.prev;a.prev.next=a.next;a.prevZ&&(a.prevZ.nextZ=a.nextZ);a.nextZ&&(a.nextZ.prevZ=a.prevZ)}function be(a,b,c){this.i=a;this.x=b;this.y=c;this.nextZ=this.prevZ=this.z=this.next=this.prev=null;this.steiner=!1}function ff(a){var b=a.length;2<b&&a[b-1].equals(a[0])&&a.pop()}function gf(a,b){for(var c=0;c<b.length;c++)a.push(b[c].x),
17560 a.push(b[c].y)}function rb(a,b){R.call(this);this.type="ExtrudeGeometry";this.parameters={shapes:a,options:b};this.fromBufferGeometry(new Oa(a,b));this.mergeVertices()}function Oa(a,b){function c(a){function c(a,b,c){b||console.error("THREE.ExtrudeGeometry: vec does not exist");return b.clone().multiplyScalar(c).add(a)}function g(a,b,c){var d=a.x-b.x;var e=a.y-b.y;var f=c.x-a.x;var g=c.y-a.y,h=d*d+e*e;if(Math.abs(d*g-e*f)>Number.EPSILON){var k=Math.sqrt(h),m=Math.sqrt(f*f+g*g);h=b.x-e/k;b=b.y+d/k;
17561 g=((c.x-g/m-h)*g-(c.y+f/m-b)*f)/(d*g-e*f);f=h+d*g-a.x;d=b+e*g-a.y;e=f*f+d*d;if(2>=e)return new z(f,d);e=Math.sqrt(e/2)}else a=!1,d>Number.EPSILON?f>Number.EPSILON&&(a=!0):d<-Number.EPSILON?f<-Number.EPSILON&&(a=!0):Math.sign(e)===Math.sign(g)&&(a=!0),a?(f=-e,e=Math.sqrt(h)):(f=d,d=e,e=Math.sqrt(h/2));return new z(f/e,d/e)}function h(a,b){for(M=a.length;0<=--M;){var c=M;var f=M-1;0>f&&(f=a.length-1);var g,h=w+2*O;for(g=0;g<h;g++){var k=Z*g,m=Z*(g+1),q=b+f+k,n=b+f+m;m=b+c+m;r(b+c+k);r(q);r(m);r(q);
17562 r(n);r(m);k=e.length/3;k=D.generateSideWallUV(d,e,k-6,k-3,k-2,k-1);v(k[0]);v(k[1]);v(k[3]);v(k[1]);v(k[2]);v(k[3])}}}function k(a,b,c){y.push(a);y.push(b);y.push(c)}function l(a,b,c){r(a);r(b);r(c);a=e.length/3;a=D.generateTopUV(d,e,a-3,a-2,a-1);v(a[0]);v(a[1]);v(a[2])}function r(a){e.push(y[3*a]);e.push(y[3*a+1]);e.push(y[3*a+2])}function v(a){f.push(a.x);f.push(a.y)}var y=[],x=void 0!==b.curveSegments?b.curveSegments:12,w=void 0!==b.steps?b.steps:1,B=void 0!==b.depth?b.depth:100,E=void 0!==b.bevelEnabled?
17563 b.bevelEnabled:!0,P=void 0!==b.bevelThickness?b.bevelThickness:6,N=void 0!==b.bevelSize?b.bevelSize:P-2,O=void 0!==b.bevelSegments?b.bevelSegments:3,A=b.extrudePath,D=void 0!==b.UVGenerator?b.UVGenerator:Qg;void 0!==b.amount&&(console.warn("THREE.ExtrudeBufferGeometry: amount has been renamed to depth."),B=b.amount);var C=!1;if(A){var G=A.getSpacedPoints(w);C=!0;E=!1;var K=A.computeFrenetFrames(w,!1);var L=new p;var R=new p;var Q=new p}E||(N=P=O=0);var I;x=a.extractPoints(x);a=x.shape;var J=x.holes;
17564 if(!Va.isClockWise(a)){a=a.reverse();var H=0;for(I=J.length;H<I;H++){var S=J[H];Va.isClockWise(S)&&(J[H]=S.reverse())}}var Y=Va.triangulateShape(a,J),W=a;H=0;for(I=J.length;H<I;H++)S=J[H],a=a.concat(S);var T,Z=a.length,V,ea=Y.length;x=[];var M=0;var U=W.length;var X=U-1;for(T=M+1;M<U;M++,X++,T++)X===U&&(X=0),T===U&&(T=0),x[M]=g(W[M],W[X],W[T]);A=[];var fa=x.concat();H=0;for(I=J.length;H<I;H++){S=J[H];var ca=[];M=0;U=S.length;X=U-1;for(T=M+1;M<U;M++,X++,T++)X===U&&(X=0),T===U&&(T=0),ca[M]=g(S[M],S[X],
17565 S[T]);A.push(ca);fa=fa.concat(ca)}for(X=0;X<O;X++){U=X/O;var da=P*Math.cos(U*Math.PI/2);T=N*Math.sin(U*Math.PI/2);M=0;for(U=W.length;M<U;M++){var aa=c(W[M],x[M],T);k(aa.x,aa.y,-da)}H=0;for(I=J.length;H<I;H++)for(S=J[H],ca=A[H],M=0,U=S.length;M<U;M++)aa=c(S[M],ca[M],T),k(aa.x,aa.y,-da)}T=N;for(M=0;M<Z;M++)aa=E?c(a[M],fa[M],T):a[M],C?(R.copy(K.normals[0]).multiplyScalar(aa.x),L.copy(K.binormals[0]).multiplyScalar(aa.y),Q.copy(G[0]).add(R).add(L),k(Q.x,Q.y,Q.z)):k(aa.x,aa.y,0);for(U=1;U<=w;U++)for(M=
17566 0;M<Z;M++)aa=E?c(a[M],fa[M],T):a[M],C?(R.copy(K.normals[U]).multiplyScalar(aa.x),L.copy(K.binormals[U]).multiplyScalar(aa.y),Q.copy(G[U]).add(R).add(L),k(Q.x,Q.y,Q.z)):k(aa.x,aa.y,B/w*U);for(X=O-1;0<=X;X--){U=X/O;da=P*Math.cos(U*Math.PI/2);T=N*Math.sin(U*Math.PI/2);M=0;for(U=W.length;M<U;M++)aa=c(W[M],x[M],T),k(aa.x,aa.y,B+da);H=0;for(I=J.length;H<I;H++)for(S=J[H],ca=A[H],M=0,U=S.length;M<U;M++)aa=c(S[M],ca[M],T),C?k(aa.x,aa.y+G[w-1].y,G[w-1].x+da):k(aa.x,aa.y,B+da)}(function(){var a=e.length/3;if(E){var b=
17567 0*Z;for(M=0;M<ea;M++)V=Y[M],l(V[2]+b,V[1]+b,V[0]+b);b=Z*(w+2*O);for(M=0;M<ea;M++)V=Y[M],l(V[0]+b,V[1]+b,V[2]+b)}else{for(M=0;M<ea;M++)V=Y[M],l(V[2],V[1],V[0]);for(M=0;M<ea;M++)V=Y[M],l(V[0]+Z*w,V[1]+Z*w,V[2]+Z*w)}d.addGroup(a,e.length/3-a,0)})();(function(){var a=e.length/3,b=0;h(W,b);b+=W.length;H=0;for(I=J.length;H<I;H++)S=J[H],h(S,b),b+=S.length;d.addGroup(a,e.length/3-a,1)})()}C.call(this);this.type="ExtrudeBufferGeometry";this.parameters={shapes:a,options:b};a=Array.isArray(a)?a:[a];for(var d=
17568 this,e=[],f=[],g=0,h=a.length;g<h;g++)c(a[g]);this.addAttribute("position",new A(e,3));this.addAttribute("uv",new A(f,2));this.computeVertexNormals()}function hf(a,b,c){c.shapes=[];if(Array.isArray(a))for(var d=0,e=a.length;d<e;d++)c.shapes.push(a[d].uuid);else c.shapes.push(a.uuid);void 0!==b.extrudePath&&(c.options.extrudePath=b.extrudePath.toJSON());return c}function Sc(a,b){R.call(this);this.type="TextGeometry";this.parameters={text:a,parameters:b};this.fromBufferGeometry(new Yb(a,b));this.mergeVertices()}
17569 function Yb(a,b){b=b||{};var c=b.font;if(!c||!c.isFont)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new R;a=c.generateShapes(a,b.size);b.depth=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);Oa.call(this,a,b);this.type="TextBufferGeometry"}function Tc(a,b,c,d,e,f,g){R.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,
17570 heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new sb(a,b,c,d,e,f,g));this.mergeVertices()}function sb(a,b,c,d,e,f,g){C.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||1;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||6);d=void 0!==d?d:0;e=void 0!==e?e:2*Math.PI;f=void 0!==f?f:0;g=void 0!==g?g:Math.PI;var h=f+g,k,m,q=0,n=[],l=new p,
17571 u=new p,r=[],v=[],y=[],x=[];for(m=0;m<=c;m++){var w=[],B=m/c;for(k=0;k<=b;k++){var E=k/b;l.x=-a*Math.cos(d+E*e)*Math.sin(f+B*g);l.y=a*Math.cos(f+B*g);l.z=a*Math.sin(d+E*e)*Math.sin(f+B*g);v.push(l.x,l.y,l.z);u.set(l.x,l.y,l.z).normalize();y.push(u.x,u.y,u.z);x.push(E,1-B);w.push(q++)}n.push(w)}for(m=0;m<c;m++)for(k=0;k<b;k++)a=n[m][k+1],d=n[m][k],e=n[m+1][k],g=n[m+1][k+1],(0!==m||0<f)&&r.push(a,d,g),(m!==c-1||h<Math.PI)&&r.push(d,e,g);this.setIndex(r);this.addAttribute("position",new A(v,3));this.addAttribute("normal",
17572 new A(y,3));this.addAttribute("uv",new A(x,2))}function Uc(a,b,c,d,e,f){R.call(this);this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Zb(a,b,c,d,e,f));this.mergeVertices()}function Zb(a,b,c,d,e,f){C.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||.5;b=b||1;e=void 0!==e?e:0;f=void 0!==f?f:2*Math.PI;
17573 c=void 0!==c?Math.max(3,c):8;d=void 0!==d?Math.max(1,d):1;var g=[],h=[],k=[],m=[],q=a,n=(b-a)/d,l=new p,u=new z,r,v;for(r=0;r<=d;r++){for(v=0;v<=c;v++)a=e+v/c*f,l.x=q*Math.cos(a),l.y=q*Math.sin(a),h.push(l.x,l.y,l.z),k.push(0,0,1),u.x=(l.x/b+1)/2,u.y=(l.y/b+1)/2,m.push(u.x,u.y);q+=n}for(r=0;r<d;r++)for(b=r*(c+1),v=0;v<c;v++)a=v+b,e=a+c+1,f=a+c+2,q=a+1,g.push(a,e,q),g.push(e,f,q);this.setIndex(g);this.addAttribute("position",new A(h,3));this.addAttribute("normal",new A(k,3));this.addAttribute("uv",
17574 new A(m,2))}function Vc(a,b,c,d){R.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new $b(a,b,c,d));this.mergeVertices()}function $b(a,b,c,d){C.call(this);this.type="LatheBufferGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};b=Math.floor(b)||12;c=c||0;d=d||2*Math.PI;d=H.clamp(d,0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new p,m=new z,q;for(q=0;q<=b;q++){var n=c+q*h*d;var l=Math.sin(n),u=Math.cos(n);for(n=
17575 0;n<=a.length-1;n++)k.x=a[n].x*l,k.y=a[n].y,k.z=a[n].x*u,f.push(k.x,k.y,k.z),m.x=q/b,m.y=n/(a.length-1),g.push(m.x,m.y)}for(q=0;q<b;q++)for(n=0;n<a.length-1;n++)c=n+q*a.length,h=c+a.length,k=c+a.length+1,m=c+1,e.push(c,h,m),e.push(h,k,m);this.setIndex(e);this.addAttribute("position",new A(f,3));this.addAttribute("uv",new A(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=this.attributes.normal.array,e=new p,f=new p,g=new p,c=b*a.length*3,n=q=0;q<a.length;q++,n+=3)e.x=d[n+0],e.y=d[n+1],e.z=
17576 d[n+2],f.x=d[c+n+0],f.y=d[c+n+1],f.z=d[c+n+2],g.addVectors(e,f).normalize(),d[n+0]=d[c+n+0]=g.x,d[n+1]=d[c+n+1]=g.y,d[n+2]=d[c+n+2]=g.z}function tb(a,b){R.call(this);this.type="ShapeGeometry";"object"===typeof b&&(console.warn("THREE.ShapeGeometry: Options parameter has been removed."),b=b.curveSegments);this.parameters={shapes:a,curveSegments:b};this.fromBufferGeometry(new ub(a,b));this.mergeVertices()}function ub(a,b){function c(a){var c,h=e.length/3;a=a.extractPoints(b);var m=a.shape,q=a.holes;
17577 if(!1===Va.isClockWise(m))for(m=m.reverse(),a=0,c=q.length;a<c;a++){var l=q[a];!0===Va.isClockWise(l)&&(q[a]=l.reverse())}var p=Va.triangulateShape(m,q);a=0;for(c=q.length;a<c;a++)l=q[a],m=m.concat(l);a=0;for(c=m.length;a<c;a++)l=m[a],e.push(l.x,l.y,0),f.push(0,0,1),g.push(l.x,l.y);a=0;for(c=p.length;a<c;a++)m=p[a],d.push(m[0]+h,m[1]+h,m[2]+h),k+=3}C.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);
17578 else for(var m=0;m<a.length;m++)c(a[m]),this.addGroup(h,k,m),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new A(e,3));this.addAttribute("normal",new A(f,3));this.addAttribute("uv",new A(g,2))}function jf(a,b){b.shapes=[];if(Array.isArray(a))for(var c=0,d=a.length;c<d;c++)b.shapes.push(a[c].uuid);else b.shapes.push(a.uuid);return b}function ac(a,b){C.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var c=[];b=Math.cos(H.DEG2RAD*(void 0!==b?b:1));var d=[0,0],e={},f=
17579 ["a","b","c"];if(a.isBufferGeometry){var g=new R;g.fromBufferGeometry(a)}else g=a.clone();g.mergeVertices();g.computeFaceNormals();a=g.vertices;g=g.faces;for(var h=0,k=g.length;h<k;h++)for(var m=g[h],q=0;3>q;q++){var n=m[f[q]];var l=m[f[(q+1)%3]];d[0]=Math.min(n,l);d[1]=Math.max(n,l);n=d[0]+","+d[1];void 0===e[n]?e[n]={index1:d[0],index2:d[1],face1:h,face2:void 0}:e[n].face2=h}for(n in e)if(d=e[n],void 0===d.face2||g[d.face1].normal.dot(g[d.face2].normal)<=b)f=a[d.index1],c.push(f.x,f.y,f.z),f=a[d.index2],
17580 c.push(f.x,f.y,f.z);this.addAttribute("position",new A(c,3))}function vb(a,b,c,d,e,f,g,h){R.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()}function Wa(a,b,c,d,e,f,g,h){function k(c){var e,f=new z,k=new p,t=0,v=!0===c?a:b,w=!0===c?1:-1;var A=r;for(e=1;e<=d;e++)n.push(0,y*w,0),l.push(0,w,0),u.push(.5,.5),r++;var C=
17581 r;for(e=0;e<=d;e++){var D=e/d*h+g,H=Math.cos(D);D=Math.sin(D);k.x=v*D;k.y=y*w;k.z=v*H;n.push(k.x,k.y,k.z);l.push(0,w,0);f.x=.5*H+.5;f.y=.5*D*w+.5;u.push(f.x,f.y);r++}for(e=0;e<d;e++)f=A+e,k=C+e,!0===c?q.push(k,k+1,f):q.push(k+1,k,f),t+=3;m.addGroup(x,t,!0===c?1:2);x+=t}C.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var m=this;a=void 0!==a?a:1;b=void 0!==b?b:1;c=c||1;d=Math.floor(d)||
17582 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 q=[],n=[],l=[],u=[],r=0,v=[],y=c/2,x=0;(function(){var f,k,t=new p,P=new p,N=0,z=(b-a)/c;for(k=0;k<=e;k++){var A=[],D=k/e,C=D*(b-a)+a;for(f=0;f<=d;f++){var H=f/d,G=H*h+g,K=Math.sin(G);G=Math.cos(G);P.x=C*K;P.y=-D*c+y;P.z=C*G;n.push(P.x,P.y,P.z);t.set(K,z,G).normalize();l.push(t.x,t.y,t.z);u.push(H,1-D);A.push(r++)}v.push(A)}for(f=0;f<d;f++)for(k=0;k<e;k++)t=v[k+1][f],P=v[k+1][f+1],z=v[k][f+1],q.push(v[k][f],t,z),
17583 q.push(t,P,z),N+=6;m.addGroup(x,N,0);x+=N})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(q);this.addAttribute("position",new A(n,3));this.addAttribute("normal",new A(l,3));this.addAttribute("uv",new A(u,2))}function Wc(a,b,c,d,e,f,g){vb.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 Xc(a,b,c,d,e,f,g){Wa.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters=
17584 {radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Yc(a,b,c,d){R.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new bc(a,b,c,d));this.mergeVertices()}function bc(a,b,c,d){C.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||1;b=void 0!==b?Math.max(3,b):8;c=void 0!==c?c:0;d=void 0!==d?d:2*Math.PI;var e=[],f=
17585 [],g=[],h=[],k,m=new p,q=new z;f.push(0,0,0);g.push(0,0,1);h.push(.5,.5);var n=0;for(k=3;n<=b;n++,k+=3){var l=c+n/b*d;m.x=a*Math.cos(l);m.y=a*Math.sin(l);f.push(m.x,m.y,m.z);g.push(0,0,1);q.x=(f[k]/a+1)/2;q.y=(f[k+1]/a+1)/2;h.push(q.x,q.y)}for(k=1;k<=b;k++)e.push(k,k+1,0);this.setIndex(e);this.addAttribute("position",new A(f,3));this.addAttribute("normal",new A(g,3));this.addAttribute("uv",new A(h,2))}function wb(a){J.call(this);this.type="ShadowMaterial";this.color=new G(0);this.transparent=!0;this.setValues(a)}
17586 function cc(a){ta.call(this,a);this.type="RawShaderMaterial"}function Pa(a){J.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new G(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=0;this.normalScale=new z(1,1);this.displacementMap=null;this.displacementScale=
17587 1;this.displacementBias=0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function xb(a){Pa.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Fa(a){J.call(this);
17588 this.type="MeshPhongMaterial";this.color=new G(16777215);this.specular=new G(1118481);this.shininess=30;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=0;this.normalScale=new z(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;
17589 this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function yb(a){Fa.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function zb(a){J.call(this);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=0;this.normalScale=new z(1,1);this.displacementMap=
17590 null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=!1;this.setValues(a)}function Ab(a){J.call(this);this.type="MeshLambertMaterial";this.color=new G(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.envMap=this.alphaMap=this.specularMap=this.emissiveMap=null;this.combine=0;this.reflectivity=
17591 1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function Bb(a){Y.call(this);this.type="LineDashedMaterial";this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(a)}function ce(a,b,c){var d=this,e=!1,f=0,g=0,h=void 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,
17592 f,g);e=!0};this.itemEnd=function(a){f++;if(void 0!==d.onProgress)d.onProgress(a,f,g);if(f===g&&(e=!1,void 0!==d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)};this.resolveURL=function(a){return h?h(a):a};this.setURLModifier=function(a){h=a;return this}}function Ga(a){this.manager=void 0!==a?a:ka}function kf(a){this.manager=void 0!==a?a:ka;this._parser=null}function de(a){this.manager=void 0!==a?a:ka;this._parser=null}function Zc(a){this.manager=void 0!==a?a:ka}
17593 function ee(a){this.manager=void 0!==a?a:ka}function vd(a){this.manager=void 0!==a?a:ka}function L(){this.type="Curve";this.arcLengthDivisions=200}function za(a,b,c,d,e,f,g,h){L.call(this);this.type="EllipseCurve";this.aX=a||0;this.aY=b||0;this.xRadius=c||1;this.yRadius=d||1;this.aStartAngle=e||0;this.aEndAngle=f||2*Math.PI;this.aClockwise=g||!1;this.aRotation=h||0}function dc(a,b,c,d,e,f){za.call(this,a,b,c,c,d,e,f);this.type="ArcCurve"}function fe(){var a=0,b=0,c=0,d=0;return{initCatmullRom:function(e,
17594 f,g,h,k){e=k*(g-e);h=k*(h-f);a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},initNonuniformCatmullRom:function(e,f,g,h,k,m,q){e=((f-e)/k-(g-e)/(k+m)+(g-f)/m)*m;h=((g-f)/m-(h-f)/(m+q)+(h-g)/q)*m;a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},calc:function(e){var f=e*e;return a+b*e+c*f+d*f*e}}}function ca(a,b,c,d){L.call(this);this.type="CatmullRomCurve3";this.points=a||[];this.closed=b||!1;this.curveType=c||"centripetal";this.tension=d||.5}function lf(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2*c-2*d+b+e)*
17595 a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function $c(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function ad(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}function Ha(a,b,c,d){L.call(this);this.type="CubicBezierCurve";this.v0=a||new z;this.v1=b||new z;this.v2=c||new z;this.v3=d||new z}function Qa(a,b,c,d){L.call(this);this.type="CubicBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=c||new p;this.v3=d||new p}function va(a,b){L.call(this);this.type="LineCurve";this.v1=a||
17596 new z;this.v2=b||new z}function Ia(a,b){L.call(this);this.type="LineCurve3";this.v1=a||new p;this.v2=b||new p}function Ja(a,b,c){L.call(this);this.type="QuadraticBezierCurve";this.v0=a||new z;this.v1=b||new z;this.v2=c||new z}function Ra(a,b,c){L.call(this);this.type="QuadraticBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=c||new p}function Ka(a){L.call(this);this.type="SplineCurve";this.points=a||[]}function Xa(){L.call(this);this.type="CurvePath";this.curves=[];this.autoClose=!1}function La(a){Xa.call(this);
17597 this.type="Path";this.currentPoint=new z;a&&this.setFromPoints(a)}function db(a){La.call(this,a);this.uuid=H.generateUUID();this.type="Shape";this.holes=[]}function X(a,b){D.call(this);this.type="Light";this.color=new G(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function wd(a,b,c){X.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(D.DefaultUp);this.updateMatrix();this.groundColor=new G(b)}function Cb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=
17598 new z(512,512);this.map=null;this.matrix=new I}function xd(){Cb.call(this,new Z(50,1,.5,500))}function yd(a,b,c,d,e,f){X.call(this,a,b);this.type="SpotLight";this.position.copy(D.DefaultUp);this.updateMatrix();this.target=new D;Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(a){this.intensity=a/Math.PI}});this.distance=void 0!==c?c:0;this.angle=void 0!==d?d:Math.PI/3;this.penumbra=void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=new xd}function zd(a,
17599 b,c,d){X.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 Cb(new Z(90,1,.5,500))}function Ad(){Cb.call(this,new Hb(-5,5,5,-5,.5,500))}function Bd(a,b){X.call(this,a,b);this.type="DirectionalLight";this.position.copy(D.DefaultUp);this.updateMatrix();this.target=new D;this.shadow=new Ad}function Cd(a,b){X.call(this,
17600 a,b);this.type="AmbientLight";this.castShadow=void 0}function Dd(a,b,c,d){X.call(this,a,b);this.type="RectAreaLight";this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function wa(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 Ed(a,b,c,d){wa.call(this,a,b,c,d);this._offsetNext=this._weightNext=this._offsetPrev=this._weightPrev=-0}function bd(a,b,c,d){wa.call(this,a,b,c,d)}function Fd(a,b,
17601 c,d){wa.call(this,a,b,c,d)}function oa(a,b,c,d){if(void 0===a)throw Error("THREE.KeyframeTrack: track name is undefined");if(void 0===b||0===b.length)throw Error("THREE.KeyframeTrack: no keyframes in track named "+a);this.name=a;this.times=ia.convertArray(b,this.TimeBufferType);this.values=ia.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation)}function Gd(a,b,c){oa.call(this,a,b,c)}function Hd(a,b,c,d){oa.call(this,a,b,c,d)}function ec(a,b,c,d){oa.call(this,a,
17602 b,c,d)}function Id(a,b,c,d){wa.call(this,a,b,c,d)}function cd(a,b,c,d){oa.call(this,a,b,c,d)}function Jd(a,b,c,d){oa.call(this,a,b,c,d)}function fc(a,b,c,d){oa.call(this,a,b,c,d)}function Ca(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=H.generateUUID();0>this.duration&&this.resetDuration()}function Rg(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return ec;case "vector":case "vector2":case "vector3":case "vector4":return fc;
17603 case "color":return Hd;case "quaternion":return cd;case "bool":case "boolean":return Gd;case "string":return Jd}throw Error("THREE.KeyframeTrack: Unsupported typeName: "+a);}function Sg(a){if(void 0===a.type)throw Error("THREE.KeyframeTrack: track type undefined, can not parse");var b=Rg(a.type);if(void 0===a.times){var c=[],d=[];ia.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)}function Kd(a){this.manager=void 0!==
17604 a?a:ka;this.textures={}}function ge(a){this.manager=void 0!==a?a:ka}function gc(){}function he(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:ka;this.withCredentials=!1}function mf(a){this.manager=void 0!==a?a:ka;this.texturePath=""}function ie(a){"undefined"===typeof createImageBitmap&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported.");"undefined"===typeof fetch&&console.warn("THREE.ImageBitmapLoader: fetch() not supported.");
17605 this.manager=void 0!==a?a:ka;this.options=void 0}function je(){this.type="ShapePath";this.color=new G;this.subPaths=[];this.currentPath=null}function ke(a){this.type="Font";this.data=a}function nf(a){this.manager=void 0!==a?a:ka}function le(a){this.manager=void 0!==a?a:ka}function of(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new Z;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new Z;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=
17606 !1}function dd(a,b,c){D.call(this);this.type="CubeCamera";var d=new Z(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new p(1,0,0));this.add(d);var e=new Z(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new p(-1,0,0));this.add(e);var f=new Z(90,1,a,b);f.up.set(0,0,1);f.lookAt(new p(0,1,0));this.add(f);var g=new Z(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new p(0,-1,0));this.add(g);var h=new Z(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new p(0,0,1));this.add(h);var k=new Z(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new p(0,0,-1));this.add(k);
17607 this.renderTarget=new Gb(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.update=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,m=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=m;c.activeCubeFace=5;a.render(b,
17608 k,c);a.setRenderTarget(null)};this.clear=function(a,b,c,d){for(var e=this.renderTarget,f=0;6>f;f++)e.activeCubeFace=f,a.setRenderTarget(e),a.clear(b,c,d);a.setRenderTarget(null)}}function me(){D.call(this);this.type="AudioListener";this.context=ne.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function hc(a){D.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=
17609 !1;this.buffer=null;this.loop=!1;this.offset=this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function oe(a){hc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function pe(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 qe(a,b,c){this.binding=a;this.valueSize=
17610 c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function pf(a,b,c){c=c||pa.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function pa(a,b,c){this.path=b;this.parsedPath=c||pa.parseTrackName(b);this.node=pa.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function qf(){this.uuid=
17611 H.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var a={};this._indicesByUUID=a;for(var b=0,c=arguments.length;b!==c;++b)a[arguments[b].uuid]=b;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var d=this;this.stats={objects:{get total(){return d._objects.length},get inUse(){return this.total-d.nCachedObjects_}},get bindingsPerObject(){return d._bindings.length}}}function rf(a,b,c){this._mixer=a;this._clip=b;this._localRoot=
17612 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=2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;
17613 this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function re(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Ld(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function se(){C.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function te(a,b,c){ob.call(this,a,b);this.meshPerAttribute=c||1}function ue(a,b,c){Q.call(this,
17614 a,b);this.meshPerAttribute=c||1}function sf(a,b,c,d){this.ray=new mb(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 tf(a,b){return a.distance-b.distance}function ve(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++)ve(a[d],
17615 b,c,!0)}}function uf(a){this.autoStart=void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function vf(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 wf(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 we(a,b){this.min=void 0!==a?a:new z(Infinity,Infinity);this.max=void 0!==b?b:new z(-Infinity,-Infinity)}function xe(a,b){this.start=void 0!==a?a:new p;this.end=
17616 void 0!==b?b:new p}function ed(a){D.call(this);this.material=a;this.render=function(){}}function fd(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 C;b=new A(6*b,3);c.addAttribute("position",b);W.call(this,c,new Y({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function ic(a,b){D.call(this);this.light=a;this.light.updateMatrixWorld();
17617 this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new C;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];for(var 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 A(b,3));b=new Y({fog:!1});this.cone=new W(a,b);this.add(this.cone);this.update()}function xf(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,xf(a.children[c]));return b}
17618 function jc(a){for(var b=xf(a),c=new C,d=[],e=[],f=new G(0,0,1),g=new G(0,1,0),h=0;h<b.length;h++){var k=b[h];k.parent&&k.parent.isBone&&(d.push(0,0,0),d.push(0,0,0),e.push(f.r,f.g,f.b),e.push(g.r,g.g,g.b))}c.addAttribute("position",new A(d,3));c.addAttribute("color",new A(e,3));d=new Y({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});W.call(this,c,d);this.root=a;this.bones=b;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1}function kc(a,b,c){this.light=a;this.light.updateMatrixWorld();
17619 this.color=c;a=new sb(b,4,2);b=new da({wireframe:!0,fog:!1});la.call(this,a,b);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1;this.update()}function lc(a,b){D.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new Y({fog:!1});b=new C;b.addAttribute("position",new Q(new Float32Array(15),3));this.line=new sa(b,a);this.add(this.line);this.update()}function mc(a,b,c){D.call(this);this.light=a;this.light.updateMatrixWorld();
17620 this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;a=new pb(b);a.rotateY(.5*Math.PI);this.material=new da({wireframe:!0,fog:!1});void 0===this.color&&(this.material.vertexColors=2);b=a.getAttribute("position");b=new Float32Array(3*b.count);a.addAttribute("color",new Q(b,3));this.add(new la(a,this.material));this.update()}function gd(a,b,c,d){a=a||10;b=b||10;c=new G(void 0!==c?c:4473924);d=new G(void 0!==d?d:8947848);var e=b/2,f=a/b,g=a/2;a=[];for(var h=[],k=0,m=0,q=-g;k<=b;k++,q+=f){a.push(-g,
17621 0,q,g,0,q);a.push(q,0,-g,q,0,g);var n=k===e?c:d;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3}b=new C;b.addAttribute("position",new A(a,3));b.addAttribute("color",new A(h,3));c=new Y({vertexColors:2});W.call(this,b,c)}function Md(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new G(void 0!==e?e:4473924);f=new G(void 0!==f?f:8947848);var g=[],h=[],k;for(k=0;k<=b;k++){var m=k/b*2*Math.PI;var q=Math.sin(m)*a;m=Math.cos(m)*a;g.push(0,0,0);g.push(q,0,m);var n=k&1?e:f;h.push(n.r,
17622 n.g,n.b);h.push(n.r,n.g,n.b)}for(k=0;k<=c;k++){n=k&1?e:f;var l=a-a/c*k;for(b=0;b<d;b++)m=b/d*2*Math.PI,q=Math.sin(m)*l,m=Math.cos(m)*l,g.push(q,0,m),h.push(n.r,n.g,n.b),m=(b+1)/d*2*Math.PI,q=Math.sin(m)*l,m=Math.cos(m)*l,g.push(q,0,m),h.push(n.r,n.g,n.b)}a=new C;a.addAttribute("position",new A(g,3));a.addAttribute("color",new A(h,3));g=new Y({vertexColors:2});W.call(this,a,g)}function hd(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)&&
17623 c.isGeometry?b=c.faces.length:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");c=new C;b=new A(6*b,3);c.addAttribute("position",b);W.call(this,c,new Y({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function nc(a,b,c){D.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;void 0===b&&(b=1);a=new C;a.addAttribute("position",new A([-b,b,0,b,b,0,b,-b,0,-b,
17624 -b,0,-b,b,0],3));b=new Y({fog:!1});this.lightPlane=new sa(a,b);this.add(this.lightPlane);a=new C;a.addAttribute("position",new A([0,0,0,0,0,1],3));this.targetLine=new sa(a,b);this.add(this.targetLine);this.update()}function id(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){f.push(0,0,0);g.push(b.r,b.g,b.b);void 0===h[a]&&(h[a]=[]);h[a].push(f.length/3-1)}var d=new C,e=new Y({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new G(16755200),m=new G(16711680),q=new G(43775),n=new G(16777215),l=new G(3355443);
17625 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",q);b("u2","u3",q);b("u3","u1",q);b("c","t",n);b("p","c",l);b("cn1","cn2",l);b("cn3","cn4",l);b("cf1","cf2",l);b("cf3","cf4",l);d.addAttribute("position",new A(f,3));d.addAttribute("color",new A(g,3));W.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&
17626 this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function Db(a,b){this.object=a;void 0===b&&(b=16776960);a=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]);var c=new Float32Array(24),d=new C;d.setIndex(new Q(a,1));d.addAttribute("position",new Q(c,3));W.call(this,d,new Y({color:b}));this.matrixAutoUpdate=!1;this.update()}function jd(a,b){this.type="Box3Helper";this.box=a;a=void 0!==b?b:16776960;b=new Uint16Array([0,
17627 1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var c=new C;c.setIndex(new Q(b,1));c.addAttribute("position",new A([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3));W.call(this,c,new Y({color:a}));this.geometry.computeBoundingSphere()}function kd(a,b,c){this.type="PlaneHelper";this.plane=a;this.size=void 0===b?1:b;a=void 0!==c?c:16776960;b=new C;b.addAttribute("position",new A([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,0,1,0,0,0],3));b.computeBoundingSphere();sa.call(this,
17628 b,new Y({color:a}));b=new C;b.addAttribute("position",new A([1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1],3));b.computeBoundingSphere();this.add(new la(b,new da({color:a,opacity:.2,transparent:!0,depthWrite:!1})))}function Eb(a,b,c,d,e,f){D.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);void 0===Nd&&(Nd=new C,Nd.addAttribute("position",new A([0,0,0,0,1,0],3)),ye=new Wa(0,.5,1,5,1),ye.translate(0,-.5,0));this.position.copy(b);this.line=new sa(Nd,new Y({color:d}));
17629 this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new la(ye,new da({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,e,f)}function ld(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 C;a.addAttribute("position",new A(b,3));a.addAttribute("color",new A([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new Y({vertexColors:2});W.call(this,a,b)}function yf(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");
17630 ca.call(this,a);this.type="catmullrom";this.closed=!0}function zf(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ca.call(this,a);this.type="catmullrom"}function ze(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");ca.call(this,a);this.type="catmullrom"}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Number.isInteger&&(Number.isInteger=function(a){return"number"===typeof a&&isFinite(a)&&Math.floor(a)===
17631 a});void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0<a?1:+a});!1==="name"in Function.prototype&&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,
17632 e)&&(b[e]=d[e])}return b}}();Object.assign(ya.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){void 0!==this._listeners&&(a=this._listeners[a],void 0!==a&&(b=a.indexOf(b),-1!==b&&a.splice(b,1)))},dispatchEvent:function(a){if(void 0!==
17633 this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;b=b.slice(0);for(var c=0,d=b.length;c<d;c++)b[c].call(this,a)}}}});var H={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){for(var a=[],b=0;256>b;b++)a[b]=(16>b?"0":"")+b.toString(16);return function(){var b=4294967295*Math.random()|0,d=4294967295*Math.random()|0,e=4294967295*Math.random()|0,f=4294967295*Math.random()|0;return(a[b&255]+a[b>>8&255]+a[b>>16&255]+a[b>>24&255]+"-"+a[d&255]+a[d>>8&255]+"-"+a[d>>
17634 16&15|64]+a[d>>24&255]+"-"+a[e&63|128]+a[e>>8&255]+"-"+a[e>>16&255]+a[e>>24&255]+a[f&255]+a[f>>8&255]+a[f>>16&255]+a[f>>24&255]).toUpperCase()}}(),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;
17635 a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*H.DEG2RAD},radToDeg:function(a){return a*H.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},ceilPowerOfTwo:function(a){return Math.pow(2,Math.ceil(Math.log(a)/Math.LN2))},floorPowerOfTwo:function(a){return Math.pow(2,Math.floor(Math.log(a)/
17636 Math.LN2))}};Object.defineProperties(z.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}});Object.assign(z.prototype,{isVector2:!0,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: "+
17637 a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==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},
17638 addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),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*=
17639 a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},applyMatrix3:function(a){var b=this.x,c=this.y;a=a.elements;this.x=a[0]*b+a[3]*c+a[6];this.y=a[1]*b+a[4]*c+a[7];return this},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,
17640 b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new z,b=new z;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,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=
17641 Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},cross:function(a){return this.x*a.y-this.y*a.x},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},manhattanLength:function(){return Math.abs(this.x)+
17642 Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||1)},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=
17643 (a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);
17644 return this},rotateAround:function(a,b){var c=Math.cos(b);b=Math.sin(b);var d=this.x-a.x,e=this.y-a.y;this.x=d*c-e*b+a.x;this.y=d*b+e*c+a.y;return this}});Object.assign(I.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,q,n,l,u,r,p){var t=this.elements;t[0]=a;t[4]=b;t[8]=c;t[12]=d;t[1]=e;t[5]=f;t[9]=g;t[13]=h;t[2]=k;t[6]=m;t[10]=q;t[14]=n;t[3]=l;t[7]=u;t[11]=r;t[15]=p;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 I).fromArray(this.elements)},
17645 copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,
17646 b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new p;return function(b){var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[3]=0;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[7]=0;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;c[11]=0;c[12]=0;c[13]=0;c[14]=0;c[15]=1;return this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");
17647 var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c);c=Math.sin(c);var g=Math.cos(d);d=Math.sin(d);var h=Math.cos(e);e=Math.sin(e);if("XYZ"===a.order){a=f*h;var k=f*e,m=c*h,q=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-q*d;b[9]=-c*g;b[2]=q-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a+q*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]=q+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a-q*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=
17648 q-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,q=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*d+q,b[1]=g*e,b[5]=q*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,q=c*d,b[0]=g*h,b[4]=q-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-q*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+q,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=q*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(){var a=
17649 new p(0,0,0),b=new p(1,1,1);return function(c){return this.compose(a,c,b)}}(),lookAt:function(){var a=new p,b=new p,c=new p;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4,c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==
17650 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;b=this.elements;a=c[0];var e=c[4],f=c[8],g=c[12],h=c[1],k=c[5],m=c[9],q=c[13],n=c[2],l=c[6],u=c[10],r=c[14],p=c[3],y=c[7],x=c[11];c=c[15];var w=d[0],B=d[4],E=d[8],P=d[12],N=d[1],z=d[5],A=d[9],D=d[13],C=d[2],
17651 H=d[6],G=d[10],K=d[14],L=d[3],I=d[7],J=d[11];d=d[15];b[0]=a*w+e*N+f*C+g*L;b[4]=a*B+e*z+f*H+g*I;b[8]=a*E+e*A+f*G+g*J;b[12]=a*P+e*D+f*K+g*d;b[1]=h*w+k*N+m*C+q*L;b[5]=h*B+k*z+m*H+q*I;b[9]=h*E+k*A+m*G+q*J;b[13]=h*P+k*D+m*K+q*d;b[2]=n*w+l*N+u*C+r*L;b[6]=n*B+l*z+u*H+r*I;b[10]=n*E+l*A+u*G+r*J;b[14]=n*P+l*D+u*K+r*d;b[3]=p*w+y*N+x*C+c*L;b[7]=p*B+y*z+x*H+c*I;b[11]=p*E+y*A+x*G+c*J;b[15]=p*P+y*D+x*K+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=
17652 a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=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],q=a[6],n=a[10],l=a[14];return a[3]*(+e*h*q-d*k*q-e*g*n+c*k*n+d*g*l-c*h*l)+a[7]*(+b*h*l-b*k*n+e*f*n-
17653 d*f*l+d*k*m-e*h*m)+a[11]*(+b*k*q-b*g*l-e*f*q+c*f*l+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*q+b*g*n+d*f*q-c*f*n+c*h*m)},transpose:function(){var a=this.elements;var 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;a=d[0];var e=d[1],f=d[2],g=d[3],h=d[4],
17654 k=d[5],m=d[6],q=d[7],n=d[8],l=d[9],u=d[10],r=d[11],p=d[12],y=d[13],x=d[14];d=d[15];var w=l*x*q-y*u*q+y*m*r-k*x*r-l*m*d+k*u*d,B=p*u*q-n*x*q-p*m*r+h*x*r+n*m*d-h*u*d,E=n*y*q-p*l*q+p*k*r-h*y*r-n*k*d+h*l*d,z=p*l*m-n*y*m-p*k*u+h*y*u+n*k*x-h*l*x,N=a*w+e*B+f*E+g*z;if(0===N){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()}b=1/N;c[0]=w*b;c[1]=(y*u*g-l*x*g-y*f*
17655 r+e*x*r+l*f*d-e*u*d)*b;c[2]=(k*x*g-y*m*g+y*f*q-e*x*q-k*f*d+e*m*d)*b;c[3]=(l*m*g-k*u*g-l*f*q+e*u*q+k*f*r-e*m*r)*b;c[4]=B*b;c[5]=(n*x*g-p*u*g+p*f*r-a*x*r-n*f*d+a*u*d)*b;c[6]=(p*m*g-h*x*g-p*f*q+a*x*q+h*f*d-a*m*d)*b;c[7]=(h*u*g-n*m*g+n*f*q-a*u*q-h*f*r+a*m*r)*b;c[8]=E*b;c[9]=(p*l*g-n*y*g-p*e*r+a*y*r+n*e*d-a*l*d)*b;c[10]=(h*y*g-p*k*g+p*e*q-a*y*q-h*e*d+a*k*d)*b;c[11]=(n*k*g-h*l*g-n*e*q+a*l*q+h*e*r-a*k*r)*b;c[12]=z*b;c[13]=(n*y*f-p*l*f+p*e*u-a*y*u-n*e*x+a*l*x)*b;c[14]=(p*k*f-h*y*f-p*e*m+a*y*m+h*e*x-a*k*x)*
17656 b;c[15]=(h*l*f-n*k*f+n*e*m-a*l*m-h*e*u+a*k*u)*b;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=
17657 Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=Math.cos(b);b=Math.sin(b);var d=1-c,e=a.x,f=a.y;a=a.z;var g=d*e,h=d*f;this.set(g*e+c,g*f-b*a,g*a+b*f,0,g*f+b*a,h*f+c,h*a-b*e,0,g*a-b*f,h*a+b*e,d*a*a+c,0,0,
17658 0,0,1);return this},makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},makeShear:function(a,b,c){this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1);return this},compose:function(a,b,c){var d=this.elements,e=b._x,f=b._y,g=b._z,h=b._w,k=e+e,m=f+f,q=g+g;b=e*k;var l=e*m;e*=q;var t=f*m;f*=q;g*=q;k*=h;m*=h;h*=q;q=c.x;var u=c.y;c=c.z;d[0]=(1-(t+g))*q;d[1]=(l+h)*q;d[2]=(e-m)*q;d[3]=0;d[4]=(l-h)*u;d[5]=(1-(b+g))*u;d[6]=(f+k)*u;d[7]=0;d[8]=(e+m)*c;d[9]=(f-k)*c;d[10]=(1-(b+t))*c;d[11]=0;
17659 d[12]=a.x;d[13]=a.y;d[14]=a.z;d[15]=1;return this},decompose:function(){var a=new p,b=new I;return function(c,d,e){var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),k=a.set(f[8],f[9],f[10]).length();0>this.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.copy(this);c=1/g;f=1/h;var 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);
17660 e.x=g;e.y=h;e.z=k;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),m=1/(f-e);g[0]=
17661 2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];
17662 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}});Object.assign(fa,{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 q=e[f+1],l=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==q||m!==l){f=1-g;var t=h*d+k*q+m*l+c*e,u=0<=t?1:-1,r=1-t*t;r>Number.EPSILON&&(r=Math.sqrt(r),t=Math.atan2(r,t*u),f=Math.sin(f*t)/r,g=Math.sin(g*
17663 t)/r);u*=g;h=h*f+d*u;k=k*f+q*u;m=m*f+l*u;c=c*f+e*u;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m*m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});Object.defineProperties(fa.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=
17664 a;this.onChangeCallback()}}});Object.assign(fa.prototype,{set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,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(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=
17665 a._x,d=a._y,e=a._z;a=a.order;var f=Math.cos,g=Math.sin,h=f(c/2),k=f(d/2);f=f(e/2);c=g(c/2);d=g(d/2);e=g(e/2);"XYZ"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"YXZ"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"ZXY"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"ZYX"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"YZX"===a?(this._x=c*k*f+
17666 h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f-c*d*e):"XZY"===a&&(this._x=c*k*f-h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,b){b/=2;var c=Math.sin(b);this._x=a.x*c;this._y=a.y*c;this._z=a.z*c;this._w=Math.cos(b);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];var m=c+f+b;0<m?(c=.5/
17667 Math.sqrt(m+1),this._w=.25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new p,b;return function(c,d){void 0===a&&(a=new p);b=c.dot(d)+1;1E-6>b?(b=0,
17668 Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),angleTo:function(a){return 2*Math.acos(Math.abs(H.clamp(this.dot(a),-1,1)))},rotateTowards:function(a,b){var c=this.angleTo(a);if(0===c)return this;this.slerp(a,Math.min(1,b/c));return this},inverse:function(){return this.conjugate()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*
17669 a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),
17670 this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z;a=a._w;var f=b._x,g=b._y,h=b._z;b=b._w;this._x=c*b+a*f+d*h-e*g;this._y=d*b+a*g+e*f-c*h;this._z=e*b+a*h+c*g-d*f;this._w=a*b-c*f-d*g-e*h;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;
17671 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;a=1-g*g;if(a<=Number.EPSILON)return g=1-b,this._w=g*f+b*this._w,this._x=g*c+b*this._x,this._y=g*d+b*this._y,this._z=g*e+b*this._z,this.normalize();a=Math.sqrt(a);var h=Math.atan2(a,g);g=Math.sin((1-b)*h)/a;b=Math.sin(b*h)/a;this._w=f*g+this._w*b;this._x=c*g+this._x*b;this._y=d*g+this._y*b;this._z=e*g+this._z*b;this.onChangeCallback();return this},equals:function(a){return a._x===
17672 this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(p.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},
17673 setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,
17674 this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=
17675 a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),
17676 this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new fa;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new fa;return function(b,
17677 c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,
17678 c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,m=a*d+e*c-f*b;b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b*-g+h*-f-k*-e;return this},project:function(){var a=new I;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new I;return function(b){a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=
17679 this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=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,
17680 b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a=new p,b=new p;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,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=
17681 Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*
17682 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)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},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,
17683 b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b)):this.crossVectors(this,a)},crossVectors:function(a,b){var c=a.x,d=a.y;a=a.z;var e=b.x,f=b.y;b=b.z;this.x=d*b-a*f;this.y=a*e-c*b;this.z=c*f-d*e;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=
17684 new p;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a=new p;return function(b){return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(H.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},manhattanDistanceTo:function(a){return Math.abs(this.x-
17685 a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y=a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),
17686 c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==
17687 c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(ra.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=k;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;
17688 b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiply:function(a){return this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,
17689 this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements;b=this.elements;a=c[0];var e=c[3],f=c[6],g=c[1],h=c[4],k=c[7],m=c[2],q=c[5];c=c[8];var l=d[0],t=d[3],u=d[6],r=d[1],p=d[4],y=d[7],x=d[2],w=d[5];d=d[8];b[0]=a*l+e*r+f*x;b[3]=a*t+e*p+f*w;b[6]=a*u+e*y+f*d;b[1]=g*l+h*r+k*x;b[4]=g*t+h*p+k*w;b[7]=g*u+h*y+k*d;b[2]=m*l+q*r+c*x;b[5]=m*t+q*p+c*w;b[8]=m*u+q*y+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=
17690 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;a=this.elements;var d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],m=c[6],q=c[7];c=c[8];var l=c*h-k*q,t=k*m-c*g,u=q*g-h*m,r=d*l+e*t+f*u;if(0===r){if(!0===b)throw Error("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");
17691 console.warn("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/r;a[0]=l*b;a[1]=(f*q-c*e)*b;a[2]=(k*e-f*h)*b;a[3]=t*b;a[4]=(c*d-f*m)*b;a[5]=(f*g-k*d)*b;a[6]=u*b;a[7]=(e*m-q*d)*b;a[8]=(h*d-e*g)*b;return this},transpose:function(){var a=this.elements;var b=a[1];a[1]=a[3];a[3]=b;b=a[2];a[2]=a[6];a[6]=b;b=a[5];a[5]=a[7];a[7]=b;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},transposeIntoArray:function(a){var b=
17692 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},setUvTransform:function(a,b,c,d,e,f,g){var h=Math.cos(e);e=Math.sin(e);this.set(c*h,c*e,-c*(h*f+e*g)+f+a,-d*e,d*h,-d*(-e*f+h*g)+g+b,0,0,1)},scale:function(a,b){var c=this.elements;c[0]*=a;c[3]*=a;c[6]*=a;c[1]*=b;c[4]*=b;c[7]*=b;return this},rotate:function(a){var b=Math.cos(a);a=Math.sin(a);var c=this.elements,d=c[0],e=c[3],f=c[6],g=c[1],h=c[4],k=c[7];c[0]=b*d+a*g;c[3]=b*e+a*h;c[6]=
17693 b*f+a*k;c[1]=-a*d+b*g;c[4]=-a*e+b*h;c[7]=-a*f+b*k;return this},translate:function(a,b){var c=this.elements;c[0]+=a*c[2];c[3]+=a*c[5];c[6]+=a*c[8];c[1]+=b*c[2];c[4]+=b*c[5];c[7]+=b*c[8];return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;9>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];
17694 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}});var eb={getDataURL:function(a){if(a instanceof HTMLCanvasElement)var b=a;else{"undefined"!==typeof OffscreenCanvas?b=new OffscreenCanvas(a.width,a.height):(b=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),b.width=a.width,b.height=a.height);var c=b.getContext("2d");a instanceof ImageData?c.putImageData(a,0,0):c.drawImage(a,0,0,a.width,a.height)}return 2048<b.width||2048<b.height?b.toDataURL("image/jpeg",
17695 .6):b.toDataURL("image/png")}},Ef=0;T.DEFAULT_IMAGE=void 0;T.DEFAULT_MAPPING=300;T.prototype=Object.assign(Object.create(ya.prototype),{constructor:T,isTexture:!0,updateMatrix:function(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=
17696 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.center.copy(a.center);this.rotation=a.rotation;this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrix.copy(a.matrix);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){var b=
17697 void 0===a||"string"===typeof a;if(!b&&void 0!==a.textures[this.uuid])return a.textures[this.uuid];var c={metadata:{version:4.5,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],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==
17698 this.image){var d=this.image;void 0===d.uuid&&(d.uuid=H.generateUUID());if(!b&&void 0===a.images[d.uuid]){if(Array.isArray(d)){var e=[];for(var f=0,g=d.length;f<g;f++)e.push(eb.getDataURL(d[f]))}else e=eb.getDataURL(d);a.images[d.uuid]={uuid:d.uuid,url:e}}c.image=d.uuid}b||(a.textures[this.uuid]=c);return c},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.applyMatrix3(this.matrix);if(0>a.x||1<a.x)switch(this.wrapS){case 1E3:a.x-=Math.floor(a.x);
17699 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.defineProperty(T.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(V.prototype,{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=
17700 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: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;
17701 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,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=
17702 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-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=
17703 a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/
17704 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){a=a.elements;var b=a[0];var c=a[4];var d=a[8],e=a[1],f=a[5],g=a[9];var h=a[2];var k=a[6];var m=a[10];if(.01>Math.abs(c-e)&&.01>Math.abs(d-h)&&.01>Math.abs(g-k)){if(.1>Math.abs(c+e)&&.1>Math.abs(d+h)&&.1>Math.abs(g+k)&&.1>Math.abs(b+f+m-3))return this.set(1,0,0,0),this;a=Math.PI;
17705 b=(b+1)/2;f=(f+1)/2;m=(m+1)/2;c=(c+e)/4;d=(d+h)/4;g=(g+k)/4;b>f&&b>m?.01>b?(k=0,c=h=.707106781):(k=Math.sqrt(b),h=c/k,c=d/k):f>m?.01>f?(k=.707106781,h=0,c=.707106781):(h=Math.sqrt(f),k=c/h,c=g/h):.01>m?(h=k=.707106781,c=0):(c=Math.sqrt(m),k=d/c,h=g/c);this.set(k,h,c,a);return this}a=Math.sqrt((k-g)*(k-g)+(d-h)*(d-h)+(e-c)*(e-c));.001>Math.abs(a)&&(a=1);this.x=(k-g)/a;this.y=(d-h)/a;this.z=(e-c)/a;this.w=Math.acos((b+f+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,
17706 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));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 V,b=new V);a.set(c,
17707 c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},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);this.y=Math.round(this.y);
17708 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*
17709 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)},manhattanLength: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()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},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,
17710 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},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");
17711 this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});fb.prototype=Object.assign(Object.create(ya.prototype),{constructor:fb,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();
17712 this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Gb.prototype=Object.create(fb.prototype);Gb.prototype.constructor=Gb;Gb.prototype.isWebGLRenderTargetCube=!0;gb.prototype=Object.create(T.prototype);gb.prototype.constructor=gb;gb.prototype.isDataTexture=!0;Object.assign(Sa.prototype,{isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=
17713 Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;h<k;h+=3){var m=a[h],q=a[h+1],l=a[h+2];m<b&&(b=m);q<c&&(c=q);l<d&&(d=l);m>e&&(e=m);q>f&&(f=q);l>g&&(g=l)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var m=a.getX(h),l=a.getY(h),n=a.getZ(h);m<b&&(b=m);l<c&&(c=l);n<d&&(d=n);m>e&&(e=m);l>f&&(f=l);n>g&&(g=n)}this.min.set(b,c,d);
17714 this.max.set(e,f,g);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new p;return function(b,c){c=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(c);this.max.copy(b).add(c);return this}}(),setFromObject:function(a){this.makeEmpty();return this.expandByObject(a)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},
17715 makeEmpty:function(){this.min.x=this.min.y=this.min.z=Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(a){void 0===a&&(console.warn("THREE.Box3: .getCenter() target is now required"),a=new p);return this.isEmpty()?a.set(0,0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){void 0===a&&(console.warn("THREE.Box3: .getSize() target is now required"),
17716 a=new p);return this.isEmpty()?a.set(0,0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},expandByObject:function(){function a(a){var f=a.geometry;if(void 0!==f)if(f.isGeometry)for(f=f.vertices,c=0,d=f.length;c<d;c++)e.copy(f[c]),e.applyMatrix4(a.matrixWorld),b.expandByPoint(e);else if(f.isBufferGeometry&&
17717 (f=f.attributes.position,void 0!==f))for(c=0,d=f.count;c<d;c++)e.fromBufferAttribute(f,c).applyMatrix4(a.matrixWorld),b.expandByPoint(e)}var b,c,d,e=new p;return function(c){b=this;c.updateMatrixWorld(!0);c.traverse(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&&
17718 a.max.z<=this.max.z},getParameter:function(a,b){void 0===b&&(console.warn("THREE.Box3: .getParameter() target is now required"),b=new p);return b.set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y||a.max.z<this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a=new p;return function(b){this.clampPoint(b.center,
17719 a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){if(0<a.normal.x){var b=a.normal.x*this.min.x;var c=a.normal.x*this.max.x}else b=a.normal.x*this.max.x,c=a.normal.x*this.min.x;0<a.normal.y?(b+=a.normal.y*this.min.y,c+=a.normal.y*this.max.y):(b+=a.normal.y*this.max.y,c+=a.normal.y*this.min.y);0<a.normal.z?(b+=a.normal.z*this.min.z,c+=a.normal.z*this.max.z):(b+=a.normal.z*this.max.z,c+=a.normal.z*this.min.z);return b<=a.constant&&c>=a.constant},intersectsTriangle:function(){function a(a){var e;
17720 var f=0;for(e=a.length-3;f<=e;f+=3){h.fromArray(a,f);var g=m.x*Math.abs(h.x)+m.y*Math.abs(h.y)+m.z*Math.abs(h.z),k=b.dot(h),l=c.dot(h),q=d.dot(h);if(Math.max(-Math.max(k,l,q),Math.min(k,l,q))>g)return!1}return!0}var b=new p,c=new p,d=new p,e=new p,f=new p,g=new p,h=new p,k=new p,m=new p,l=new p;return function(h){if(this.isEmpty())return!1;this.getCenter(k);m.subVectors(this.max,k);b.subVectors(h.a,k);c.subVectors(h.b,k);d.subVectors(h.c,k);e.subVectors(c,b);f.subVectors(d,c);g.subVectors(b,d);h=
17721 [0,-e.z,e.y,0,-f.z,f.y,0,-g.z,g.y,e.z,0,-e.x,f.z,0,-f.x,g.z,0,-g.x,-e.y,e.x,0,-f.y,f.x,0,-g.y,g.x,0];if(!a(h))return!1;h=[1,0,0,0,1,0,0,0,1];if(!a(h))return!1;l.crossVectors(e,f);h=[l.x,l.y,l.z];return a(h)}}(),clampPoint:function(a,b){void 0===b&&(console.warn("THREE.Box3: .clampPoint() target is now required"),b=new p);return b.copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new p;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=
17722 new p;return function(b){void 0===b&&(console.warn("THREE.Box3: .getBoundingSphere() target is now required"),b=new Da);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(a){if(this.isEmpty())return this;a=a.elements;var b=a[0]*this.min.x,c=a[1]*this.min.x,d=a[2]*this.min.x,e=
17723 a[0]*this.max.x,f=a[1]*this.max.x,g=a[2]*this.max.x,h=a[4]*this.min.y,k=a[5]*this.min.y,m=a[6]*this.min.y,l=a[4]*this.max.y,n=a[5]*this.max.y,t=a[6]*this.max.y,u=a[8]*this.min.z,r=a[9]*this.min.z,p=a[10]*this.min.z,y=a[8]*this.max.z,x=a[9]*this.max.z,w=a[10]*this.max.z;this.min.x=Math.min(b,e)+Math.min(h,l)+Math.min(u,y)+a[12];this.min.y=Math.min(c,f)+Math.min(k,n)+Math.min(r,x)+a[13];this.min.z=Math.min(d,g)+Math.min(m,t)+Math.min(p,w)+a[14];this.max.x=Math.max(b,e)+Math.max(h,l)+Math.max(u,y)+a[12];
17724 this.max.y=Math.max(c,f)+Math.max(k,n)+Math.max(r,x)+a[13];this.max.z=Math.max(d,g)+Math.max(m,t)+Math.max(p,w)+a[14];return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Da.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new Sa;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=
17725 c=0,f=b.length;e<f;e++)c=Math.max(c,d.distanceToSquared(b[e]));this.radius=Math.sqrt(c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.center.copy(a.center);this.radius=a.radius;return this},empty:function(){return 0>=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;
17726 return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(a.distanceToPoint(this.center))<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a);void 0===b&&(console.warn("THREE.Sphere: .clampPoint() target is now required"),b=new p);b.copy(a);c>this.radius*this.radius&&(b.sub(this.center).normalize(),b.multiplyScalar(this.radius).add(this.center));return b},getBoundingBox:function(a){void 0===
17727 a&&(console.warn("THREE.Sphere: .getBoundingBox() target is now required"),a=new Sa);a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Ma.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,
17728 b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=new p,b=new p;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=
17729 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){void 0===b&&(console.warn("THREE.Plane: .projectPoint() target is now required"),b=new p);return b.copy(this.normal).multiplyScalar(-this.distanceToPoint(a)).add(a)},intersectLine:function(){var a=
17730 new p;return function(b,c){void 0===c&&(console.warn("THREE.Plane: .intersectLine() target is now required"),c=new p);var d=b.delta(a),e=this.normal.dot(d);if(0===e){if(0===this.distanceToPoint(b.start))return c.copy(b.start)}else if(e=-(b.start.dot(this.normal)+this.constant)/e,!(0>e||1<e))return c.copy(d).multiplyScalar(e).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)},
17731 intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){void 0===a&&(console.warn("THREE.Plane: .coplanarPoint() target is now required"),a=new p);return a.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new p,b=new ra;return function(c,d){d=d||b.getNormalMatrix(c);c=this.coplanarPoint(a).applyMatrix4(c);d=this.normal.applyMatrix3(d).normalize();this.constant=-c.dot(d);return this}}(),translate:function(a){this.constant-=a.dot(this.normal);
17732 return this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===this.constant}});Object.assign(md.prototype,{set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],
17733 h=c[5],k=c[6],m=c[7],l=c[8],n=c[9],t=c[10],p=c[11],r=c[12],v=c[13],y=c[14];c=c[15];b[0].setComponents(f-a,m-g,p-l,c-r).normalize();b[1].setComponents(f+a,m+g,p+l,c+r).normalize();b[2].setComponents(f+d,m+h,p+n,c+v).normalize();b[3].setComponents(f-d,m-h,p-n,c-v).normalize();b[4].setComponents(f-e,m-k,p-t,c-y).normalize();b[5].setComponents(f+e,m+k,p+t,c+y).normalize();return this},intersectsObject:function(){var a=new Da;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();
17734 a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Da;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)<a)return!1;return!0},intersectsBox:function(){var a=new p;return function(b){for(var c=this.planes,d=0;6>d;d++){var e=c[d];
17735 a.x=0<e.normal.x?b.max.x:b.min.x;a.y=0<e.normal.y?b.max.y:b.min.y;a.z=0<e.normal.z?b.max.z:b.min.z;if(0>e.distanceToPoint(a))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}});var S={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",
17736 aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",
17737 begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE  = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS  = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n",
17738 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 = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\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\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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",
17739 clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif\n",
17740 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",
17741 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 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\n",
17742 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( sampler2D envMap, 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",
17743 defaultnormal_vertex:"vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\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 += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n",
17744 emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n",encodings_fragment:"  gl_FragColor = linearToOutputTexel( gl_FragColor );\n",encodings_pars_fragment:"\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M      = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM            = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D      = max( maxRange / maxRGB, 1.0 );\n\tD            = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value )  {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n",
17745 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, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = 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",
17746 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\tuniform int maxMipLevel;\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",
17747 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_physical_pars_fragment:"#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( envMap, 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( envMap, queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent ));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 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",
17748 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",
17749 fog_vertex:"\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n  varying float fogDepth;\n#endif\n",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n",
17750 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",
17751 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\t#pragma unroll_loop\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\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\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\t#pragma unroll_loop\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",
17752 lights_pars_begin:"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\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\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 ltc_1;\tuniform sampler2D ltc_2;\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",
17753 lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\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_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n",
17754 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",
17755 lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3(    0, 1,    0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material )   GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material )   GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n",
17756 lights_fragment_begin:"\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\t#pragma unroll_loop\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 ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 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\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\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#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearCoatRadiance = vec3( 0.0 );\n#endif\n",
17757 lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\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 defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), maxMipLevel );\n\t#ifndef STANDARD\n\t\tclearCoatRadiance += getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), maxMipLevel );\n\t#endif\n#endif\n",
17758 lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",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",
17759 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\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n",map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",
17760 map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n",
17761 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",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",
17762 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",
17763 normal_fragment_begin:"#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 );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n",normal_fragment_maps:"#ifdef USE_NORMALMAP\n\t#ifdef OBJECTSPACE_NORMALMAP\n\t\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t#ifdef FLIP_SIDED\n\t\t\tnormal = - normal;\n\t\t#endif\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tnormal = normalize( normalMatrix * normal );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n",
17764 normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\t#ifdef OBJECTSPACE_NORMALMAP\n\t\tuniform mat3 normalMatrix;\n\t#else\n\t\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\t\tvec2 st0 = dFdx( vUv.st );\n\t\t\tvec2 st1 = dFdy( vUv.st );\n\t\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\t\tvec3 N = normalize( surf_norm );\n\t\t\tmat3 tsn = mat3( S, T, N );\n\t\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t\tmapN.xy *= normalScale;\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\treturn normalize( tsn * mapN );\n\t\t}\n\t#endif\n#endif\n",
17765 packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n",
17766 premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n",project_vertex:"vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n",dithering_fragment:"#if defined( DITHERING )\n  gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n",dithering_pars_fragment:"#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n",
17767 roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\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\tshadow = (\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\tshadow = (\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\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\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, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\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",
17768 shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n",
17769 shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n",
17770 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\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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 ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
17771 skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n",
17772 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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\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",
17773 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:"#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n",
17774 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 mat3 uvTransform;\n#endif\n",
17775 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 = ( uvTransform * vec3( uv, 1 ) ).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",
17776 uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n",
17777 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\tgl_Position.z = gl_Position.w;\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( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n",
17778 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#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n",
17779 distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n",
17780 distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n",
17781 equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 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",
17782 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",
17783 linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n",
17784 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 <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",
17785 meshbasic_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n",
17786 meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\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 <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
17787 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_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
17788 meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\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_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
17789 meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
17790 meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\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 <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
17791 meshphysical_vert:"#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <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 <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
17792 normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_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_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
17793 normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_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 <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_NORMALMAP ) )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n",
17794 points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_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\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",
17795 points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_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 <morphtarget_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 <fog_vertex>\n}\n",
17796 shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}\n",shadow_vert:"#include <fog_pars_vertex>\n#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\t#include <fog_vertex>\n}\n",
17797 sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_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\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
17798 sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tvec4 mvPosition;\n\tmvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n"},
17799 Aa={merge:function(a){for(var b={},c=0;c<a.length;c++){var d=this.clone(a[c]),e;for(e in d)b[e]=d[e]}return b},clone:function(a){var b={},c;for(c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},Tg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,
17800 blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,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,
17801 darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,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,
17802 lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,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,
17803 mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,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,
17804 rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,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};Object.assign(G.prototype,
17805 {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,
17806 c,d){b=H.euclideanModulo(b,1);c=H.clamp(c,0,1);d=H.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=
17807 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)){d=parseFloat(c[1])/
17808 360;var 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=Tg[a],
17809 void 0!==c?this.setHex(c):console.warn("THREE.Color: Unknown color "+a));return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a,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);b=0<b?1/b:1;this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},convertGammaToLinear:function(a){this.copyGammaToLinear(this,
17810 a);return this},convertLinearToGamma:function(a){this.copyLinearToGamma(this,a);return this},copySRGBToLinear:function(){function a(a){return.04045>a?.0773993808*a:Math.pow(.9478672986*a+.0521327014,2.4)}return function(b){this.r=a(b.r);this.g=a(b.g);this.b=a(b.b);return this}}(),copyLinearToSRGB:function(){function a(a){return.0031308>a?12.92*a:1.055*Math.pow(a,.41666)-.055}return function(b){this.r=a(b.r);this.g=a(b.g);this.b=a(b.b);return this}}(),convertSRGBToLinear:function(){this.copySRGBToLinear(this);
17811 return this},convertLinearToSRGB:function(){this.copyLinearToSRGB(this);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){void 0===a&&(console.warn("THREE.Color: .getHSL() target is now required"),a={h:0,s:0,l:0});var b=this.r,c=this.g,d=this.b,e=Math.max(b,c,d),f=Math.min(b,c,d),g,h=(f+e)/2;if(f===e)f=g=0;else{var k=e-f;f=.5>=h?k/(e+f):k/(2-e-f);switch(e){case b:g=(c-
17812 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(){var a={};return function(b,c,d){this.getHSL(a);a.h+=b;a.s+=c;a.l+=d;this.setHSL(a.h,a.s,a.l);return this}}(),add:function(a){this.r+=a.r;this.g+=a.g;this.b+=a.b;return this},addColors:function(a,b){this.r=a.r+b.r;this.g=a.g+b.g;this.b=a.b+b.b;return this},addScalar:function(a){this.r+=a;this.g+=
17813 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=0);this.r=
17814 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 K={common:{diffuse:{value:new G(15658734)},opacity:{value:1},map:{value:null},uvTransform:{value:new ra},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98},maxMipLevel:{value:0}},aomap:{aoMap:{value:null},
17815 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 z(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:2.5E-4},fogNear:{value:1},
17816 fogFar:{value:2E3},fogColor:{value:new G(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},
17817 pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new G(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},uvTransform:{value:new ra}},
17818 sprite:{diffuse:{value:new G(15658734)},opacity:{value:1},center:{value:new z(.5,.5)},rotation:{value:0},map:{value:null},uvTransform:{value:new ra}}},nb={basic:{uniforms:Aa.merge([K.common,K.specularmap,K.envmap,K.aomap,K.lightmap,K.fog]),vertexShader:S.meshbasic_vert,fragmentShader:S.meshbasic_frag},lambert:{uniforms:Aa.merge([K.common,K.specularmap,K.envmap,K.aomap,K.lightmap,K.emissivemap,K.fog,K.lights,{emissive:{value:new G(0)}}]),vertexShader:S.meshlambert_vert,fragmentShader:S.meshlambert_frag},
17819 phong:{uniforms:Aa.merge([K.common,K.specularmap,K.envmap,K.aomap,K.lightmap,K.emissivemap,K.bumpmap,K.normalmap,K.displacementmap,K.gradientmap,K.fog,K.lights,{emissive:{value:new G(0)},specular:{value:new G(1118481)},shininess:{value:30}}]),vertexShader:S.meshphong_vert,fragmentShader:S.meshphong_frag},standard:{uniforms:Aa.merge([K.common,K.envmap,K.aomap,K.lightmap,K.emissivemap,K.bumpmap,K.normalmap,K.displacementmap,K.roughnessmap,K.metalnessmap,K.fog,K.lights,{emissive:{value:new G(0)},roughness:{value:.5},
17820 metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:S.meshphysical_vert,fragmentShader:S.meshphysical_frag},points:{uniforms:Aa.merge([K.points,K.fog]),vertexShader:S.points_vert,fragmentShader:S.points_frag},dashed:{uniforms:Aa.merge([K.common,K.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:S.linedashed_vert,fragmentShader:S.linedashed_frag},depth:{uniforms:Aa.merge([K.common,K.displacementmap]),vertexShader:S.depth_vert,fragmentShader:S.depth_frag},normal:{uniforms:Aa.merge([K.common,
17821 K.bumpmap,K.normalmap,K.displacementmap,{opacity:{value:1}}]),vertexShader:S.normal_vert,fragmentShader:S.normal_frag},sprite:{uniforms:Aa.merge([K.sprite,K.fog]),vertexShader:S.sprite_vert,fragmentShader:S.sprite_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:S.cube_vert,fragmentShader:S.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:S.equirect_vert,fragmentShader:S.equirect_frag},distanceRGBA:{uniforms:Aa.merge([K.common,K.displacementmap,
17822 {referencePosition:{value:new p},nearDistance:{value:1},farDistance:{value:1E3}}]),vertexShader:S.distanceRGBA_vert,fragmentShader:S.distanceRGBA_frag},shadow:{uniforms:Aa.merge([K.lights,K.fog,{color:{value:new G(0)},opacity:{value:1}}]),vertexShader:S.shadow_vert,fragmentShader:S.shadow_frag}};nb.physical={uniforms:Aa.merge([nb.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:S.meshphysical_vert,fragmentShader:S.meshphysical_frag};hb.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");
17823 hb.DefaultOrder="XYZ";Object.defineProperties(hb.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a;this.onChangeCallback()}}});Object.assign(hb.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z=
17824 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=H.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],l=e[2],n=e[6];e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-m,e),this._z=
17825 Math.atan2(-f,a)):(this._x=Math.atan2(n,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-l,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(n,-1,1)),.99999>Math.abs(n)?(this._y=Math.atan2(-l,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)?(this._x=Math.atan2(n,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===
17826 b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-l,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(n,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new I;return function(b,c,d){a.makeRotationFromQuaternion(b);
17827 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 fa;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];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);
17828 void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new p(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Rd.prototype,{set:function(a){this.mask=1<<a|0},enable:function(a){this.mask=this.mask|1<<a|0},toggle:function(a){this.mask^=1<<a|0},disable:function(a){this.mask&=~(1<<a|0)},test:function(a){return 0!==(this.mask&
17829 a.mask)}});var Gf=0;D.DefaultUp=new p(0,1,0);D.DefaultMatrixAutoUpdate=!0;D.prototype=Object.assign(Object.create(ya.prototype),{constructor:D,isObject3D:!0,onBeforeRender:function(){},onAfterRender:function(){},applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},applyQuaternion:function(a){this.quaternion.premultiply(a);return this},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,
17830 !0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new fa;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateOnWorldAxis:function(){var a=new fa;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.premultiply(a);return this}}(),rotateX:function(){var a=new p(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=
17831 new p(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new p(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new p;return function(b,c){a.copy(b).applyQuaternion(this.quaternion);this.position.add(a.multiplyScalar(c));return this}}(),translateX:function(){var a=new p(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new p(0,1,0);return function(b){return this.translateOnAxis(a,
17832 b)}}(),translateZ:function(){var a=new p(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=new I;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new I,b=new p;return function(c,d,e){c.isVector3?b.copy(c):b.set(c,d,e);this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up);this.quaternion.setFromRotationMatrix(a)}}(),
17833 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"}),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]);
17834 return this}b=this.children.indexOf(a);-1!==b&&(a.parent=null,a.dispatchEvent({type:"removed"}),this.children.splice(b,1));return this},getObjectById:function(a){return this.getObjectByProperty("id",a)},getObjectByName:function(a){return this.getObjectByProperty("name",a)},getObjectByProperty:function(a,b){if(this[a]===b)return this;for(var c=0,d=this.children.length;c<d;c++){var e=this.children[c].getObjectByProperty(a,b);if(void 0!==e)return e}},getWorldPosition:function(a){void 0===a&&(console.warn("THREE.Object3D: .getWorldPosition() target is now required"),
17835 a=new p);this.updateMatrixWorld(!0);return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new p,b=new p;return function(c){void 0===c&&(console.warn("THREE.Object3D: .getWorldQuaternion() target is now required"),c=new fa);this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldScale:function(){var a=new p,b=new fa;return function(c){void 0===c&&(console.warn("THREE.Object3D: .getWorldScale() target is now required"),c=new p);this.updateMatrixWorld(!0);
17836 this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new fa;return function(b){void 0===b&&(console.warn("THREE.Object3D: .getWorldDirection() target is now required"),b=new p);this.getWorldQuaternion(a);return b.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverseVisible(a)}},
17837 traverseAncestors:function(a){var b=this.parent;null!==b&&(a(b),b.traverseAncestors(a))},updateMatrix:function(){this.matrix.compose(this.position,this.quaternion,this.scale);this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate&&this.updateMatrix();if(this.matrixWorldNeedsUpdate||a)null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0;for(var b=this.children,c=
17838 0,d=b.length;c<d;c++)b[c].updateMatrixWorld(a)},toJSON:function(a){function b(b,c){void 0===b[c.uuid]&&(b[c.uuid]=c.toJSON(a));return c.uuid}function c(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var d=void 0===a||"string"===typeof a,e={};d&&(a={geometries:{},materials:{},textures:{},images:{},shapes:{}},e.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"});var f={};f.uuid=this.uuid;f.type=this.type;""!==this.name&&(f.name=this.name);!0===this.castShadow&&
17839 (f.castShadow=!0);!0===this.receiveShadow&&(f.receiveShadow=!0);!1===this.visible&&(f.visible=!1);!1===this.frustumCulled&&(f.frustumCulled=!1);0!==this.renderOrder&&(f.renderOrder=this.renderOrder);"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData);f.layers=this.layers.mask;f.matrix=this.matrix.toArray();!1===this.matrixAutoUpdate&&(f.matrixAutoUpdate=!1);if(this.isMesh||this.isLine||this.isPoints){f.geometry=b(a.geometries,this.geometry);var g=this.geometry.parameters;if(void 0!==
17840 g&&void 0!==g.shapes)if(g=g.shapes,Array.isArray(g))for(var h=0,k=g.length;h<k;h++)b(a.shapes,g[h]);else b(a.shapes,g)}if(void 0!==this.material)if(Array.isArray(this.material)){g=[];h=0;for(k=this.material.length;h<k;h++)g.push(b(a.materials,this.material[h]));f.material=g}else f.material=b(a.materials,this.material);if(0<this.children.length)for(f.children=[],h=0;h<this.children.length;h++)f.children.push(this.children[h].toJSON(a).object);if(d){d=c(a.geometries);h=c(a.materials);k=c(a.textures);
17841 var m=c(a.images);g=c(a.shapes);0<d.length&&(e.geometries=d);0<h.length&&(e.materials=h);0<k.length&&(e.textures=k);0<m.length&&(e.images=m);0<g.length&&(e.shapes=g)}e.object=f;return e},clone:function(a){return(new this.constructor).copy(this,a)},copy:function(a,b){void 0===b&&(b=!0);this.name=a.name;this.up.copy(a.up);this.position.copy(a.position);this.quaternion.copy(a.quaternion);this.scale.copy(a.scale);this.matrix.copy(a.matrix);this.matrixWorld.copy(a.matrixWorld);this.matrixAutoUpdate=a.matrixAutoUpdate;
17842 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(b=0;b<a.children.length;b++)this.add(a.children[b].clone());return this}});Na.prototype=Object.assign(Object.create(D.prototype),{constructor:Na,isCamera:!0,copy:function(a,b){D.prototype.copy.call(this,
17843 a,b);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);return this},getWorldDirection:function(){var a=new fa;return function(b){void 0===b&&(console.warn("THREE.Camera: .getWorldDirection() target is now required"),b=new p);this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}(),updateMatrixWorld:function(a){D.prototype.updateMatrixWorld.call(this,a);this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}});
17844 Hb.prototype=Object.assign(Object.create(Na.prototype),{constructor:Hb,isOrthographicCamera:!0,copy:function(a,b){Na.prototype.copy.call(this,a,b);this.left=a.left;this.right=a.right;this.top=a.top;this.bottom=a.bottom;this.near=a.near;this.far=a.far;this.zoom=a.zoom;this.view=null===a.view?null:Object.assign({},a.view);return this},setViewOffset:function(a,b,c,d,e,f){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1});this.view.enabled=!0;this.view.fullWidth=
17845 a;this.view.fullHeight=b;this.view.offsetX=c;this.view.offsetY=d;this.view.width=e;this.view.height=f;this.updateProjectionMatrix()},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1);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+=a;a=d+b;b=d-b;if(null!==this.view&&this.view.enabled){c=this.zoom/(this.view.width/this.view.fullWidth);
17846 b=this.zoom/(this.view.height/this.view.fullHeight);var f=(this.right-this.left)/this.view.width;d=(this.top-this.bottom)/this.view.height;e+=this.view.offsetX/c*f;c=e+this.view.width/c*f;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=D.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;
17847 a.object.far=this.far;null!==this.view&&(a.object.view=Object.assign({},this.view));return a}});Object.assign(Ta.prototype,{clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}});
17848 var Hf=0;R.prototype=Object.assign(Object.create(ya.prototype),{constructor:R,isGeometry:!0,applyMatrix:function(a){for(var b=(new ra).getNormalMatrix(a),c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<f;e++)a.vertexNormals[e].applyMatrix3(b).normalize()}null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();
17849 this.normalsNeedUpdate=this.verticesNeedUpdate=!0;return this},rotateX:function(){var a=new I;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new I;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new I;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new I;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=
17850 new I;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new D;return function(b){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()]:[],q=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new Ta(a,b,d,f,q,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([n[a].clone(),n[b].clone(),n[d].clone()]);void 0!==
17851 m&&c.faceVertexUvs[1].push([t[a].clone(),t[b].clone(),t[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,g=void 0!==e.normal?e.normal.array:void 0,h=void 0!==e.color?e.color.array:void 0,k=void 0!==e.uv?e.uv.array:void 0,m=void 0!==e.uv2?e.uv2.array:void 0;void 0!==m&&(this.faceVertexUvs[1]=[]);for(var l=[],n=[],t=[],u=e=0;e<f.length;e+=3,u+=2)c.vertices.push(new p(f[e],f[e+1],f[e+2])),void 0!==g&&l.push(new p(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new G(h[e],
17852 h[e+1],h[e+2])),void 0!==k&&n.push(new z(k[u],k[u+1])),void 0!==m&&t.push(new z(m[u],m[u+1]));var r=a.groups;if(0<r.length)for(e=0;e<r.length;e++){f=r[e];var v=f.start,y=f.count;u=v;for(v+=y;u<v;u+=3)void 0!==d?b(d[u],d[u+1],d[u+2],f.materialIndex):b(u,u+1,u+2,f.materialIndex)}else if(void 0!==d)for(e=0;e<d.length;e+=3)b(d[e],d[e+1],d[e+2]);else for(e=0;e<f.length/3;e+=3)b(e,e+1,e+2);this.computeFaceNormals();null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());null!==a.boundingSphere&&
17853 (this.boundingSphere=a.boundingSphere.clone());return this},center:function(){var a=new p;return function(){this.computeBoundingBox();this.boundingBox.getCenter(a).negate();this.translate(a.x,a.y,a.z);return this}}(),normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius;b=0===b?1:1/b;var c=new I;c.set(b,0,0,-b*a.x,0,b,0,-b*a.y,0,0,b,-b*a.z,0,0,0,1);this.applyMatrix(c);return this},computeFaceNormals:function(){for(var a=new p,b=new p,c=0,d=
17854 this.faces.length;c<d;c++){var e=this.faces[c],f=this.vertices[e.a],g=this.vertices[e.b];a.subVectors(this.vertices[e.c],g);b.subVectors(f,g);a.cross(b);a.normalize();e.normal.copy(a)}},computeVertexNormals:function(a){void 0===a&&(a=!0);var b;var c=Array(this.vertices.length);var d=0;for(b=this.vertices.length;d<b;d++)c[d]=new p;if(a){var e=new p,f=new p;a=0;for(d=this.faces.length;a<d;a++){b=this.faces[a];var g=this.vertices[b.a];var h=this.vertices[b.b];var k=this.vertices[b.c];e.subVectors(k,
17855 h);f.subVectors(g,h);e.cross(f);c[b.a].add(e);c[b.b].add(e);c[b.c].add(e)}}else for(this.computeFaceNormals(),a=0,d=this.faces.length;a<d;a++)b=this.faces[a],c[b.a].add(b.normal),c[b.b].add(b.normal),c[b.c].add(b.normal);d=0;for(b=this.vertices.length;d<b;d++)c[d].normalize();a=0;for(d=this.faces.length;a<d;a++)b=this.faces[a],g=b.vertexNormals,3===g.length?(g[0].copy(c[b.a]),g[1].copy(c[b.b]),g[2].copy(c[b.c])):(g[0]=c[b.a].clone(),g[1]=c[b.b].clone(),g[2]=c[b.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=
17856 !0)},computeFlatVertexNormals:function(){var a;this.computeFaceNormals();var b=0;for(a=this.faces.length;b<a;b++){var c=this.faces[b];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),d[1].copy(c.normal),d[2].copy(c.normal)):(d[0]=c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var a,b;var c=0;for(b=this.faces.length;c<b;c++){var d=this.faces[c];d.__originalFaceNormal?d.__originalFaceNormal.copy(d.normal):
17857 d.__originalFaceNormal=d.normal.clone();d.__originalVertexNormals||(d.__originalVertexNormals=[]);var e=0;for(a=d.vertexNormals.length;e<a;e++)d.__originalVertexNormals[e]?d.__originalVertexNormals[e].copy(d.vertexNormals[e]):d.__originalVertexNormals[e]=d.vertexNormals[e].clone()}var f=new R;f.faces=this.faces;e=0;for(a=this.morphTargets.length;e<a;e++){if(!this.morphNormals[e]){this.morphNormals[e]={};this.morphNormals[e].faceNormals=[];this.morphNormals[e].vertexNormals=[];d=this.morphNormals[e].faceNormals;
17858 var g=this.morphNormals[e].vertexNormals;c=0;for(b=this.faces.length;c<b;c++){var h=new p;var k={a:new p,b:new p,c:new p};d.push(h);g.push(k)}}g=this.morphNormals[e];f.vertices=this.morphTargets[e].vertices;f.computeFaceNormals();f.computeVertexNormals();c=0;for(b=this.faces.length;c<b;c++)d=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(d.normal),k.a.copy(d.vertexNormals[0]),k.b.copy(d.vertexNormals[1]),k.c.copy(d.vertexNormals[2])}c=0;for(b=this.faces.length;c<b;c++)d=this.faces[c],
17859 d.normal=d.__originalFaceNormal,d.vertexNormals=d.__originalVertexNormals},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new Sa);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Da);this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(a&&a.isGeometry){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],
17860 n=this.colors,t=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new ra).getNormalMatrix(b));a=0;for(var p=g.length;a<p;a++){var r=g[a].clone();void 0!==b&&r.applyMatrix4(b);f.push(r)}a=0;for(p=t.length;a<p;a++)n.push(t[a].clone());a=0;for(p=k.length;a<p;a++){g=k[a];var v=g.vertexNormals;t=g.vertexColors;n=new Ta(g.a+e,g.b+e,g.c+e);n.normal.copy(g.normal);void 0!==d&&n.normal.applyMatrix3(d).normalize();b=0;for(f=v.length;b<f;b++)r=v[b].clone(),void 0!==d&&r.applyMatrix3(d).normalize(),n.vertexNormals.push(r);
17861 n.color.copy(g.color);b=0;for(f=t.length;b<f;b++)r=t[b],n.vertexColors.push(r.clone());n.materialIndex=g.materialIndex+c;h.push(n)}a=0;for(p=l.length;a<p;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)}}else console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a)},mergeMesh:function(a){a&&a.isMesh?(a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix)):console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",
17862 a)},mergeVertices:function(){var a={},b=[],c=[],d=Math.pow(10,4),e;var f=0;for(e=this.vertices.length;f<e;f++){var g=this.vertices[f];g=Math.round(g.x*d)+"_"+Math.round(g.y*d)+"_"+Math.round(g.z*d);void 0===a[g]?(a[g]=f,b.push(this.vertices[f]),c[f]=b.length-1):c[f]=c[a[g]]}a=[];f=0;for(e=this.faces.length;f<e;f++)for(d=this.faces[f],d.a=c[d.a],d.b=c[d.b],d.c=c[d.c],d=[d.a,d.b,d.c],g=0;3>g;g++)if(d[g]===d[(g+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(d=a[f],this.faces.splice(d,1),c=0,e=
17863 this.faceVertexUvs.length;c<e;c++)this.faceVertexUvs[c].splice(d,1);f=this.vertices.length-b.length;this.vertices=b;return f},setFromPoints:function(a){this.vertices=[];for(var b=0,c=a.length;b<c;b++){var d=a[b];this.vertices.push(new p(d.x,d.y,d.z||0))}return this},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&&
17864 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()+a.z.toString();if(void 0!==m[b])return m[b];m[b]=k.length/3;k.push(a.x,a.y,a.z);return m[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==n[b])return n[b];n[b]=l.length;l.push(a.getHex());return n[b]}function d(a){var b=
17865 a.x.toString()+a.y.toString();if(void 0!==p[b])return p[b];p[b]=t.length/2;t.push(a.x,a.y);return p[b]}var e={metadata:{version:4.5,type:"Geometry",generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==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)}h=[];var k=[],m={},l=[],n={},t=[],p={};for(g=0;g<this.faces.length;g++){var r=
17866 this.faces[g],v=void 0!==this.faceVertexUvs[0][g],y=0<r.normal.length(),x=0<r.vertexNormals.length,w=1!==r.color.r||1!==r.color.g||1!==r.color.b,B=0<r.vertexColors.length,E=0;E=a(E,0,0);E=a(E,1,!0);E=a(E,2,!1);E=a(E,3,v);E=a(E,4,y);E=a(E,5,x);E=a(E,6,w);E=a(E,7,B);h.push(E);h.push(r.a,r.b,r.c);h.push(r.materialIndex);v&&(v=this.faceVertexUvs[0][g],h.push(d(v[0]),d(v[1]),d(v[2])));y&&h.push(b(r.normal));x&&(y=r.vertexNormals,h.push(b(y[0]),b(y[1]),b(y[2])));w&&h.push(c(r.color));B&&(r=r.vertexColors,
17867 h.push(c(r[0]),c(r[1]),c(r[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<l.length&&(e.data.colors=l);0<t.length&&(e.data.uvs=[t]);e.data.faces=h;return e},clone:function(){return(new R).copy(this)},copy:function(a){var b,c,d;this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;var e=a.vertices;var f=0;for(b=e.length;f<
17868 b;f++)this.vertices.push(e[f].clone());e=a.colors;f=0;for(b=e.length;f<b;f++)this.colors.push(e[f].clone());e=a.faces;f=0;for(b=e.length;f<b;f++)this.faces.push(e[f].clone());f=0;for(b=a.faceVertexUvs.length;f<b;f++){var g=a.faceVertexUvs[f];void 0===this.faceVertexUvs[f]&&(this.faceVertexUvs[f]=[]);e=0;for(c=g.length;e<c;e++){var h=g[e],k=[];var m=0;for(d=h.length;m<d;m++)k.push(h[m].clone());this.faceVertexUvs[f].push(k)}}m=a.morphTargets;f=0;for(b=m.length;f<b;f++){d={};d.name=m[f].name;if(void 0!==
17869 m[f].vertices)for(d.vertices=[],e=0,c=m[f].vertices.length;e<c;e++)d.vertices.push(m[f].vertices[e].clone());if(void 0!==m[f].normals)for(d.normals=[],e=0,c=m[f].normals.length;e<c;e++)d.normals.push(m[f].normals[e].clone());this.morphTargets.push(d)}m=a.morphNormals;f=0;for(b=m.length;f<b;f++){d={};if(void 0!==m[f].vertexNormals)for(d.vertexNormals=[],e=0,c=m[f].vertexNormals.length;e<c;e++)g=m[f].vertexNormals[e],h={},h.a=g.a.clone(),h.b=g.b.clone(),h.c=g.c.clone(),d.vertexNormals.push(h);if(void 0!==
17870 m[f].faceNormals)for(d.faceNormals=[],e=0,c=m[f].faceNormals.length;e<c;e++)d.faceNormals.push(m[f].faceNormals[e].clone());this.morphNormals.push(d)}e=a.skinWeights;f=0;for(b=e.length;f<b;f++)this.skinWeights.push(e[f].clone());e=a.skinIndices;f=0;for(b=e.length;f<b;f++)this.skinIndices.push(e[f].clone());e=a.lineDistances;f=0;for(b=e.length;f<b;f++)this.lineDistances.push(e[f]);f=a.boundingBox;null!==f&&(this.boundingBox=f.clone());f=a.boundingSphere;null!==f&&(this.boundingSphere=f.clone());this.elementsNeedUpdate=
17871 a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Object.defineProperty(Q.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(Q.prototype,{isBufferAttribute:!0,onUploadCallback:function(){},
17872 setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.itemSize:0;this.array=a;return this},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.name=a.name;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<
17873 e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new G);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}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",
17874 d),f=new z);b[c++]=f.x;b[c++]=f.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),f=new p);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z}return this},copyVector4sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",d),f=new V);b[c++]=f.x;b[c++]=f.y;
17875 b[c++]=f.z;b[c++]=f.w}return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*this.itemSize]},setX:function(a,b){this.array[a*this.itemSize]=b;return this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){this.array[a*this.itemSize+1]=b;return this},getZ:function(a){return this.array[a*this.itemSize+2]},setZ:function(a,b){this.array[a*this.itemSize+2]=b;return this},getW:function(a){return this.array[a*this.itemSize+
17876 3]},setW:function(a,b){this.array[a*this.itemSize+3]=b;return this},setXY:function(a,b,c){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;this.array[a+3]=e;return this},onUpload:function(a){this.onUploadCallback=a;return this},clone:function(){return(new this.constructor(this.array,
17877 this.itemSize)).copy(this)}});oc.prototype=Object.create(Q.prototype);oc.prototype.constructor=oc;pc.prototype=Object.create(Q.prototype);pc.prototype.constructor=pc;qc.prototype=Object.create(Q.prototype);qc.prototype.constructor=qc;rc.prototype=Object.create(Q.prototype);rc.prototype.constructor=rc;ib.prototype=Object.create(Q.prototype);ib.prototype.constructor=ib;sc.prototype=Object.create(Q.prototype);sc.prototype.constructor=sc;jb.prototype=Object.create(Q.prototype);jb.prototype.constructor=
17878 jb;A.prototype=Object.create(Q.prototype);A.prototype.constructor=A;tc.prototype=Object.create(Q.prototype);tc.prototype.constructor=tc;Object.assign(Ee.prototype,{computeGroups:function(a){var b=[],c=void 0;a=a.faces;for(var d=0;d<a.length;d++){var e=a[d];if(e.materialIndex!==c){c=e.materialIndex;void 0!==f&&(f.count=3*d-f.start,b.push(f));var f={start:3*d,materialIndex:c}}}void 0!==f&&(f.count=3*d-f.start,b.push(f));this.groups=b},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,
17879 e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length;if(0<h){var k=[];for(var m=0;m<h;m++)k[m]=[];this.morphTargets.position=k}var l=a.morphNormals,n=l.length;if(0<n){var t=[];for(m=0;m<n;m++)t[m]=[];this.morphTargets.normal=t}var p=a.skinIndices,r=a.skinWeights,v=p.length===c.length,y=r.length===c.length;0<c.length&&0===b.length&&console.error("THREE.DirectGeometry: Faceless geometries are not supported.");for(m=0;m<b.length;m++){var x=b[m];this.vertices.push(c[x.a],c[x.b],c[x.c]);
17880 var w=x.vertexNormals;3===w.length?this.normals.push(w[0],w[1],w[2]):(w=x.normal,this.normals.push(w,w,w));w=x.vertexColors;3===w.length?this.colors.push(w[0],w[1],w[2]):(w=x.color,this.colors.push(w,w,w));!0===e&&(w=d[0][m],void 0!==w?this.uvs.push(w[0],w[1],w[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",m),this.uvs.push(new z,new z,new z)));!0===f&&(w=d[1][m],void 0!==w?this.uvs2.push(w[0],w[1],w[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",
17881 m),this.uvs2.push(new z,new z,new z)));for(w=0;w<h;w++){var B=g[w].vertices;k[w].push(B[x.a],B[x.b],B[x.c])}for(w=0;w<n;w++)B=l[w].vertexNormals[m],t[w].push(B.a,B.b,B.c);v&&this.skinIndices.push(p[x.a],p[x.b],p[x.c]);y&&this.skinWeights.push(r[x.a],r[x.b],r[x.c])}this.computeGroups(a);this.verticesNeedUpdate=a.verticesNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this}});
17882 var If=1;C.prototype=Object.assign(Object.create(ya.prototype),{constructor:C,isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){Array.isArray(a)?this.index=new (65535<Fe(a)?jb:ib)(a,1):this.index=a},addAttribute:function(a,b,c){if(!(b&&b.isBufferAttribute||b&&b.isInterleavedBufferAttribute))return console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.addAttribute(a,new Q(b,c));if("index"===a)return console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),
17883 this.setIndex(b),this;this.attributes[a]=b;return 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.applyToBufferAttribute(b),b.needsUpdate=!0);b=this.attributes.normal;
17884 void 0!==b&&((new ra).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new I;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new I;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new I;return function(b){a.makeRotationZ(b);this.applyMatrix(a);
17885 return this}}(),translate:function(){var a=new I;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new I;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new D;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){var a=new p;return function(){this.computeBoundingBox();this.boundingBox.getCenter(a).negate();this.translate(a.x,a.y,a.z);return this}}(),
17886 setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new A(3*b.vertices.length,3);var c=new A(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 A(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&
17887 (this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},setFromPoints:function(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c];b.push(e.x,e.y,e.z||0)}this.addAttribute("position",new A(b,3));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=
17888 b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=!1;b.normalsNeedUpdate=!1;b.colorsNeedUpdate=!1;b.uvsNeedUpdate=!1;b.groupsNeedUpdate=!1;b=c}!0===b.verticesNeedUpdate&&(c=this.attributes.position,void 0!==c&&(c.copyVector3sArray(b.vertices),c.needsUpdate=!0),b.verticesNeedUpdate=!1);!0===b.normalsNeedUpdate&&(c=this.attributes.normal,void 0!==c&&(c.copyVector3sArray(b.normals),c.needsUpdate=!0),b.normalsNeedUpdate=
17889 !1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),c.needsUpdate=!0),b.colorsNeedUpdate=!1);b.uvsNeedUpdate&&(c=this.attributes.uv,void 0!==c&&(c.copyVector2sArray(b.uvs),c.needsUpdate=!0),b.uvsNeedUpdate=!1);b.lineDistancesNeedUpdate&&(c=this.attributes.lineDistance,void 0!==c&&(c.copyArray(b.lineDistances),c.needsUpdate=!0),b.lineDistancesNeedUpdate=!1);b.groupsNeedUpdate&&(b.computeGroups(a.geometry),this.groups=b.groups,b.groupsNeedUpdate=!1);return this},
17890 fromGeometry:function(a){a.__directGeometry=(new Ee).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new Q(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new Q(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new Q(b,3)).copyColorsArray(a.colors)));
17891 0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new Q(b,2)).copyVector2sArray(a.uvs)));0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new Q(b,2)).copyVector2sArray(a.uvs2)));this.groups=a.groups;for(var c in a.morphTargets){b=[];for(var d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],h=new A(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new A(4*a.skinIndices.length,4),this.addAttribute("skinIndex",
17892 c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new A(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 Sa);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):this.boundingBox.makeEmpty();
17893 (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 Sa,b=new p;return function(){null===this.boundingSphere&&(this.boundingSphere=new Da);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);a.getCenter(d);for(var e=0,
17894 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;if(void 0===b.normal)this.addAttribute("normal",
17895 new Q(new Float32Array(d.length),3));else for(var e=b.normal.array,f=0,g=e.length;f<g;f++)e[f]=0;e=b.normal.array;var h=new p,k=new p,m=new p,l=new p,n=new p;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var t=0,u=c.length;t<u;++t){f=c[t];g=f.start;var r=f.count;f=g;for(g+=r;f<g;f+=3){r=3*a[f+0];var v=3*a[f+1];var y=3*a[f+2];h.fromArray(d,r);k.fromArray(d,v);m.fromArray(d,y);l.subVectors(m,k);n.subVectors(h,k);l.cross(n);e[r]+=l.x;e[r+1]+=l.y;e[r+2]+=l.z;e[v]+=l.x;e[v+1]+=l.y;e[v+2]+=
17896 l.z;e[y]+=l.x;e[y+1]+=l.y;e[y+2]+=l.z}}}else for(f=0,g=d.length;f<g;f+=9)h.fromArray(d,f),k.fromArray(d,f+3),m.fromArray(d,f+6),l.subVectors(m,k),n.subVectors(h,k),l.cross(n),e[f]=l.x,e[f+1]=l.y,e[f+2]=l.z,e[f+3]=l.x,e[f+4]=l.y,e[f+5]=l.z,e[f+6]=l.x,e[f+7]=l.y,e[f+8]=l.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,b){if(a&&a.isBufferGeometry){void 0===b&&(b=0,console.warn("THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge."));
17897 var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d]){var e=c[d].array,f=a.attributes[d],g=f.array,h=0;for(f=f.itemSize*b;h<g.length;h++,f++)e[f]=g[h]}return this}console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",a)},normalizeNormals:function(){var a=new p;return function(){for(var b=this.attributes.normal,c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.normalize(),b.setXYZ(c,a.x,a.y,a.z)}}(),toNonIndexed:function(){if(null===
17898 this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),this;var a=new C,b=this.index.array,c=this.attributes,d;for(d in c){var e=c[d],f=e.array,g=e.itemSize,h=new f.constructor(b.length*g),k=0;e=0;for(var m=b.length;e<m;e++){var l=b[e]*g;for(var n=0;n<g;n++)h[k++]=f[l++]}a.addAttribute(d,new Q(h,g))}b=this.groups;e=0;for(m=b.length;e<m;e++)c=b[e],a.addGroup(c.start,c.count,c.materialIndex);return a},toJSON:function(){var a={metadata:{version:4.5,type:"BufferGeometry",
17899 generator:"BufferGeometry.toJSON"}};a.uuid=this.uuid;a.type=this.type;""!==this.name&&(a.name=this.name);0<Object.keys(this.userData).length&&(a.userData=this.userData);if(void 0!==this.parameters){var b=this.parameters;for(e in b)void 0!==b[e]&&(a[e]=b[e]);return a}a.data={attributes:{}};var c=this.index;null!==c&&(b=Array.prototype.slice.call(c.array),a.data.index={type:c.array.constructor.name,array:b});c=this.attributes;for(e in c){var d=c[e];b=Array.prototype.slice.call(d.array);a.data.attributes[e]=
17900 {itemSize:d.itemSize,type:d.array.constructor.name,array:b,normalized:d.normalized}}var e=this.groups;0<e.length&&(a.data.groups=JSON.parse(JSON.stringify(e)));e=this.boundingSphere;null!==e&&(a.data.boundingSphere={center:e.center.toArray(),radius:e.radius});return a},clone:function(){return(new C).copy(this)},copy:function(a){var b;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;var c=a.index;null!==c&&this.setIndex(c.clone());
17901 c=a.attributes;for(g in c)this.addAttribute(g,c[g].clone());var d=a.morphAttributes;for(g in d){var e=[],f=d[g];c=0;for(b=f.length;c<b;c++)e.push(f[c].clone());this.morphAttributes[g]=e}var g=a.groups;c=0;for(b=g.length;c<b;c++)d=g[c],this.addGroup(d.start,d.count,d.materialIndex);g=a.boundingBox;null!==g&&(this.boundingBox=g.clone());g=a.boundingSphere;null!==g&&(this.boundingSphere=g.clone());this.drawRange.start=a.drawRange.start;this.drawRange.count=a.drawRange.count;this.userData=a.userData;
17902 return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ib.prototype=Object.create(R.prototype);Ib.prototype.constructor=Ib;kb.prototype=Object.create(C.prototype);kb.prototype.constructor=kb;uc.prototype=Object.create(R.prototype);uc.prototype.constructor=uc;lb.prototype=Object.create(C.prototype);lb.prototype.constructor=lb;var Kf=0;J.prototype=Object.assign(Object.create(ya.prototype),{constructor:J,isMaterial:!0,onBeforeCompile:function(){},setValues:function(a){if(void 0!==a)for(var b in a){var c=
17903 a[b];if(void 0===c)console.warn("THREE.Material: '"+b+"' parameter is undefined.");else if("shading"===b)console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===c?!0:!1;else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=
17904 a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a||"string"===typeof a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.5,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);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());1!==
17905 this.emissiveIntensity&&(d.emissiveIntensity=this.emissiveIntensity);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=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&
17906 (d.lightMap=this.lightMap.toJSON(a).uuid);this.aoMap&&this.aoMap.isTexture&&(d.aoMap=this.aoMap.toJSON(a).uuid,d.aoMapIntensity=this.aoMapIntensity);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.normalMapType=this.normalMapType,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,
17907 d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&
17908 (d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);!0===this.flatShading&&(d.flatShading=this.flatShading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);
17909 !0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0!==this.rotation&&(d.rotation=this.rotation);1!==this.linewidth&&(d.linewidth=this.linewidth);void 0!==this.dashSize&&(d.dashSize=this.dashSize);void 0!==this.gapSize&&(d.gapSize=this.gapSize);void 0!==this.scale&&(d.scale=this.scale);!0===this.dithering&&(d.dithering=!0);0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=
17910 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);!0===this.morphTargets&&(d.morphTargets=!0);!0===this.skinning&&(d.skinning=!0);!1===this.visible&&(d.visible=!1);"{}"!==JSON.stringify(this.userData)&&(d.userData=this.userData);c&&(c=b(a.textures),
17911 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.flatShading=a.flatShading;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=
17912 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.dithering=a.dithering;this.alphaTest=a.alphaTest;this.premultipliedAlpha=a.premultipliedAlpha;this.overdraw=a.overdraw;this.visible=a.visible;this.userData=JSON.parse(JSON.stringify(a.userData));
17913 this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;var b=a.clippingPlanes,c=null;if(null!==b){var d=b.length;c=Array(d);for(var e=0;e!==d;++e)c[e]=b[e].clone()}this.clippingPlanes=c;this.shadowSide=a.shadowSide;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});da.prototype=Object.create(J.prototype);da.prototype.constructor=da;da.prototype.isMeshBasicMaterial=!0;da.prototype.copy=function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);this.map=
17914 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;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=
17915 a.morphTargets;return this};ta.prototype=Object.create(J.prototype);ta.prototype.constructor=ta;ta.prototype.isShaderMaterial=!0;ta.prototype.copy=function(a){J.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;this.uniforms=Aa.clone(a.uniforms);this.defines=Object.assign({},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;
17916 this.morphNormals=a.morphNormals;this.extensions=a.extensions;return this};ta.prototype.toJSON=function(a){a=J.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};Object.assign(mb.prototype,{set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.origin.copy(a.origin);this.direction.copy(a.direction);return this},at:function(a,
17917 b){void 0===b&&(console.warn("THREE.Ray: .at() target is now required"),b=new p);return b.copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){this.direction.copy(a).sub(this.origin).normalize();return this},recast:function(){var a=new p;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,b){void 0===b&&(console.warn("THREE.Ray: .closestPointToPoint() target is now required"),b=new p);b.subVectors(a,this.origin);a=b.dot(this.direction);
17918 return 0>a?b.copy(this.origin):b.copy(this.direction).multiplyScalar(a).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new p;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new p,b=new p,c=new p;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);
17919 b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),l=-c.dot(b),n=c.lengthSq(),t=Math.abs(1-k*k);if(0<t){d=k*l-m;e=k*m-l;var p=h*t;0<=d?e>=-p?e<=p?(h=1/t,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*l)+n):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n):e<=-p?(d=Math.max(0,-(-k*h+m)),e=0<d?-h:Math.min(Math.max(-h,-l),h),k=-d*d+e*(e+2*l)+n):e<=p?(d=0,e=Math.min(Math.max(-h,-l),h),k=
17920 e*(e+2*l)+n):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,-l),h),k=-d*d+e*(e+2*l)+n)}else e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n;f&&f.copy(this.direction).multiplyScalar(d).add(this.origin);g&&g.copy(b).multiplyScalar(e).add(a);return k}}(),intersectSphere:function(){var a=new p;return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d;b=b.radius*b.radius;if(e>b)return null;b=Math.sqrt(b-e);e=d-b;d+=b;return 0>e&&0>d?null:0>e?this.at(d,
17921 c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=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){a=this.distanceToPlane(a);return null===a?null:this.at(a,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,
17922 b){var c=1/this.direction.x;var d=1/this.direction.y;var e=1/this.direction.z,f=this.origin;if(0<=c){var g=(a.min.x-f.x)*c;c*=a.max.x-f.x}else g=(a.max.x-f.x)*c,c*=a.min.x-f.x;if(0<=d){var h=(a.min.y-f.y)*d;d*=a.max.y-f.y}else h=(a.max.y-f.y)*d,d*=a.min.y-f.y;if(g>d||h>c)return null;if(h>g||g!==g)g=h;if(d<c||c!==c)c=d;0<=e?(h=(a.min.z-f.z)*e,a=(a.max.z-f.z)*e):(h=(a.max.z-f.z)*e,a=(a.min.z-f.z)*e);if(g>a||h>c)return null;if(h>g||g!==g)g=h;if(a<c||c!==c)c=a;return 0>c?null:this.at(0<=g?g:c,b)},intersectsBox:function(){var a=
17923 new p;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new p,b=new p,c=new p,d=new p;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0<f){if(h)return null;h=1}else if(0>f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),
17924 applyMatrix4:function(a){this.origin.applyMatrix4(a);this.direction.transformDirection(a);return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});Object.assign(ja,{getNormal:function(){var a=new p;return function(b,c,d,e){void 0===e&&(console.warn("THREE.Triangle: .getNormal() target is now required"),e=new p);e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0<b?e.multiplyScalar(1/Math.sqrt(b)):e.set(0,0,0)}}(),getBarycoord:function(){var a=
17925 new p,b=new p,c=new p;return function(d,e,f,g,h){a.subVectors(g,e);b.subVectors(f,e);c.subVectors(d,e);d=a.dot(a);e=a.dot(b);f=a.dot(c);var k=b.dot(b);g=b.dot(c);var m=d*k-e*e;void 0===h&&(console.warn("THREE.Triangle: .getBarycoord() target is now required"),h=new p);if(0===m)return h.set(-2,-1,-1);m=1/m;k=(k*f-e*g)*m;d=(d*g-e*f)*m;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new p;return function(b,c,d,e){ja.getBarycoord(b,c,d,e,a);return 0<=a.x&&0<=a.y&&1>=a.x+a.y}}()});Object.assign(ja.prototype,
17926 {set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},getArea:function(){var a=new p,b=new p;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),getMidpoint:function(a){void 0===
17927 a&&(console.warn("THREE.Triangle: .getMidpoint() target is now required"),a=new p);return a.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},getNormal:function(a){return ja.getNormal(this.a,this.b,this.c,a)},getPlane:function(a){void 0===a&&(console.warn("THREE.Triangle: .getPlane() target is now required"),a=new p);return a.setFromCoplanarPoints(this.a,this.b,this.c)},getBarycoord:function(a,b){return ja.getBarycoord(a,this.a,this.b,this.c,b)},containsPoint:function(a){return ja.containsPoint(a,
17928 this.a,this.b,this.c)},intersectsBox:function(a){return a.intersectsTriangle(this)},closestPointToPoint:function(){var a=new p,b=new p,c=new p,d=new p,e=new p,f=new p;return function(g,h){void 0===h&&(console.warn("THREE.Triangle: .closestPointToPoint() target is now required"),h=new p);var k=this.a,m=this.b,l=this.c;a.subVectors(m,k);b.subVectors(l,k);d.subVectors(g,k);var n=a.dot(d),t=b.dot(d);if(0>=n&&0>=t)return h.copy(k);e.subVectors(g,m);var u=a.dot(e),r=b.dot(e);if(0<=u&&r<=u)return h.copy(m);
17929 var v=n*r-u*t;if(0>=v&&0<=n&&0>=u)return m=n/(n-u),h.copy(k).addScaledVector(a,m);f.subVectors(g,l);g=a.dot(f);var y=b.dot(f);if(0<=y&&g<=y)return h.copy(l);n=g*t-n*y;if(0>=n&&0<=t&&0>=y)return v=t/(t-y),h.copy(k).addScaledVector(b,v);t=u*y-g*r;if(0>=t&&0<=r-u&&0<=g-y)return c.subVectors(l,m),v=(r-u)/(r-u+(g-y)),h.copy(m).addScaledVector(c,v);l=1/(t+n+v);m=n*l;v*=l;return h.copy(k).addScaledVector(a,m).addScaledVector(b,v)}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});
17930 la.prototype=Object.assign(Object.create(D.prototype),{constructor:la,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){D.prototype.copy.call(this,a);this.drawMode=a.drawMode;void 0!==a.morphTargetInfluences&&(this.morphTargetInfluences=a.morphTargetInfluences.slice());void 0!==a.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},a.morphTargetDictionary));return this},updateMorphTargets:function(){var a=this.geometry;if(a.isBufferGeometry){a=a.morphAttributes;var b=
17931 Object.keys(a);if(0<b.length){var c=a[b[0]];if(void 0!==c)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=c.length;a<b;a++){var d=c[a].name||String(a);this.morphTargetInfluences.push(0);this.morphTargetDictionary[d]=a}}}else if(c=a.morphTargets,void 0!==c&&0<c.length)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=c.length;a<b;a++)d=c[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[d]=a},raycast:function(){function a(a,b,
17932 c,d,e,f,g){ja.getBarycoord(a,b,c,d,v);e.multiplyScalar(v.x);f.multiplyScalar(v.y);g.multiplyScalar(v.z);e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g,h){if(null===(1===b.side?d.intersectTriangle(g,f,e,!0,h):d.intersectTriangle(e,f,g,2!==b.side,h)))return null;x.copy(h);x.applyMatrix4(a.matrixWorld);b=c.ray.origin.distanceTo(x);return b<c.near||b>c.far?null:{distance:b,point:x.clone(),object:a}}function c(c,d,e,f,m,l,n,q,p){g.fromBufferAttribute(m,n);h.fromBufferAttribute(m,q);k.fromBufferAttribute(m,
17933 p);if(c=b(c,d,e,f,g,h,k,y))l&&(t.fromBufferAttribute(l,n),u.fromBufferAttribute(l,q),r.fromBufferAttribute(l,p),c.uv=a(y,g,h,k,t,u,r)),l=new Ta(n,q,p),ja.getNormal(g,h,k,l.normal),c.face=l;return c}var d=new I,e=new mb,f=new Da,g=new p,h=new p,k=new p,m=new p,l=new p,n=new p,t=new z,u=new z,r=new z,v=new p,y=new p,x=new p;return function(q,p){var v=this.geometry,w=this.material,x=this.matrixWorld;if(void 0!==w&&(null===v.boundingSphere&&v.computeBoundingSphere(),f.copy(v.boundingSphere),f.applyMatrix4(x),
17934 !1!==q.ray.intersectsSphere(f)&&(d.getInverse(x),e.copy(q.ray).applyMatrix4(d),null===v.boundingBox||!1!==e.intersectsBox(v.boundingBox))))if(v.isBufferGeometry){var z=v.index,B=v.attributes.position,A=v.attributes.uv,D=v.groups;v=v.drawRange;var C;if(null!==z)if(Array.isArray(w)){var H=0;for(C=D.length;H<C;H++){var G=D[H];var K=w[G.materialIndex];x=Math.max(G.start,v.start);var L=Math.min(G.start+G.count,v.start+v.count);for(G=x;G<L;G+=3){x=z.getX(G);var I=z.getX(G+1);var J=z.getX(G+2);if(x=c(this,
17935 K,q,e,B,A,x,I,J))x.faceIndex=Math.floor(G/3),p.push(x)}}}else for(x=Math.max(0,v.start),L=Math.min(z.count,v.start+v.count),H=x,C=L;H<C;H+=3){if(x=z.getX(H),I=z.getX(H+1),J=z.getX(H+2),x=c(this,w,q,e,B,A,x,I,J))x.faceIndex=Math.floor(H/3),p.push(x)}else if(void 0!==B)if(Array.isArray(w))for(H=0,C=D.length;H<C;H++)for(G=D[H],K=w[G.materialIndex],x=Math.max(G.start,v.start),L=Math.min(G.start+G.count,v.start+v.count),G=x;G<L;G+=3){if(x=G,I=G+1,J=G+2,x=c(this,K,q,e,B,A,x,I,J))x.faceIndex=Math.floor(G/
17936 3),p.push(x)}else for(x=Math.max(0,v.start),L=Math.min(B.count,v.start+v.count),H=x,C=L;H<C;H+=3)if(x=H,I=H+1,J=H+2,x=c(this,w,q,e,B,A,x,I,J))x.faceIndex=Math.floor(H/3),p.push(x)}else if(v.isGeometry)for(B=Array.isArray(w),A=v.vertices,D=v.faces,x=v.faceVertexUvs[0],0<x.length&&(z=x),G=0,L=D.length;G<L;G++)if(I=D[G],x=B?w[I.materialIndex]:w,void 0!==x){H=A[I.a];C=A[I.b];K=A[I.c];if(!0===x.morphTargets){J=v.morphTargets;var R=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var Q=
17937 0,S=J.length;Q<S;Q++){var T=R[Q];if(0!==T){var V=J[Q].vertices;g.addScaledVector(m.subVectors(V[I.a],H),T);h.addScaledVector(l.subVectors(V[I.b],C),T);k.addScaledVector(n.subVectors(V[I.c],K),T)}}g.add(H);h.add(C);k.add(K);H=g;C=h;K=k}if(x=b(this,x,q,e,H,C,K,y))z&&z[G]&&(J=z[G],t.copy(J[0]),u.copy(J[1]),r.copy(J[2]),x.uv=a(y,H,C,K,t,u,r)),x.face=I,x.faceIndex=G,p.push(x)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});Ua.prototype=Object.create(T.prototype);
17938 Ua.prototype.constructor=Ua;Ua.prototype.isCubeTexture=!0;Object.defineProperty(Ua.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Me=new T,Ne=new Ua,Ge=[],Ie=[],Le=new Float32Array(16),Ke=new Float32Array(9),Je=new Float32Array(4);Re.prototype.updateCache=function(a){var b=this.cache;a instanceof Float32Array&&b.length!==a.length&&(this.cache=new Float32Array(a.length));qa(b,a)};Se.prototype.setValue=function(a,b,c){for(var d=this.seq,e=0,f=d.length;e!==
17939 f;++e){var g=d[e];g.setValue(a,b[g.id],c)}};var Vd=/([\w\d_]+)(\])?(\[|\.)?/g;Za.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};Za.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};Za.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)}};Za.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 yg=
17940 0,Hg=0;$a.prototype=Object.create(J.prototype);$a.prototype.constructor=$a;$a.prototype.isMeshDepthMaterial=!0;$a.prototype.copy=function(a){J.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};
17941 ab.prototype=Object.create(J.prototype);ab.prototype.constructor=ab;ab.prototype.isMeshDistanceMaterial=!0;ab.prototype.copy=function(a){J.prototype.copy.call(this,a);this.referencePosition.copy(a.referencePosition);this.nearDistance=a.nearDistance;this.farDistance=a.farDistance;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;
17942 return this};Kb.prototype=Object.assign(Object.create(D.prototype),{constructor:Kb,isGroup:!0});Z.prototype=Object.assign(Object.create(Na.prototype),{constructor:Z,isPerspectiveCamera:!0,copy:function(a,b){Na.prototype.copy.call(this,a,b);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()/
17943 a;this.fov=2*H.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*H.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*H.RAD2DEG*Math.atan(Math.tan(.5*H.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;null===this.view&&(this.view={enabled:!0,fullWidth:1,
17944 fullHeight:1,offsetX:0,offsetY:0,width:1,height:1});this.view.enabled=!0;this.view.fullWidth=a;this.view.fullHeight=b;this.view.offsetX=c;this.view.offsetY=d;this.view.width=e;this.view.height=f;this.updateProjectionMatrix()},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1);this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*H.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==this.view&&this.view.enabled){var g=
17945 f.fullWidth,h=f.fullHeight;e+=f.offsetX*d/g;b-=f.offsetY*c/h;d*=f.width/g;c*=f.height/h}f=this.filmOffset;0!==f&&(e+=a*f/this.getFilmWidth());this.projectionMatrix.makePerspective(e,e+d,b,b-c,a,this.far)},toJSON:function(a){a=D.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=
17946 this.filmOffset;return a}});yc.prototype=Object.assign(Object.create(Z.prototype),{constructor:yc,isArrayCamera:!0});Lb.prototype.isFogExp2=!0;Lb.prototype.clone=function(){return new Lb(this.color,this.density)};Lb.prototype.toJSON=function(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};Mb.prototype.isFog=!0;Mb.prototype.clone=function(){return new Mb(this.color,this.near,this.far)};Mb.prototype.toJSON=function(){return{type:"Fog",color:this.color.getHex(),near:this.near,
17947 far:this.far}};qd.prototype=Object.assign(Object.create(D.prototype),{constructor:qd,copy:function(a,b){D.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},toJSON:function(a){var b=D.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));
17948 null!==this.fog&&(b.object.fog=this.fog.toJSON());return b}});Object.defineProperty(ob.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ob.prototype,{isInterleavedBuffer:!0,onUploadCallback:function(){},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;return this},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=
17949 new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(a){this.onUploadCallback=a;return this}});Object.defineProperties(zc.prototype,{count:{get:function(){return this.data.count}},
17950 array:{get:function(){return this.data.array}}});Object.assign(zc.prototype,{isInterleavedBufferAttribute:!0,setX:function(a,b){this.data.array[a*this.data.stride+this.offset]=b;return this},setY:function(a,b){this.data.array[a*this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+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+
17951 this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;return this},setXYZW:function(a,
17952 b,c,d,e){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;this.data.array[a+3]=e;return this}});cb.prototype=Object.create(J.prototype);cb.prototype.constructor=cb;cb.prototype.isSpriteMaterial=!0;cb.prototype.copy=function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};var Nb;Ac.prototype=Object.assign(Object.create(D.prototype),{constructor:Ac,isSprite:!0,raycast:function(){function a(a,
17953 b,c,d,h,k){e.subVectors(a,c).addScalar(.5).multiply(d);void 0!==h?(f.x=k*e.x-h*e.y,f.y=h*e.x+k*e.y):f.copy(e);a.copy(b);a.x+=f.x;a.y+=f.y;a.applyMatrix4(g)}var b=new p,c=new p,d=new p,e=new z,f=new z,g=new I,h=new p,k=new p,m=new p;return function(e,f){c.setFromMatrixScale(this.matrixWorld);g.getInverse(this.modelViewMatrix).premultiply(this.matrixWorld);d.setFromMatrixPosition(this.modelViewMatrix);var l=this.material.rotation;if(0!==l){var n=Math.cos(l);var q=Math.sin(l)}l=this.center;a(h.set(-.5,
17954 -.5,0),d,l,c,q,n);a(k.set(.5,-.5,0),d,l,c,q,n);a(m.set(.5,.5,0),d,l,c,q,n);var p=e.ray.intersectTriangle(h,k,m,!1,b);if(null===p&&(a(k.set(-.5,.5,0),d,l,c,q,n),p=e.ray.intersectTriangle(h,m,k,!1,b),null===p))return;q=e.ray.origin.distanceTo(b);q<e.near||q>e.far||f.push({distance:q,point:b.clone(),face:null,object:this})}}(),clone:function(){return(new this.constructor(this.material)).copy(this)},copy:function(a){D.prototype.copy.call(this,a);void 0!==a.center&&this.center.copy(a.center);return this}});
17955 Bc.prototype=Object.assign(Object.create(D.prototype),{constructor:Bc,copy:function(a){D.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-
17956 1].object},raycast:function(){var a=new p;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=b.ray.origin.distanceTo(a);this.getObjectForDistance(d).raycast(b,c)}}(),update:function(){var a=new p,b=new p;return function(c){var d=this.levels;if(1<d.length){a.setFromMatrixPosition(c.matrixWorld);b.setFromMatrixPosition(this.matrixWorld);c=a.distanceTo(b);d[0].object.visible=!0;for(var e=1,f=d.length;e<f;e++)if(c>=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;
17957 for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=D.prototype.toJSON.call(this,a);a.object.levels=[];for(var b=this.levels,c=0,d=b.length;c<d;c++){var e=b[c];a.object.levels.push({object:e.object.uuid,distance:e.distance})}return a}});Object.assign(Cc.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new I;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){var a,b;var c=0;for(b=this.bones.length;c<
17958 b;c++)(a=this.bones[c])&&a.matrixWorld.getInverse(this.boneInverses[c]);c=0;for(b=this.bones.length;c<b;c++)if(a=this.bones[c])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 I,b=new I;return function(){for(var c=this.bones,d=this.boneInverses,e=this.boneMatrices,f=this.boneTexture,g=0,h=c.length;g<h;g++)a.multiplyMatrices(c[g]?c[g].matrixWorld:
17959 b,d[g]),a.toArray(e,16*g);void 0!==f&&(f.needsUpdate=!0)}}(),clone:function(){return new Cc(this.bones,this.boneInverses)},getBoneByName:function(a){for(var b=0,c=this.bones.length;b<c;b++){var d=this.bones[b];if(d.name===a)return d}}});rd.prototype=Object.assign(Object.create(D.prototype),{constructor:rd,isBone:!0});sd.prototype=Object.assign(Object.create(la.prototype),{constructor:sd,isSkinnedMesh:!0,initBones:function(){var a=[],b;if(this.geometry&&void 0!==this.geometry.bones){var c=0;for(b=
17960 this.geometry.bones.length;c<b;c++){var d=this.geometry.bones[c];var e=new rd;a.push(e);e.name=d.name;e.position.fromArray(d.pos);e.quaternion.fromArray(d.rotq);void 0!==d.scl&&e.scale.fromArray(d.scl)}c=0;for(b=this.geometry.bones.length;c<b;c++)d=this.geometry.bones[c],-1!==d.parent&&null!==d.parent&&void 0!==a[d.parent]?a[d.parent].add(a[c]):this.add(a[c])}this.updateMatrixWorld(!0);return a},bind:function(a,b){this.skeleton=a;void 0===b&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),
17961 b=this.matrixWorld);this.bindMatrix.copy(b);this.bindMatrixInverse.getInverse(b)},pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){var a;if(this.geometry&&this.geometry.isGeometry)for(a=0;a<this.geometry.skinWeights.length;a++){var b=this.geometry.skinWeights[a];var c=1/b.manhattanLength();Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry){b=new V;var d=this.geometry.attributes.skinWeight;for(a=0;a<d.count;a++)b.x=d.getX(a),
17962 b.y=d.getY(a),b.z=d.getZ(a),b.w=d.getW(a),c=1/b.manhattanLength(),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){la.prototype.updateMatrixWorld.call(this,a);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):"detached"===this.bindMode?this.bindMatrixInverse.getInverse(this.bindMatrix):console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)},clone:function(){return(new this.constructor(this.geometry,
17963 this.material)).copy(this)}});Y.prototype=Object.create(J.prototype);Y.prototype.constructor=Y;Y.prototype.isLineBasicMaterial=!0;Y.prototype.copy=function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};sa.prototype=Object.assign(Object.create(D.prototype),{constructor:sa,isLine:!0,computeLineDistances:function(){var a=new p,b=new p;return function(){var c=this.geometry;if(c.isBufferGeometry)if(null===
17964 c.index){for(var d=c.attributes.position,e=[0],f=1,g=d.count;f<g;f++)a.fromBufferAttribute(d,f-1),b.fromBufferAttribute(d,f),e[f]=e[f-1],e[f]+=a.distanceTo(b);c.addAttribute("lineDistance",new A(e,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");else if(c.isGeometry)for(d=c.vertices,e=c.lineDistances,e[0]=0,f=1,g=d.length;f<g;f++)e[f]=e[f-1],e[f]+=d[f-1].distanceTo(d[f]);return this}}(),raycast:function(){var a=new I,b=new mb,c=
17965 new Da;return function(d,e){var f=d.linePrecision;f*=f;var g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&g.computeBoundingSphere();c.copy(g.boundingSphere);c.applyMatrix4(h);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(h);b.copy(d.ray).applyMatrix4(a);var k=new p,m=new p;h=new p;var l=new p,n=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var t=g.index,u=g.attributes.position.array;if(null!==t){t=t.array;g=0;for(var r=t.length-1;g<r;g+=n){var v=t[g+1];k.fromArray(u,3*t[g]);
17966 m.fromArray(u,3*v);v=b.distanceSqToSegment(k,m,l,h);v>f||(l.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(l),v<d.near||v>d.far||e.push({distance:v,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}else for(g=0,r=u.length/3-1;g<r;g+=n)k.fromArray(u,3*g),m.fromArray(u,3*g+3),v=b.distanceSqToSegment(k,m,l,h),v>f||(l.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(l),v<d.near||v>d.far||e.push({distance:v,point:h.clone().applyMatrix4(this.matrixWorld),
17967 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+=n)v=b.distanceSqToSegment(k[g],k[g+1],l,h),v>f||(l.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(l),v<d.near||v>d.far||e.push({distance:v,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)}});W.prototype=Object.assign(Object.create(sa.prototype),
17968 {constructor:W,isLineSegments:!0,computeLineDistances:function(){var a=new p,b=new p;return function(){var c=this.geometry;if(c.isBufferGeometry)if(null===c.index){for(var d=c.attributes.position,e=[],f=0,g=d.count;f<g;f+=2)a.fromBufferAttribute(d,f),b.fromBufferAttribute(d,f+1),e[f]=0===f?0:e[f-1],e[f+1]=e[f]+a.distanceTo(b);c.addAttribute("lineDistance",new A(e,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");else if(c.isGeometry)for(d=
17969 c.vertices,e=c.lineDistances,f=0,g=d.length;f<g;f+=2)a.copy(d[f]),b.copy(d[f+1]),e[f]=0===f?0:e[f-1],e[f+1]=e[f]+a.distanceTo(b);return this}}()});td.prototype=Object.assign(Object.create(sa.prototype),{constructor:td,isLineLoop:!0});Ea.prototype=Object.create(J.prototype);Ea.prototype.constructor=Ea;Ea.prototype.isPointsMaterial=!0;Ea.prototype.copy=function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;this.morphTargets=
17970 a.morphTargets;return this};Ob.prototype=Object.assign(Object.create(D.prototype),{constructor:Ob,isPoints:!0,raycast:function(){var a=new I,b=new mb,c=new Da;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);f<l&&(b.closestPointToPoint(a,n),n.applyMatrix4(k),a=d.ray.origin.distanceTo(n),a<d.near||a>d.far||e.push({distance:a,distanceToRay:Math.sqrt(f),point:n.clone(),index:c,face:null,object:g}))}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&
17971 h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);c.radius+=m;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);m/=(this.scale.x+this.scale.y+this.scale.z)/3;var l=m*m;m=new p;var n=new p;if(h.isBufferGeometry){var t=h.index;h=h.attributes.position.array;if(null!==t){var u=t.array;t=0;for(var r=u.length;t<r;t++){var v=u[t];m.fromArray(h,3*v);f(m,v)}}else for(t=0,u=h.length/3;t<u;t++)m.fromArray(h,3*t),f(m,t)}else for(m=h.vertices,t=0,u=m.length;t<
17972 u;t++)f(m[t],t)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});$d.prototype=Object.assign(Object.create(T.prototype),{constructor:$d,isVideoTexture:!0,update:function(){var a=this.image;a.readyState>=a.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}});Pb.prototype=Object.create(T.prototype);Pb.prototype.constructor=Pb;Pb.prototype.isCompressedTexture=!0;Dc.prototype=Object.create(T.prototype);Dc.prototype.constructor=Dc;Dc.prototype.isCanvasTexture=!0;Ec.prototype=
17973 Object.create(T.prototype);Ec.prototype.constructor=Ec;Ec.prototype.isDepthTexture=!0;Qb.prototype=Object.create(C.prototype);Qb.prototype.constructor=Qb;Fc.prototype=Object.create(R.prototype);Fc.prototype.constructor=Fc;Rb.prototype=Object.create(C.prototype);Rb.prototype.constructor=Rb;Gc.prototype=Object.create(R.prototype);Gc.prototype.constructor=Gc;na.prototype=Object.create(C.prototype);na.prototype.constructor=na;Hc.prototype=Object.create(R.prototype);Hc.prototype.constructor=Hc;Sb.prototype=
17974 Object.create(na.prototype);Sb.prototype.constructor=Sb;Ic.prototype=Object.create(R.prototype);Ic.prototype.constructor=Ic;pb.prototype=Object.create(na.prototype);pb.prototype.constructor=pb;Jc.prototype=Object.create(R.prototype);Jc.prototype.constructor=Jc;Tb.prototype=Object.create(na.prototype);Tb.prototype.constructor=Tb;Kc.prototype=Object.create(R.prototype);Kc.prototype.constructor=Kc;Ub.prototype=Object.create(na.prototype);Ub.prototype.constructor=Ub;Lc.prototype=Object.create(R.prototype);
17975 Lc.prototype.constructor=Lc;Vb.prototype=Object.create(C.prototype);Vb.prototype.constructor=Vb;Mc.prototype=Object.create(R.prototype);Mc.prototype.constructor=Mc;Wb.prototype=Object.create(C.prototype);Wb.prototype.constructor=Wb;Nc.prototype=Object.create(R.prototype);Nc.prototype.constructor=Nc;Xb.prototype=Object.create(C.prototype);Xb.prototype.constructor=Xb;var Ug={triangulate:function(a,b,c){c=c||2;var d=b&&b.length,e=d?b[0]*c:a.length,f=bf(a,0,e,c,!0),g=[];if(!f)return g;var h;if(d){var k=
17976 c;d=[];var m;var l=0;for(m=b.length;l<m;l++){var n=b[l]*k;var t=l<m-1?b[l+1]*k:a.length;n=bf(a,n,t,k,!1);n===n.next&&(n.steiner=!0);d.push(Pg(n))}d.sort(Ng);for(l=0;l<d.length;l++){b=d[l];k=f;if(k=Og(b,k))b=ef(k,b),Pc(b,b.next);f=Pc(f,f.next)}}if(a.length>80*c){var p=h=a[0];var r=d=a[1];for(k=c;k<e;k+=c)l=a[k],b=a[k+1],l<p&&(p=l),b<r&&(r=b),l>h&&(h=l),b>d&&(d=b);h=Math.max(h-p,d-r);h=0!==h?1/h:0}Qc(f,g,c,p,r,h);return g}},Va={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-
17977 a[e].x*a[d].y;return.5*c},isClockWise:function(a){return 0>Va.area(a)},triangulateShape:function(a,b){var c=[],d=[],e=[];ff(a);gf(c,a);var f=a.length;b.forEach(ff);for(a=0;a<b.length;a++)d.push(f),f+=b[a].length,gf(c,b[a]);b=Ug.triangulate(c,d);for(a=0;a<b.length;a+=3)e.push(b.slice(a,a+3));return e}};rb.prototype=Object.create(R.prototype);rb.prototype.constructor=rb;rb.prototype.toJSON=function(){var a=R.prototype.toJSON.call(this);return hf(this.parameters.shapes,this.parameters.options,a)};Oa.prototype=
17978 Object.create(C.prototype);Oa.prototype.constructor=Oa;Oa.prototype.toJSON=function(){var a=C.prototype.toJSON.call(this);return hf(this.parameters.shapes,this.parameters.options,a)};var Qg={generateTopUV:function(a,b,c,d,e){a=b[3*d];d=b[3*d+1];var f=b[3*e];e=b[3*e+1];return[new z(b[3*c],b[3*c+1]),new z(a,d),new z(f,e)]},generateSideWallUV:function(a,b,c,d,e,f){a=b[3*c];var g=b[3*c+1];c=b[3*c+2];var h=b[3*d],k=b[3*d+1];d=b[3*d+2];var m=b[3*e],l=b[3*e+1];e=b[3*e+2];var n=b[3*f],t=b[3*f+1];b=b[3*f+
17979 2];return.01>Math.abs(g-k)?[new z(a,1-c),new z(h,1-d),new z(m,1-e),new z(n,1-b)]:[new z(g,1-c),new z(k,1-d),new z(l,1-e),new z(t,1-b)]}};Sc.prototype=Object.create(R.prototype);Sc.prototype.constructor=Sc;Yb.prototype=Object.create(Oa.prototype);Yb.prototype.constructor=Yb;Tc.prototype=Object.create(R.prototype);Tc.prototype.constructor=Tc;sb.prototype=Object.create(C.prototype);sb.prototype.constructor=sb;Uc.prototype=Object.create(R.prototype);Uc.prototype.constructor=Uc;Zb.prototype=Object.create(C.prototype);
17980 Zb.prototype.constructor=Zb;Vc.prototype=Object.create(R.prototype);Vc.prototype.constructor=Vc;$b.prototype=Object.create(C.prototype);$b.prototype.constructor=$b;tb.prototype=Object.create(R.prototype);tb.prototype.constructor=tb;tb.prototype.toJSON=function(){var a=R.prototype.toJSON.call(this);return jf(this.parameters.shapes,a)};ub.prototype=Object.create(C.prototype);ub.prototype.constructor=ub;ub.prototype.toJSON=function(){var a=C.prototype.toJSON.call(this);return jf(this.parameters.shapes,
17981 a)};ac.prototype=Object.create(C.prototype);ac.prototype.constructor=ac;vb.prototype=Object.create(R.prototype);vb.prototype.constructor=vb;Wa.prototype=Object.create(C.prototype);Wa.prototype.constructor=Wa;Wc.prototype=Object.create(vb.prototype);Wc.prototype.constructor=Wc;Xc.prototype=Object.create(Wa.prototype);Xc.prototype.constructor=Xc;Yc.prototype=Object.create(R.prototype);Yc.prototype.constructor=Yc;bc.prototype=Object.create(C.prototype);bc.prototype.constructor=bc;var xa=Object.freeze({WireframeGeometry:Qb,
17982 ParametricGeometry:Fc,ParametricBufferGeometry:Rb,TetrahedronGeometry:Hc,TetrahedronBufferGeometry:Sb,OctahedronGeometry:Ic,OctahedronBufferGeometry:pb,IcosahedronGeometry:Jc,IcosahedronBufferGeometry:Tb,DodecahedronGeometry:Kc,DodecahedronBufferGeometry:Ub,PolyhedronGeometry:Gc,PolyhedronBufferGeometry:na,TubeGeometry:Lc,TubeBufferGeometry:Vb,TorusKnotGeometry:Mc,TorusKnotBufferGeometry:Wb,TorusGeometry:Nc,TorusBufferGeometry:Xb,TextGeometry:Sc,TextBufferGeometry:Yb,SphereGeometry:Tc,SphereBufferGeometry:sb,
17983 RingGeometry:Uc,RingBufferGeometry:Zb,PlaneGeometry:uc,PlaneBufferGeometry:lb,LatheGeometry:Vc,LatheBufferGeometry:$b,ShapeGeometry:tb,ShapeBufferGeometry:ub,ExtrudeGeometry:rb,ExtrudeBufferGeometry:Oa,EdgesGeometry:ac,ConeGeometry:Wc,ConeBufferGeometry:Xc,CylinderGeometry:vb,CylinderBufferGeometry:Wa,CircleGeometry:Yc,CircleBufferGeometry:bc,BoxGeometry:Ib,BoxBufferGeometry:kb});wb.prototype=Object.create(J.prototype);wb.prototype.constructor=wb;wb.prototype.isShadowMaterial=!0;wb.prototype.copy=
17984 function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);return this};cc.prototype=Object.create(ta.prototype);cc.prototype.constructor=cc;cc.prototype.isRawShaderMaterial=!0;Pa.prototype=Object.create(J.prototype);Pa.prototype.constructor=Pa;Pa.prototype.isMeshStandardMaterial=!0;Pa.prototype.copy=function(a){J.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=
17985 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.normalMapType=a.normalMapType;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=
17986 a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};xb.prototype=Object.create(Pa.prototype);xb.prototype.constructor=xb;xb.prototype.isMeshPhysicalMaterial=
17987 !0;xb.prototype.copy=function(a){Pa.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Fa.prototype=Object.create(J.prototype);Fa.prototype.constructor=Fa;Fa.prototype.isMeshPhongMaterial=!0;Fa.prototype.copy=function(a){J.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=
17988 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.normalMapType=a.normalMapType;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;
17989 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};yb.prototype=Object.create(Fa.prototype);yb.prototype.constructor=yb;yb.prototype.isMeshToonMaterial=!0;yb.prototype.copy=function(a){Fa.prototype.copy.call(this,
17990 a);this.gradientMap=a.gradientMap;return this};zb.prototype=Object.create(J.prototype);zb.prototype.constructor=zb;zb.prototype.isMeshNormalMaterial=!0;zb.prototype.copy=function(a){J.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalMapType=a.normalMapType;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;
17991 this.wireframeLinewidth=a.wireframeLinewidth;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};Ab.prototype=Object.create(J.prototype);Ab.prototype.constructor=Ab;Ab.prototype.isMeshLambertMaterial=!0;Ab.prototype.copy=function(a){J.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);
17992 this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};
17993 Bb.prototype=Object.create(Y.prototype);Bb.prototype.constructor=Bb;Bb.prototype.isLineDashedMaterial=!0;Bb.prototype.copy=function(a){Y.prototype.copy.call(this,a);this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var Vg=Object.freeze({ShadowMaterial:wb,SpriteMaterial:cb,RawShaderMaterial:cc,ShaderMaterial:ta,PointsMaterial:Ea,MeshPhysicalMaterial:xb,MeshStandardMaterial:Pa,MeshPhongMaterial:Fa,MeshToonMaterial:yb,MeshNormalMaterial:zb,MeshLambertMaterial:Ab,MeshDepthMaterial:$a,
17994 MeshDistanceMaterial:ab,MeshBasicMaterial:da,LineDashedMaterial:Bb,LineBasicMaterial:Y,Material:J}),Fb={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={}}},ka=new ce,Ya={};Object.assign(Ga.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var e=this,f=Fb.get(a);if(void 0!==f)return e.manager.itemStart(a),
17995 setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;if(void 0!==Ya[a])Ya[a].push({onLoad:b,onProgress:c,onError:d});else{var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){c=g[1];var h=!!g[2];g=g[3];g=window.decodeURIComponent(g);h&&(g=window.atob(g));try{var k=(this.responseType||"").toLowerCase();switch(k){case "arraybuffer":case "blob":var m=new Uint8Array(g.length);for(h=0;h<g.length;h++)m[h]=g.charCodeAt(h);var l="blob"===k?new Blob([m.buffer],{type:c}):m.buffer;break;case "document":l=
17996 (new DOMParser).parseFromString(g,c);break;case "json":l=JSON.parse(g);break;default:l=g}window.setTimeout(function(){b&&b(l);e.manager.itemEnd(a)},0)}catch(t){window.setTimeout(function(){d&&d(t);e.manager.itemEnd(a);e.manager.itemError(a)},0)}}else{Ya[a]=[];Ya[a].push({onLoad:b,onProgress:c,onError:d});var n=new XMLHttpRequest;n.open("GET",a,!0);n.addEventListener("load",function(b){var c=this.response;Fb.add(a,c);var d=Ya[a];delete Ya[a];if(200===this.status||0===this.status){0===this.status&&
17997 console.warn("THREE.FileLoader: HTTP Status 0 received.");for(var f=0,g=d.length;f<g;f++){var h=d[f];if(h.onLoad)h.onLoad(c)}e.manager.itemEnd(a)}else{f=0;for(g=d.length;f<g;f++)if(h=d[f],h.onError)h.onError(b);e.manager.itemEnd(a);e.manager.itemError(a)}},!1);n.addEventListener("progress",function(b){for(var c=Ya[a],d=0,e=c.length;d<e;d++){var f=c[d];if(f.onProgress)f.onProgress(b)}},!1);n.addEventListener("error",function(b){var c=Ya[a];delete Ya[a];for(var d=0,f=c.length;d<f;d++){var g=c[d];if(g.onError)g.onError(b)}e.manager.itemEnd(a);
17998 e.manager.itemError(a)},!1);void 0!==this.responseType&&(n.responseType=this.responseType);void 0!==this.withCredentials&&(n.withCredentials=this.withCredentials);n.overrideMimeType&&n.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");for(h in this.requestHeader)n.setRequestHeader(h,this.requestHeader[h]);n.send(null)}e.manager.itemStart(a);return n}},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=a;return this},setWithCredentials:function(a){this.withCredentials=
17999 a;return this},setMimeType:function(a){this.mimeType=a;return this},setRequestHeader:function(a){this.requestHeader=a;return this}});Object.assign(kf.prototype,{load:function(a,b,c,d){function e(e){k.load(a[e],function(a){a=f._parser(a,!0);g[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};m+=1;6===m&&(1===a.mipmapCount&&(h.minFilter=1006),h.format=a.format,h.needsUpdate=!0,b&&b(h))},c,d)}var f=this,g=[],h=new Pb;h.image=g;var k=new Ga(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");
18000 if(Array.isArray(a))for(var m=0,l=0,n=a.length;l<n;++l)e(l);else k.load(a,function(a){a=f._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){g[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)g[d].mipmaps.push(a.mipmaps[d*a.mipmapCount+e]),g[d].format=a.format,g[d].width=a.width,g[d].height=a.height}else h.image.width=a.width,h.image.height=a.height,h.mipmaps=a.mipmaps;1===a.mipmapCount&&(h.minFilter=1006);h.format=a.format;h.needsUpdate=!0;b&&b(h)},c,d);return h},setPath:function(a){this.path=
18001 a;return this}});Object.assign(de.prototype,{load:function(a,b,c,d){var e=this,f=new gb,g=new Ga(this.manager);g.setResponseType("arraybuffer");g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?
18002 a.anisotropy:1,void 0!==a.format&&(f.format=a.format),void 0!==a.type&&(f.type=a.type),void 0!==a.mipmaps&&(f.mipmaps=a.mipmaps),1===a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Zc.prototype,{crossOrigin:"anonymous",load:function(a,b,c,d){function e(){k.removeEventListener("load",e,!1);k.removeEventListener("error",f,!1);Fb.add(a,this);b&&b(this);g.manager.itemEnd(a)}function f(b){k.removeEventListener("load",e,!1);k.removeEventListener("error",f,!1);
18003 d&&d(b);g.manager.itemEnd(a);g.manager.itemError(a)}void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var g=this,h=Fb.get(a);if(void 0!==h)return g.manager.itemStart(a),setTimeout(function(){b&&b(h);g.manager.itemEnd(a)},0),h;var k=document.createElementNS("http://www.w3.org/1999/xhtml","img");k.addEventListener("load",e,!1);k.addEventListener("error",f,!1);"data:"!==a.substr(0,5)&&void 0!==this.crossOrigin&&(k.crossOrigin=this.crossOrigin);g.manager.itemStart(a);
18004 k.src=a;return k},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(ee.prototype,{crossOrigin:"anonymous",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 Ua,g=new Zc(this.manager);g.setCrossOrigin(this.crossOrigin);g.setPath(this.path);var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=
18005 a;return this}});Object.assign(vd.prototype,{crossOrigin:"anonymous",load:function(a,b,c,d){var e=new T,f=new Zc(this.manager);f.setCrossOrigin(this.crossOrigin);f.setPath(this.path);f.load(a,function(c){e.image=c;c=0<a.search(/\.(jpg|jpeg)$/)||0===a.search(/^data:image\/jpeg/);e.format=c?1022:1023;e.needsUpdate=!0;void 0!==b&&b(e)},c,d);return e},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(L.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");
18006 return null},getPointAt:function(a,b){a=this.getUtoTmapping(a);return this.getPoint(a,b)},getPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));return b},getSpacedPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/a));return b},getLength:function(){var a=this.getLengths();return a[a.length-1]},getLengths:function(a){void 0===a&&(a=this.arcLengthDivisions);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;
18007 this.needsUpdate=!1;var b=[],c=this.getPoint(0),d,e=0;b.push(0);for(d=1;d<=a;d++){var f=this.getPoint(d/a);e+=f.distanceTo(c);b.push(e);c=f}return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,b){var c=this.getLengths(),d=c.length;b=b?b:a*c[d-1];for(var e=0,f=d-1,g;e<=f;)if(a=Math.floor(e+(f-e)/2),g=c[a]-b,0>g)e=a+1;else if(0<g)f=a-1;else{f=a;break}a=f;if(c[a]===b)return a/(d-1);e=c[a];return(a+(b-e)/(c[a+1]-e))/(d-1)},getTangent:function(a){var b=
18008 a-1E-4;a+=1E-4;0>b&&(b=0);1<a&&(a=1);b=this.getPoint(b);return this.getPoint(a).clone().sub(b).normalize()},getTangentAt:function(a){a=this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new p,d=[],e=[],f=[],g=new p,h=new I,k;for(k=0;k<=a;k++){var m=k/a;d[k]=this.getTangentAt(m);d[k].normalize()}e[0]=new p;f[0]=new p;k=Number.MAX_VALUE;m=Math.abs(d[0].x);var l=Math.abs(d[0].y),n=Math.abs(d[0].z);m<=k&&(k=m,c.set(1,0,0));l<=k&&(k=l,c.set(0,1,0));n<=k&&c.set(0,
18009 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-1].clone(),g.crossVectors(d[k-1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(H.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(H.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],
18010 c*k)),f[k].crossVectors(d[k],e[k]);return{tangents:d,normals:e,binormals:f}},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.arcLengthDivisions=a.arcLengthDivisions;return this},toJSON:function(){var a={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};a.arcLengthDivisions=this.arcLengthDivisions;a.type=this.type;return a},fromJSON:function(a){this.arcLengthDivisions=a.arcLengthDivisions;return this}});za.prototype=Object.create(L.prototype);za.prototype.constructor=
18011 za;za.prototype.isEllipseCurve=!0;za.prototype.getPoint=function(a,b){b=b||new z;for(var c=2*Math.PI,d=this.aEndAngle-this.aStartAngle,e=Math.abs(d)<Number.EPSILON;0>d;)d+=c;for(;d>c;)d-=c;d<Number.EPSILON&&(d=e?0:c);!0!==this.aClockwise||e||(d=d===c?-c:d-c);c=this.aStartAngle+a*d;a=this.aX+this.xRadius*Math.cos(c);var f=this.aY+this.yRadius*Math.sin(c);0!==this.aRotation&&(c=Math.cos(this.aRotation),d=Math.sin(this.aRotation),e=a-this.aX,f-=this.aY,a=e*c-f*d+this.aX,f=e*d+f*c+this.aY);return b.set(a,
18012 f)};za.prototype.copy=function(a){L.prototype.copy.call(this,a);this.aX=a.aX;this.aY=a.aY;this.xRadius=a.xRadius;this.yRadius=a.yRadius;this.aStartAngle=a.aStartAngle;this.aEndAngle=a.aEndAngle;this.aClockwise=a.aClockwise;this.aRotation=a.aRotation;return this};za.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.aX=this.aX;a.aY=this.aY;a.xRadius=this.xRadius;a.yRadius=this.yRadius;a.aStartAngle=this.aStartAngle;a.aEndAngle=this.aEndAngle;a.aClockwise=this.aClockwise;a.aRotation=
18013 this.aRotation;return a};za.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.aX=a.aX;this.aY=a.aY;this.xRadius=a.xRadius;this.yRadius=a.yRadius;this.aStartAngle=a.aStartAngle;this.aEndAngle=a.aEndAngle;this.aClockwise=a.aClockwise;this.aRotation=a.aRotation;return this};dc.prototype=Object.create(za.prototype);dc.prototype.constructor=dc;dc.prototype.isArcCurve=!0;var Od=new p,Ae=new fe,Be=new fe,Ce=new fe;ca.prototype=Object.create(L.prototype);ca.prototype.constructor=ca;ca.prototype.isCatmullRomCurve3=
18014 !0;ca.prototype.getPoint=function(a,b){b=b||new p;var c=this.points,d=c.length;a*=d-(this.closed?0:1);var e=Math.floor(a);a-=e;this.closed?e+=0<e?0:(Math.floor(Math.abs(e)/d)+1)*d:0===a&&e===d-1&&(e=d-2,a=1);if(this.closed||0<e)var f=c[(e-1)%d];else Od.subVectors(c[0],c[1]).add(c[0]),f=Od;var g=c[e%d];var h=c[(e+1)%d];this.closed||e+2<d?c=c[(e+2)%d]:(Od.subVectors(c[d-1],c[d-2]).add(c[d-1]),c=Od);if("centripetal"===this.curveType||"chordal"===this.curveType){var k="chordal"===this.curveType?.5:.25;
18015 d=Math.pow(f.distanceToSquared(g),k);e=Math.pow(g.distanceToSquared(h),k);k=Math.pow(h.distanceToSquared(c),k);1E-4>e&&(e=1);1E-4>d&&(d=e);1E-4>k&&(k=e);Ae.initNonuniformCatmullRom(f.x,g.x,h.x,c.x,d,e,k);Be.initNonuniformCatmullRom(f.y,g.y,h.y,c.y,d,e,k);Ce.initNonuniformCatmullRom(f.z,g.z,h.z,c.z,d,e,k)}else"catmullrom"===this.curveType&&(Ae.initCatmullRom(f.x,g.x,h.x,c.x,this.tension),Be.initCatmullRom(f.y,g.y,h.y,c.y,this.tension),Ce.initCatmullRom(f.z,g.z,h.z,c.z,this.tension));b.set(Ae.calc(a),
18016 Be.calc(a),Ce.calc(a));return b};ca.prototype.copy=function(a){L.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++)this.points.push(a.points[b].clone());this.closed=a.closed;this.curveType=a.curveType;this.tension=a.tension;return this};ca.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.points=[];for(var b=0,c=this.points.length;b<c;b++)a.points.push(this.points[b].toArray());a.closed=this.closed;a.curveType=this.curveType;a.tension=this.tension;return a};
18017 ca.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++){var d=a.points[b];this.points.push((new p).fromArray(d))}this.closed=a.closed;this.curveType=a.curveType;this.tension=a.tension;return this};Ha.prototype=Object.create(L.prototype);Ha.prototype.constructor=Ha;Ha.prototype.isCubicBezierCurve=!0;Ha.prototype.getPoint=function(a,b){b=b||new z;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(ad(a,c.x,d.x,e.x,f.x),ad(a,c.y,d.y,e.y,
18018 f.y));return b};Ha.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);this.v3.copy(a.v3);return this};Ha.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v0=this.v0.toArray();a.v1=this.v1.toArray();a.v2=this.v2.toArray();a.v3=this.v3.toArray();return a};Ha.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v0.fromArray(a.v0);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);this.v3.fromArray(a.v3);return this};
18019 Qa.prototype=Object.create(L.prototype);Qa.prototype.constructor=Qa;Qa.prototype.isCubicBezierCurve3=!0;Qa.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(ad(a,c.x,d.x,e.x,f.x),ad(a,c.y,d.y,e.y,f.y),ad(a,c.z,d.z,e.z,f.z));return b};Qa.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);this.v3.copy(a.v3);return this};Qa.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v0=this.v0.toArray();
18020 a.v1=this.v1.toArray();a.v2=this.v2.toArray();a.v3=this.v3.toArray();return a};Qa.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v0.fromArray(a.v0);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);this.v3.fromArray(a.v3);return this};va.prototype=Object.create(L.prototype);va.prototype.constructor=va;va.prototype.isLineCurve=!0;va.prototype.getPoint=function(a,b){b=b||new z;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};va.prototype.getPointAt=
18021 function(a,b){return this.getPoint(a,b)};va.prototype.getTangent=function(){return this.v2.clone().sub(this.v1).normalize()};va.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};va.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v1=this.v1.toArray();a.v2=this.v2.toArray();return a};va.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);return this};Ia.prototype=
18022 Object.create(L.prototype);Ia.prototype.constructor=Ia;Ia.prototype.isLineCurve3=!0;Ia.prototype.getPoint=function(a,b){b=b||new p;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};Ia.prototype.getPointAt=function(a,b){return this.getPoint(a,b)};Ia.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};Ia.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v1=this.v1.toArray();a.v2=this.v2.toArray();
18023 return a};Ia.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);return this};Ja.prototype=Object.create(L.prototype);Ja.prototype.constructor=Ja;Ja.prototype.isQuadraticBezierCurve=!0;Ja.prototype.getPoint=function(a,b){b=b||new z;var c=this.v0,d=this.v1,e=this.v2;b.set($c(a,c.x,d.x,e.x),$c(a,c.y,d.y,e.y));return b};Ja.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};
18024 Ja.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v0=this.v0.toArray();a.v1=this.v1.toArray();a.v2=this.v2.toArray();return a};Ja.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v0.fromArray(a.v0);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);return this};Ra.prototype=Object.create(L.prototype);Ra.prototype.constructor=Ra;Ra.prototype.isQuadraticBezierCurve3=!0;Ra.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,e=this.v2;b.set($c(a,c.x,
18025 d.x,e.x),$c(a,c.y,d.y,e.y),$c(a,c.z,d.z,e.z));return b};Ra.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};Ra.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v0=this.v0.toArray();a.v1=this.v1.toArray();a.v2=this.v2.toArray();return a};Ra.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v0.fromArray(a.v0);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);return this};Ka.prototype=Object.create(L.prototype);
18026 Ka.prototype.constructor=Ka;Ka.prototype.isSplineCurve=!0;Ka.prototype.getPoint=function(a,b){b=b||new z;var c=this.points,d=(c.length-1)*a;a=Math.floor(d);d-=a;var e=c[0===a?a:a-1],f=c[a],g=c[a>c.length-2?c.length-1:a+1];c=c[a>c.length-3?c.length-1:a+2];b.set(lf(d,e.x,f.x,g.x,c.x),lf(d,e.y,f.y,g.y,c.y));return b};Ka.prototype.copy=function(a){L.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++)this.points.push(a.points[b].clone());return this};Ka.prototype.toJSON=function(){var a=
18027 L.prototype.toJSON.call(this);a.points=[];for(var b=0,c=this.points.length;b<c;b++)a.points.push(this.points[b].toArray());return a};Ka.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++){var d=a.points[b];this.points.push((new z).fromArray(d))}return this};var Af=Object.freeze({ArcCurve:dc,CatmullRomCurve3:ca,CubicBezierCurve:Ha,CubicBezierCurve3:Qa,EllipseCurve:za,LineCurve:va,LineCurve3:Ia,QuadraticBezierCurve:Ja,QuadraticBezierCurve3:Ra,
18028 SplineCurve:Ka});Xa.prototype=Object.assign(Object.create(L.prototype),{constructor:Xa,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 va(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();
18029 return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getCurveLengths()},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){void 0===a&&(a=40);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));this.autoClose&&b.push(b[0]);return b},getPoints:function(a){a=
18030 a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++){var f=e[d];f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&(f.isLineCurve||f.isLineCurve3)?1:f&&f.isSplineCurve?a*f.points.length:a);for(var 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},copy:function(a){L.prototype.copy.call(this,a);this.curves=[];for(var b=0,c=a.curves.length;b<c;b++)this.curves.push(a.curves[b].clone());this.autoClose=a.autoClose;return this},
18031 toJSON:function(){var a=L.prototype.toJSON.call(this);a.autoClose=this.autoClose;a.curves=[];for(var b=0,c=this.curves.length;b<c;b++)a.curves.push(this.curves[b].toJSON());return a},fromJSON:function(a){L.prototype.fromJSON.call(this,a);this.autoClose=a.autoClose;this.curves=[];for(var b=0,c=a.curves.length;b<c;b++){var d=a.curves[b];this.curves.push((new Af[d.type]).fromJSON(d))}return this}});La.prototype=Object.assign(Object.create(Xa.prototype),{constructor:La,setFromPoints:function(a){this.moveTo(a[0].x,
18032 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 va(this.currentPoint.clone(),new z(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new Ja(this.currentPoint.clone(),new z(a,b),new z(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new Ha(this.currentPoint.clone(),new z(a,b),new z(c,d),new z(e,f));this.curves.push(a);
18033 this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a);b=new Ka(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,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 za(a,b,c,d,e,f,g,h);0<this.curves.length&&
18034 (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)},copy:function(a){Xa.prototype.copy.call(this,a);this.currentPoint.copy(a.currentPoint);return this},toJSON:function(){var a=Xa.prototype.toJSON.call(this);a.currentPoint=this.currentPoint.toArray();return a},fromJSON:function(a){Xa.prototype.fromJSON.call(this,a);this.currentPoint.fromArray(a.currentPoint);return this}});db.prototype=Object.assign(Object.create(La.prototype),
18035 {constructor:db,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractPoints:function(a){return{shape:this.getPoints(a),holes:this.getPointsHoles(a)}},copy:function(a){La.prototype.copy.call(this,a);this.holes=[];for(var b=0,c=a.holes.length;b<c;b++)this.holes.push(a.holes[b].clone());return this},toJSON:function(){var a=La.prototype.toJSON.call(this);a.uuid=this.uuid;a.holes=[];for(var b=0,c=this.holes.length;b<c;b++)a.holes.push(this.holes[b].toJSON());
18036 return a},fromJSON:function(a){La.prototype.fromJSON.call(this,a);this.uuid=a.uuid;this.holes=[];for(var b=0,c=a.holes.length;b<c;b++){var d=a.holes[b];this.holes.push((new La).fromJSON(d))}return this}});X.prototype=Object.assign(Object.create(D.prototype),{constructor:X,isLight:!0,copy:function(a){D.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=D.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=
18037 this.intensity;void 0!==this.groundColor&&(a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&(a.object.shadow=this.shadow.toJSON());return a}});wd.prototype=Object.assign(Object.create(X.prototype),{constructor:wd,isHemisphereLight:!0,copy:function(a){X.prototype.copy.call(this,
18038 a);this.groundColor.copy(a.groundColor);return this}});Object.assign(Cb.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;
18039 return a}});xd.prototype=Object.assign(Object.create(Cb.prototype),{constructor:xd,isSpotLightShadow:!0,update:function(a){var b=this.camera,c=2*H.RAD2DEG*a.angle,d=this.mapSize.width/this.mapSize.height;a=a.distance||b.far;if(c!==b.fov||d!==b.aspect||a!==b.far)b.fov=c,b.aspect=d,b.far=a,b.updateProjectionMatrix()}});yd.prototype=Object.assign(Object.create(X.prototype),{constructor:yd,isSpotLight:!0,copy:function(a){X.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=
18040 a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});zd.prototype=Object.assign(Object.create(X.prototype),{constructor:zd,isPointLight:!0,copy:function(a){X.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();return this}});Ad.prototype=Object.assign(Object.create(Cb.prototype),{constructor:Ad});Bd.prototype=Object.assign(Object.create(X.prototype),{constructor:Bd,isDirectionalLight:!0,copy:function(a){X.prototype.copy.call(this,
18041 a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});Cd.prototype=Object.assign(Object.create(X.prototype),{constructor:Cd,isAmbientLight:!0});Dd.prototype=Object.assign(Object.create(X.prototype),{constructor:Dd,isRectAreaLight:!0,copy:function(a){X.prototype.copy.call(this,a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=X.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var ia={arraySlice:function(a,
18042 b,c){return ia.isTypedArray(a)?new a.constructor(a.subarray(b,void 0!==c?c:a.length)):a.slice(b,c)},convertArray:function(a,b,c){return!a||!c&&a.constructor===b?a:"number"===typeof b.BYTES_PER_ELEMENT?new b(a):Array.prototype.slice.call(a)},isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof DataView)},getKeyframeOrder:function(a){for(var b=a.length,c=Array(b),d=0;d!==b;++d)c[d]=d;c.sort(function(b,c){return a[b]-a[c]});return c},sortedArray:function(a,b,c){for(var d=a.length,e=
18043 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],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++];
18044 while(void 0!==f)}}}};Object.assign(wa.prototype,{evaluate:function(a){var b=this.parameterPositions,c=this._cachedIndex,d=b[c],e=b[c-1];a:{b:{c:{d:if(!(a<d)){for(var f=c+2;;){if(void 0===d){if(a<e)break d;this._cachedIndex=c=b.length;return this.afterEnd_(c-1,a,e)}if(c===f)break;e=d;d=b[++c];if(a<d)break b}d=b.length;break c}if(a>=e)break a;else{f=b[1];a<f&&(c=2,e=f);for(f=c-2;;){if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(c===f)break;d=e;e=b[--c-1];if(a>=e)break b}d=c;c=
18045 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||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]=
18046 c[a+e];return b},interpolate_:function(){throw Error("call to abstract method");},intervalChanged_:function(){}});Object.assign(wa.prototype,{beforeStart_:wa.prototype.copySampleValue_,afterEnd_:wa.prototype.copySampleValue_});Ed.prototype=Object.assign(Object.create(wa.prototype),{constructor:Ed,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,b,c){var d=this.parameterPositions,e=a-2,f=a+1,g=d[e],h=d[f];if(void 0===g)switch(this.getSettings_().endingStart){case 2401:e=
18047 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,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,m=this._offsetNext,l=this._weightPrev,n=this._weightNext,
18048 p=(c-b)/(d-b);c=p*p;d=c*p;b=-l*d+2*l*c-l*p;l=(1+l)*d+(-1.5-2*l)*c+(-.5+l)*p+1;p=(-1-n)*d+(1.5+n)*c+.5*p;n=n*d-n*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+l*f[h+c]+p*f[a+c]+n*f[m+c];return e}});bd.prototype=Object.assign(Object.create(wa.prototype),{constructor:bd,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g;b=(c-b)/(d-b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Fd.prototype=Object.assign(Object.create(wa.prototype),{constructor:Fd,
18049 interpolate_:function(a){return this.copySampleValue_(a-1)}});Object.assign(oa,{toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{b={name:a.name,times:ia.convertArray(a.times,Array),values:ia.convertArray(a.values,Array)};var c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b}});Object.assign(oa.prototype,{constructor:oa,TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Fd(this.times,
18050 this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new bd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Ed(this.times,this.values,this.getValueSize(),a)},setInterpolation:function(a){switch(a){case 2300:var 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+
18051 " keyframe track named "+this.name;if(void 0===this.createInterpolant)if(a!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(b);console.warn("THREE.KeyframeTrack:",b);return this}this.createInterpolant=b;return this},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/
18052 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=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),a=this.getValueSize(),this.times=ia.arraySlice(c,e,f),this.values=ia.arraySlice(this.values,e*a,f*a);return this},validate:function(){var a=
18053 !0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),a=!1);var c=this.times;b=this.values;var d=c.length;0===d&&(console.error("THREE.KeyframeTrack: Track is empty.",this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("THREE.KeyframeTrack: Out of order keys.",this,f,g,e);a=!1;break}e=
18054 g}if(void 0!==b&&ia.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("THREE.KeyframeTrack: 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,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{var m=g*c,l=m-c,n=m+c;for(k=0;k!==c;++k){var p=b[m+k];if(p!==b[l+k]||p!==b[n+k]){h=!0;break}}}if(h){if(g!==e)for(a[e]=
18055 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=ia.arraySlice(a,0,e),this.values=ia.arraySlice(b,0,e*c));return this}});Gd.prototype=Object.assign(Object.create(oa.prototype),{constructor:Gd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Hd.prototype=Object.assign(Object.create(oa.prototype),{constructor:Hd,
18056 ValueTypeName:"color"});ec.prototype=Object.assign(Object.create(oa.prototype),{constructor:ec,ValueTypeName:"number"});Id.prototype=Object.assign(Object.create(wa.prototype),{constructor:Id,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)fa.slerpFlat(e,0,f,a-g,f,a,b);return e}});cd.prototype=Object.assign(Object.create(oa.prototype),{constructor:cd,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Id(this.times,
18057 this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});Jd.prototype=Object.assign(Object.create(oa.prototype),{constructor:Jd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});fc.prototype=Object.assign(Object.create(oa.prototype),{constructor:fc,ValueTypeName:"vector"});Object.assign(Ca,{parse:function(a){for(var b=[],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(Sg(c[e]).scale(d));
18058 return new Ca(a.name,a.duration,b)},toJSON:function(a){var b=[],c=a.tracks;a={name:a.name,duration:a.duration,tracks:b,uuid:a.uuid};for(var d=0,e=c.length;d!==e;++d)b.push(oa.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=ia.getKeyframeOrder(h);h=ia.sortedArray(h,1,m);k=ia.sortedArray(k,1,m);d||0!==h[0]||(h.push(e),k.push(k[0]));f.push((new ec(".morphTargetInfluences["+b[g].name+
18059 "]",h,k)).scale(1/c))}return new Ca(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(a=0;a<c.length;a++)if(c[a].name===b)return c[a];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(Ca.CreateFromMorphTargetSequence(m,d[m],b,c));return a},parseAnimation:function(a,
18060 b){if(!a)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];ia.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;a=a.hierarchy||[];for(var h=0;h<a.length;h++){var k=a[h].keys;if(k&&0!==k.length)if(k[0].morphTargets){f={};for(var m=0;m<k.length;m++)if(k[m].morphTargets)for(var l=0;l<k[m].morphTargets.length;l++)f[k[m].morphTargets[l]]=-1;for(var n in f){var p=
18061 [],u=[];for(l=0;l!==k[m].morphTargets.length;++l){var r=k[m];p.push(r.time);u.push(r.morphTarget===n?1:0)}d.push(new ec(".morphTargetInfluence["+n+"]",p,u))}f=f.length*(g||1)}else m=".bones["+b[h].name+"]",c(fc,m+".position",k,"pos",d),c(cd,m+".quaternion",k,"rot",d),c(fc,m+".scale",k,"scl",d)}return 0===d.length?null:new Ca(e,f,d)}});Object.assign(Ca.prototype,{resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==c;++b){var d=this.tracks[b];a=Math.max(a,d.times[d.times.length-1])}this.duration=
18062 a;return this},trim:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].trim(0,this.duration);return this},validate:function(){for(var a=!0,b=0;b<this.tracks.length;b++)a=a&&this.tracks[b].validate();return a},optimize:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].optimize();return this}});Object.assign(Kd.prototype,{load:function(a,b,c,d){var e=this;(new Ga(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=a},parse:function(a){function b(a){void 0===
18063 c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new Vg[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);void 0!==a.clearCoat&&(d.clearCoat=
18064 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.flatShading&&(d.flatShading=a.flatShading);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==a.opacity&&(d.opacity=
18065 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&&(d.wireframeLinejoin=
18066 a.wireframeLinejoin);void 0!==a.rotation&&(d.rotation=a.rotation);1!==a.linewidth&&(d.linewidth=a.linewidth);void 0!==a.dashSize&&(d.dashSize=a.dashSize);void 0!==a.gapSize&&(d.gapSize=a.gapSize);void 0!==a.scale&&(d.scale=a.scale);void 0!==a.polygonOffset&&(d.polygonOffset=a.polygonOffset);void 0!==a.polygonOffsetFactor&&(d.polygonOffsetFactor=a.polygonOffsetFactor);void 0!==a.polygonOffsetUnits&&(d.polygonOffsetUnits=a.polygonOffsetUnits);void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&
18067 (d.morphTargets=a.morphTargets);void 0!==a.dithering&&(d.dithering=a.dithering);void 0!==a.visible&&(d.visible=a.visible);void 0!==a.userData&&(d.userData=a.userData);void 0!==a.shading&&(d.flatShading=1===a.shading);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);
18068 void 0!==a.normalMap&&(d.normalMap=b(a.normalMap));void 0!==a.normalMapType&&(d.normalMapType=a.normalMapType);if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new z).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!==
18069 a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=a.emissiveIntensity);void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));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!==
18070 a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=b(a.gradientMap));return d}});Object.assign(ge.prototype,{load:function(a,b,c,d){var e=this;(new Ga(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new C,c=a.data.index;void 0!==c&&(c=new Bf[c.type](c.array),b.setIndex(new Q(c,1)));var d=a.data.attributes;for(f in d){var e=d[f];c=new Bf[e.type](e.array);b.addAttribute(f,new Q(c,e.itemSize,e.normalized))}var f=a.data.groups||
18071 a.data.drawcalls||a.data.offsets;if(void 0!==f)for(c=0,d=f.length;c!==d;++c)e=f[c],b.addGroup(e.start,e.count,e.materialIndex);a=a.data.boundingSphere;void 0!==a&&(f=new p,void 0!==a.center&&f.fromArray(a.center),b.boundingSphere=new Da(f,a.radius));return b}});var Bf={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:"undefined"!==typeof Uint8ClampedArray?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,
18072 Float64Array:Float64Array};gc.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(gc.prototype,{crossOrigin:"anonymous",onLoadStart:function(){},onLoadProgress:function(){},onLoadComplete:function(){},initMaterials:function(a,b,c){for(var d=[],e=0;e<a.length;++e)d[e]=this.createMaterial(a[e],b,c);return d},createMaterial:function(){var a={NoBlending:0,NormalBlending:1,
18073 AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},b=new G,c=new vd,d=new Kd;return function(e,f,g){function h(a,b,d,e,h){a=f+a;var m=gc.Handlers.get(a);null!==m?a=m.load(a):(c.setCrossOrigin(g),a=c.load(a));void 0!==b&&(a.repeat.fromArray(b),1!==b[0]&&(a.wrapS=1E3),1!==b[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==e&&("repeat"===e[0]&&(a.wrapS=1E3),"mirror"===e[0]&&(a.wrapS=1002),"repeat"===e[1]&&(a.wrapT=1E3),"mirror"===e[1]&&(a.wrapT=1002));void 0!==
18074 h&&(a.anisotropy=h);b=H.generateUUID();k[b]=a;return b}var k={},m={uuid:H.generateUUID(),type:"MeshLambertMaterial"},l;for(l in e){var n=e[l];switch(l){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":m.name=n;break;case "blending":m.blending=a[n];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",l,"is no longer supported.");break;case "colorDiffuse":m.color=b.fromArray(n).getHex();break;case "colorSpecular":m.specular=
18075 b.fromArray(n).getHex();break;case "colorEmissive":m.emissive=b.fromArray(n).getHex();break;case "specularCoef":m.shininess=n;break;case "shading":"basic"===n.toLowerCase()&&(m.type="MeshBasicMaterial");"phong"===n.toLowerCase()&&(m.type="MeshPhongMaterial");"standard"===n.toLowerCase()&&(m.type="MeshStandardMaterial");break;case "mapDiffuse":m.map=h(n,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;
18076 case "mapEmissive":m.emissiveMap=h(n,e.mapEmissiveRepeat,e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":m.lightMap=h(n,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;case "mapAO":m.aoMap=h(n,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,
18077 e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;case "mapBump":m.bumpMap=h(n,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":m.bumpScale=n;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":m.normalMap=h(n,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);break;case "mapNormalFactor":m.normalScale=n;break;
18078 case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":m.specularMap=h(n,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":m.metalnessMap=h(n,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;
18079 case "mapRoughness":m.roughnessMap=h(n,e.mapRoughnessRepeat,e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":m.alphaMap=h(n,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;case "flipSided":m.side=1;break;case "doubleSided":m.side=
18080 2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");m.opacity=n;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":m[l]=n;break;case "vertexColors":!0===n&&(m.vertexColors=2);"face"===n&&(m.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",l,n)}}"MeshBasicMaterial"===m.type&&delete m.emissive;"MeshPhongMaterial"!==
18081 m.type&&delete m.specular;1>m.opacity&&(m.transparent=!0);d.setTextures(k);return d.parse(m)}}()});var De={decodeText:function(a){if("undefined"!==typeof TextDecoder)return(new TextDecoder).decode(a);for(var b="",c=0,d=a.length;c<d;c++)b+=String.fromCharCode(a[c]);return decodeURIComponent(escape(b))},extractUrlBase:function(a){var b=a.lastIndexOf("/");return-1===b?"./":a.substr(0,b+1)}};Object.assign(he.prototype,{crossOrigin:"anonymous",load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===
18082 typeof this.texturePath?this.texturePath:De.extractUrlBase(a),g=new Ga(this.manager);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&&"object"===d.toLowerCase())){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setCrossOrigin:function(a){this.crossOrigin=a;return this},setTexturePath:function(a){this.texturePath=a;return this},
18083 parse:function(){return function(a,b){void 0!==a.data&&(a=a.data);a.scale=void 0!==a.scale?1/a.scale:1;var c=new R,d=a,e,f,g,h=d.faces;var k=d.vertices;var m=d.normals,l=d.colors;var n=d.scale;var t=0;if(void 0!==d.uvs){for(e=0;e<d.uvs.length;e++)d.uvs[e].length&&t++;for(e=0;e<t;e++)c.faceVertexUvs[e]=[]}var u=0;for(g=k.length;u<g;)e=new p,e.x=k[u++]*n,e.y=k[u++]*n,e.z=k[u++]*n,c.vertices.push(e);u=0;for(g=h.length;u<g;){k=h[u++];var r=k&1;var v=k&2;e=k&8;var y=k&16;var x=k&32;n=k&64;k&=128;if(r){r=
18084 new Ta;r.a=h[u];r.b=h[u+1];r.c=h[u+3];var w=new Ta;w.a=h[u+1];w.b=h[u+2];w.c=h[u+3];u+=4;v&&(v=h[u++],r.materialIndex=v,w.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++){var B=d.uvs[e];c.faceVertexUvs[e][v]=[];c.faceVertexUvs[e][v+1]=[];for(f=0;4>f;f++){var E=h[u++];var A=B[2*E];E=B[2*E+1];A=new z(A,E);2!==f&&c.faceVertexUvs[e][v].push(A);0!==f&&c.faceVertexUvs[e][v+1].push(A)}}y&&(y=3*h[u++],r.normal.set(m[y++],m[y++],m[y]),w.normal.copy(r.normal));if(x)for(e=0;4>e;e++)y=3*h[u++],x=new p(m[y++],
18085 m[y++],m[y]),2!==e&&r.vertexNormals.push(x),0!==e&&w.vertexNormals.push(x);n&&(n=h[u++],n=l[n],r.color.setHex(n),w.color.setHex(n));if(k)for(e=0;4>e;e++)n=h[u++],n=l[n],2!==e&&r.vertexColors.push(new G(n)),0!==e&&w.vertexColors.push(new G(n));c.faces.push(r);c.faces.push(w)}else{r=new Ta;r.a=h[u++];r.b=h[u++];r.c=h[u++];v&&(v=h[u++],r.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++)for(B=d.uvs[e],c.faceVertexUvs[e][v]=[],f=0;3>f;f++)E=h[u++],A=B[2*E],E=B[2*E+1],A=new z(A,E),c.faceVertexUvs[e][v].push(A);
18086 y&&(y=3*h[u++],r.normal.set(m[y++],m[y++],m[y]));if(x)for(e=0;3>e;e++)y=3*h[u++],x=new p(m[y++],m[y++],m[y]),r.vertexNormals.push(x);n&&(n=h[u++],r.color.setHex(l[n]));if(k)for(e=0;3>e;e++)n=h[u++],r.vertexColors.push(new G(l[n]));c.faces.push(r)}}d=a;u=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(g=0,h=d.skinWeights.length;g<h;g+=u)c.skinWeights.push(new V(d.skinWeights[g],1<u?d.skinWeights[g+1]:0,2<u?d.skinWeights[g+2]:0,3<u?d.skinWeights[g+3]:0));if(d.skinIndices)for(g=
18087 0,h=d.skinIndices.length;g<h;g+=u)c.skinIndices.push(new V(d.skinIndices[g],1<u?d.skinIndices[g+1]:0,2<u?d.skinIndices[g+2]:0,3<u?d.skinIndices[g+3]:0));c.bones=d.bones;c.bones&&0<c.bones.length&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+c.skinWeights.length+") should match.");g=a;h=g.scale;if(void 0!==g.morphTargets)for(d=
18088 0,u=g.morphTargets.length;d<u;d++)for(c.morphTargets[d]={},c.morphTargets[d].name=g.morphTargets[d].name,c.morphTargets[d].vertices=[],m=c.morphTargets[d].vertices,l=g.morphTargets[d].vertices,t=0,k=l.length;t<k;t+=3)n=new p,n.x=l[t]*h,n.y=l[t+1]*h,n.z=l[t+2]*h,m.push(n);if(void 0!==g.morphColors&&0<g.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),h=c.faces,g=g.morphColors[0].colors,d=0,u=h.length;d<u;d++)h[d].color.fromArray(g,
18089 3*d);g=a;d=[];u=[];void 0!==g.animation&&u.push(g.animation);void 0!==g.animations&&(g.animations.length?u=u.concat(g.animations):u.push(g.animations));for(g=0;g<u.length;g++)(h=Ca.parseAnimation(u[g],c.bones))&&d.push(h);c.morphTargets&&(u=Ca.CreateClipsFromMorphTargetSequences(c.morphTargets,10),d=d.concat(u));0<d.length&&(c.animations=d);c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===a.materials.length)return{geometry:c};a=gc.prototype.initMaterials(a.materials,b,
18090 this.crossOrigin);return{geometry:c,materials:a}}}()});Object.assign(mf.prototype,{crossOrigin:"anonymous",load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ga(e.manager)).load(a,function(c){var f=null;try{f=JSON.parse(c)}catch(h){void 0!==d&&d(h);console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=f.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?console.error("THREE.ObjectLoader: Can't load "+
18091 a+". Use THREE.JSONLoader instead."):e.parse(f,b)},c,d)},setTexturePath:function(a){this.texturePath=a;return this},setCrossOrigin:function(a){this.crossOrigin=a;return this},parse:function(a,b){var c=this.parseShape(a.shapes);c=this.parseGeometries(a.geometries,c);var d=this.parseImages(a.images,function(){void 0!==b&&b(e)});d=this.parseTextures(a.textures,d);d=this.parseMaterials(a.materials,d);var e=this.parseObject(a.object,c,d);a.animations&&(e.animations=this.parseAnimations(a.animations));
18092 void 0!==a.images&&0!==a.images.length||void 0===b||b(e);return e},parseShape:function(a){var b={};if(void 0!==a)for(var c=0,d=a.length;c<d;c++){var e=(new db).fromJSON(a[c]);b[e.uuid]=e}return b},parseGeometries:function(a,b){var c={};if(void 0!==a)for(var d=new he,e=new ge,f=0,g=a.length;f<g;f++){var h=a[f];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":var k=new xa[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":k=
18093 new xa[h.type](h.width,h.height,h.depth,h.widthSegments,h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":k=new xa[h.type](h.radius,h.segments,h.thetaStart,h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":k=new xa[h.type](h.radiusTop,h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":k=new xa[h.type](h.radius,h.height,h.radialSegments,
18094 h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":k=new xa[h.type](h.radius,h.widthSegments,h.heightSegments,h.phiStart,h.phiLength,h.thetaStart,h.thetaLength);break;case "DodecahedronGeometry":case "DodecahedronBufferGeometry":case "IcosahedronGeometry":case "IcosahedronBufferGeometry":case "OctahedronGeometry":case "OctahedronBufferGeometry":case "TetrahedronGeometry":case "TetrahedronBufferGeometry":k=new xa[h.type](h.radius,h.detail);
18095 break;case "RingGeometry":case "RingBufferGeometry":k=new xa[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":k=new xa[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":k=new xa[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":k=new xa[h.type](h.points,
18096 h.segments,h.phiStart,h.phiLength);break;case "PolyhedronGeometry":case "PolyhedronBufferGeometry":k=new xa[h.type](h.vertices,h.indices,h.radius,h.details);break;case "ShapeGeometry":case "ShapeBufferGeometry":k=[];for(var m=0,l=h.shapes.length;m<l;m++){var n=b[h.shapes[m]];k.push(n)}k=new xa[h.type](k,h.curveSegments);break;case "ExtrudeGeometry":case "ExtrudeBufferGeometry":k=[];m=0;for(l=h.shapes.length;m<l;m++)n=b[h.shapes[m]],k.push(n);m=h.options.extrudePath;void 0!==m&&(h.options.extrudePath=
18097 (new Af[m.type]).fromJSON(m));k=new xa[h.type](k,h.options);break;case "BufferGeometry":k=e.parse(h);break;case "Geometry":k=d.parse(h,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+h.type+'"');continue}k.uuid=h.uuid;void 0!==h.name&&(k.name=h.name);!0===k.isBufferGeometry&&void 0!==h.userData&&(k.userData=h.userData);c[h.uuid]=k}return c},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Kd;d.setTextures(b);b=0;for(var e=a.length;b<
18098 e;b++){var f=a[b];if("MultiMaterial"===f.type){for(var g=[],h=0;h<f.materials.length;h++)g.push(d.parse(f.materials[h]));c[f.uuid]=g}else c[f.uuid]=d.parse(f)}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c],e=Ca.parse(d);void 0!==d.uuid&&(e.uuid=d.uuid);b.push(e)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return f.load(a,function(){d.manager.itemEnd(a)},void 0,function(){d.manager.itemEnd(a);d.manager.itemError(a)})}var d=this,e={};
18099 if(void 0!==a&&0<a.length){b=new ce(b);var f=new Zc(b);f.setCrossOrigin(this.crossOrigin);b=0;for(var g=a.length;b<g;b++){var h=a[b],k=h.url;if(Array.isArray(k)){e[h.uuid]=[];for(var m=0,l=k.length;m<l;m++){var n=k[m];n=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(n)?n:d.texturePath+n;e[h.uuid].push(c(n))}}else n=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(h.url)?h.url:d.texturePath+h.url,e[h.uuid]=c(n)}}return e},parseTextures:function(a,b){function c(a,b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",
18100 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=Array.isArray(b[g.image])?new Ua(b[g.image]):new T(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,Wg));void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);
18101 void 0!==g.center&&h.center.fromArray(g.center);void 0!==g.rotation&&(h.rotation=g.rotation);void 0!==g.wrap&&(h.wrapS=c(g.wrap[0],Cf),h.wrapT=c(g.wrap[1],Cf));void 0!==g.format&&(h.format=g.format);void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,Df));void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,Df));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(a,b,c){function d(a){void 0===b[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",
18102 a);return b[a]}function e(a){if(void 0!==a){if(Array.isArray(a)){for(var b=[],d=0,e=a.length;d<e;d++){var f=a[d];void 0===c[f]&&console.warn("THREE.ObjectLoader: Undefined material",f);b.push(c[f])}return b}void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined material",a);return c[a]}}switch(a.type){case "Scene":var f=new qd;void 0!==a.background&&Number.isInteger(a.background)&&(f.background=new G(a.background));void 0!==a.fog&&("Fog"===a.fog.type?f.fog=new Mb(a.fog.color,a.fog.near,a.fog.far):
18103 "FogExp2"===a.fog.type&&(f.fog=new Lb(a.fog.color,a.fog.density)));break;case "PerspectiveCamera":f=new Z(a.fov,a.aspect,a.near,a.far);void 0!==a.focus&&(f.focus=a.focus);void 0!==a.zoom&&(f.zoom=a.zoom);void 0!==a.filmGauge&&(f.filmGauge=a.filmGauge);void 0!==a.filmOffset&&(f.filmOffset=a.filmOffset);void 0!==a.view&&(f.view=Object.assign({},a.view));break;case "OrthographicCamera":f=new Hb(a.left,a.right,a.top,a.bottom,a.near,a.far);void 0!==a.zoom&&(f.zoom=a.zoom);void 0!==a.view&&(f.view=Object.assign({},
18104 a.view));break;case "AmbientLight":f=new Cd(a.color,a.intensity);break;case "DirectionalLight":f=new Bd(a.color,a.intensity);break;case "PointLight":f=new zd(a.color,a.intensity,a.distance,a.decay);break;case "RectAreaLight":f=new Dd(a.color,a.intensity,a.width,a.height);break;case "SpotLight":f=new yd(a.color,a.intensity,a.distance,a.angle,a.penumbra,a.decay);break;case "HemisphereLight":f=new wd(a.color,a.groundColor,a.intensity);break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.");
18105 case "Mesh":f=d(a.geometry);var g=e(a.material);f=f.bones&&0<f.bones.length?new sd(f,g):new la(f,g);break;case "LOD":f=new Bc;break;case "Line":f=new sa(d(a.geometry),e(a.material),a.mode);break;case "LineLoop":f=new td(d(a.geometry),e(a.material));break;case "LineSegments":f=new W(d(a.geometry),e(a.material));break;case "PointCloud":case "Points":f=new Ob(d(a.geometry),e(a.material));break;case "Sprite":f=new Ac(e(a.material));break;case "Group":f=new Kb;break;default:f=new D}f.uuid=a.uuid;void 0!==
18106 a.name&&(f.name=a.name);void 0!==a.matrix?(f.matrix.fromArray(a.matrix),void 0!==a.matrixAutoUpdate&&(f.matrixAutoUpdate=a.matrixAutoUpdate),f.matrixAutoUpdate&&f.matrix.decompose(f.position,f.quaternion,f.scale)):(void 0!==a.position&&f.position.fromArray(a.position),void 0!==a.rotation&&f.rotation.fromArray(a.rotation),void 0!==a.quaternion&&f.quaternion.fromArray(a.quaternion),void 0!==a.scale&&f.scale.fromArray(a.scale));void 0!==a.castShadow&&(f.castShadow=a.castShadow);void 0!==a.receiveShadow&&
18107 (f.receiveShadow=a.receiveShadow);a.shadow&&(void 0!==a.shadow.bias&&(f.shadow.bias=a.shadow.bias),void 0!==a.shadow.radius&&(f.shadow.radius=a.shadow.radius),void 0!==a.shadow.mapSize&&f.shadow.mapSize.fromArray(a.shadow.mapSize),void 0!==a.shadow.camera&&(f.shadow.camera=this.parseObject(a.shadow.camera)));void 0!==a.visible&&(f.visible=a.visible);void 0!==a.frustumCulled&&(f.frustumCulled=a.frustumCulled);void 0!==a.renderOrder&&(f.renderOrder=a.renderOrder);void 0!==a.userData&&(f.userData=a.userData);
18108 void 0!==a.layers&&(f.layers.mask=a.layers);if(void 0!==a.children){g=a.children;for(var h=0;h<g.length;h++)f.add(this.parseObject(g[h],b,c))}if("LOD"===a.type)for(a=a.levels,g=0;g<a.length;g++){h=a[g];var k=f.getObjectByProperty("uuid",h.object);void 0!==k&&f.addLevel(k,h.distance)}return f}});var Wg={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,
18109 CubeUVRefractionMapping:307},Cf={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},Df={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008};ie.prototype={constructor:ie,setOptions:function(a){this.options=a;return this},load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var e=this,f=Fb.get(a);if(void 0!==f)return e.manager.itemStart(a),
18110 setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;fetch(a).then(function(a){return a.blob()}).then(function(a){return createImageBitmap(a,e.options)}).then(function(c){Fb.add(a,c);b&&b(c);e.manager.itemEnd(a)}).catch(function(b){d&&d(b);e.manager.itemEnd(a);e.manager.itemError(a)})},setCrossOrigin:function(){return this},setPath:function(a){this.path=a;return this}};Object.assign(je.prototype,{moveTo:function(a,b){this.currentPath=new La;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,
18111 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,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 db;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)>
18112 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<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Va.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);b=[];if(1===f.length){var g=f[0];var h=new db;h.curves=g.curves;b.push(h);return b}var k=!e(f[0].getPoints());k=a?!k:k;h=[];var m=[],l=[],n=0;m[n]=void 0;l[n]=[];for(var p=
18113 0,u=f.length;p<u;p++){g=f[p];var r=g.getPoints();var v=e(r);(v=a?!v:v)?(!k&&m[n]&&n++,m[n]={s:new db,p:r},m[n].s.curves=g.curves,k&&n++,l[n]=[]):l[n].push({h:g,p:r[0]})}if(!m[0])return c(f);if(1<m.length){p=!1;a=[];e=0;for(f=m.length;e<f;e++)h[e]=[];e=0;for(f=m.length;e<f;e++)for(g=l[e],v=0;v<g.length;v++){k=g[v];n=!0;for(r=0;r<m.length;r++)d(k.p,m[r].p)&&(e!==r&&a.push({froms:e,tos:r,hole:v}),n?(n=!1,h[r].push(k)):p=!0);n&&h[e].push(k)}0<a.length&&(p||(l=h))}p=0;for(e=m.length;p<e;p++)for(h=m[p].s,
18114 b.push(h),a=l[p],f=0,g=a.length;f<g;f++)h.holes.push(a[f].h);return b}});Object.assign(ke.prototype,{isFont:!0,generateShapes:function(a,b){void 0===b&&(b=100);var c=[],d=b;b=this.data;var e=Array.from?Array.from(a):String(a).split("");d/=b.resolution;var f=(b.boundingBox.yMax-b.boundingBox.yMin+b.underlineThickness)*d;a=[];for(var g=0,h=0,k=0;k<e.length;k++){var m=e[k];if("\n"===m)g=0,h-=f;else{var l=d;var n=g,p=h;if(m=b.glyphs[m]||b.glyphs["?"]){var u=new je;if(m.o)for(var r=m._cachedOutline||(m._cachedOutline=
18115 m.o.split(" ")),v=0,y=r.length;v<y;)switch(r[v++]){case "m":var x=r[v++]*l+n;var w=r[v++]*l+p;u.moveTo(x,w);break;case "l":x=r[v++]*l+n;w=r[v++]*l+p;u.lineTo(x,w);break;case "q":var z=r[v++]*l+n;var A=r[v++]*l+p;var C=r[v++]*l+n;var D=r[v++]*l+p;u.quadraticCurveTo(C,D,z,A);break;case "b":z=r[v++]*l+n,A=r[v++]*l+p,C=r[v++]*l+n,D=r[v++]*l+p,x=r[v++]*l+n,w=r[v++]*l+p,u.bezierCurveTo(C,D,x,w,z,A)}l={offsetX:m.ha*l,path:u}}else l=void 0;g+=l.offsetX;a.push(l.path)}}b=0;for(e=a.length;b<e;b++)Array.prototype.push.apply(c,
18116 a[b].toShapes());return c}});Object.assign(nf.prototype,{load:function(a,b,c,d){var e=this,f=new Ga(this.manager);f.setPath(this.path);f.load(a,function(a){try{var c=JSON.parse(a)}catch(k){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 ke(a)},setPath:function(a){this.path=a;return this}});var Pd,ne={getContext:function(){void 0===Pd&&(Pd=new (window.AudioContext||
18117 window.webkitAudioContext));return Pd},setContext:function(a){Pd=a}};Object.assign(le.prototype,{load:function(a,b,c,d){var e=new Ga(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){a=a.slice(0);ne.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Object.assign(of.prototype,{update:function(){var a,b,c,d,e,f,g,h,k=new I,l=new I;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||h!==this.eyeSep){a=this;b=
18118 m.focus;c=m.fov;d=m.aspect*this.aspect;e=m.near;f=m.far;g=m.zoom;var n=m.projectionMatrix.clone();h=this.eyeSep/2;var p=h*e/b,q=e*Math.tan(H.DEG2RAD*c*.5)/g;l.elements[12]=-h;k.elements[12]=h;var r=-q*d+p;var v=q*d+p;n.elements[0]=2*e/(v-r);n.elements[8]=(v+r)/(v-r);this.cameraL.projectionMatrix.copy(n);r=-q*d-p;v=q*d-p;n.elements[0]=2*e/(v-r);n.elements[8]=(v+r)/(v-r);this.cameraR.projectionMatrix.copy(n)}this.cameraL.matrixWorld.copy(m.matrixWorld).multiply(l);this.cameraR.matrixWorld.copy(m.matrixWorld).multiply(k)}}()});
18119 dd.prototype=Object.create(D.prototype);dd.prototype.constructor=dd;me.prototype=Object.assign(Object.create(D.prototype),{constructor:me,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);return this},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):
18120 this.gain.disconnect(this.context.destination);this.filter=a;this.gain.connect(this.filter);this.filter.connect(this.context.destination);return this},getMasterVolume:function(){return this.gain.gain.value},setMasterVolume:function(a){this.gain.gain.setTargetAtTime(a,this.context.currentTime,.01);return this},updateMatrixWorld:function(){var a=new p,b=new fa,c=new p,d=new p;return function(e){D.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,
18121 b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,this.context.currentTime),e.positionY.setValueAtTime(a.y,this.context.currentTime),e.positionZ.setValueAtTime(a.z,this.context.currentTime),e.forwardX.setValueAtTime(d.x,this.context.currentTime),e.forwardY.setValueAtTime(d.y,this.context.currentTime),e.forwardZ.setValueAtTime(d.z,this.context.currentTime),e.upX.setValueAtTime(f.x,this.context.currentTime),e.upY.setValueAtTime(f.y,this.context.currentTime),e.upZ.setValueAtTime(f.z,
18122 this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,d.y,d.z,f.x,f.y,f.z))}}()});hc.prototype=Object.assign(Object.create(D.prototype),{constructor:hc,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setMediaElementSource:function(a){this.hasPlaybackControl=!1;this.sourceType="mediaNode";this.source=this.context.createMediaElementSource(a);this.connect();return this},
18123 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.");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);this.startTime=this.context.currentTime;
18124 a.start(this.startTime,this.offset);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!0===this.isPlaying&&(this.source.stop(),this.source.onended=null,this.offset+=(this.context.currentTime-this.startTime)*this.playbackRate,this.isPlaying=!1),this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),
18125 this.source.onended=null,this.offset=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-1].disconnect(this.filters[a]);
18126 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.");
18127 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=
18128 a,!0===this.isPlaying&&(this.source.loop=this.loop),this},getVolume:function(){return this.gain.gain.value},setVolume:function(a){this.gain.gain.setTargetAtTime(a,this.context.currentTime,.01);return this}});oe.prototype=Object.assign(Object.create(hc.prototype),{constructor:oe,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=a;return this},getRolloffFactor:function(){return this.panner.rolloffFactor},
18129 setRolloffFactor:function(a){this.panner.rolloffFactor=a;return this},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=a;return this},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a;return this},setDirectionalCone:function(a,b,c){this.panner.coneInnerAngle=a;this.panner.coneOuterAngle=b;this.panner.coneOuterGain=c;return this},updateMatrixWorld:function(){var a=new p,
18130 b=new fa,c=new p,d=new p;return function(e){D.prototype.updateMatrixWorld.call(this,e);e=this.panner;this.matrixWorld.decompose(a,b,c);d.set(0,0,1).applyQuaternion(b);e.setPosition(a.x,a.y,a.z);e.setOrientation(d.x,d.y,d.z)}}()});Object.assign(pe.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);return this.data},getAverageFrequency:function(){for(var a=0,b=this.getFrequencyData(),c=0;c<b.length;c++)a+=b[c];return a/b.length}});Object.assign(qe.prototype,{accumulate:function(a,
18131 b){var c=this.buffer,d=this.valueSize;a=a*d+d;var e=this.cumulativeWeight;if(0===e){for(e=0;e!==d;++e)c[a+e]=c[e];e=b}else e+=b,this._mixBufferRegion(c,a,0,b/e,d);this.cumulativeWeight=e},apply:function(a){var b=this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&this._mixBufferRegion(c,a,3*b,1-d,b);d=b;for(var 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,
18132 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){fa.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(pf.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,
18133 b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(pa,{Composite:pf,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new pa.Composite(a,b,c):new pa(a,b,c)},sanitizeNodeName:function(){var a=
18134 /[\[\]\.:\/]/g;return function(b){return b.replace(/\s/g,"_").replace(a,"")}}(),parseTrackName:function(){var a="[^"+"\\[\\]\\.:\\/".replace("\\.","")+"]",b=/((?:WC+[\/:])*)/.source.replace("WC","[^\\[\\]\\.:\\/]");a=/(WCOD+)?/.source.replace("WCOD",a);var c=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC","[^\\[\\]\\.:\\/]"),d=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC","[^\\[\\]\\.:\\/]"),e=new RegExp("^"+b+a+c+d+"$"),f=["material","materials","bones"];return function(a){var b=e.exec(a);if(!b)throw Error("PropertyBinding: Cannot parse trackName: "+
18135 a);b={nodeName:b[2],objectName:b[3],objectIndex:b[4],propertyName:b[5],propertyIndex:b[6]};var c=b.nodeName&&b.nodeName.lastIndexOf(".");if(void 0!==c&&-1!==c){var d=b.nodeName.substring(c+1);-1!==f.indexOf(d)&&(b.nodeName=b.nodeName.substring(0,c),b.objectName=d)}if(null===b.propertyName||0===b.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+a);return b}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;
18136 if(a.skeleton){var c=a.skeleton.getBoneByName(b);if(void 0!==c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var e=a[c];if(e.name===b||e.uuid===b||(e=d(e.children)))return e}return null};if(a=d(a.children))return a}return null}});Object.assign(pa.prototype,{_getValue_unavailable:function(){},_setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,
18137 b){a[b]=this.node[this.propertyName]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.targetObject[this.propertyName]=a[b]},function(a,b){this.targetObject[this.propertyName]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.targetObject[this.propertyName]=a[b];this.targetObject.matrixWorldNeedsUpdate=
18138 !0}],[function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.needsUpdate=!0},function(a,
18139 b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.matrixWorldNeedsUpdate=!0}]],getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=this.node,b=this.parsedPath,c=b.objectName,
18140 d=b.propertyName,e=b.propertyIndex;a||(this.node=a=pa.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("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!a.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",
18141 this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error("THREE.PropertyBinding: 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("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}a=a[c]}if(void 0!==f){if(void 0===a[f]){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",
18142 this,a);return}a=a[f]}}f=a[d];if(void 0===f)console.error("THREE.PropertyBinding: 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"===d){if(!a.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",
18143 this);return}if(a.geometry.isBufferGeometry){if(!a.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}for(c=0;c<this.node.geometry.morphAttributes.position.length;c++)if(a.geometry.morphAttributes.position[c].name===e){e=c;break}}else{if(!a.geometry.morphTargets){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.",
18144 this);return}for(c=0;c<this.node.geometry.morphTargets.length;c++)if(a.geometry.morphTargets[c].name===e){e=c;break}}}c=this.BindingType.ArrayElement;this.resolvedProperty=f;this.propertyIndex=e}else void 0!==f.fromArray&&void 0!==f.toArray?(c=this.BindingType.HasFromToArray,this.resolvedProperty=f):Array.isArray(f)?(c=this.BindingType.EntireArray,this.resolvedProperty=f):this.propertyName=d;this.getValue=this.GetterByBindingType[c];this.setValue=this.SetterByBindingTypeAndVersioning[c][b]}}else console.error("THREE.PropertyBinding: Trying to update node for track: "+
18145 this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(pa.prototype,{_getValue_unbound:pa.prototype.getValue,_setValue_unbound:pa.prototype.setValue});Object.assign(qf.prototype,{isAnimationObjectGroup:!0,add:function(){for(var a=this._objects,b=a.length,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._paths,f=this._parsedPaths,g=this._bindings,h=g.length,k=void 0,l=0,p=arguments.length;l!==
18146 p;++l){var n=arguments[l],t=n.uuid,u=d[t];if(void 0===u){u=b++;d[t]=u;a.push(n);t=0;for(var r=h;t!==r;++t)g[t].push(new pa(n,e[t],f[t]))}else if(u<c){k=a[u];var v=--c;r=a[v];d[r.uuid]=u;a[u]=r;d[t]=v;a[v]=n;t=0;for(r=h;t!==r;++t){var y=g[t],x=y[u];y[u]=y[v];void 0===x&&(x=new pa(n,e[t],f[t]));y[v]=x}}else a[u]!==k&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=
18147 c},remove:function(){for(var a=this._objects,b=this.nCachedObjects_,c=this._indicesByUUID,d=this._bindings,e=d.length,f=0,g=arguments.length;f!==g;++f){var h=arguments[f],k=h.uuid,l=c[k];if(void 0!==l&&l>=b){var p=b++,n=a[p];c[n.uuid]=l;a[l]=n;c[k]=p;a[p]=h;h=0;for(k=e;h!==k;++h){n=d[h];var t=n[l];n[l]=n[p];n[p]=t}}}this.nCachedObjects_=b},uncache:function(){for(var a=this._objects,b=a.length,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._bindings,f=e.length,g=0,h=arguments.length;g!==h;++g){var k=
18148 arguments[g].uuid,l=d[k];if(void 0!==l)if(delete d[k],l<c){k=--c;var p=a[k],n=--b,t=a[n];d[p.uuid]=l;a[l]=p;d[t.uuid]=k;a[k]=t;a.pop();p=0;for(t=f;p!==t;++p){var u=e[p],r=u[n];u[l]=u[k];u[k]=r;u.pop()}}else for(n=--b,t=a[n],d[t.uuid]=l,a[l]=t,a.pop(),p=0,t=f;p!==t;++p)u=e[p],u[l]=u[n],u.pop()}this.nCachedObjects_=c},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_,
18149 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 pa(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=this._bindings,g=f.length-1,h=f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}});Object.assign(rf.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},
18150 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&&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;
18151 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,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;
18152 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},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,
18153 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=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||
18154 this._mixer._root},_update:function(a,b,c,d){if(this.enabled){var e=this._startTime;if(null!==e){b=(a-e)*c;if(0>b||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0<a){b=this._interpolants;e=this._propertyBindings;for(var f=0,g=b.length;f!==g;++f)b[f].evaluate(c),e[f].accumulate(d,a)}}else this._updateWeight(a)},_updateWeight:function(a){var b=0;if(this.enabled){b=this.weight;var c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0];
18155 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){b=this.timeScale;var c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0];b*=d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a,c=this._clip.duration,d=this.loop,e=this._loopCount,f=2202===d;if(0===a)return-1===
18156 e?b:f&&1===(e&1)?c-b:b;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{-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,f)):this._setEndings(0===this.repetitions,!0,f));if(b>=c||0>b){d=Math.floor(b/c);b-=c*d;e+=Math.abs(d);var g=this.repetitions-e;0>=g?(this.clampWhenFinished?this.paused=!0:
18157 this.enabled=!1,b=0<a?c:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:0<a?1:-1})):(1===g?(a=0>a,this._setEndings(a,!a,f)):this._setEndings(!1,!1,f),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:d}))}if(f&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:
18158 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}});re.prototype=Object.assign(Object.create(ya.prototype),{constructor:re,_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings;a=a._interpolants;var g=c.uuid,h=this._bindingsByRootAndName,k=h[g];void 0===
18159 k&&(k={},h[g]=k);for(h=0;h!==e;++h){var l=d[h],p=l.name,n=k[p];if(void 0===n){n=f[h];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,g,p));continue}n=new qe(pa.create(c,p,b&&b._propertyBindings[h].binding.parsedPath),l.ValueTypeName,l.getValueSize());++n.referenceCount;this._addInactiveBinding(n,g,p)}f[h]=n;a[h].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,
18160 d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_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=
18161 [];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},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}}}},
18162 _isActiveAction:function(a){a=a._cacheIndex;return null!==a&&a<this._nActiveActions},_addInactiveAction:function(a,b,c){var d=this._actions,e=this._actionsByClip,f=e[b];void 0===f?(f={knownActions:[a],actionByRoot:{}},a._byClipCacheIndex=0,e[b]=f):(b=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;b=a._clip.uuid;
18163 c=this._actionsByClip;d=c[b];var e=d.knownActions,f=e[e.length-1],g=a._byClipCacheIndex;f._byClipCacheIndex=g;e[g]=f;e.pop();a._byClipCacheIndex=null;delete d.actionByRoot[(a._localRoot||this._root).uuid];0===e.length&&delete c[b];this._removeInactiveBindingsForAction(a)},_removeInactiveBindingsForAction:function(a){a=a._propertyBindings;for(var b=0,c=a.length;b!==c;++b){var d=a[b];0===--d.referenceCount&&this._removeInactiveBinding(d)}},_lendAction:function(a){var b=this._actions,c=a._cacheIndex,
18164 d=this._nActiveActions++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=this._actions,c=a._cacheIndex,d=--this._nActiveActions,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_addInactiveBinding:function(a,b,c){var d=this._bindingsByRootAndName,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;var e=this._bindingsByRootAndName,
18165 f=e[d],g=b[b.length-1];a=a._cacheIndex;g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;delete e[d]}},_lendBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=this._nActiveBindings++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackBinding:function(a){var b=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++,
18166 c=a[b];void 0===c&&(c=new bd(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=d;b[d]=a;e.__cacheIndex=c;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid;c="string"===typeof a?Ca.findByName(c,a):a;a=null!==c?c.uuid:a;var e=
18167 this._actionsByClip[a],f=null;if(void 0!==e){f=e.actionByRoot[d];if(void 0!==f)return f;f=e.knownActions[0];null===c&&(c=f._clip)}if(null===c)return null;b=new rf(this,c,b);this._bindAction(b,f);this._addInactiveAction(b,a,d);return b},existingAction:function(a,b){var c=b||this._root;b=c.uuid;c="string"===typeof a?Ca.findByName(c,a):a;a=this._actionsByClip[c?c.uuid:a];return void 0!==a?a.actionByRoot[b]||null:null},stopAllAction:function(){for(var a=this._actions,b=this._nActiveActions,c=this._bindings,
18168 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)b[g]._update(d,a,e,f);a=this._bindings;b=this._nActiveBindings;for(g=0;g!==b;++g)a[g].apply(f);return this},getRoot:function(){return this._root},uncacheClip:function(a){var b=this._actions;a=a.uuid;var c=this._actionsByClip,
18169 d=c[a];if(void 0!==d){d=d.knownActions;for(var 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;for(d in b){var c=b[d].actionByRoot[a];void 0!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}var d=this._bindingsByRootAndName[a];if(void 0!==d)for(var e in d)a=
18170 d[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){a=this.existingAction(a,b);null!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}});Ld.prototype.clone=function(){return new Ld(void 0===this.value.clone?this.value:this.value.clone())};se.prototype=Object.assign(Object.create(C.prototype),{constructor:se,isInstancedBufferGeometry:!0,copy:function(a){C.prototype.copy.call(this,a);this.maxInstancedCount=a.maxInstancedCount;return this},clone:function(){return(new this.constructor).copy(this)}});
18171 te.prototype=Object.assign(Object.create(ob.prototype),{constructor:te,isInstancedInterleavedBuffer:!0,copy:function(a){ob.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});ue.prototype=Object.assign(Object.create(Q.prototype),{constructor:ue,isInstancedBufferAttribute:!0,copy:function(a){Q.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});Object.assign(sf.prototype,{linePrecision:1,set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,
18172 b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b,c){c=c||[];ve(a,this,c,b);c.sort(tf);return c},intersectObjects:function(a,b,c){c=c||
18173 [];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++)ve(a[d],this,c,b);c.sort(tf);return c}});Object.assign(uf.prototype,{start:function(){this.oldTime=this.startTime=("undefined"===typeof performance?Date:performance).now();this.elapsedTime=0;this.running=!0},stop:function(){this.getElapsedTime();this.autoStart=this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=
18174 0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){var b=("undefined"===typeof performance?Date:performance).now();a=(b-this.oldTime)/1E3;this.oldTime=b;this.elapsedTime+=a}return a}});Object.assign(vf.prototype,{set:function(a,b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=Math.max(1E-6,Math.min(Math.PI-
18175 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(H.clamp(a.y/this.radius,-1,1)));return this}});Object.assign(wf.prototype,{set:function(a,b,c){this.radius=a;this.theta=b;this.y=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.theta=a.theta;this.y=a.y;return this},setFromVector3:function(a){this.radius=Math.sqrt(a.x*
18176 a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});Object.assign(we.prototype,{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 z;return function(b,c){c=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(c);this.max.copy(b).add(c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);
18177 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){void 0===a&&(console.warn("THREE.Box2: .getCenter() target is now required"),a=new z);return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){void 0===a&&(console.warn("THREE.Box2: .getSize() target is now required"),a=new z);return this.isEmpty()?
18178 a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y},getParameter:function(a,
18179 b){void 0===b&&(console.warn("THREE.Box2: .getParameter() target is now required"),b=new z);return b.set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y?!1:!0},clampPoint:function(a,b){void 0===b&&(console.warn("THREE.Box2: .clampPoint() target is now required"),b=new z);return b.copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new z;
18180 return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(xe.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},
18181 copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},getCenter:function(a){void 0===a&&(console.warn("THREE.Line3: .getCenter() target is now required"),a=new p);return a.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){void 0===a&&(console.warn("THREE.Line3: .delta() target is now required"),a=new p);return a.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},
18182 at:function(a,b){void 0===b&&(console.warn("THREE.Line3: .at() target is now required"),b=new p);return this.delta(b).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new p,b=new p;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);c=b.dot(b);c=b.dot(a)/c;d&&(c=H.clamp(c,0,1));return c}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);void 0===c&&(console.warn("THREE.Line3: .closestPointToPoint() target is now required"),
18183 c=new p);return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});ed.prototype=Object.create(D.prototype);ed.prototype.constructor=ed;ed.prototype.isImmediateRenderObject=!0;fd.prototype=Object.create(W.prototype);fd.prototype.constructor=fd;fd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){var d=["a","b",
18184 "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,p=k.length;l<p;l++)for(var n=k[l],t=0,u=n.vertexNormals.length;t<u;t++){var r=n.vertexNormals[t];a.copy(h[n[d[t]]]).applyMatrix4(e);b.copy(r).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=
18185 g.attributes.position,h=g.attributes.normal,t=g=0,u=d.count;t<u;t++)a.set(d.getX(t),d.getY(t),d.getZ(t)).applyMatrix4(e),b.set(h.getX(t),h.getY(t),h.getZ(t)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),f.setXYZ(g,a.x,a.y,a.z),g+=1,f.setXYZ(g,b.x,b.y,b.z),g+=1;f.needsUpdate=!0}}();ic.prototype=Object.create(D.prototype);ic.prototype.constructor=ic;ic.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};ic.prototype.update=function(){var a=new p,
18186 b=new p;return function(){this.light.updateMatrixWorld();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));void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}();jc.prototype=Object.create(W.prototype);jc.prototype.constructor=jc;jc.prototype.updateMatrixWorld=
18187 function(){var a=new p,b=new I,c=new I;return function(d){var e=this.bones,f=this.geometry,g=f.getAttribute("position");c.getInverse(this.root.matrixWorld);for(var h=0,k=0;h<e.length;h++){var l=e[h];l.parent&&l.parent.isBone&&(b.multiplyMatrices(c,l.matrixWorld),a.setFromMatrixPosition(b),g.setXYZ(k,a.x,a.y,a.z),b.multiplyMatrices(c,l.parent.matrixWorld),a.setFromMatrixPosition(b),g.setXYZ(k+1,a.x,a.y,a.z),k+=2)}f.getAttribute("position").needsUpdate=!0;D.prototype.updateMatrixWorld.call(this,d)}}();
18188 kc.prototype=Object.create(la.prototype);kc.prototype.constructor=kc;kc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};kc.prototype.update=function(){void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)};lc.prototype=Object.create(D.prototype);lc.prototype.constructor=lc;lc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};lc.prototype.update=function(){var a=.5*this.light.width,
18189 b=.5*this.light.height,c=this.line.geometry.attributes.position,d=c.array;d[0]=a;d[1]=-b;d[2]=0;d[3]=a;d[4]=b;d[5]=0;d[6]=-a;d[7]=b;d[8]=0;d[9]=-a;d[10]=-b;d[11]=0;d[12]=a;d[13]=-b;d[14]=0;c.needsUpdate=!0;void 0!==this.color?this.line.material.color.set(this.color):this.line.material.color.copy(this.light.color)};mc.prototype=Object.create(D.prototype);mc.prototype.constructor=mc;mc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};mc.prototype.update=
18190 function(){var a=new p,b=new G,c=new G;return function(){var d=this.children[0];if(void 0!==this.color)this.material.color.set(this.color);else{var e=d.geometry.getAttribute("color");b.copy(this.light.color);c.copy(this.light.groundColor);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)}e.needsUpdate=!0}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate())}}();gd.prototype=Object.create(W.prototype);gd.prototype.constructor=gd;Md.prototype=Object.create(W.prototype);
18191 Md.prototype.constructor=Md;hd.prototype=Object.create(W.prototype);hd.prototype.constructor=hd;hd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices;f=f.faces;for(var h=0,k=0,l=f.length;k<l;k++){var p=f[k],n=p.normal;a.copy(g[p.a]).add(g[p.b]).add(g[p.c]).divideScalar(3).applyMatrix4(d);b.copy(n).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);
18192 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}}();nc.prototype=Object.create(D.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){this.lightPlane.geometry.dispose();this.lightPlane.material.dispose();this.targetLine.geometry.dispose();this.targetLine.material.dispose()};nc.prototype.update=function(){var a=new p,b=new p,c=new p;return function(){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);c.subVectors(b,
18193 a);this.lightPlane.lookAt(c);void 0!==this.color?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color));this.targetLine.lookAt(c);this.targetLine.scale.z=c.length()}}();id.prototype=Object.create(W.prototype);id.prototype.constructor=id;id.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=b.getAttribute("position"),
18194 h=0,k=a.length;h<k;h++)g.setXYZ(a[h],d.x,d.y,d.z)}var b,c,d=new p,e=new Na;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",-1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",
18195 0,1,-1);b.getAttribute("position").needsUpdate=!0}}();Db.prototype=Object.create(W.prototype);Db.prototype.constructor=Db;Db.prototype.update=function(){var a=new Sa;return function(b){void 0!==b&&console.warn("THREE.BoxHelper: .update() has no longer arguments.");void 0!==this.object&&a.setFromObject(this.object);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,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]=
18196 c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}();Db.prototype.setFromObject=function(a){this.object=a;this.update();return this};jd.prototype=Object.create(W.prototype);jd.prototype.constructor=jd;jd.prototype.updateMatrixWorld=function(a){var b=this.box;b.isEmpty()||(b.getCenter(this.position),b.getSize(this.scale),this.scale.multiplyScalar(.5),D.prototype.updateMatrixWorld.call(this,
18197 a))};kd.prototype=Object.create(sa.prototype);kd.prototype.constructor=kd;kd.prototype.updateMatrixWorld=function(a){var b=-this.plane.constant;1E-8>Math.abs(b)&&(b=1E-8);this.scale.set(.5*this.size,.5*this.size,b);this.children[0].material.side=0>b?1:0;this.lookAt(this.plane.normal);D.prototype.updateMatrixWorld.call(this,a)};var Nd,ye;Eb.prototype=Object.create(D.prototype);Eb.prototype.constructor=Eb;Eb.prototype.setDirection=function(){var a=new p,b;return function(c){.99999<c.y?this.quaternion.set(0,
18198 0,0,1):-.99999>c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Eb.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()};Eb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};ld.prototype=Object.create(W.prototype);
18199 ld.prototype.constructor=ld;L.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(L.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};Object.assign(Xa.prototype,{createPointsGeometry:function(a){console.warn("THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){console.warn("THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");
18200 a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){console.warn("THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");for(var b=new R,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new p(e.x,e.y,e.z||0))}return b}});Object.assign(La.prototype,{fromPoints:function(a){console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints().");this.setFromPoints(a)}});yf.prototype=Object.create(ca.prototype);
18201 zf.prototype=Object.create(ca.prototype);ze.prototype=Object.create(ca.prototype);Object.assign(ze.prototype,{initFromArray:function(){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},reparametrizeByArcLength:function(){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});gd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};
18202 jc.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};Object.assign(gc.prototype,{extractUrlBase:function(a){console.warn("THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.");return De.extractUrlBase(a)}});Object.assign(we.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().");
18203 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(Sa.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().");
18204 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)}});xe.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");
18205 return this.getCenter(a)};Object.assign(H,{random16:function(){console.warn("THREE.Math: .random16() has been deprecated. Use Math.random() instead.");return Math.random()},nearestPowerOfTwo:function(a){console.warn("THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().");return H.floorPowerOfTwo(a)},nextPowerOfTwo:function(a){console.warn("THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().");return H.ceilPowerOfTwo(a)}});Object.assign(ra.prototype,{flattenToArrayOffset:function(a,
18206 b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},multiplyVector3Array:function(){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},applyToBuffer:function(a){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
18207 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(I.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");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;
18208 return function(){void 0===a&&(a=new p);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");return a.setFromMatrixColumn(this,3)}}(),setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyToArray:function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.");
18209 return a.applyMatrix4(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector3Array:function(){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},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.");
18210 return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},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){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
18211 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},makeFrustum:function(a,b,c,d,e,f){console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.");return this.makePerspective(a,b,d,c,e,f)}});Ma.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};
18212 fa.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(mb.prototype,{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},
18213 isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(ja.prototype,{area:function(){console.warn("THREE.Triangle: .area() has been renamed to .getArea().");return this.getArea()},barycoordFromPoint:function(a,b){console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().");return this.getBarycoord(a,b)},midpoint:function(a){console.warn("THREE.Triangle: .midpoint() has been renamed to .getMidpoint().");
18214 return this.getMidpoint(a)},normal:function(a){console.warn("THREE.Triangle: .normal() has been renamed to .getNormal().");return this.getNormal(a)},plane:function(a){console.warn("THREE.Triangle: .plane() has been renamed to .getPlane().");return this.getPlane(a)}});Object.assign(ja,{barycoordFromPoint:function(a,b,c,d,e){console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().");return ja.getBarycoord(a,b,c,d,e)},normal:function(a,b,c,d){console.warn("THREE.Triangle: .normal() has been renamed to .getNormal().");
18215 return ja.getNormal(a,b,c,d)}});Object.assign(db.prototype,{extractAllPoints:function(a){console.warn("THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.");return this.extractPoints(a)},extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new rb(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new tb(this,a)}});Object.assign(z.prototype,
18216 {fromAttribute:function(a,b,c){console.warn("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},distanceToManhattan:function(a){console.warn("THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().");return this.manhattanDistanceTo(a)},lengthManhattan:function(){console.warn("THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});Object.assign(p.prototype,
18217 {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().");
18218 return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b,a)},applyProjection:function(a){console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.");return this.applyMatrix4(a)},fromAttribute:function(a,b,c){console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,
18219 b,c)},distanceToManhattan:function(a){console.warn("THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().");return this.manhattanDistanceTo(a)},lengthManhattan:function(){console.warn("THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});Object.assign(V.prototype,{fromAttribute:function(a,b,c){console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,
18220 b,c)},lengthManhattan:function(){console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});Object.assign(R.prototype,{computeTangents:function(){console.error("THREE.Geometry: .computeTangents() has been removed.")},computeLineDistances:function(){console.error("THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.")}});Object.assign(D.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");
18221 return this.getObjectByName(a)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)},getWorldRotation:function(){console.error("THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.")}});Object.defineProperties(D.prototype,
18222 {eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});
18223 Object.defineProperties(Bc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(Cc.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(L.prototype,"__arcLengthDivisions",{get:function(){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");
18224 return this.arcLengthDivisions},set:function(a){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");this.arcLengthDivisions=a}});Z.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(X.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");
18225 this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");
18226 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.")}},shadowBias:{set:function(a){console.warn("THREE.Light: .shadowBias is now .shadow.bias.");
18227 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(Q.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");
18228 return this.array.length}},copyIndicesArray:function(){console.error("THREE.BufferAttribute: .copyIndicesArray() has been removed.")}});Object.assign(C.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,b,c){void 0!==c&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.");console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(a,b)},
18229 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(C.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.");
18230 return this.groups}}});Object.assign(Oa.prototype,{getArrays:function(){console.error("THREE.ExtrudeBufferGeometry: .getArrays() has been removed.")},addShapeList:function(){console.error("THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.")},addShape:function(){console.error("THREE.ExtrudeBufferGeometry: .addShape() has been removed.")}});Object.defineProperties(Ld.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},
18231 onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.");return this}}});Object.defineProperties(J.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new G}},shading:{get:function(){console.error("THREE."+this.type+
18232 ": .shading has been removed. Use the boolean .flatShading instead.")},set:function(a){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");this.flatShading=1===a}}});Object.defineProperties(Fa.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")}}});
18233 Object.defineProperties(ta.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Zd.prototype,{animate:function(a){console.warn("THREE.WebGLRenderer: .animate() is now .setAnimationLoop().");this.setAnimationLoop(a)},getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");
18234 return this.getRenderTarget()},getMaxAnisotropy:function(){console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().");return this.capabilities.getMaxAnisotropy()},getPrecision:function(){console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.");return this.capabilities.precision},resetGLState:function(){console.warn("THREE.WebGLRenderer: .resetGLState() is now .state.reset().");return this.state.reset()},supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");
18235 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' ).");
18236 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.");
18237 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.")},
18238 addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")},setFaceCulling:function(){console.warn("THREE.WebGLRenderer: .setFaceCulling() has been removed.")}});Object.defineProperties(Zd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");
18239 this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");this.shadowMap.type=a}},shadowMapCullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")}}});Object.defineProperties(Ze.prototype,
18240 {cullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")}},renderReverseSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")}},
18241 renderSingleSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")}}});Object.defineProperties(fb.prototype,{wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");
18242 this.texture.wrapS=a}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=a}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=
18243 a}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=a}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=
18244 a}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(a){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=a}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat},set:function(a){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=a}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");
18245 return this.texture.format},set:function(a){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=a}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(a){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},
18246 set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});Object.defineProperties(af.prototype,{standing:{set:function(){console.warn("THREE.WebVRManager: .standing has been removed.")}}});hc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new le).load(a,function(a){b.setBuffer(a)});return this};pe.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");
18247 return this.getFrequencyData()};dd.prototype.updateCubeMap=function(a,b){console.warn("THREE.CubeCamera: .updateCubeMap() is now .update().");return this.update(a,b)};eb.crossOrigin=void 0;eb.loadTexture=function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");var e=new vd;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a};eb.loadTextureCube=function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");
18248 var e=new ee;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a};eb.loadCompressedTexture=function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")};eb.loadCompressedTextureCube=function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")};l.WebGLRenderTargetCube=Gb;l.WebGLRenderTarget=fb;l.WebGLRenderer=Zd;l.ShaderLib=nb;l.UniformsLib=K;l.UniformsUtils=
18249 Aa;l.ShaderChunk=S;l.FogExp2=Lb;l.Fog=Mb;l.Scene=qd;l.Sprite=Ac;l.LOD=Bc;l.SkinnedMesh=sd;l.Skeleton=Cc;l.Bone=rd;l.Mesh=la;l.LineSegments=W;l.LineLoop=td;l.Line=sa;l.Points=Ob;l.Group=Kb;l.VideoTexture=$d;l.DataTexture=gb;l.CompressedTexture=Pb;l.CubeTexture=Ua;l.CanvasTexture=Dc;l.DepthTexture=Ec;l.Texture=T;l.CompressedTextureLoader=kf;l.DataTextureLoader=de;l.CubeTextureLoader=ee;l.TextureLoader=vd;l.ObjectLoader=mf;l.MaterialLoader=Kd;l.BufferGeometryLoader=ge;l.DefaultLoadingManager=ka;l.LoadingManager=
18250 ce;l.JSONLoader=he;l.ImageLoader=Zc;l.ImageBitmapLoader=ie;l.FontLoader=nf;l.FileLoader=Ga;l.Loader=gc;l.LoaderUtils=De;l.Cache=Fb;l.AudioLoader=le;l.SpotLightShadow=xd;l.SpotLight=yd;l.PointLight=zd;l.RectAreaLight=Dd;l.HemisphereLight=wd;l.DirectionalLightShadow=Ad;l.DirectionalLight=Bd;l.AmbientLight=Cd;l.LightShadow=Cb;l.Light=X;l.StereoCamera=of;l.PerspectiveCamera=Z;l.OrthographicCamera=Hb;l.CubeCamera=dd;l.ArrayCamera=yc;l.Camera=Na;l.AudioListener=me;l.PositionalAudio=oe;l.AudioContext=ne;
18251 l.AudioAnalyser=pe;l.Audio=hc;l.VectorKeyframeTrack=fc;l.StringKeyframeTrack=Jd;l.QuaternionKeyframeTrack=cd;l.NumberKeyframeTrack=ec;l.ColorKeyframeTrack=Hd;l.BooleanKeyframeTrack=Gd;l.PropertyMixer=qe;l.PropertyBinding=pa;l.KeyframeTrack=oa;l.AnimationUtils=ia;l.AnimationObjectGroup=qf;l.AnimationMixer=re;l.AnimationClip=Ca;l.Uniform=Ld;l.InstancedBufferGeometry=se;l.BufferGeometry=C;l.Geometry=R;l.InterleavedBufferAttribute=zc;l.InstancedInterleavedBuffer=te;l.InterleavedBuffer=ob;l.InstancedBufferAttribute=
18252 ue;l.Face3=Ta;l.Object3D=D;l.Raycaster=sf;l.Layers=Rd;l.EventDispatcher=ya;l.Clock=uf;l.QuaternionLinearInterpolant=Id;l.LinearInterpolant=bd;l.DiscreteInterpolant=Fd;l.CubicInterpolant=Ed;l.Interpolant=wa;l.Triangle=ja;l.Math=H;l.Spherical=vf;l.Cylindrical=wf;l.Plane=Ma;l.Frustum=md;l.Sphere=Da;l.Ray=mb;l.Matrix4=I;l.Matrix3=ra;l.Box3=Sa;l.Box2=we;l.Line3=xe;l.Euler=hb;l.Vector4=V;l.Vector3=p;l.Vector2=z;l.Quaternion=fa;l.Color=G;l.ImmediateRenderObject=ed;l.VertexNormalsHelper=fd;l.SpotLightHelper=
18253 ic;l.SkeletonHelper=jc;l.PointLightHelper=kc;l.RectAreaLightHelper=lc;l.HemisphereLightHelper=mc;l.GridHelper=gd;l.PolarGridHelper=Md;l.FaceNormalsHelper=hd;l.DirectionalLightHelper=nc;l.CameraHelper=id;l.BoxHelper=Db;l.Box3Helper=jd;l.PlaneHelper=kd;l.ArrowHelper=Eb;l.AxesHelper=ld;l.Shape=db;l.Path=La;l.ShapePath=je;l.Font=ke;l.CurvePath=Xa;l.Curve=L;l.ImageUtils=eb;l.ShapeUtils=Va;l.WebGLUtils=$e;l.WireframeGeometry=Qb;l.ParametricGeometry=Fc;l.ParametricBufferGeometry=Rb;l.TetrahedronGeometry=
18254 Hc;l.TetrahedronBufferGeometry=Sb;l.OctahedronGeometry=Ic;l.OctahedronBufferGeometry=pb;l.IcosahedronGeometry=Jc;l.IcosahedronBufferGeometry=Tb;l.DodecahedronGeometry=Kc;l.DodecahedronBufferGeometry=Ub;l.PolyhedronGeometry=Gc;l.PolyhedronBufferGeometry=na;l.TubeGeometry=Lc;l.TubeBufferGeometry=Vb;l.TorusKnotGeometry=Mc;l.TorusKnotBufferGeometry=Wb;l.TorusGeometry=Nc;l.TorusBufferGeometry=Xb;l.TextGeometry=Sc;l.TextBufferGeometry=Yb;l.SphereGeometry=Tc;l.SphereBufferGeometry=sb;l.RingGeometry=Uc;l.RingBufferGeometry=
18255 Zb;l.PlaneGeometry=uc;l.PlaneBufferGeometry=lb;l.LatheGeometry=Vc;l.LatheBufferGeometry=$b;l.ShapeGeometry=tb;l.ShapeBufferGeometry=ub;l.ExtrudeGeometry=rb;l.ExtrudeBufferGeometry=Oa;l.EdgesGeometry=ac;l.ConeGeometry=Wc;l.ConeBufferGeometry=Xc;l.CylinderGeometry=vb;l.CylinderBufferGeometry=Wa;l.CircleGeometry=Yc;l.CircleBufferGeometry=bc;l.BoxGeometry=Ib;l.BoxBufferGeometry=kb;l.ShadowMaterial=wb;l.SpriteMaterial=cb;l.RawShaderMaterial=cc;l.ShaderMaterial=ta;l.PointsMaterial=Ea;l.MeshPhysicalMaterial=
18256 xb;l.MeshStandardMaterial=Pa;l.MeshPhongMaterial=Fa;l.MeshToonMaterial=yb;l.MeshNormalMaterial=zb;l.MeshLambertMaterial=Ab;l.MeshDepthMaterial=$a;l.MeshDistanceMaterial=ab;l.MeshBasicMaterial=da;l.LineDashedMaterial=Bb;l.LineBasicMaterial=Y;l.Material=J;l.Float64BufferAttribute=tc;l.Float32BufferAttribute=A;l.Uint32BufferAttribute=jb;l.Int32BufferAttribute=sc;l.Uint16BufferAttribute=ib;l.Int16BufferAttribute=rc;l.Uint8ClampedBufferAttribute=qc;l.Uint8BufferAttribute=pc;l.Int8BufferAttribute=oc;l.BufferAttribute=
18257 Q;l.ArcCurve=dc;l.CatmullRomCurve3=ca;l.CubicBezierCurve=Ha;l.CubicBezierCurve3=Qa;l.EllipseCurve=za;l.LineCurve=va;l.LineCurve3=Ia;l.QuadraticBezierCurve=Ja;l.QuadraticBezierCurve3=Ra;l.SplineCurve=Ka;l.REVISION="95";l.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};l.CullFaceNone=0;l.CullFaceBack=1;l.CullFaceFront=2;l.CullFaceFrontBack=3;l.FrontFaceDirectionCW=0;l.FrontFaceDirectionCCW=1;l.BasicShadowMap=0;l.PCFShadowMap=1;l.PCFSoftShadowMap=2;l.FrontSide=0;l.BackSide=1;l.DoubleSide=2;l.FlatShading=1;l.SmoothShading=
18258 2;l.NoColors=0;l.FaceColors=1;l.VertexColors=2;l.NoBlending=0;l.NormalBlending=1;l.AdditiveBlending=2;l.SubtractiveBlending=3;l.MultiplyBlending=4;l.CustomBlending=5;l.AddEquation=100;l.SubtractEquation=101;l.ReverseSubtractEquation=102;l.MinEquation=103;l.MaxEquation=104;l.ZeroFactor=200;l.OneFactor=201;l.SrcColorFactor=202;l.OneMinusSrcColorFactor=203;l.SrcAlphaFactor=204;l.OneMinusSrcAlphaFactor=205;l.DstAlphaFactor=206;l.OneMinusDstAlphaFactor=207;l.DstColorFactor=208;l.OneMinusDstColorFactor=
18259 209;l.SrcAlphaSaturateFactor=210;l.NeverDepth=0;l.AlwaysDepth=1;l.LessDepth=2;l.LessEqualDepth=3;l.EqualDepth=4;l.GreaterEqualDepth=5;l.GreaterDepth=6;l.NotEqualDepth=7;l.MultiplyOperation=0;l.MixOperation=1;l.AddOperation=2;l.NoToneMapping=0;l.LinearToneMapping=1;l.ReinhardToneMapping=2;l.Uncharted2ToneMapping=3;l.CineonToneMapping=4;l.UVMapping=300;l.CubeReflectionMapping=301;l.CubeRefractionMapping=302;l.EquirectangularReflectionMapping=303;l.EquirectangularRefractionMapping=304;l.SphericalReflectionMapping=
18260 305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=307;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.NearestFilter=1003;l.NearestMipMapNearestFilter=1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;l.UnsignedIntType=1014;l.FloatType=1015;l.HalfFloatType=1016;l.UnsignedShort4444Type=1017;
18261 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=33776;l.RGBA_S3TC_DXT1_Format=33777;l.RGBA_S3TC_DXT3_Format=33778;l.RGBA_S3TC_DXT5_Format=33779;l.RGB_PVRTC_4BPPV1_Format=35840;l.RGB_PVRTC_2BPPV1_Format=35841;l.RGBA_PVRTC_4BPPV1_Format=35842;l.RGBA_PVRTC_2BPPV1_Format=35843;l.RGB_ETC1_Format=
18262 36196;l.RGBA_ASTC_4x4_Format=37808;l.RGBA_ASTC_5x4_Format=37809;l.RGBA_ASTC_5x5_Format=37810;l.RGBA_ASTC_6x5_Format=37811;l.RGBA_ASTC_6x6_Format=37812;l.RGBA_ASTC_8x5_Format=37813;l.RGBA_ASTC_8x6_Format=37814;l.RGBA_ASTC_8x8_Format=37815;l.RGBA_ASTC_10x5_Format=37816;l.RGBA_ASTC_10x6_Format=37817;l.RGBA_ASTC_10x8_Format=37818;l.RGBA_ASTC_10x10_Format=37819;l.RGBA_ASTC_12x10_Format=37820;l.RGBA_ASTC_12x12_Format=37821;l.LoopOnce=2200;l.LoopRepeat=2201;l.LoopPingPong=2202;l.InterpolateDiscrete=2300;
18263 l.InterpolateLinear=2301;l.InterpolateSmooth=2302;l.ZeroCurvatureEnding=2400;l.ZeroSlopeEnding=2401;l.WrapAroundEnding=2402;l.TrianglesDrawMode=0;l.TriangleStripDrawMode=1;l.TriangleFanDrawMode=2;l.LinearEncoding=3E3;l.sRGBEncoding=3001;l.GammaEncoding=3007;l.RGBEEncoding=3002;l.LogLuvEncoding=3003;l.RGBM7Encoding=3004;l.RGBM16Encoding=3005;l.RGBDEncoding=3006;l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.TangentSpaceNormalMap=0;l.ObjectSpaceNormalMap=1;l.CubeGeometry=Ib;l.Face4=function(a,b,
18264 c,d,e,f,g){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");return new Ta(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};l.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};l.PointCloud=function(a,
18265 b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Ob(a,b)};l.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new Ac(a)};l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Ob(a,b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new Ea(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");
18266 return new Ea(a)};l.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new Ea(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new p(a,b,c)};l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return(new Q(a,b)).setDynamic(!0)};l.Int8Attribute=function(a,
18267 b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new oc(a,b)};l.Uint8Attribute=function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new pc(a,b)};l.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new qc(a,b)};l.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");
18268 return new rc(a,b)};l.Uint16Attribute=function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new ib(a,b)};l.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new sc(a,b)};l.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");return new jb(a,b)};l.Float32Attribute=
18269 function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new A(a,b)};l.Float64Attribute=function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new tc(a,b)};l.ClosedSplineCurve3=yf;l.SplineCurve3=zf;l.Spline=ze;l.AxisHelper=function(a){console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper.");return new ld(a)};l.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");
18270 return new Db(a,b)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new W(new ac(a.geometry),new Y({color:void 0!==b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new W(new Qb(a.geometry),new Y({color:void 0!==b?b:16777215}))};l.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ga(a)};
18271 l.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new de(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.");if(b.isMesh){b.matrixAutoUpdate&&b.updateMatrix();var 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.");
18272 return a.center()}};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=
18273 function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};l.SceneUtils={createMultiMaterialObject:function(){console.error("THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js")},detach:function(){console.error("THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js")},
18274 attach:function(){console.error("THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js")}};l.LensFlare=function(){console.error("THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js")};Object.defineProperty(l,"__esModule",{value:!0})});
18275
18276 },{}],227:[function(require,module,exports){
18277 'use strict';
18278
18279 module.exports = TinyQueue;
18280
18281 function TinyQueue(data, compare) {
18282     if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
18283
18284     this.data = data || [];
18285     this.length = this.data.length;
18286     this.compare = compare || defaultCompare;
18287
18288     if (this.length > 0) {
18289         for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
18290     }
18291 }
18292
18293 function defaultCompare(a, b) {
18294     return a < b ? -1 : a > b ? 1 : 0;
18295 }
18296
18297 TinyQueue.prototype = {
18298
18299     push: function (item) {
18300         this.data.push(item);
18301         this.length++;
18302         this._up(this.length - 1);
18303     },
18304
18305     pop: function () {
18306         if (this.length === 0) return undefined;
18307         var top = this.data[0];
18308         this.length--;
18309         if (this.length > 0) {
18310             this.data[0] = this.data[this.length];
18311             this._down(0);
18312         }
18313         this.data.pop();
18314         return top;
18315     },
18316
18317     peek: function () {
18318         return this.data[0];
18319     },
18320
18321     _up: function (pos) {
18322         var data = this.data;
18323         var compare = this.compare;
18324         var item = data[pos];
18325
18326         while (pos > 0) {
18327             var parent = (pos - 1) >> 1;
18328             var current = data[parent];
18329             if (compare(item, current) >= 0) break;
18330             data[pos] = current;
18331             pos = parent;
18332         }
18333
18334         data[pos] = item;
18335     },
18336
18337     _down: function (pos) {
18338         var data = this.data;
18339         var compare = this.compare;
18340         var len = this.length;
18341         var halfLen = len >> 1;
18342         var item = data[pos];
18343
18344         while (pos < halfLen) {
18345             var left = (pos << 1) + 1;
18346             var right = left + 1;
18347             var best = data[left];
18348
18349             if (right < len && compare(data[right], best) < 0) {
18350                 left = right;
18351                 best = data[right];
18352             }
18353             if (compare(best, item) >= 0) break;
18354
18355             data[pos] = best;
18356             pos = left;
18357         }
18358
18359         data[pos] = item;
18360     }
18361 };
18362
18363 },{}],228:[function(require,module,exports){
18364 var createElement = require("./vdom/create-element.js")
18365
18366 module.exports = createElement
18367
18368 },{"./vdom/create-element.js":234}],229:[function(require,module,exports){
18369 var diff = require("./vtree/diff.js")
18370
18371 module.exports = diff
18372
18373 },{"./vtree/diff.js":254}],230:[function(require,module,exports){
18374 var h = require("./virtual-hyperscript/index.js")
18375
18376 module.exports = h
18377
18378 },{"./virtual-hyperscript/index.js":241}],231:[function(require,module,exports){
18379 var diff = require("./diff.js")
18380 var patch = require("./patch.js")
18381 var h = require("./h.js")
18382 var create = require("./create-element.js")
18383 var VNode = require('./vnode/vnode.js')
18384 var VText = require('./vnode/vtext.js')
18385
18386 module.exports = {
18387     diff: diff,
18388     patch: patch,
18389     h: h,
18390     create: create,
18391     VNode: VNode,
18392     VText: VText
18393 }
18394
18395 },{"./create-element.js":228,"./diff.js":229,"./h.js":230,"./patch.js":232,"./vnode/vnode.js":250,"./vnode/vtext.js":252}],232:[function(require,module,exports){
18396 var patch = require("./vdom/patch.js")
18397
18398 module.exports = patch
18399
18400 },{"./vdom/patch.js":237}],233:[function(require,module,exports){
18401 var isObject = require("is-object")
18402 var isHook = require("../vnode/is-vhook.js")
18403
18404 module.exports = applyProperties
18405
18406 function applyProperties(node, props, previous) {
18407     for (var propName in props) {
18408         var propValue = props[propName]
18409
18410         if (propValue === undefined) {
18411             removeProperty(node, propName, propValue, previous);
18412         } else if (isHook(propValue)) {
18413             removeProperty(node, propName, propValue, previous)
18414             if (propValue.hook) {
18415                 propValue.hook(node,
18416                     propName,
18417                     previous ? previous[propName] : undefined)
18418             }
18419         } else {
18420             if (isObject(propValue)) {
18421                 patchObject(node, props, previous, propName, propValue);
18422             } else {
18423                 node[propName] = propValue
18424             }
18425         }
18426     }
18427 }
18428
18429 function removeProperty(node, propName, propValue, previous) {
18430     if (previous) {
18431         var previousValue = previous[propName]
18432
18433         if (!isHook(previousValue)) {
18434             if (propName === "attributes") {
18435                 for (var attrName in previousValue) {
18436                     node.removeAttribute(attrName)
18437                 }
18438             } else if (propName === "style") {
18439                 for (var i in previousValue) {
18440                     node.style[i] = ""
18441                 }
18442             } else if (typeof previousValue === "string") {
18443                 node[propName] = ""
18444             } else {
18445                 node[propName] = null
18446             }
18447         } else if (previousValue.unhook) {
18448             previousValue.unhook(node, propName, propValue)
18449         }
18450     }
18451 }
18452
18453 function patchObject(node, props, previous, propName, propValue) {
18454     var previousValue = previous ? previous[propName] : undefined
18455
18456     // Set attributes
18457     if (propName === "attributes") {
18458         for (var attrName in propValue) {
18459             var attrValue = propValue[attrName]
18460
18461             if (attrValue === undefined) {
18462                 node.removeAttribute(attrName)
18463             } else {
18464                 node.setAttribute(attrName, attrValue)
18465             }
18466         }
18467
18468         return
18469     }
18470
18471     if(previousValue && isObject(previousValue) &&
18472         getPrototype(previousValue) !== getPrototype(propValue)) {
18473         node[propName] = propValue
18474         return
18475     }
18476
18477     if (!isObject(node[propName])) {
18478         node[propName] = {}
18479     }
18480
18481     var replacer = propName === "style" ? "" : undefined
18482
18483     for (var k in propValue) {
18484         var value = propValue[k]
18485         node[propName][k] = (value === undefined) ? replacer : value
18486     }
18487 }
18488
18489 function getPrototype(value) {
18490     if (Object.getPrototypeOf) {
18491         return Object.getPrototypeOf(value)
18492     } else if (value.__proto__) {
18493         return value.__proto__
18494     } else if (value.constructor) {
18495         return value.constructor.prototype
18496     }
18497 }
18498
18499 },{"../vnode/is-vhook.js":245,"is-object":20}],234:[function(require,module,exports){
18500 var document = require("global/document")
18501
18502 var applyProperties = require("./apply-properties")
18503
18504 var isVNode = require("../vnode/is-vnode.js")
18505 var isVText = require("../vnode/is-vtext.js")
18506 var isWidget = require("../vnode/is-widget.js")
18507 var handleThunk = require("../vnode/handle-thunk.js")
18508
18509 module.exports = createElement
18510
18511 function createElement(vnode, opts) {
18512     var doc = opts ? opts.document || document : document
18513     var warn = opts ? opts.warn : null
18514
18515     vnode = handleThunk(vnode).a
18516
18517     if (isWidget(vnode)) {
18518         return vnode.init()
18519     } else if (isVText(vnode)) {
18520         return doc.createTextNode(vnode.text)
18521     } else if (!isVNode(vnode)) {
18522         if (warn) {
18523             warn("Item is not a valid virtual dom node", vnode)
18524         }
18525         return null
18526     }
18527
18528     var node = (vnode.namespace === null) ?
18529         doc.createElement(vnode.tagName) :
18530         doc.createElementNS(vnode.namespace, vnode.tagName)
18531
18532     var props = vnode.properties
18533     applyProperties(node, props)
18534
18535     var children = vnode.children
18536
18537     for (var i = 0; i < children.length; i++) {
18538         var childNode = createElement(children[i], opts)
18539         if (childNode) {
18540             node.appendChild(childNode)
18541         }
18542     }
18543
18544     return node
18545 }
18546
18547 },{"../vnode/handle-thunk.js":243,"../vnode/is-vnode.js":246,"../vnode/is-vtext.js":247,"../vnode/is-widget.js":248,"./apply-properties":233,"global/document":16}],235:[function(require,module,exports){
18548 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
18549 // We don't want to read all of the DOM nodes in the tree so we use
18550 // the in-order tree indexing to eliminate recursion down certain branches.
18551 // We only recurse into a DOM node if we know that it contains a child of
18552 // interest.
18553
18554 var noChild = {}
18555
18556 module.exports = domIndex
18557
18558 function domIndex(rootNode, tree, indices, nodes) {
18559     if (!indices || indices.length === 0) {
18560         return {}
18561     } else {
18562         indices.sort(ascending)
18563         return recurse(rootNode, tree, indices, nodes, 0)
18564     }
18565 }
18566
18567 function recurse(rootNode, tree, indices, nodes, rootIndex) {
18568     nodes = nodes || {}
18569
18570
18571     if (rootNode) {
18572         if (indexInRange(indices, rootIndex, rootIndex)) {
18573             nodes[rootIndex] = rootNode
18574         }
18575
18576         var vChildren = tree.children
18577
18578         if (vChildren) {
18579
18580             var childNodes = rootNode.childNodes
18581
18582             for (var i = 0; i < tree.children.length; i++) {
18583                 rootIndex += 1
18584
18585                 var vChild = vChildren[i] || noChild
18586                 var nextIndex = rootIndex + (vChild.count || 0)
18587
18588                 // skip recursion down the tree if there are no nodes down here
18589                 if (indexInRange(indices, rootIndex, nextIndex)) {
18590                     recurse(childNodes[i], vChild, indices, nodes, rootIndex)
18591                 }
18592
18593                 rootIndex = nextIndex
18594             }
18595         }
18596     }
18597
18598     return nodes
18599 }
18600
18601 // Binary search for an index in the interval [left, right]
18602 function indexInRange(indices, left, right) {
18603     if (indices.length === 0) {
18604         return false
18605     }
18606
18607     var minIndex = 0
18608     var maxIndex = indices.length - 1
18609     var currentIndex
18610     var currentItem
18611
18612     while (minIndex <= maxIndex) {
18613         currentIndex = ((maxIndex + minIndex) / 2) >> 0
18614         currentItem = indices[currentIndex]
18615
18616         if (minIndex === maxIndex) {
18617             return currentItem >= left && currentItem <= right
18618         } else if (currentItem < left) {
18619             minIndex = currentIndex + 1
18620         } else  if (currentItem > right) {
18621             maxIndex = currentIndex - 1
18622         } else {
18623             return true
18624         }
18625     }
18626
18627     return false;
18628 }
18629
18630 function ascending(a, b) {
18631     return a > b ? 1 : -1
18632 }
18633
18634 },{}],236:[function(require,module,exports){
18635 var applyProperties = require("./apply-properties")
18636
18637 var isWidget = require("../vnode/is-widget.js")
18638 var VPatch = require("../vnode/vpatch.js")
18639
18640 var updateWidget = require("./update-widget")
18641
18642 module.exports = applyPatch
18643
18644 function applyPatch(vpatch, domNode, renderOptions) {
18645     var type = vpatch.type
18646     var vNode = vpatch.vNode
18647     var patch = vpatch.patch
18648
18649     switch (type) {
18650         case VPatch.REMOVE:
18651             return removeNode(domNode, vNode)
18652         case VPatch.INSERT:
18653             return insertNode(domNode, patch, renderOptions)
18654         case VPatch.VTEXT:
18655             return stringPatch(domNode, vNode, patch, renderOptions)
18656         case VPatch.WIDGET:
18657             return widgetPatch(domNode, vNode, patch, renderOptions)
18658         case VPatch.VNODE:
18659             return vNodePatch(domNode, vNode, patch, renderOptions)
18660         case VPatch.ORDER:
18661             reorderChildren(domNode, patch)
18662             return domNode
18663         case VPatch.PROPS:
18664             applyProperties(domNode, patch, vNode.properties)
18665             return domNode
18666         case VPatch.THUNK:
18667             return replaceRoot(domNode,
18668                 renderOptions.patch(domNode, patch, renderOptions))
18669         default:
18670             return domNode
18671     }
18672 }
18673
18674 function removeNode(domNode, vNode) {
18675     var parentNode = domNode.parentNode
18676
18677     if (parentNode) {
18678         parentNode.removeChild(domNode)
18679     }
18680
18681     destroyWidget(domNode, vNode);
18682
18683     return null
18684 }
18685
18686 function insertNode(parentNode, vNode, renderOptions) {
18687     var newNode = renderOptions.render(vNode, renderOptions)
18688
18689     if (parentNode) {
18690         parentNode.appendChild(newNode)
18691     }
18692
18693     return parentNode
18694 }
18695
18696 function stringPatch(domNode, leftVNode, vText, renderOptions) {
18697     var newNode
18698
18699     if (domNode.nodeType === 3) {
18700         domNode.replaceData(0, domNode.length, vText.text)
18701         newNode = domNode
18702     } else {
18703         var parentNode = domNode.parentNode
18704         newNode = renderOptions.render(vText, renderOptions)
18705
18706         if (parentNode && newNode !== domNode) {
18707             parentNode.replaceChild(newNode, domNode)
18708         }
18709     }
18710
18711     return newNode
18712 }
18713
18714 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
18715     var updating = updateWidget(leftVNode, widget)
18716     var newNode
18717
18718     if (updating) {
18719         newNode = widget.update(leftVNode, domNode) || domNode
18720     } else {
18721         newNode = renderOptions.render(widget, renderOptions)
18722     }
18723
18724     var parentNode = domNode.parentNode
18725
18726     if (parentNode && newNode !== domNode) {
18727         parentNode.replaceChild(newNode, domNode)
18728     }
18729
18730     if (!updating) {
18731         destroyWidget(domNode, leftVNode)
18732     }
18733
18734     return newNode
18735 }
18736
18737 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
18738     var parentNode = domNode.parentNode
18739     var newNode = renderOptions.render(vNode, renderOptions)
18740
18741     if (parentNode && newNode !== domNode) {
18742         parentNode.replaceChild(newNode, domNode)
18743     }
18744
18745     return newNode
18746 }
18747
18748 function destroyWidget(domNode, w) {
18749     if (typeof w.destroy === "function" && isWidget(w)) {
18750         w.destroy(domNode)
18751     }
18752 }
18753
18754 function reorderChildren(domNode, moves) {
18755     var childNodes = domNode.childNodes
18756     var keyMap = {}
18757     var node
18758     var remove
18759     var insert
18760
18761     for (var i = 0; i < moves.removes.length; i++) {
18762         remove = moves.removes[i]
18763         node = childNodes[remove.from]
18764         if (remove.key) {
18765             keyMap[remove.key] = node
18766         }
18767         domNode.removeChild(node)
18768     }
18769
18770     var length = childNodes.length
18771     for (var j = 0; j < moves.inserts.length; j++) {
18772         insert = moves.inserts[j]
18773         node = keyMap[insert.key]
18774         // this is the weirdest bug i've ever seen in webkit
18775         domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
18776     }
18777 }
18778
18779 function replaceRoot(oldRoot, newRoot) {
18780     if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
18781         oldRoot.parentNode.replaceChild(newRoot, oldRoot)
18782     }
18783
18784     return newRoot;
18785 }
18786
18787 },{"../vnode/is-widget.js":248,"../vnode/vpatch.js":251,"./apply-properties":233,"./update-widget":238}],237:[function(require,module,exports){
18788 var document = require("global/document")
18789 var isArray = require("x-is-array")
18790
18791 var render = require("./create-element")
18792 var domIndex = require("./dom-index")
18793 var patchOp = require("./patch-op")
18794 module.exports = patch
18795
18796 function patch(rootNode, patches, renderOptions) {
18797     renderOptions = renderOptions || {}
18798     renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
18799         ? renderOptions.patch
18800         : patchRecursive
18801     renderOptions.render = renderOptions.render || render
18802
18803     return renderOptions.patch(rootNode, patches, renderOptions)
18804 }
18805
18806 function patchRecursive(rootNode, patches, renderOptions) {
18807     var indices = patchIndices(patches)
18808
18809     if (indices.length === 0) {
18810         return rootNode
18811     }
18812
18813     var index = domIndex(rootNode, patches.a, indices)
18814     var ownerDocument = rootNode.ownerDocument
18815
18816     if (!renderOptions.document && ownerDocument !== document) {
18817         renderOptions.document = ownerDocument
18818     }
18819
18820     for (var i = 0; i < indices.length; i++) {
18821         var nodeIndex = indices[i]
18822         rootNode = applyPatch(rootNode,
18823             index[nodeIndex],
18824             patches[nodeIndex],
18825             renderOptions)
18826     }
18827
18828     return rootNode
18829 }
18830
18831 function applyPatch(rootNode, domNode, patchList, renderOptions) {
18832     if (!domNode) {
18833         return rootNode
18834     }
18835
18836     var newNode
18837
18838     if (isArray(patchList)) {
18839         for (var i = 0; i < patchList.length; i++) {
18840             newNode = patchOp(patchList[i], domNode, renderOptions)
18841
18842             if (domNode === rootNode) {
18843                 rootNode = newNode
18844             }
18845         }
18846     } else {
18847         newNode = patchOp(patchList, domNode, renderOptions)
18848
18849         if (domNode === rootNode) {
18850             rootNode = newNode
18851         }
18852     }
18853
18854     return rootNode
18855 }
18856
18857 function patchIndices(patches) {
18858     var indices = []
18859
18860     for (var key in patches) {
18861         if (key !== "a") {
18862             indices.push(Number(key))
18863         }
18864     }
18865
18866     return indices
18867 }
18868
18869 },{"./create-element":234,"./dom-index":235,"./patch-op":236,"global/document":16,"x-is-array":273}],238:[function(require,module,exports){
18870 var isWidget = require("../vnode/is-widget.js")
18871
18872 module.exports = updateWidget
18873
18874 function updateWidget(a, b) {
18875     if (isWidget(a) && isWidget(b)) {
18876         if ("name" in a && "name" in b) {
18877             return a.id === b.id
18878         } else {
18879             return a.init === b.init
18880         }
18881     }
18882
18883     return false
18884 }
18885
18886 },{"../vnode/is-widget.js":248}],239:[function(require,module,exports){
18887 'use strict';
18888
18889 var EvStore = require('ev-store');
18890
18891 module.exports = EvHook;
18892
18893 function EvHook(value) {
18894     if (!(this instanceof EvHook)) {
18895         return new EvHook(value);
18896     }
18897
18898     this.value = value;
18899 }
18900
18901 EvHook.prototype.hook = function (node, propertyName) {
18902     var es = EvStore(node);
18903     var propName = propertyName.substr(3);
18904
18905     es[propName] = this.value;
18906 };
18907
18908 EvHook.prototype.unhook = function(node, propertyName) {
18909     var es = EvStore(node);
18910     var propName = propertyName.substr(3);
18911
18912     es[propName] = undefined;
18913 };
18914
18915 },{"ev-store":9}],240:[function(require,module,exports){
18916 'use strict';
18917
18918 module.exports = SoftSetHook;
18919
18920 function SoftSetHook(value) {
18921     if (!(this instanceof SoftSetHook)) {
18922         return new SoftSetHook(value);
18923     }
18924
18925     this.value = value;
18926 }
18927
18928 SoftSetHook.prototype.hook = function (node, propertyName) {
18929     if (node[propertyName] !== this.value) {
18930         node[propertyName] = this.value;
18931     }
18932 };
18933
18934 },{}],241:[function(require,module,exports){
18935 'use strict';
18936
18937 var isArray = require('x-is-array');
18938
18939 var VNode = require('../vnode/vnode.js');
18940 var VText = require('../vnode/vtext.js');
18941 var isVNode = require('../vnode/is-vnode');
18942 var isVText = require('../vnode/is-vtext');
18943 var isWidget = require('../vnode/is-widget');
18944 var isHook = require('../vnode/is-vhook');
18945 var isVThunk = require('../vnode/is-thunk');
18946
18947 var parseTag = require('./parse-tag.js');
18948 var softSetHook = require('./hooks/soft-set-hook.js');
18949 var evHook = require('./hooks/ev-hook.js');
18950
18951 module.exports = h;
18952
18953 function h(tagName, properties, children) {
18954     var childNodes = [];
18955     var tag, props, key, namespace;
18956
18957     if (!children && isChildren(properties)) {
18958         children = properties;
18959         props = {};
18960     }
18961
18962     props = props || properties || {};
18963     tag = parseTag(tagName, props);
18964
18965     // support keys
18966     if (props.hasOwnProperty('key')) {
18967         key = props.key;
18968         props.key = undefined;
18969     }
18970
18971     // support namespace
18972     if (props.hasOwnProperty('namespace')) {
18973         namespace = props.namespace;
18974         props.namespace = undefined;
18975     }
18976
18977     // fix cursor bug
18978     if (tag === 'INPUT' &&
18979         !namespace &&
18980         props.hasOwnProperty('value') &&
18981         props.value !== undefined &&
18982         !isHook(props.value)
18983     ) {
18984         props.value = softSetHook(props.value);
18985     }
18986
18987     transformProperties(props);
18988
18989     if (children !== undefined && children !== null) {
18990         addChild(children, childNodes, tag, props);
18991     }
18992
18993
18994     return new VNode(tag, props, childNodes, key, namespace);
18995 }
18996
18997 function addChild(c, childNodes, tag, props) {
18998     if (typeof c === 'string') {
18999         childNodes.push(new VText(c));
19000     } else if (typeof c === 'number') {
19001         childNodes.push(new VText(String(c)));
19002     } else if (isChild(c)) {
19003         childNodes.push(c);
19004     } else if (isArray(c)) {
19005         for (var i = 0; i < c.length; i++) {
19006             addChild(c[i], childNodes, tag, props);
19007         }
19008     } else if (c === null || c === undefined) {
19009         return;
19010     } else {
19011         throw UnexpectedVirtualElement({
19012             foreignObject: c,
19013             parentVnode: {
19014                 tagName: tag,
19015                 properties: props
19016             }
19017         });
19018     }
19019 }
19020
19021 function transformProperties(props) {
19022     for (var propName in props) {
19023         if (props.hasOwnProperty(propName)) {
19024             var value = props[propName];
19025
19026             if (isHook(value)) {
19027                 continue;
19028             }
19029
19030             if (propName.substr(0, 3) === 'ev-') {
19031                 // add ev-foo support
19032                 props[propName] = evHook(value);
19033             }
19034         }
19035     }
19036 }
19037
19038 function isChild(x) {
19039     return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
19040 }
19041
19042 function isChildren(x) {
19043     return typeof x === 'string' || isArray(x) || isChild(x);
19044 }
19045
19046 function UnexpectedVirtualElement(data) {
19047     var err = new Error();
19048
19049     err.type = 'virtual-hyperscript.unexpected.virtual-element';
19050     err.message = 'Unexpected virtual child passed to h().\n' +
19051         'Expected a VNode / Vthunk / VWidget / string but:\n' +
19052         'got:\n' +
19053         errorString(data.foreignObject) +
19054         '.\n' +
19055         'The parent vnode is:\n' +
19056         errorString(data.parentVnode)
19057         '\n' +
19058         'Suggested fix: change your `h(..., [ ... ])` callsite.';
19059     err.foreignObject = data.foreignObject;
19060     err.parentVnode = data.parentVnode;
19061
19062     return err;
19063 }
19064
19065 function errorString(obj) {
19066     try {
19067         return JSON.stringify(obj, null, '    ');
19068     } catch (e) {
19069         return String(obj);
19070     }
19071 }
19072
19073 },{"../vnode/is-thunk":244,"../vnode/is-vhook":245,"../vnode/is-vnode":246,"../vnode/is-vtext":247,"../vnode/is-widget":248,"../vnode/vnode.js":250,"../vnode/vtext.js":252,"./hooks/ev-hook.js":239,"./hooks/soft-set-hook.js":240,"./parse-tag.js":242,"x-is-array":273}],242:[function(require,module,exports){
19074 'use strict';
19075
19076 var split = require('browser-split');
19077
19078 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
19079 var notClassId = /^\.|#/;
19080
19081 module.exports = parseTag;
19082
19083 function parseTag(tag, props) {
19084     if (!tag) {
19085         return 'DIV';
19086     }
19087
19088     var noId = !(props.hasOwnProperty('id'));
19089
19090     var tagParts = split(tag, classIdSplit);
19091     var tagName = null;
19092
19093     if (notClassId.test(tagParts[1])) {
19094         tagName = 'DIV';
19095     }
19096
19097     var classes, part, type, i;
19098
19099     for (i = 0; i < tagParts.length; i++) {
19100         part = tagParts[i];
19101
19102         if (!part) {
19103             continue;
19104         }
19105
19106         type = part.charAt(0);
19107
19108         if (!tagName) {
19109             tagName = part;
19110         } else if (type === '.') {
19111             classes = classes || [];
19112             classes.push(part.substring(1, part.length));
19113         } else if (type === '#' && noId) {
19114             props.id = part.substring(1, part.length);
19115         }
19116     }
19117
19118     if (classes) {
19119         if (props.className) {
19120             classes.push(props.className);
19121         }
19122
19123         props.className = classes.join(' ');
19124     }
19125
19126     return props.namespace ? tagName : tagName.toUpperCase();
19127 }
19128
19129 },{"browser-split":5}],243:[function(require,module,exports){
19130 var isVNode = require("./is-vnode")
19131 var isVText = require("./is-vtext")
19132 var isWidget = require("./is-widget")
19133 var isThunk = require("./is-thunk")
19134
19135 module.exports = handleThunk
19136
19137 function handleThunk(a, b) {
19138     var renderedA = a
19139     var renderedB = b
19140
19141     if (isThunk(b)) {
19142         renderedB = renderThunk(b, a)
19143     }
19144
19145     if (isThunk(a)) {
19146         renderedA = renderThunk(a, null)
19147     }
19148
19149     return {
19150         a: renderedA,
19151         b: renderedB
19152     }
19153 }
19154
19155 function renderThunk(thunk, previous) {
19156     var renderedThunk = thunk.vnode
19157
19158     if (!renderedThunk) {
19159         renderedThunk = thunk.vnode = thunk.render(previous)
19160     }
19161
19162     if (!(isVNode(renderedThunk) ||
19163             isVText(renderedThunk) ||
19164             isWidget(renderedThunk))) {
19165         throw new Error("thunk did not return a valid node");
19166     }
19167
19168     return renderedThunk
19169 }
19170
19171 },{"./is-thunk":244,"./is-vnode":246,"./is-vtext":247,"./is-widget":248}],244:[function(require,module,exports){
19172 module.exports = isThunk
19173
19174 function isThunk(t) {
19175     return t && t.type === "Thunk"
19176 }
19177
19178 },{}],245:[function(require,module,exports){
19179 module.exports = isHook
19180
19181 function isHook(hook) {
19182     return hook &&
19183       (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
19184        typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
19185 }
19186
19187 },{}],246:[function(require,module,exports){
19188 var version = require("./version")
19189
19190 module.exports = isVirtualNode
19191
19192 function isVirtualNode(x) {
19193     return x && x.type === "VirtualNode" && x.version === version
19194 }
19195
19196 },{"./version":249}],247:[function(require,module,exports){
19197 var version = require("./version")
19198
19199 module.exports = isVirtualText
19200
19201 function isVirtualText(x) {
19202     return x && x.type === "VirtualText" && x.version === version
19203 }
19204
19205 },{"./version":249}],248:[function(require,module,exports){
19206 module.exports = isWidget
19207
19208 function isWidget(w) {
19209     return w && w.type === "Widget"
19210 }
19211
19212 },{}],249:[function(require,module,exports){
19213 module.exports = "2"
19214
19215 },{}],250:[function(require,module,exports){
19216 var version = require("./version")
19217 var isVNode = require("./is-vnode")
19218 var isWidget = require("./is-widget")
19219 var isThunk = require("./is-thunk")
19220 var isVHook = require("./is-vhook")
19221
19222 module.exports = VirtualNode
19223
19224 var noProperties = {}
19225 var noChildren = []
19226
19227 function VirtualNode(tagName, properties, children, key, namespace) {
19228     this.tagName = tagName
19229     this.properties = properties || noProperties
19230     this.children = children || noChildren
19231     this.key = key != null ? String(key) : undefined
19232     this.namespace = (typeof namespace === "string") ? namespace : null
19233
19234     var count = (children && children.length) || 0
19235     var descendants = 0
19236     var hasWidgets = false
19237     var hasThunks = false
19238     var descendantHooks = false
19239     var hooks
19240
19241     for (var propName in properties) {
19242         if (properties.hasOwnProperty(propName)) {
19243             var property = properties[propName]
19244             if (isVHook(property) && property.unhook) {
19245                 if (!hooks) {
19246                     hooks = {}
19247                 }
19248
19249                 hooks[propName] = property
19250             }
19251         }
19252     }
19253
19254     for (var i = 0; i < count; i++) {
19255         var child = children[i]
19256         if (isVNode(child)) {
19257             descendants += child.count || 0
19258
19259             if (!hasWidgets && child.hasWidgets) {
19260                 hasWidgets = true
19261             }
19262
19263             if (!hasThunks && child.hasThunks) {
19264                 hasThunks = true
19265             }
19266
19267             if (!descendantHooks && (child.hooks || child.descendantHooks)) {
19268                 descendantHooks = true
19269             }
19270         } else if (!hasWidgets && isWidget(child)) {
19271             if (typeof child.destroy === "function") {
19272                 hasWidgets = true
19273             }
19274         } else if (!hasThunks && isThunk(child)) {
19275             hasThunks = true;
19276         }
19277     }
19278
19279     this.count = count + descendants
19280     this.hasWidgets = hasWidgets
19281     this.hasThunks = hasThunks
19282     this.hooks = hooks
19283     this.descendantHooks = descendantHooks
19284 }
19285
19286 VirtualNode.prototype.version = version
19287 VirtualNode.prototype.type = "VirtualNode"
19288
19289 },{"./is-thunk":244,"./is-vhook":245,"./is-vnode":246,"./is-widget":248,"./version":249}],251:[function(require,module,exports){
19290 var version = require("./version")
19291
19292 VirtualPatch.NONE = 0
19293 VirtualPatch.VTEXT = 1
19294 VirtualPatch.VNODE = 2
19295 VirtualPatch.WIDGET = 3
19296 VirtualPatch.PROPS = 4
19297 VirtualPatch.ORDER = 5
19298 VirtualPatch.INSERT = 6
19299 VirtualPatch.REMOVE = 7
19300 VirtualPatch.THUNK = 8
19301
19302 module.exports = VirtualPatch
19303
19304 function VirtualPatch(type, vNode, patch) {
19305     this.type = Number(type)
19306     this.vNode = vNode
19307     this.patch = patch
19308 }
19309
19310 VirtualPatch.prototype.version = version
19311 VirtualPatch.prototype.type = "VirtualPatch"
19312
19313 },{"./version":249}],252:[function(require,module,exports){
19314 var version = require("./version")
19315
19316 module.exports = VirtualText
19317
19318 function VirtualText(text) {
19319     this.text = String(text)
19320 }
19321
19322 VirtualText.prototype.version = version
19323 VirtualText.prototype.type = "VirtualText"
19324
19325 },{"./version":249}],253:[function(require,module,exports){
19326 var isObject = require("is-object")
19327 var isHook = require("../vnode/is-vhook")
19328
19329 module.exports = diffProps
19330
19331 function diffProps(a, b) {
19332     var diff
19333
19334     for (var aKey in a) {
19335         if (!(aKey in b)) {
19336             diff = diff || {}
19337             diff[aKey] = undefined
19338         }
19339
19340         var aValue = a[aKey]
19341         var bValue = b[aKey]
19342
19343         if (aValue === bValue) {
19344             continue
19345         } else if (isObject(aValue) && isObject(bValue)) {
19346             if (getPrototype(bValue) !== getPrototype(aValue)) {
19347                 diff = diff || {}
19348                 diff[aKey] = bValue
19349             } else if (isHook(bValue)) {
19350                  diff = diff || {}
19351                  diff[aKey] = bValue
19352             } else {
19353                 var objectDiff = diffProps(aValue, bValue)
19354                 if (objectDiff) {
19355                     diff = diff || {}
19356                     diff[aKey] = objectDiff
19357                 }
19358             }
19359         } else {
19360             diff = diff || {}
19361             diff[aKey] = bValue
19362         }
19363     }
19364
19365     for (var bKey in b) {
19366         if (!(bKey in a)) {
19367             diff = diff || {}
19368             diff[bKey] = b[bKey]
19369         }
19370     }
19371
19372     return diff
19373 }
19374
19375 function getPrototype(value) {
19376   if (Object.getPrototypeOf) {
19377     return Object.getPrototypeOf(value)
19378   } else if (value.__proto__) {
19379     return value.__proto__
19380   } else if (value.constructor) {
19381     return value.constructor.prototype
19382   }
19383 }
19384
19385 },{"../vnode/is-vhook":245,"is-object":20}],254:[function(require,module,exports){
19386 var isArray = require("x-is-array")
19387
19388 var VPatch = require("../vnode/vpatch")
19389 var isVNode = require("../vnode/is-vnode")
19390 var isVText = require("../vnode/is-vtext")
19391 var isWidget = require("../vnode/is-widget")
19392 var isThunk = require("../vnode/is-thunk")
19393 var handleThunk = require("../vnode/handle-thunk")
19394
19395 var diffProps = require("./diff-props")
19396
19397 module.exports = diff
19398
19399 function diff(a, b) {
19400     var patch = { a: a }
19401     walk(a, b, patch, 0)
19402     return patch
19403 }
19404
19405 function walk(a, b, patch, index) {
19406     if (a === b) {
19407         return
19408     }
19409
19410     var apply = patch[index]
19411     var applyClear = false
19412
19413     if (isThunk(a) || isThunk(b)) {
19414         thunks(a, b, patch, index)
19415     } else if (b == null) {
19416
19417         // If a is a widget we will add a remove patch for it
19418         // Otherwise any child widgets/hooks must be destroyed.
19419         // This prevents adding two remove patches for a widget.
19420         if (!isWidget(a)) {
19421             clearState(a, patch, index)
19422             apply = patch[index]
19423         }
19424
19425         apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
19426     } else if (isVNode(b)) {
19427         if (isVNode(a)) {
19428             if (a.tagName === b.tagName &&
19429                 a.namespace === b.namespace &&
19430                 a.key === b.key) {
19431                 var propsPatch = diffProps(a.properties, b.properties)
19432                 if (propsPatch) {
19433                     apply = appendPatch(apply,
19434                         new VPatch(VPatch.PROPS, a, propsPatch))
19435                 }
19436                 apply = diffChildren(a, b, patch, apply, index)
19437             } else {
19438                 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
19439                 applyClear = true
19440             }
19441         } else {
19442             apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
19443             applyClear = true
19444         }
19445     } else if (isVText(b)) {
19446         if (!isVText(a)) {
19447             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
19448             applyClear = true
19449         } else if (a.text !== b.text) {
19450             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
19451         }
19452     } else if (isWidget(b)) {
19453         if (!isWidget(a)) {
19454             applyClear = true
19455         }
19456
19457         apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
19458     }
19459
19460     if (apply) {
19461         patch[index] = apply
19462     }
19463
19464     if (applyClear) {
19465         clearState(a, patch, index)
19466     }
19467 }
19468
19469 function diffChildren(a, b, patch, apply, index) {
19470     var aChildren = a.children
19471     var orderedSet = reorder(aChildren, b.children)
19472     var bChildren = orderedSet.children
19473
19474     var aLen = aChildren.length
19475     var bLen = bChildren.length
19476     var len = aLen > bLen ? aLen : bLen
19477
19478     for (var i = 0; i < len; i++) {
19479         var leftNode = aChildren[i]
19480         var rightNode = bChildren[i]
19481         index += 1
19482
19483         if (!leftNode) {
19484             if (rightNode) {
19485                 // Excess nodes in b need to be added
19486                 apply = appendPatch(apply,
19487                     new VPatch(VPatch.INSERT, null, rightNode))
19488             }
19489         } else {
19490             walk(leftNode, rightNode, patch, index)
19491         }
19492
19493         if (isVNode(leftNode) && leftNode.count) {
19494             index += leftNode.count
19495         }
19496     }
19497
19498     if (orderedSet.moves) {
19499         // Reorder nodes last
19500         apply = appendPatch(apply, new VPatch(
19501             VPatch.ORDER,
19502             a,
19503             orderedSet.moves
19504         ))
19505     }
19506
19507     return apply
19508 }
19509
19510 function clearState(vNode, patch, index) {
19511     // TODO: Make this a single walk, not two
19512     unhook(vNode, patch, index)
19513     destroyWidgets(vNode, patch, index)
19514 }
19515
19516 // Patch records for all destroyed widgets must be added because we need
19517 // a DOM node reference for the destroy function
19518 function destroyWidgets(vNode, patch, index) {
19519     if (isWidget(vNode)) {
19520         if (typeof vNode.destroy === "function") {
19521             patch[index] = appendPatch(
19522                 patch[index],
19523                 new VPatch(VPatch.REMOVE, vNode, null)
19524             )
19525         }
19526     } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
19527         var children = vNode.children
19528         var len = children.length
19529         for (var i = 0; i < len; i++) {
19530             var child = children[i]
19531             index += 1
19532
19533             destroyWidgets(child, patch, index)
19534
19535             if (isVNode(child) && child.count) {
19536                 index += child.count
19537             }
19538         }
19539     } else if (isThunk(vNode)) {
19540         thunks(vNode, null, patch, index)
19541     }
19542 }
19543
19544 // Create a sub-patch for thunks
19545 function thunks(a, b, patch, index) {
19546     var nodes = handleThunk(a, b)
19547     var thunkPatch = diff(nodes.a, nodes.b)
19548     if (hasPatches(thunkPatch)) {
19549         patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
19550     }
19551 }
19552
19553 function hasPatches(patch) {
19554     for (var index in patch) {
19555         if (index !== "a") {
19556             return true
19557         }
19558     }
19559
19560     return false
19561 }
19562
19563 // Execute hooks when two nodes are identical
19564 function unhook(vNode, patch, index) {
19565     if (isVNode(vNode)) {
19566         if (vNode.hooks) {
19567             patch[index] = appendPatch(
19568                 patch[index],
19569                 new VPatch(
19570                     VPatch.PROPS,
19571                     vNode,
19572                     undefinedKeys(vNode.hooks)
19573                 )
19574             )
19575         }
19576
19577         if (vNode.descendantHooks || vNode.hasThunks) {
19578             var children = vNode.children
19579             var len = children.length
19580             for (var i = 0; i < len; i++) {
19581                 var child = children[i]
19582                 index += 1
19583
19584                 unhook(child, patch, index)
19585
19586                 if (isVNode(child) && child.count) {
19587                     index += child.count
19588                 }
19589             }
19590         }
19591     } else if (isThunk(vNode)) {
19592         thunks(vNode, null, patch, index)
19593     }
19594 }
19595
19596 function undefinedKeys(obj) {
19597     var result = {}
19598
19599     for (var key in obj) {
19600         result[key] = undefined
19601     }
19602
19603     return result
19604 }
19605
19606 // List diff, naive left to right reordering
19607 function reorder(aChildren, bChildren) {
19608     // O(M) time, O(M) memory
19609     var bChildIndex = keyIndex(bChildren)
19610     var bKeys = bChildIndex.keys
19611     var bFree = bChildIndex.free
19612
19613     if (bFree.length === bChildren.length) {
19614         return {
19615             children: bChildren,
19616             moves: null
19617         }
19618     }
19619
19620     // O(N) time, O(N) memory
19621     var aChildIndex = keyIndex(aChildren)
19622     var aKeys = aChildIndex.keys
19623     var aFree = aChildIndex.free
19624
19625     if (aFree.length === aChildren.length) {
19626         return {
19627             children: bChildren,
19628             moves: null
19629         }
19630     }
19631
19632     // O(MAX(N, M)) memory
19633     var newChildren = []
19634
19635     var freeIndex = 0
19636     var freeCount = bFree.length
19637     var deletedItems = 0
19638
19639     // Iterate through a and match a node in b
19640     // O(N) time,
19641     for (var i = 0 ; i < aChildren.length; i++) {
19642         var aItem = aChildren[i]
19643         var itemIndex
19644
19645         if (aItem.key) {
19646             if (bKeys.hasOwnProperty(aItem.key)) {
19647                 // Match up the old keys
19648                 itemIndex = bKeys[aItem.key]
19649                 newChildren.push(bChildren[itemIndex])
19650
19651             } else {
19652                 // Remove old keyed items
19653                 itemIndex = i - deletedItems++
19654                 newChildren.push(null)
19655             }
19656         } else {
19657             // Match the item in a with the next free item in b
19658             if (freeIndex < freeCount) {
19659                 itemIndex = bFree[freeIndex++]
19660                 newChildren.push(bChildren[itemIndex])
19661             } else {
19662                 // There are no free items in b to match with
19663                 // the free items in a, so the extra free nodes
19664                 // are deleted.
19665                 itemIndex = i - deletedItems++
19666                 newChildren.push(null)
19667             }
19668         }
19669     }
19670
19671     var lastFreeIndex = freeIndex >= bFree.length ?
19672         bChildren.length :
19673         bFree[freeIndex]
19674
19675     // Iterate through b and append any new keys
19676     // O(M) time
19677     for (var j = 0; j < bChildren.length; j++) {
19678         var newItem = bChildren[j]
19679
19680         if (newItem.key) {
19681             if (!aKeys.hasOwnProperty(newItem.key)) {
19682                 // Add any new keyed items
19683                 // We are adding new items to the end and then sorting them
19684                 // in place. In future we should insert new items in place.
19685                 newChildren.push(newItem)
19686             }
19687         } else if (j >= lastFreeIndex) {
19688             // Add any leftover non-keyed items
19689             newChildren.push(newItem)
19690         }
19691     }
19692
19693     var simulate = newChildren.slice()
19694     var simulateIndex = 0
19695     var removes = []
19696     var inserts = []
19697     var simulateItem
19698
19699     for (var k = 0; k < bChildren.length;) {
19700         var wantedItem = bChildren[k]
19701         simulateItem = simulate[simulateIndex]
19702
19703         // remove items
19704         while (simulateItem === null && simulate.length) {
19705             removes.push(remove(simulate, simulateIndex, null))
19706             simulateItem = simulate[simulateIndex]
19707         }
19708
19709         if (!simulateItem || simulateItem.key !== wantedItem.key) {
19710             // if we need a key in this position...
19711             if (wantedItem.key) {
19712                 if (simulateItem && simulateItem.key) {
19713                     // if an insert doesn't put this key in place, it needs to move
19714                     if (bKeys[simulateItem.key] !== k + 1) {
19715                         removes.push(remove(simulate, simulateIndex, simulateItem.key))
19716                         simulateItem = simulate[simulateIndex]
19717                         // if the remove didn't put the wanted item in place, we need to insert it
19718                         if (!simulateItem || simulateItem.key !== wantedItem.key) {
19719                             inserts.push({key: wantedItem.key, to: k})
19720                         }
19721                         // items are matching, so skip ahead
19722                         else {
19723                             simulateIndex++
19724                         }
19725                     }
19726                     else {
19727                         inserts.push({key: wantedItem.key, to: k})
19728                     }
19729                 }
19730                 else {
19731                     inserts.push({key: wantedItem.key, to: k})
19732                 }
19733                 k++
19734             }
19735             // a key in simulate has no matching wanted key, remove it
19736             else if (simulateItem && simulateItem.key) {
19737                 removes.push(remove(simulate, simulateIndex, simulateItem.key))
19738             }
19739         }
19740         else {
19741             simulateIndex++
19742             k++
19743         }
19744     }
19745
19746     // remove all the remaining nodes from simulate
19747     while(simulateIndex < simulate.length) {
19748         simulateItem = simulate[simulateIndex]
19749         removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
19750     }
19751
19752     // If the only moves we have are deletes then we can just
19753     // let the delete patch remove these items.
19754     if (removes.length === deletedItems && !inserts.length) {
19755         return {
19756             children: newChildren,
19757             moves: null
19758         }
19759     }
19760
19761     return {
19762         children: newChildren,
19763         moves: {
19764             removes: removes,
19765             inserts: inserts
19766         }
19767     }
19768 }
19769
19770 function remove(arr, index, key) {
19771     arr.splice(index, 1)
19772
19773     return {
19774         from: index,
19775         key: key
19776     }
19777 }
19778
19779 function keyIndex(children) {
19780     var keys = {}
19781     var free = []
19782     var length = children.length
19783
19784     for (var i = 0; i < length; i++) {
19785         var child = children[i]
19786
19787         if (child.key) {
19788             keys[child.key] = i
19789         } else {
19790             free.push(i)
19791         }
19792     }
19793
19794     return {
19795         keys: keys,     // A hash of key name to index
19796         free: free      // An array of unkeyed item indices
19797     }
19798 }
19799
19800 function appendPatch(apply, patch) {
19801     if (apply) {
19802         if (isArray(apply)) {
19803             apply.push(patch)
19804         } else {
19805             apply = [apply, patch]
19806         }
19807
19808         return apply
19809     } else {
19810         return patch
19811     }
19812 }
19813
19814 },{"../vnode/handle-thunk":243,"../vnode/is-thunk":244,"../vnode/is-vnode":246,"../vnode/is-vtext":247,"../vnode/is-widget":248,"../vnode/vpatch":251,"./diff-props":253,"x-is-array":273}],255:[function(require,module,exports){
19815 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19816 /** @author Brian Cavalier */
19817 /** @author John Hann */
19818
19819 (function(define) { 'use strict';
19820 define(function (require) {
19821
19822         var makePromise = require('./makePromise');
19823         var Scheduler = require('./Scheduler');
19824         var async = require('./env').asap;
19825
19826         return makePromise({
19827                 scheduler: new Scheduler(async)
19828         });
19829
19830 });
19831 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
19832
19833 },{"./Scheduler":256,"./env":268,"./makePromise":270}],256:[function(require,module,exports){
19834 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19835 /** @author Brian Cavalier */
19836 /** @author John Hann */
19837
19838 (function(define) { 'use strict';
19839 define(function() {
19840
19841         // Credit to Twisol (https://github.com/Twisol) for suggesting
19842         // this type of extensible queue + trampoline approach for next-tick conflation.
19843
19844         /**
19845          * Async task scheduler
19846          * @param {function} async function to schedule a single async function
19847          * @constructor
19848          */
19849         function Scheduler(async) {
19850                 this._async = async;
19851                 this._running = false;
19852
19853                 this._queue = this;
19854                 this._queueLen = 0;
19855                 this._afterQueue = {};
19856                 this._afterQueueLen = 0;
19857
19858                 var self = this;
19859                 this.drain = function() {
19860                         self._drain();
19861                 };
19862         }
19863
19864         /**
19865          * Enqueue a task
19866          * @param {{ run:function }} task
19867          */
19868         Scheduler.prototype.enqueue = function(task) {
19869                 this._queue[this._queueLen++] = task;
19870                 this.run();
19871         };
19872
19873         /**
19874          * Enqueue a task to run after the main task queue
19875          * @param {{ run:function }} task
19876          */
19877         Scheduler.prototype.afterQueue = function(task) {
19878                 this._afterQueue[this._afterQueueLen++] = task;
19879                 this.run();
19880         };
19881
19882         Scheduler.prototype.run = function() {
19883                 if (!this._running) {
19884                         this._running = true;
19885                         this._async(this.drain);
19886                 }
19887         };
19888
19889         /**
19890          * Drain the handler queue entirely, and then the after queue
19891          */
19892         Scheduler.prototype._drain = function() {
19893                 var i = 0;
19894                 for (; i < this._queueLen; ++i) {
19895                         this._queue[i].run();
19896                         this._queue[i] = void 0;
19897                 }
19898
19899                 this._queueLen = 0;
19900                 this._running = false;
19901
19902                 for (i = 0; i < this._afterQueueLen; ++i) {
19903                         this._afterQueue[i].run();
19904                         this._afterQueue[i] = void 0;
19905                 }
19906
19907                 this._afterQueueLen = 0;
19908         };
19909
19910         return Scheduler;
19911
19912 });
19913 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19914
19915 },{}],257:[function(require,module,exports){
19916 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19917 /** @author Brian Cavalier */
19918 /** @author John Hann */
19919
19920 (function(define) { 'use strict';
19921 define(function() {
19922
19923         /**
19924          * Custom error type for promises rejected by promise.timeout
19925          * @param {string} message
19926          * @constructor
19927          */
19928         function TimeoutError (message) {
19929                 Error.call(this);
19930                 this.message = message;
19931                 this.name = TimeoutError.name;
19932                 if (typeof Error.captureStackTrace === 'function') {
19933                         Error.captureStackTrace(this, TimeoutError);
19934                 }
19935         }
19936
19937         TimeoutError.prototype = Object.create(Error.prototype);
19938         TimeoutError.prototype.constructor = TimeoutError;
19939
19940         return TimeoutError;
19941 });
19942 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19943 },{}],258:[function(require,module,exports){
19944 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19945 /** @author Brian Cavalier */
19946 /** @author John Hann */
19947
19948 (function(define) { 'use strict';
19949 define(function() {
19950
19951         makeApply.tryCatchResolve = tryCatchResolve;
19952
19953         return makeApply;
19954
19955         function makeApply(Promise, call) {
19956                 if(arguments.length < 2) {
19957                         call = tryCatchResolve;
19958                 }
19959
19960                 return apply;
19961
19962                 function apply(f, thisArg, args) {
19963                         var p = Promise._defer();
19964                         var l = args.length;
19965                         var params = new Array(l);
19966                         callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
19967
19968                         return p;
19969                 }
19970
19971                 function callAndResolve(c, h) {
19972                         if(c.i < 0) {
19973                                 return call(c.f, c.thisArg, c.params, h);
19974                         }
19975
19976                         var handler = Promise._handler(c.args[c.i]);
19977                         handler.fold(callAndResolveNext, c, void 0, h);
19978                 }
19979
19980                 function callAndResolveNext(c, x, h) {
19981                         c.params[c.i] = x;
19982                         c.i -= 1;
19983                         callAndResolve(c, h);
19984                 }
19985         }
19986
19987         function tryCatchResolve(f, thisArg, args, resolver) {
19988                 try {
19989                         resolver.resolve(f.apply(thisArg, args));
19990                 } catch(e) {
19991                         resolver.reject(e);
19992                 }
19993         }
19994
19995 });
19996 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19997
19998
19999
20000 },{}],259:[function(require,module,exports){
20001 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20002 /** @author Brian Cavalier */
20003 /** @author John Hann */
20004
20005 (function(define) { 'use strict';
20006 define(function(require) {
20007
20008         var state = require('../state');
20009         var applier = require('../apply');
20010
20011         return function array(Promise) {
20012
20013                 var applyFold = applier(Promise);
20014                 var toPromise = Promise.resolve;
20015                 var all = Promise.all;
20016
20017                 var ar = Array.prototype.reduce;
20018                 var arr = Array.prototype.reduceRight;
20019                 var slice = Array.prototype.slice;
20020
20021                 // Additional array combinators
20022
20023                 Promise.any = any;
20024                 Promise.some = some;
20025                 Promise.settle = settle;
20026
20027                 Promise.map = map;
20028                 Promise.filter = filter;
20029                 Promise.reduce = reduce;
20030                 Promise.reduceRight = reduceRight;
20031
20032                 /**
20033                  * When this promise fulfills with an array, do
20034                  * onFulfilled.apply(void 0, array)
20035                  * @param {function} onFulfilled function to apply
20036                  * @returns {Promise} promise for the result of applying onFulfilled
20037                  */
20038                 Promise.prototype.spread = function(onFulfilled) {
20039                         return this.then(all).then(function(array) {
20040                                 return onFulfilled.apply(this, array);
20041                         });
20042                 };
20043
20044                 return Promise;
20045
20046                 /**
20047                  * One-winner competitive race.
20048                  * Return a promise that will fulfill when one of the promises
20049                  * in the input array fulfills, or will reject when all promises
20050                  * have rejected.
20051                  * @param {array} promises
20052                  * @returns {Promise} promise for the first fulfilled value
20053                  */
20054                 function any(promises) {
20055                         var p = Promise._defer();
20056                         var resolver = p._handler;
20057                         var l = promises.length>>>0;
20058
20059                         var pending = l;
20060                         var errors = [];
20061
20062                         for (var h, x, i = 0; i < l; ++i) {
20063                                 x = promises[i];
20064                                 if(x === void 0 && !(i in promises)) {
20065                                         --pending;
20066                                         continue;
20067                                 }
20068
20069                                 h = Promise._handler(x);
20070                                 if(h.state() > 0) {
20071                                         resolver.become(h);
20072                                         Promise._visitRemaining(promises, i, h);
20073                                         break;
20074                                 } else {
20075                                         h.visit(resolver, handleFulfill, handleReject);
20076                                 }
20077                         }
20078
20079                         if(pending === 0) {
20080                                 resolver.reject(new RangeError('any(): array must not be empty'));
20081                         }
20082
20083                         return p;
20084
20085                         function handleFulfill(x) {
20086                                 /*jshint validthis:true*/
20087                                 errors = null;
20088                                 this.resolve(x); // this === resolver
20089                         }
20090
20091                         function handleReject(e) {
20092                                 /*jshint validthis:true*/
20093                                 if(this.resolved) { // this === resolver
20094                                         return;
20095                                 }
20096
20097                                 errors.push(e);
20098                                 if(--pending === 0) {
20099                                         this.reject(errors);
20100                                 }
20101                         }
20102                 }
20103
20104                 /**
20105                  * N-winner competitive race
20106                  * Return a promise that will fulfill when n input promises have
20107                  * fulfilled, or will reject when it becomes impossible for n
20108                  * input promises to fulfill (ie when promises.length - n + 1
20109                  * have rejected)
20110                  * @param {array} promises
20111                  * @param {number} n
20112                  * @returns {Promise} promise for the earliest n fulfillment values
20113                  *
20114                  * @deprecated
20115                  */
20116                 function some(promises, n) {
20117                         /*jshint maxcomplexity:7*/
20118                         var p = Promise._defer();
20119                         var resolver = p._handler;
20120
20121                         var results = [];
20122                         var errors = [];
20123
20124                         var l = promises.length>>>0;
20125                         var nFulfill = 0;
20126                         var nReject;
20127                         var x, i; // reused in both for() loops
20128
20129                         // First pass: count actual array items
20130                         for(i=0; i<l; ++i) {
20131                                 x = promises[i];
20132                                 if(x === void 0 && !(i in promises)) {
20133                                         continue;
20134                                 }
20135                                 ++nFulfill;
20136                         }
20137
20138                         // Compute actual goals
20139                         n = Math.max(n, 0);
20140                         nReject = (nFulfill - n + 1);
20141                         nFulfill = Math.min(n, nFulfill);
20142
20143                         if(n > nFulfill) {
20144                                 resolver.reject(new RangeError('some(): array must contain at least '
20145                                 + n + ' item(s), but had ' + nFulfill));
20146                         } else if(nFulfill === 0) {
20147                                 resolver.resolve(results);
20148                         }
20149
20150                         // Second pass: observe each array item, make progress toward goals
20151                         for(i=0; i<l; ++i) {
20152                                 x = promises[i];
20153                                 if(x === void 0 && !(i in promises)) {
20154                                         continue;
20155                                 }
20156
20157                                 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
20158                         }
20159
20160                         return p;
20161
20162                         function fulfill(x) {
20163                                 /*jshint validthis:true*/
20164                                 if(this.resolved) { // this === resolver
20165                                         return;
20166                                 }
20167
20168                                 results.push(x);
20169                                 if(--nFulfill === 0) {
20170                                         errors = null;
20171                                         this.resolve(results);
20172                                 }
20173                         }
20174
20175                         function reject(e) {
20176                                 /*jshint validthis:true*/
20177                                 if(this.resolved) { // this === resolver
20178                                         return;
20179                                 }
20180
20181                                 errors.push(e);
20182                                 if(--nReject === 0) {
20183                                         results = null;
20184                                         this.reject(errors);
20185                                 }
20186                         }
20187                 }
20188
20189                 /**
20190                  * Apply f to the value of each promise in a list of promises
20191                  * and return a new list containing the results.
20192                  * @param {array} promises
20193                  * @param {function(x:*, index:Number):*} f mapping function
20194                  * @returns {Promise}
20195                  */
20196                 function map(promises, f) {
20197                         return Promise._traverse(f, promises);
20198                 }
20199
20200                 /**
20201                  * Filter the provided array of promises using the provided predicate.  Input may
20202                  * contain promises and values
20203                  * @param {Array} promises array of promises and values
20204                  * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
20205                  *  Must return truthy (or promise for truthy) for items to retain.
20206                  * @returns {Promise} promise that will fulfill with an array containing all items
20207                  *  for which predicate returned truthy.
20208                  */
20209                 function filter(promises, predicate) {
20210                         var a = slice.call(promises);
20211                         return Promise._traverse(predicate, a).then(function(keep) {
20212                                 return filterSync(a, keep);
20213                         });
20214                 }
20215
20216                 function filterSync(promises, keep) {
20217                         // Safe because we know all promises have fulfilled if we've made it this far
20218                         var l = keep.length;
20219                         var filtered = new Array(l);
20220                         for(var i=0, j=0; i<l; ++i) {
20221                                 if(keep[i]) {
20222                                         filtered[j++] = Promise._handler(promises[i]).value;
20223                                 }
20224                         }
20225                         filtered.length = j;
20226                         return filtered;
20227
20228                 }
20229
20230                 /**
20231                  * Return a promise that will always fulfill with an array containing
20232                  * the outcome states of all input promises.  The returned promise
20233                  * will never reject.
20234                  * @param {Array} promises
20235                  * @returns {Promise} promise for array of settled state descriptors
20236                  */
20237                 function settle(promises) {
20238                         return all(promises.map(settleOne));
20239                 }
20240
20241                 function settleOne(p) {
20242                         // Optimize the case where we get an already-resolved when.js promise
20243                         //  by extracting its state:
20244                         var handler;
20245                         if (p instanceof Promise) {
20246                                 // This is our own Promise type and we can reach its handler internals:
20247                                 handler = p._handler.join();
20248                         }
20249                         if((handler && handler.state() === 0) || !handler) {
20250                                 // Either still pending, or not a Promise at all:
20251                                 return toPromise(p).then(state.fulfilled, state.rejected);
20252                         }
20253
20254                         // The promise is our own, but it is already resolved. Take a shortcut.
20255                         // Since we're not actually handling the resolution, we need to disable
20256                         // rejection reporting.
20257                         handler._unreport();
20258                         return state.inspect(handler);
20259                 }
20260
20261                 /**
20262                  * Traditional reduce function, similar to `Array.prototype.reduce()`, but
20263                  * input may contain promises and/or values, and reduceFunc
20264                  * may return either a value or a promise, *and* initialValue may
20265                  * be a promise for the starting value.
20266                  * @param {Array|Promise} promises array or promise for an array of anything,
20267                  *      may contain a mix of promises and values.
20268                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
20269                  * @returns {Promise} that will resolve to the final reduced value
20270                  */
20271                 function reduce(promises, f /*, initialValue */) {
20272                         return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
20273                                         : ar.call(promises, liftCombine(f));
20274                 }
20275
20276                 /**
20277                  * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
20278                  * input may contain promises and/or values, and reduceFunc
20279                  * may return either a value or a promise, *and* initialValue may
20280                  * be a promise for the starting value.
20281                  * @param {Array|Promise} promises array or promise for an array of anything,
20282                  *      may contain a mix of promises and values.
20283                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
20284                  * @returns {Promise} that will resolve to the final reduced value
20285                  */
20286                 function reduceRight(promises, f /*, initialValue */) {
20287                         return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
20288                                         : arr.call(promises, liftCombine(f));
20289                 }
20290
20291                 function liftCombine(f) {
20292                         return function(z, x, i) {
20293                                 return applyFold(f, void 0, [z,x,i]);
20294                         };
20295                 }
20296         };
20297
20298 });
20299 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20300
20301 },{"../apply":258,"../state":271}],260:[function(require,module,exports){
20302 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20303 /** @author Brian Cavalier */
20304 /** @author John Hann */
20305
20306 (function(define) { 'use strict';
20307 define(function() {
20308
20309         return function flow(Promise) {
20310
20311                 var resolve = Promise.resolve;
20312                 var reject = Promise.reject;
20313                 var origCatch = Promise.prototype['catch'];
20314
20315                 /**
20316                  * Handle the ultimate fulfillment value or rejection reason, and assume
20317                  * responsibility for all errors.  If an error propagates out of result
20318                  * or handleFatalError, it will be rethrown to the host, resulting in a
20319                  * loud stack track on most platforms and a crash on some.
20320                  * @param {function?} onResult
20321                  * @param {function?} onError
20322                  * @returns {undefined}
20323                  */
20324                 Promise.prototype.done = function(onResult, onError) {
20325                         this._handler.visit(this._handler.receiver, onResult, onError);
20326                 };
20327
20328                 /**
20329                  * Add Error-type and predicate matching to catch.  Examples:
20330                  * promise.catch(TypeError, handleTypeError)
20331                  *   .catch(predicate, handleMatchedErrors)
20332                  *   .catch(handleRemainingErrors)
20333                  * @param onRejected
20334                  * @returns {*}
20335                  */
20336                 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
20337                         if (arguments.length < 2) {
20338                                 return origCatch.call(this, onRejected);
20339                         }
20340
20341                         if(typeof onRejected !== 'function') {
20342                                 return this.ensure(rejectInvalidPredicate);
20343                         }
20344
20345                         return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
20346                 };
20347
20348                 /**
20349                  * Wraps the provided catch handler, so that it will only be called
20350                  * if the predicate evaluates truthy
20351                  * @param {?function} handler
20352                  * @param {function} predicate
20353                  * @returns {function} conditional catch handler
20354                  */
20355                 function createCatchFilter(handler, predicate) {
20356                         return function(e) {
20357                                 return evaluatePredicate(e, predicate)
20358                                         ? handler.call(this, e)
20359                                         : reject(e);
20360                         };
20361                 }
20362
20363                 /**
20364                  * Ensures that onFulfilledOrRejected will be called regardless of whether
20365                  * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
20366                  * receive the promises' value or reason.  Any returned value will be disregarded.
20367                  * onFulfilledOrRejected may throw or return a rejected promise to signal
20368                  * an additional error.
20369                  * @param {function} handler handler to be called regardless of
20370                  *  fulfillment or rejection
20371                  * @returns {Promise}
20372                  */
20373                 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
20374                         if(typeof handler !== 'function') {
20375                                 return this;
20376                         }
20377
20378                         return this.then(function(x) {
20379                                 return runSideEffect(handler, this, identity, x);
20380                         }, function(e) {
20381                                 return runSideEffect(handler, this, reject, e);
20382                         });
20383                 };
20384
20385                 function runSideEffect (handler, thisArg, propagate, value) {
20386                         var result = handler.call(thisArg);
20387                         return maybeThenable(result)
20388                                 ? propagateValue(result, propagate, value)
20389                                 : propagate(value);
20390                 }
20391
20392                 function propagateValue (result, propagate, x) {
20393                         return resolve(result).then(function () {
20394                                 return propagate(x);
20395                         });
20396                 }
20397
20398                 /**
20399                  * Recover from a failure by returning a defaultValue.  If defaultValue
20400                  * is a promise, it's fulfillment value will be used.  If defaultValue is
20401                  * a promise that rejects, the returned promise will reject with the
20402                  * same reason.
20403                  * @param {*} defaultValue
20404                  * @returns {Promise} new promise
20405                  */
20406                 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
20407                         return this.then(void 0, function() {
20408                                 return defaultValue;
20409                         });
20410                 };
20411
20412                 /**
20413                  * Shortcut for .then(function() { return value; })
20414                  * @param  {*} value
20415                  * @return {Promise} a promise that:
20416                  *  - is fulfilled if value is not a promise, or
20417                  *  - if value is a promise, will fulfill with its value, or reject
20418                  *    with its reason.
20419                  */
20420                 Promise.prototype['yield'] = function(value) {
20421                         return this.then(function() {
20422                                 return value;
20423                         });
20424                 };
20425
20426                 /**
20427                  * Runs a side effect when this promise fulfills, without changing the
20428                  * fulfillment value.
20429                  * @param {function} onFulfilledSideEffect
20430                  * @returns {Promise}
20431                  */
20432                 Promise.prototype.tap = function(onFulfilledSideEffect) {
20433                         return this.then(onFulfilledSideEffect)['yield'](this);
20434                 };
20435
20436                 return Promise;
20437         };
20438
20439         function rejectInvalidPredicate() {
20440                 throw new TypeError('catch predicate must be a function');
20441         }
20442
20443         function evaluatePredicate(e, predicate) {
20444                 return isError(predicate) ? e instanceof predicate : predicate(e);
20445         }
20446
20447         function isError(predicate) {
20448                 return predicate === Error
20449                         || (predicate != null && predicate.prototype instanceof Error);
20450         }
20451
20452         function maybeThenable(x) {
20453                 return (typeof x === 'object' || typeof x === 'function') && x !== null;
20454         }
20455
20456         function identity(x) {
20457                 return x;
20458         }
20459
20460 });
20461 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20462
20463 },{}],261:[function(require,module,exports){
20464 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20465 /** @author Brian Cavalier */
20466 /** @author John Hann */
20467 /** @author Jeff Escalante */
20468
20469 (function(define) { 'use strict';
20470 define(function() {
20471
20472         return function fold(Promise) {
20473
20474                 Promise.prototype.fold = function(f, z) {
20475                         var promise = this._beget();
20476
20477                         this._handler.fold(function(z, x, to) {
20478                                 Promise._handler(z).fold(function(x, z, to) {
20479                                         to.resolve(f.call(this, z, x));
20480                                 }, x, this, to);
20481                         }, z, promise._handler.receiver, promise._handler);
20482
20483                         return promise;
20484                 };
20485
20486                 return Promise;
20487         };
20488
20489 });
20490 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20491
20492 },{}],262:[function(require,module,exports){
20493 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20494 /** @author Brian Cavalier */
20495 /** @author John Hann */
20496
20497 (function(define) { 'use strict';
20498 define(function(require) {
20499
20500         var inspect = require('../state').inspect;
20501
20502         return function inspection(Promise) {
20503
20504                 Promise.prototype.inspect = function() {
20505                         return inspect(Promise._handler(this));
20506                 };
20507
20508                 return Promise;
20509         };
20510
20511 });
20512 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20513
20514 },{"../state":271}],263:[function(require,module,exports){
20515 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20516 /** @author Brian Cavalier */
20517 /** @author John Hann */
20518
20519 (function(define) { 'use strict';
20520 define(function() {
20521
20522         return function generate(Promise) {
20523
20524                 var resolve = Promise.resolve;
20525
20526                 Promise.iterate = iterate;
20527                 Promise.unfold = unfold;
20528
20529                 return Promise;
20530
20531                 /**
20532                  * @deprecated Use github.com/cujojs/most streams and most.iterate
20533                  * Generate a (potentially infinite) stream of promised values:
20534                  * x, f(x), f(f(x)), etc. until condition(x) returns true
20535                  * @param {function} f function to generate a new x from the previous x
20536                  * @param {function} condition function that, given the current x, returns
20537                  *  truthy when the iterate should stop
20538                  * @param {function} handler function to handle the value produced by f
20539                  * @param {*|Promise} x starting value, may be a promise
20540                  * @return {Promise} the result of the last call to f before
20541                  *  condition returns true
20542                  */
20543                 function iterate(f, condition, handler, x) {
20544                         return unfold(function(x) {
20545                                 return [x, f(x)];
20546                         }, condition, handler, x);
20547                 }
20548
20549                 /**
20550                  * @deprecated Use github.com/cujojs/most streams and most.unfold
20551                  * Generate a (potentially infinite) stream of promised values
20552                  * by applying handler(generator(seed)) iteratively until
20553                  * condition(seed) returns true.
20554                  * @param {function} unspool function that generates a [value, newSeed]
20555                  *  given a seed.
20556                  * @param {function} condition function that, given the current seed, returns
20557                  *  truthy when the unfold should stop
20558                  * @param {function} handler function to handle the value produced by unspool
20559                  * @param x {*|Promise} starting value, may be a promise
20560                  * @return {Promise} the result of the last value produced by unspool before
20561                  *  condition returns true
20562                  */
20563                 function unfold(unspool, condition, handler, x) {
20564                         return resolve(x).then(function(seed) {
20565                                 return resolve(condition(seed)).then(function(done) {
20566                                         return done ? seed : resolve(unspool(seed)).spread(next);
20567                                 });
20568                         });
20569
20570                         function next(item, newSeed) {
20571                                 return resolve(handler(item)).then(function() {
20572                                         return unfold(unspool, condition, handler, newSeed);
20573                                 });
20574                         }
20575                 }
20576         };
20577
20578 });
20579 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20580
20581 },{}],264:[function(require,module,exports){
20582 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20583 /** @author Brian Cavalier */
20584 /** @author John Hann */
20585
20586 (function(define) { 'use strict';
20587 define(function() {
20588
20589         return function progress(Promise) {
20590
20591                 /**
20592                  * @deprecated
20593                  * Register a progress handler for this promise
20594                  * @param {function} onProgress
20595                  * @returns {Promise}
20596                  */
20597                 Promise.prototype.progress = function(onProgress) {
20598                         return this.then(void 0, void 0, onProgress);
20599                 };
20600
20601                 return Promise;
20602         };
20603
20604 });
20605 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20606
20607 },{}],265:[function(require,module,exports){
20608 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20609 /** @author Brian Cavalier */
20610 /** @author John Hann */
20611
20612 (function(define) { 'use strict';
20613 define(function(require) {
20614
20615         var env = require('../env');
20616         var TimeoutError = require('../TimeoutError');
20617
20618         function setTimeout(f, ms, x, y) {
20619                 return env.setTimer(function() {
20620                         f(x, y, ms);
20621                 }, ms);
20622         }
20623
20624         return function timed(Promise) {
20625                 /**
20626                  * Return a new promise whose fulfillment value is revealed only
20627                  * after ms milliseconds
20628                  * @param {number} ms milliseconds
20629                  * @returns {Promise}
20630                  */
20631                 Promise.prototype.delay = function(ms) {
20632                         var p = this._beget();
20633                         this._handler.fold(handleDelay, ms, void 0, p._handler);
20634                         return p;
20635                 };
20636
20637                 function handleDelay(ms, x, h) {
20638                         setTimeout(resolveDelay, ms, x, h);
20639                 }
20640
20641                 function resolveDelay(x, h) {
20642                         h.resolve(x);
20643                 }
20644
20645                 /**
20646                  * Return a new promise that rejects after ms milliseconds unless
20647                  * this promise fulfills earlier, in which case the returned promise
20648                  * fulfills with the same value.
20649                  * @param {number} ms milliseconds
20650                  * @param {Error|*=} reason optional rejection reason to use, defaults
20651                  *   to a TimeoutError if not provided
20652                  * @returns {Promise}
20653                  */
20654                 Promise.prototype.timeout = function(ms, reason) {
20655                         var p = this._beget();
20656                         var h = p._handler;
20657
20658                         var t = setTimeout(onTimeout, ms, reason, p._handler);
20659
20660                         this._handler.visit(h,
20661                                 function onFulfill(x) {
20662                                         env.clearTimer(t);
20663                                         this.resolve(x); // this = h
20664                                 },
20665                                 function onReject(x) {
20666                                         env.clearTimer(t);
20667                                         this.reject(x); // this = h
20668                                 },
20669                                 h.notify);
20670
20671                         return p;
20672                 };
20673
20674                 function onTimeout(reason, h, ms) {
20675                         var e = typeof reason === 'undefined'
20676                                 ? new TimeoutError('timed out after ' + ms + 'ms')
20677                                 : reason;
20678                         h.reject(e);
20679                 }
20680
20681                 return Promise;
20682         };
20683
20684 });
20685 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20686
20687 },{"../TimeoutError":257,"../env":268}],266:[function(require,module,exports){
20688 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20689 /** @author Brian Cavalier */
20690 /** @author John Hann */
20691
20692 (function(define) { 'use strict';
20693 define(function(require) {
20694
20695         var setTimer = require('../env').setTimer;
20696         var format = require('../format');
20697
20698         return function unhandledRejection(Promise) {
20699
20700                 var logError = noop;
20701                 var logInfo = noop;
20702                 var localConsole;
20703
20704                 if(typeof console !== 'undefined') {
20705                         // Alias console to prevent things like uglify's drop_console option from
20706                         // removing console.log/error. Unhandled rejections fall into the same
20707                         // category as uncaught exceptions, and build tools shouldn't silence them.
20708                         localConsole = console;
20709                         logError = typeof localConsole.error !== 'undefined'
20710                                 ? function (e) { localConsole.error(e); }
20711                                 : function (e) { localConsole.log(e); };
20712
20713                         logInfo = typeof localConsole.info !== 'undefined'
20714                                 ? function (e) { localConsole.info(e); }
20715                                 : function (e) { localConsole.log(e); };
20716                 }
20717
20718                 Promise.onPotentiallyUnhandledRejection = function(rejection) {
20719                         enqueue(report, rejection);
20720                 };
20721
20722                 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
20723                         enqueue(unreport, rejection);
20724                 };
20725
20726                 Promise.onFatalRejection = function(rejection) {
20727                         enqueue(throwit, rejection.value);
20728                 };
20729
20730                 var tasks = [];
20731                 var reported = [];
20732                 var running = null;
20733
20734                 function report(r) {
20735                         if(!r.handled) {
20736                                 reported.push(r);
20737                                 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
20738                         }
20739                 }
20740
20741                 function unreport(r) {
20742                         var i = reported.indexOf(r);
20743                         if(i >= 0) {
20744                                 reported.splice(i, 1);
20745                                 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
20746                         }
20747                 }
20748
20749                 function enqueue(f, x) {
20750                         tasks.push(f, x);
20751                         if(running === null) {
20752                                 running = setTimer(flush, 0);
20753                         }
20754                 }
20755
20756                 function flush() {
20757                         running = null;
20758                         while(tasks.length > 0) {
20759                                 tasks.shift()(tasks.shift());
20760                         }
20761                 }
20762
20763                 return Promise;
20764         };
20765
20766         function throwit(e) {
20767                 throw e;
20768         }
20769
20770         function noop() {}
20771
20772 });
20773 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20774
20775 },{"../env":268,"../format":269}],267:[function(require,module,exports){
20776 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20777 /** @author Brian Cavalier */
20778 /** @author John Hann */
20779
20780 (function(define) { 'use strict';
20781 define(function() {
20782
20783         return function addWith(Promise) {
20784                 /**
20785                  * Returns a promise whose handlers will be called with `this` set to
20786                  * the supplied receiver.  Subsequent promises derived from the
20787                  * returned promise will also have their handlers called with receiver
20788                  * as `this`. Calling `with` with undefined or no arguments will return
20789                  * a promise whose handlers will again be called in the usual Promises/A+
20790                  * way (no `this`) thus safely undoing any previous `with` in the
20791                  * promise chain.
20792                  *
20793                  * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
20794                  * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
20795                  *
20796                  * @param {object} receiver `this` value for all handlers attached to
20797                  *  the returned promise.
20798                  * @returns {Promise}
20799                  */
20800                 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
20801                         var p = this._beget();
20802                         var child = p._handler;
20803                         child.receiver = receiver;
20804                         this._handler.chain(child, receiver);
20805                         return p;
20806                 };
20807
20808                 return Promise;
20809         };
20810
20811 });
20812 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20813
20814
20815 },{}],268:[function(require,module,exports){
20816 (function (process){
20817 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20818 /** @author Brian Cavalier */
20819 /** @author John Hann */
20820
20821 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
20822 (function(define) { 'use strict';
20823 define(function(require) {
20824         /*jshint maxcomplexity:6*/
20825
20826         // Sniff "best" async scheduling option
20827         // Prefer process.nextTick or MutationObserver, then check for
20828         // setTimeout, and finally vertx, since its the only env that doesn't
20829         // have setTimeout
20830
20831         var MutationObs;
20832         var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
20833
20834         // Default env
20835         var setTimer = function(f, ms) { return setTimeout(f, ms); };
20836         var clearTimer = function(t) { return clearTimeout(t); };
20837         var asap = function (f) { return capturedSetTimeout(f, 0); };
20838
20839         // Detect specific env
20840         if (isNode()) { // Node
20841                 asap = function (f) { return process.nextTick(f); };
20842
20843         } else if (MutationObs = hasMutationObserver()) { // Modern browser
20844                 asap = initMutationObserver(MutationObs);
20845
20846         } else if (!capturedSetTimeout) { // vert.x
20847                 var vertxRequire = require;
20848                 var vertx = vertxRequire('vertx');
20849                 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
20850                 clearTimer = vertx.cancelTimer;
20851                 asap = vertx.runOnLoop || vertx.runOnContext;
20852         }
20853
20854         return {
20855                 setTimer: setTimer,
20856                 clearTimer: clearTimer,
20857                 asap: asap
20858         };
20859
20860         function isNode () {
20861                 return typeof process !== 'undefined' &&
20862                         Object.prototype.toString.call(process) === '[object process]';
20863         }
20864
20865         function hasMutationObserver () {
20866             return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
20867                         (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
20868         }
20869
20870         function initMutationObserver(MutationObserver) {
20871                 var scheduled;
20872                 var node = document.createTextNode('');
20873                 var o = new MutationObserver(run);
20874                 o.observe(node, { characterData: true });
20875
20876                 function run() {
20877                         var f = scheduled;
20878                         scheduled = void 0;
20879                         f();
20880                 }
20881
20882                 var i = 0;
20883                 return function (f) {
20884                         scheduled = f;
20885                         node.data = (i ^= 1);
20886                 };
20887         }
20888 });
20889 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20890
20891 }).call(this,require('_process'))
20892
20893 },{"_process":6}],269:[function(require,module,exports){
20894 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20895 /** @author Brian Cavalier */
20896 /** @author John Hann */
20897
20898 (function(define) { 'use strict';
20899 define(function() {
20900
20901         return {
20902                 formatError: formatError,
20903                 formatObject: formatObject,
20904                 tryStringify: tryStringify
20905         };
20906
20907         /**
20908          * Format an error into a string.  If e is an Error and has a stack property,
20909          * it's returned.  Otherwise, e is formatted using formatObject, with a
20910          * warning added about e not being a proper Error.
20911          * @param {*} e
20912          * @returns {String} formatted string, suitable for output to developers
20913          */
20914         function formatError(e) {
20915                 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
20916                 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
20917         }
20918
20919         /**
20920          * Format an object, detecting "plain" objects and running them through
20921          * JSON.stringify if possible.
20922          * @param {Object} o
20923          * @returns {string}
20924          */
20925         function formatObject(o) {
20926                 var s = String(o);
20927                 if(s === '[object Object]' && typeof JSON !== 'undefined') {
20928                         s = tryStringify(o, s);
20929                 }
20930                 return s;
20931         }
20932
20933         /**
20934          * Try to return the result of JSON.stringify(x).  If that fails, return
20935          * defaultValue
20936          * @param {*} x
20937          * @param {*} defaultValue
20938          * @returns {String|*} JSON.stringify(x) or defaultValue
20939          */
20940         function tryStringify(x, defaultValue) {
20941                 try {
20942                         return JSON.stringify(x);
20943                 } catch(e) {
20944                         return defaultValue;
20945                 }
20946         }
20947
20948 });
20949 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20950
20951 },{}],270:[function(require,module,exports){
20952 (function (process){
20953 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20954 /** @author Brian Cavalier */
20955 /** @author John Hann */
20956
20957 (function(define) { 'use strict';
20958 define(function() {
20959
20960         return function makePromise(environment) {
20961
20962                 var tasks = environment.scheduler;
20963                 var emitRejection = initEmitRejection();
20964
20965                 var objectCreate = Object.create ||
20966                         function(proto) {
20967                                 function Child() {}
20968                                 Child.prototype = proto;
20969                                 return new Child();
20970                         };
20971
20972                 /**
20973                  * Create a promise whose fate is determined by resolver
20974                  * @constructor
20975                  * @returns {Promise} promise
20976                  * @name Promise
20977                  */
20978                 function Promise(resolver, handler) {
20979                         this._handler = resolver === Handler ? handler : init(resolver);
20980                 }
20981
20982                 /**
20983                  * Run the supplied resolver
20984                  * @param resolver
20985                  * @returns {Pending}
20986                  */
20987                 function init(resolver) {
20988                         var handler = new Pending();
20989
20990                         try {
20991                                 resolver(promiseResolve, promiseReject, promiseNotify);
20992                         } catch (e) {
20993                                 promiseReject(e);
20994                         }
20995
20996                         return handler;
20997
20998                         /**
20999                          * Transition from pre-resolution state to post-resolution state, notifying
21000                          * all listeners of the ultimate fulfillment or rejection
21001                          * @param {*} x resolution value
21002                          */
21003                         function promiseResolve (x) {
21004                                 handler.resolve(x);
21005                         }
21006                         /**
21007                          * Reject this promise with reason, which will be used verbatim
21008                          * @param {Error|*} reason rejection reason, strongly suggested
21009                          *   to be an Error type
21010                          */
21011                         function promiseReject (reason) {
21012                                 handler.reject(reason);
21013                         }
21014
21015                         /**
21016                          * @deprecated
21017                          * Issue a progress event, notifying all progress listeners
21018                          * @param {*} x progress event payload to pass to all listeners
21019                          */
21020                         function promiseNotify (x) {
21021                                 handler.notify(x);
21022                         }
21023                 }
21024
21025                 // Creation
21026
21027                 Promise.resolve = resolve;
21028                 Promise.reject = reject;
21029                 Promise.never = never;
21030
21031                 Promise._defer = defer;
21032                 Promise._handler = getHandler;
21033
21034                 /**
21035                  * Returns a trusted promise. If x is already a trusted promise, it is
21036                  * returned, otherwise returns a new trusted Promise which follows x.
21037                  * @param  {*} x
21038                  * @return {Promise} promise
21039                  */
21040                 function resolve(x) {
21041                         return isPromise(x) ? x
21042                                 : new Promise(Handler, new Async(getHandler(x)));
21043                 }
21044
21045                 /**
21046                  * Return a reject promise with x as its reason (x is used verbatim)
21047                  * @param {*} x
21048                  * @returns {Promise} rejected promise
21049                  */
21050                 function reject(x) {
21051                         return new Promise(Handler, new Async(new Rejected(x)));
21052                 }
21053
21054                 /**
21055                  * Return a promise that remains pending forever
21056                  * @returns {Promise} forever-pending promise.
21057                  */
21058                 function never() {
21059                         return foreverPendingPromise; // Should be frozen
21060                 }
21061
21062                 /**
21063                  * Creates an internal {promise, resolver} pair
21064                  * @private
21065                  * @returns {Promise}
21066                  */
21067                 function defer() {
21068                         return new Promise(Handler, new Pending());
21069                 }
21070
21071                 // Transformation and flow control
21072
21073                 /**
21074                  * Transform this promise's fulfillment value, returning a new Promise
21075                  * for the transformed result.  If the promise cannot be fulfilled, onRejected
21076                  * is called with the reason.  onProgress *may* be called with updates toward
21077                  * this promise's fulfillment.
21078                  * @param {function=} onFulfilled fulfillment handler
21079                  * @param {function=} onRejected rejection handler
21080                  * @param {function=} onProgress @deprecated progress handler
21081                  * @return {Promise} new promise
21082                  */
21083                 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
21084                         var parent = this._handler;
21085                         var state = parent.join().state();
21086
21087                         if ((typeof onFulfilled !== 'function' && state > 0) ||
21088                                 (typeof onRejected !== 'function' && state < 0)) {
21089                                 // Short circuit: value will not change, simply share handler
21090                                 return new this.constructor(Handler, parent);
21091                         }
21092
21093                         var p = this._beget();
21094                         var child = p._handler;
21095
21096                         parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
21097
21098                         return p;
21099                 };
21100
21101                 /**
21102                  * If this promise cannot be fulfilled due to an error, call onRejected to
21103                  * handle the error. Shortcut for .then(undefined, onRejected)
21104                  * @param {function?} onRejected
21105                  * @return {Promise}
21106                  */
21107                 Promise.prototype['catch'] = function(onRejected) {
21108                         return this.then(void 0, onRejected);
21109                 };
21110
21111                 /**
21112                  * Creates a new, pending promise of the same type as this promise
21113                  * @private
21114                  * @returns {Promise}
21115                  */
21116                 Promise.prototype._beget = function() {
21117                         return begetFrom(this._handler, this.constructor);
21118                 };
21119
21120                 function begetFrom(parent, Promise) {
21121                         var child = new Pending(parent.receiver, parent.join().context);
21122                         return new Promise(Handler, child);
21123                 }
21124
21125                 // Array combinators
21126
21127                 Promise.all = all;
21128                 Promise.race = race;
21129                 Promise._traverse = traverse;
21130
21131                 /**
21132                  * Return a promise that will fulfill when all promises in the
21133                  * input array have fulfilled, or will reject when one of the
21134                  * promises rejects.
21135                  * @param {array} promises array of promises
21136                  * @returns {Promise} promise for array of fulfillment values
21137                  */
21138                 function all(promises) {
21139                         return traverseWith(snd, null, promises);
21140                 }
21141
21142                 /**
21143                  * Array<Promise<X>> -> Promise<Array<f(X)>>
21144                  * @private
21145                  * @param {function} f function to apply to each promise's value
21146                  * @param {Array} promises array of promises
21147                  * @returns {Promise} promise for transformed values
21148                  */
21149                 function traverse(f, promises) {
21150                         return traverseWith(tryCatch2, f, promises);
21151                 }
21152
21153                 function traverseWith(tryMap, f, promises) {
21154                         var handler = typeof f === 'function' ? mapAt : settleAt;
21155
21156                         var resolver = new Pending();
21157                         var pending = promises.length >>> 0;
21158                         var results = new Array(pending);
21159
21160                         for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
21161                                 x = promises[i];
21162
21163                                 if (x === void 0 && !(i in promises)) {
21164                                         --pending;
21165                                         continue;
21166                                 }
21167
21168                                 traverseAt(promises, handler, i, x, resolver);
21169                         }
21170
21171                         if(pending === 0) {
21172                                 resolver.become(new Fulfilled(results));
21173                         }
21174
21175                         return new Promise(Handler, resolver);
21176
21177                         function mapAt(i, x, resolver) {
21178                                 if(!resolver.resolved) {
21179                                         traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
21180                                 }
21181                         }
21182
21183                         function settleAt(i, x, resolver) {
21184                                 results[i] = x;
21185                                 if(--pending === 0) {
21186                                         resolver.become(new Fulfilled(results));
21187                                 }
21188                         }
21189                 }
21190
21191                 function traverseAt(promises, handler, i, x, resolver) {
21192                         if (maybeThenable(x)) {
21193                                 var h = getHandlerMaybeThenable(x);
21194                                 var s = h.state();
21195
21196                                 if (s === 0) {
21197                                         h.fold(handler, i, void 0, resolver);
21198                                 } else if (s > 0) {
21199                                         handler(i, h.value, resolver);
21200                                 } else {
21201                                         resolver.become(h);
21202                                         visitRemaining(promises, i+1, h);
21203                                 }
21204                         } else {
21205                                 handler(i, x, resolver);
21206                         }
21207                 }
21208
21209                 Promise._visitRemaining = visitRemaining;
21210                 function visitRemaining(promises, start, handler) {
21211                         for(var i=start; i<promises.length; ++i) {
21212                                 markAsHandled(getHandler(promises[i]), handler);
21213                         }
21214                 }
21215
21216                 function markAsHandled(h, handler) {
21217                         if(h === handler) {
21218                                 return;
21219                         }
21220
21221                         var s = h.state();
21222                         if(s === 0) {
21223                                 h.visit(h, void 0, h._unreport);
21224                         } else if(s < 0) {
21225                                 h._unreport();
21226                         }
21227                 }
21228
21229                 /**
21230                  * Fulfill-reject competitive race. Return a promise that will settle
21231                  * to the same state as the earliest input promise to settle.
21232                  *
21233                  * WARNING: The ES6 Promise spec requires that race()ing an empty array
21234                  * must return a promise that is pending forever.  This implementation
21235                  * returns a singleton forever-pending promise, the same singleton that is
21236                  * returned by Promise.never(), thus can be checked with ===
21237                  *
21238                  * @param {array} promises array of promises to race
21239                  * @returns {Promise} if input is non-empty, a promise that will settle
21240                  * to the same outcome as the earliest input promise to settle. if empty
21241                  * is empty, returns a promise that will never settle.
21242                  */
21243                 function race(promises) {
21244                         if(typeof promises !== 'object' || promises === null) {
21245                                 return reject(new TypeError('non-iterable passed to race()'));
21246                         }
21247
21248                         // Sigh, race([]) is untestable unless we return *something*
21249                         // that is recognizable without calling .then() on it.
21250                         return promises.length === 0 ? never()
21251                                  : promises.length === 1 ? resolve(promises[0])
21252                                  : runRace(promises);
21253                 }
21254
21255                 function runRace(promises) {
21256                         var resolver = new Pending();
21257                         var i, x, h;
21258                         for(i=0; i<promises.length; ++i) {
21259                                 x = promises[i];
21260                                 if (x === void 0 && !(i in promises)) {
21261                                         continue;
21262                                 }
21263
21264                                 h = getHandler(x);
21265                                 if(h.state() !== 0) {
21266                                         resolver.become(h);
21267                                         visitRemaining(promises, i+1, h);
21268                                         break;
21269                                 } else {
21270                                         h.visit(resolver, resolver.resolve, resolver.reject);
21271                                 }
21272                         }
21273                         return new Promise(Handler, resolver);
21274                 }
21275
21276                 // Promise internals
21277                 // Below this, everything is @private
21278
21279                 /**
21280                  * Get an appropriate handler for x, without checking for cycles
21281                  * @param {*} x
21282                  * @returns {object} handler
21283                  */
21284                 function getHandler(x) {
21285                         if(isPromise(x)) {
21286                                 return x._handler.join();
21287                         }
21288                         return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
21289                 }
21290
21291                 /**
21292                  * Get a handler for thenable x.
21293                  * NOTE: You must only call this if maybeThenable(x) == true
21294                  * @param {object|function|Promise} x
21295                  * @returns {object} handler
21296                  */
21297                 function getHandlerMaybeThenable(x) {
21298                         return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
21299                 }
21300
21301                 /**
21302                  * Get a handler for potentially untrusted thenable x
21303                  * @param {*} x
21304                  * @returns {object} handler
21305                  */
21306                 function getHandlerUntrusted(x) {
21307                         try {
21308                                 var untrustedThen = x.then;
21309                                 return typeof untrustedThen === 'function'
21310                                         ? new Thenable(untrustedThen, x)
21311                                         : new Fulfilled(x);
21312                         } catch(e) {
21313                                 return new Rejected(e);
21314                         }
21315                 }
21316
21317                 /**
21318                  * Handler for a promise that is pending forever
21319                  * @constructor
21320                  */
21321                 function Handler() {}
21322
21323                 Handler.prototype.when
21324                         = Handler.prototype.become
21325                         = Handler.prototype.notify // deprecated
21326                         = Handler.prototype.fail
21327                         = Handler.prototype._unreport
21328                         = Handler.prototype._report
21329                         = noop;
21330
21331                 Handler.prototype._state = 0;
21332
21333                 Handler.prototype.state = function() {
21334                         return this._state;
21335                 };
21336
21337                 /**
21338                  * Recursively collapse handler chain to find the handler
21339                  * nearest to the fully resolved value.
21340                  * @returns {object} handler nearest the fully resolved value
21341                  */
21342                 Handler.prototype.join = function() {
21343                         var h = this;
21344                         while(h.handler !== void 0) {
21345                                 h = h.handler;
21346                         }
21347                         return h;
21348                 };
21349
21350                 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
21351                         this.when({
21352                                 resolver: to,
21353                                 receiver: receiver,
21354                                 fulfilled: fulfilled,
21355                                 rejected: rejected,
21356                                 progress: progress
21357                         });
21358                 };
21359
21360                 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
21361                         this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
21362                 };
21363
21364                 Handler.prototype.fold = function(f, z, c, to) {
21365                         this.when(new Fold(f, z, c, to));
21366                 };
21367
21368                 /**
21369                  * Handler that invokes fail() on any handler it becomes
21370                  * @constructor
21371                  */
21372                 function FailIfRejected() {}
21373
21374                 inherit(Handler, FailIfRejected);
21375
21376                 FailIfRejected.prototype.become = function(h) {
21377                         h.fail();
21378                 };
21379
21380                 var failIfRejected = new FailIfRejected();
21381
21382                 /**
21383                  * Handler that manages a queue of consumers waiting on a pending promise
21384                  * @constructor
21385                  */
21386                 function Pending(receiver, inheritedContext) {
21387                         Promise.createContext(this, inheritedContext);
21388
21389                         this.consumers = void 0;
21390                         this.receiver = receiver;
21391                         this.handler = void 0;
21392                         this.resolved = false;
21393                 }
21394
21395                 inherit(Handler, Pending);
21396
21397                 Pending.prototype._state = 0;
21398
21399                 Pending.prototype.resolve = function(x) {
21400                         this.become(getHandler(x));
21401                 };
21402
21403                 Pending.prototype.reject = function(x) {
21404                         if(this.resolved) {
21405                                 return;
21406                         }
21407
21408                         this.become(new Rejected(x));
21409                 };
21410
21411                 Pending.prototype.join = function() {
21412                         if (!this.resolved) {
21413                                 return this;
21414                         }
21415
21416                         var h = this;
21417
21418                         while (h.handler !== void 0) {
21419                                 h = h.handler;
21420                                 if (h === this) {
21421                                         return this.handler = cycle();
21422                                 }
21423                         }
21424
21425                         return h;
21426                 };
21427
21428                 Pending.prototype.run = function() {
21429                         var q = this.consumers;
21430                         var handler = this.handler;
21431                         this.handler = this.handler.join();
21432                         this.consumers = void 0;
21433
21434                         for (var i = 0; i < q.length; ++i) {
21435                                 handler.when(q[i]);
21436                         }
21437                 };
21438
21439                 Pending.prototype.become = function(handler) {
21440                         if(this.resolved) {
21441                                 return;
21442                         }
21443
21444                         this.resolved = true;
21445                         this.handler = handler;
21446                         if(this.consumers !== void 0) {
21447                                 tasks.enqueue(this);
21448                         }
21449
21450                         if(this.context !== void 0) {
21451                                 handler._report(this.context);
21452                         }
21453                 };
21454
21455                 Pending.prototype.when = function(continuation) {
21456                         if(this.resolved) {
21457                                 tasks.enqueue(new ContinuationTask(continuation, this.handler));
21458                         } else {
21459                                 if(this.consumers === void 0) {
21460                                         this.consumers = [continuation];
21461                                 } else {
21462                                         this.consumers.push(continuation);
21463                                 }
21464                         }
21465                 };
21466
21467                 /**
21468                  * @deprecated
21469                  */
21470                 Pending.prototype.notify = function(x) {
21471                         if(!this.resolved) {
21472                                 tasks.enqueue(new ProgressTask(x, this));
21473                         }
21474                 };
21475
21476                 Pending.prototype.fail = function(context) {
21477                         var c = typeof context === 'undefined' ? this.context : context;
21478                         this.resolved && this.handler.join().fail(c);
21479                 };
21480
21481                 Pending.prototype._report = function(context) {
21482                         this.resolved && this.handler.join()._report(context);
21483                 };
21484
21485                 Pending.prototype._unreport = function() {
21486                         this.resolved && this.handler.join()._unreport();
21487                 };
21488
21489                 /**
21490                  * Wrap another handler and force it into a future stack
21491                  * @param {object} handler
21492                  * @constructor
21493                  */
21494                 function Async(handler) {
21495                         this.handler = handler;
21496                 }
21497
21498                 inherit(Handler, Async);
21499
21500                 Async.prototype.when = function(continuation) {
21501                         tasks.enqueue(new ContinuationTask(continuation, this));
21502                 };
21503
21504                 Async.prototype._report = function(context) {
21505                         this.join()._report(context);
21506                 };
21507
21508                 Async.prototype._unreport = function() {
21509                         this.join()._unreport();
21510                 };
21511
21512                 /**
21513                  * Handler that wraps an untrusted thenable and assimilates it in a future stack
21514                  * @param {function} then
21515                  * @param {{then: function}} thenable
21516                  * @constructor
21517                  */
21518                 function Thenable(then, thenable) {
21519                         Pending.call(this);
21520                         tasks.enqueue(new AssimilateTask(then, thenable, this));
21521                 }
21522
21523                 inherit(Pending, Thenable);
21524
21525                 /**
21526                  * Handler for a fulfilled promise
21527                  * @param {*} x fulfillment value
21528                  * @constructor
21529                  */
21530                 function Fulfilled(x) {
21531                         Promise.createContext(this);
21532                         this.value = x;
21533                 }
21534
21535                 inherit(Handler, Fulfilled);
21536
21537                 Fulfilled.prototype._state = 1;
21538
21539                 Fulfilled.prototype.fold = function(f, z, c, to) {
21540                         runContinuation3(f, z, this, c, to);
21541                 };
21542
21543                 Fulfilled.prototype.when = function(cont) {
21544                         runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
21545                 };
21546
21547                 var errorId = 0;
21548
21549                 /**
21550                  * Handler for a rejected promise
21551                  * @param {*} x rejection reason
21552                  * @constructor
21553                  */
21554                 function Rejected(x) {
21555                         Promise.createContext(this);
21556
21557                         this.id = ++errorId;
21558                         this.value = x;
21559                         this.handled = false;
21560                         this.reported = false;
21561
21562                         this._report();
21563                 }
21564
21565                 inherit(Handler, Rejected);
21566
21567                 Rejected.prototype._state = -1;
21568
21569                 Rejected.prototype.fold = function(f, z, c, to) {
21570                         to.become(this);
21571                 };
21572
21573                 Rejected.prototype.when = function(cont) {
21574                         if(typeof cont.rejected === 'function') {
21575                                 this._unreport();
21576                         }
21577                         runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
21578                 };
21579
21580                 Rejected.prototype._report = function(context) {
21581                         tasks.afterQueue(new ReportTask(this, context));
21582                 };
21583
21584                 Rejected.prototype._unreport = function() {
21585                         if(this.handled) {
21586                                 return;
21587                         }
21588                         this.handled = true;
21589                         tasks.afterQueue(new UnreportTask(this));
21590                 };
21591
21592                 Rejected.prototype.fail = function(context) {
21593                         this.reported = true;
21594                         emitRejection('unhandledRejection', this);
21595                         Promise.onFatalRejection(this, context === void 0 ? this.context : context);
21596                 };
21597
21598                 function ReportTask(rejection, context) {
21599                         this.rejection = rejection;
21600                         this.context = context;
21601                 }
21602
21603                 ReportTask.prototype.run = function() {
21604                         if(!this.rejection.handled && !this.rejection.reported) {
21605                                 this.rejection.reported = true;
21606                                 emitRejection('unhandledRejection', this.rejection) ||
21607                                         Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
21608                         }
21609                 };
21610
21611                 function UnreportTask(rejection) {
21612                         this.rejection = rejection;
21613                 }
21614
21615                 UnreportTask.prototype.run = function() {
21616                         if(this.rejection.reported) {
21617                                 emitRejection('rejectionHandled', this.rejection) ||
21618                                         Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
21619                         }
21620                 };
21621
21622                 // Unhandled rejection hooks
21623                 // By default, everything is a noop
21624
21625                 Promise.createContext
21626                         = Promise.enterContext
21627                         = Promise.exitContext
21628                         = Promise.onPotentiallyUnhandledRejection
21629                         = Promise.onPotentiallyUnhandledRejectionHandled
21630                         = Promise.onFatalRejection
21631                         = noop;
21632
21633                 // Errors and singletons
21634
21635                 var foreverPendingHandler = new Handler();
21636                 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
21637
21638                 function cycle() {
21639                         return new Rejected(new TypeError('Promise cycle'));
21640                 }
21641
21642                 // Task runners
21643
21644                 /**
21645                  * Run a single consumer
21646                  * @constructor
21647                  */
21648                 function ContinuationTask(continuation, handler) {
21649                         this.continuation = continuation;
21650                         this.handler = handler;
21651                 }
21652
21653                 ContinuationTask.prototype.run = function() {
21654                         this.handler.join().when(this.continuation);
21655                 };
21656
21657                 /**
21658                  * Run a queue of progress handlers
21659                  * @constructor
21660                  */
21661                 function ProgressTask(value, handler) {
21662                         this.handler = handler;
21663                         this.value = value;
21664                 }
21665
21666                 ProgressTask.prototype.run = function() {
21667                         var q = this.handler.consumers;
21668                         if(q === void 0) {
21669                                 return;
21670                         }
21671
21672                         for (var c, i = 0; i < q.length; ++i) {
21673                                 c = q[i];
21674                                 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
21675                         }
21676                 };
21677
21678                 /**
21679                  * Assimilate a thenable, sending it's value to resolver
21680                  * @param {function} then
21681                  * @param {object|function} thenable
21682                  * @param {object} resolver
21683                  * @constructor
21684                  */
21685                 function AssimilateTask(then, thenable, resolver) {
21686                         this._then = then;
21687                         this.thenable = thenable;
21688                         this.resolver = resolver;
21689                 }
21690
21691                 AssimilateTask.prototype.run = function() {
21692                         var h = this.resolver;
21693                         tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
21694
21695                         function _resolve(x) { h.resolve(x); }
21696                         function _reject(x)  { h.reject(x); }
21697                         function _notify(x)  { h.notify(x); }
21698                 };
21699
21700                 function tryAssimilate(then, thenable, resolve, reject, notify) {
21701                         try {
21702                                 then.call(thenable, resolve, reject, notify);
21703                         } catch (e) {
21704                                 reject(e);
21705                         }
21706                 }
21707
21708                 /**
21709                  * Fold a handler value with z
21710                  * @constructor
21711                  */
21712                 function Fold(f, z, c, to) {
21713                         this.f = f; this.z = z; this.c = c; this.to = to;
21714                         this.resolver = failIfRejected;
21715                         this.receiver = this;
21716                 }
21717
21718                 Fold.prototype.fulfilled = function(x) {
21719                         this.f.call(this.c, this.z, x, this.to);
21720                 };
21721
21722                 Fold.prototype.rejected = function(x) {
21723                         this.to.reject(x);
21724                 };
21725
21726                 Fold.prototype.progress = function(x) {
21727                         this.to.notify(x);
21728                 };
21729
21730                 // Other helpers
21731
21732                 /**
21733                  * @param {*} x
21734                  * @returns {boolean} true iff x is a trusted Promise
21735                  */
21736                 function isPromise(x) {
21737                         return x instanceof Promise;
21738                 }
21739
21740                 /**
21741                  * Test just enough to rule out primitives, in order to take faster
21742                  * paths in some code
21743                  * @param {*} x
21744                  * @returns {boolean} false iff x is guaranteed *not* to be a thenable
21745                  */
21746                 function maybeThenable(x) {
21747                         return (typeof x === 'object' || typeof x === 'function') && x !== null;
21748                 }
21749
21750                 function runContinuation1(f, h, receiver, next) {
21751                         if(typeof f !== 'function') {
21752                                 return next.become(h);
21753                         }
21754
21755                         Promise.enterContext(h);
21756                         tryCatchReject(f, h.value, receiver, next);
21757                         Promise.exitContext();
21758                 }
21759
21760                 function runContinuation3(f, x, h, receiver, next) {
21761                         if(typeof f !== 'function') {
21762                                 return next.become(h);
21763                         }
21764
21765                         Promise.enterContext(h);
21766                         tryCatchReject3(f, x, h.value, receiver, next);
21767                         Promise.exitContext();
21768                 }
21769
21770                 /**
21771                  * @deprecated
21772                  */
21773                 function runNotify(f, x, h, receiver, next) {
21774                         if(typeof f !== 'function') {
21775                                 return next.notify(x);
21776                         }
21777
21778                         Promise.enterContext(h);
21779                         tryCatchReturn(f, x, receiver, next);
21780                         Promise.exitContext();
21781                 }
21782
21783                 function tryCatch2(f, a, b) {
21784                         try {
21785                                 return f(a, b);
21786                         } catch(e) {
21787                                 return reject(e);
21788                         }
21789                 }
21790
21791                 /**
21792                  * Return f.call(thisArg, x), or if it throws return a rejected promise for
21793                  * the thrown exception
21794                  */
21795                 function tryCatchReject(f, x, thisArg, next) {
21796                         try {
21797                                 next.become(getHandler(f.call(thisArg, x)));
21798                         } catch(e) {
21799                                 next.become(new Rejected(e));
21800                         }
21801                 }
21802
21803                 /**
21804                  * Same as above, but includes the extra argument parameter.
21805                  */
21806                 function tryCatchReject3(f, x, y, thisArg, next) {
21807                         try {
21808                                 f.call(thisArg, x, y, next);
21809                         } catch(e) {
21810                                 next.become(new Rejected(e));
21811                         }
21812                 }
21813
21814                 /**
21815                  * @deprecated
21816                  * Return f.call(thisArg, x), or if it throws, *return* the exception
21817                  */
21818                 function tryCatchReturn(f, x, thisArg, next) {
21819                         try {
21820                                 next.notify(f.call(thisArg, x));
21821                         } catch(e) {
21822                                 next.notify(e);
21823                         }
21824                 }
21825
21826                 function inherit(Parent, Child) {
21827                         Child.prototype = objectCreate(Parent.prototype);
21828                         Child.prototype.constructor = Child;
21829                 }
21830
21831                 function snd(x, y) {
21832                         return y;
21833                 }
21834
21835                 function noop() {}
21836
21837                 function hasCustomEvent() {
21838                         if(typeof CustomEvent === 'function') {
21839                                 try {
21840                                         var ev = new CustomEvent('unhandledRejection');
21841                                         return ev instanceof CustomEvent;
21842                                 } catch (ignoredException) {}
21843                         }
21844                         return false;
21845                 }
21846
21847                 function hasInternetExplorerCustomEvent() {
21848                         if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
21849                                 try {
21850                                         // Try to create one event to make sure it's supported
21851                                         var ev = document.createEvent('CustomEvent');
21852                                         ev.initCustomEvent('eventType', false, true, {});
21853                                         return true;
21854                                 } catch (ignoredException) {}
21855                         }
21856                         return false;
21857                 }
21858
21859                 function initEmitRejection() {
21860                         /*global process, self, CustomEvent*/
21861                         if(typeof process !== 'undefined' && process !== null
21862                                 && typeof process.emit === 'function') {
21863                                 // Returning falsy here means to call the default
21864                                 // onPotentiallyUnhandledRejection API.  This is safe even in
21865                                 // browserify since process.emit always returns falsy in browserify:
21866                                 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
21867                                 return function(type, rejection) {
21868                                         return type === 'unhandledRejection'
21869                                                 ? process.emit(type, rejection.value, rejection)
21870                                                 : process.emit(type, rejection);
21871                                 };
21872                         } else if(typeof self !== 'undefined' && hasCustomEvent()) {
21873                                 return (function (self, CustomEvent) {
21874                                         return function (type, rejection) {
21875                                                 var ev = new CustomEvent(type, {
21876                                                         detail: {
21877                                                                 reason: rejection.value,
21878                                                                 key: rejection
21879                                                         },
21880                                                         bubbles: false,
21881                                                         cancelable: true
21882                                                 });
21883
21884                                                 return !self.dispatchEvent(ev);
21885                                         };
21886                                 }(self, CustomEvent));
21887                         } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
21888                                 return (function(self, document) {
21889                                         return function(type, rejection) {
21890                                                 var ev = document.createEvent('CustomEvent');
21891                                                 ev.initCustomEvent(type, false, true, {
21892                                                         reason: rejection.value,
21893                                                         key: rejection
21894                                                 });
21895
21896                                                 return !self.dispatchEvent(ev);
21897                                         };
21898                                 }(self, document));
21899                         }
21900
21901                         return noop;
21902                 }
21903
21904                 return Promise;
21905         };
21906 });
21907 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21908
21909 }).call(this,require('_process'))
21910
21911 },{"_process":6}],271:[function(require,module,exports){
21912 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21913 /** @author Brian Cavalier */
21914 /** @author John Hann */
21915
21916 (function(define) { 'use strict';
21917 define(function() {
21918
21919         return {
21920                 pending: toPendingState,
21921                 fulfilled: toFulfilledState,
21922                 rejected: toRejectedState,
21923                 inspect: inspect
21924         };
21925
21926         function toPendingState() {
21927                 return { state: 'pending' };
21928         }
21929
21930         function toRejectedState(e) {
21931                 return { state: 'rejected', reason: e };
21932         }
21933
21934         function toFulfilledState(x) {
21935                 return { state: 'fulfilled', value: x };
21936         }
21937
21938         function inspect(handler) {
21939                 var state = handler.state();
21940                 return state === 0 ? toPendingState()
21941                          : state > 0   ? toFulfilledState(handler.value)
21942                                        : toRejectedState(handler.value);
21943         }
21944
21945 });
21946 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21947
21948 },{}],272:[function(require,module,exports){
21949 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21950
21951 /**
21952  * Promises/A+ and when() implementation
21953  * when is part of the cujoJS family of libraries (http://cujojs.com/)
21954  * @author Brian Cavalier
21955  * @author John Hann
21956  */
21957 (function(define) { 'use strict';
21958 define(function (require) {
21959
21960         var timed = require('./lib/decorators/timed');
21961         var array = require('./lib/decorators/array');
21962         var flow = require('./lib/decorators/flow');
21963         var fold = require('./lib/decorators/fold');
21964         var inspect = require('./lib/decorators/inspect');
21965         var generate = require('./lib/decorators/iterate');
21966         var progress = require('./lib/decorators/progress');
21967         var withThis = require('./lib/decorators/with');
21968         var unhandledRejection = require('./lib/decorators/unhandledRejection');
21969         var TimeoutError = require('./lib/TimeoutError');
21970
21971         var Promise = [array, flow, fold, generate, progress,
21972                 inspect, withThis, timed, unhandledRejection]
21973                 .reduce(function(Promise, feature) {
21974                         return feature(Promise);
21975                 }, require('./lib/Promise'));
21976
21977         var apply = require('./lib/apply')(Promise);
21978
21979         // Public API
21980
21981         when.promise     = promise;              // Create a pending promise
21982         when.resolve     = Promise.resolve;      // Create a resolved promise
21983         when.reject      = Promise.reject;       // Create a rejected promise
21984
21985         when.lift        = lift;                 // lift a function to return promises
21986         when['try']      = attempt;              // call a function and return a promise
21987         when.attempt     = attempt;              // alias for when.try
21988
21989         when.iterate     = Promise.iterate;      // DEPRECATED (use cujojs/most streams) Generate a stream of promises
21990         when.unfold      = Promise.unfold;       // DEPRECATED (use cujojs/most streams) Generate a stream of promises
21991
21992         when.join        = join;                 // Join 2 or more promises
21993
21994         when.all         = all;                  // Resolve a list of promises
21995         when.settle      = settle;               // Settle a list of promises
21996
21997         when.any         = lift(Promise.any);    // One-winner race
21998         when.some        = lift(Promise.some);   // Multi-winner race
21999         when.race        = lift(Promise.race);   // First-to-settle race
22000
22001         when.map         = map;                  // Array.map() for promises
22002         when.filter      = filter;               // Array.filter() for promises
22003         when.reduce      = lift(Promise.reduce);       // Array.reduce() for promises
22004         when.reduceRight = lift(Promise.reduceRight);  // Array.reduceRight() for promises
22005
22006         when.isPromiseLike = isPromiseLike;      // Is something promise-like, aka thenable
22007
22008         when.Promise     = Promise;              // Promise constructor
22009         when.defer       = defer;                // Create a {promise, resolve, reject} tuple
22010
22011         // Error types
22012
22013         when.TimeoutError = TimeoutError;
22014
22015         /**
22016          * Get a trusted promise for x, or by transforming x with onFulfilled
22017          *
22018          * @param {*} x
22019          * @param {function?} onFulfilled callback to be called when x is
22020          *   successfully fulfilled.  If promiseOrValue is an immediate value, callback
22021          *   will be invoked immediately.
22022          * @param {function?} onRejected callback to be called when x is
22023          *   rejected.
22024          * @param {function?} onProgress callback to be called when progress updates
22025          *   are issued for x. @deprecated
22026          * @returns {Promise} a new promise that will fulfill with the return
22027          *   value of callback or errback or the completion value of promiseOrValue if
22028          *   callback and/or errback is not supplied.
22029          */
22030         function when(x, onFulfilled, onRejected, onProgress) {
22031                 var p = Promise.resolve(x);
22032                 if (arguments.length < 2) {
22033                         return p;
22034                 }
22035
22036                 return p.then(onFulfilled, onRejected, onProgress);
22037         }
22038
22039         /**
22040          * Creates a new promise whose fate is determined by resolver.
22041          * @param {function} resolver function(resolve, reject, notify)
22042          * @returns {Promise} promise whose fate is determine by resolver
22043          */
22044         function promise(resolver) {
22045                 return new Promise(resolver);
22046         }
22047
22048         /**
22049          * Lift the supplied function, creating a version of f that returns
22050          * promises, and accepts promises as arguments.
22051          * @param {function} f
22052          * @returns {Function} version of f that returns promises
22053          */
22054         function lift(f) {
22055                 return function() {
22056                         for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
22057                                 a[i] = arguments[i];
22058                         }
22059                         return apply(f, this, a);
22060                 };
22061         }
22062
22063         /**
22064          * Call f in a future turn, with the supplied args, and return a promise
22065          * for the result.
22066          * @param {function} f
22067          * @returns {Promise}
22068          */
22069         function attempt(f /*, args... */) {
22070                 /*jshint validthis:true */
22071                 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
22072                         a[i] = arguments[i+1];
22073                 }
22074                 return apply(f, this, a);
22075         }
22076
22077         /**
22078          * Creates a {promise, resolver} pair, either or both of which
22079          * may be given out safely to consumers.
22080          * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
22081          */
22082         function defer() {
22083                 return new Deferred();
22084         }
22085
22086         function Deferred() {
22087                 var p = Promise._defer();
22088
22089                 function resolve(x) { p._handler.resolve(x); }
22090                 function reject(x) { p._handler.reject(x); }
22091                 function notify(x) { p._handler.notify(x); }
22092
22093                 this.promise = p;
22094                 this.resolve = resolve;
22095                 this.reject = reject;
22096                 this.notify = notify;
22097                 this.resolver = { resolve: resolve, reject: reject, notify: notify };
22098         }
22099
22100         /**
22101          * Determines if x is promise-like, i.e. a thenable object
22102          * NOTE: Will return true for *any thenable object*, and isn't truly
22103          * safe, since it may attempt to access the `then` property of x (i.e.
22104          *  clever/malicious getters may do weird things)
22105          * @param {*} x anything
22106          * @returns {boolean} true if x is promise-like
22107          */
22108         function isPromiseLike(x) {
22109                 return x && typeof x.then === 'function';
22110         }
22111
22112         /**
22113          * Return a promise that will resolve only once all the supplied arguments
22114          * have resolved. The resolution value of the returned promise will be an array
22115          * containing the resolution values of each of the arguments.
22116          * @param {...*} arguments may be a mix of promises and values
22117          * @returns {Promise}
22118          */
22119         function join(/* ...promises */) {
22120                 return Promise.all(arguments);
22121         }
22122
22123         /**
22124          * Return a promise that will fulfill once all input promises have
22125          * fulfilled, or reject when any one input promise rejects.
22126          * @param {array|Promise} promises array (or promise for an array) of promises
22127          * @returns {Promise}
22128          */
22129         function all(promises) {
22130                 return when(promises, Promise.all);
22131         }
22132
22133         /**
22134          * Return a promise that will always fulfill with an array containing
22135          * the outcome states of all input promises.  The returned promise
22136          * will only reject if `promises` itself is a rejected promise.
22137          * @param {array|Promise} promises array (or promise for an array) of promises
22138          * @returns {Promise} promise for array of settled state descriptors
22139          */
22140         function settle(promises) {
22141                 return when(promises, Promise.settle);
22142         }
22143
22144         /**
22145          * Promise-aware array map function, similar to `Array.prototype.map()`,
22146          * but input array may contain promises or values.
22147          * @param {Array|Promise} promises array of anything, may contain promises and values
22148          * @param {function(x:*, index:Number):*} mapFunc map function which may
22149          *  return a promise or value
22150          * @returns {Promise} promise that will fulfill with an array of mapped values
22151          *  or reject if any input promise rejects.
22152          */
22153         function map(promises, mapFunc) {
22154                 return when(promises, function(promises) {
22155                         return Promise.map(promises, mapFunc);
22156                 });
22157         }
22158
22159         /**
22160          * Filter the provided array of promises using the provided predicate.  Input may
22161          * contain promises and values
22162          * @param {Array|Promise} promises array of promises and values
22163          * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
22164          *  Must return truthy (or promise for truthy) for items to retain.
22165          * @returns {Promise} promise that will fulfill with an array containing all items
22166          *  for which predicate returned truthy.
22167          */
22168         function filter(promises, predicate) {
22169                 return when(promises, function(promises) {
22170                         return Promise.filter(promises, predicate);
22171                 });
22172         }
22173
22174         return when;
22175 });
22176 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
22177
22178 },{"./lib/Promise":255,"./lib/TimeoutError":257,"./lib/apply":258,"./lib/decorators/array":259,"./lib/decorators/flow":260,"./lib/decorators/fold":261,"./lib/decorators/inspect":262,"./lib/decorators/iterate":263,"./lib/decorators/progress":264,"./lib/decorators/timed":265,"./lib/decorators/unhandledRejection":266,"./lib/decorators/with":267}],273:[function(require,module,exports){
22179 var nativeIsArray = Array.isArray
22180 var toString = Object.prototype.toString
22181
22182 module.exports = nativeIsArray || isArray
22183
22184 function isArray(obj) {
22185     return toString.call(obj) === "[object Array]"
22186 }
22187
22188 },{}],274:[function(require,module,exports){
22189 "use strict";
22190 Object.defineProperty(exports, "__esModule", { value: true });
22191 var APIv3_1 = require("./api/APIv3");
22192 exports.APIv3 = APIv3_1.APIv3;
22193 var ModelCreator_1 = require("./api/ModelCreator");
22194 exports.ModelCreator = ModelCreator_1.ModelCreator;
22195
22196 },{"./api/APIv3":287,"./api/ModelCreator":288}],275:[function(require,module,exports){
22197 "use strict";
22198 function __export(m) {
22199     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22200 }
22201 Object.defineProperty(exports, "__esModule", { value: true });
22202 var Component_1 = require("./component/Component");
22203 exports.Component = Component_1.Component;
22204 var ComponentService_1 = require("./component/ComponentService");
22205 exports.ComponentService = ComponentService_1.ComponentService;
22206 var HandlerBase_1 = require("./component/utils/HandlerBase");
22207 exports.HandlerBase = HandlerBase_1.HandlerBase;
22208 var MeshFactory_1 = require("./component/utils/MeshFactory");
22209 exports.MeshFactory = MeshFactory_1.MeshFactory;
22210 var MeshScene_1 = require("./component/utils/MeshScene");
22211 exports.MeshScene = MeshScene_1.MeshScene;
22212 var MouseOperator_1 = require("./component/utils/MouseOperator");
22213 exports.MouseOperator = MouseOperator_1.MouseOperator;
22214 var ComponentSize_1 = require("./component/utils/ComponentSize");
22215 exports.ComponentSize = ComponentSize_1.ComponentSize;
22216 var AttributionComponent_1 = require("./component/AttributionComponent");
22217 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
22218 var BackgroundComponent_1 = require("./component/BackgroundComponent");
22219 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
22220 var BearingComponent_1 = require("./component/BearingComponent");
22221 exports.BearingComponent = BearingComponent_1.BearingComponent;
22222 var CacheComponent_1 = require("./component/CacheComponent");
22223 exports.CacheComponent = CacheComponent_1.CacheComponent;
22224 var CoverComponent_1 = require("./component/CoverComponent");
22225 exports.CoverComponent = CoverComponent_1.CoverComponent;
22226 var DebugComponent_1 = require("./component/DebugComponent");
22227 exports.DebugComponent = DebugComponent_1.DebugComponent;
22228 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
22229 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
22230 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
22231 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
22232 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
22233 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
22234 var ImageComponent_1 = require("./component/ImageComponent");
22235 exports.ImageComponent = ImageComponent_1.ImageComponent;
22236 var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent");
22237 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
22238 var KeyPlayHandler_1 = require("./component/keyboard/KeyPlayHandler");
22239 exports.KeyPlayHandler = KeyPlayHandler_1.KeyPlayHandler;
22240 var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler");
22241 exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler;
22242 var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler");
22243 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler;
22244 var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler");
22245 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler;
22246 var LoadingComponent_1 = require("./component/LoadingComponent");
22247 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
22248 var Marker_1 = require("./component/marker/marker/Marker");
22249 exports.Marker = Marker_1.Marker;
22250 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
22251 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
22252 var MarkerScene_1 = require("./component/marker/MarkerScene");
22253 exports.MarkerScene = MarkerScene_1.MarkerScene;
22254 var MarkerSet_1 = require("./component/marker/MarkerSet");
22255 exports.MarkerSet = MarkerSet_1.MarkerSet;
22256 var MouseComponent_1 = require("./component/mouse/MouseComponent");
22257 exports.MouseComponent = MouseComponent_1.MouseComponent;
22258 var BounceHandler_1 = require("./component/mouse/BounceHandler");
22259 exports.BounceHandler = BounceHandler_1.BounceHandler;
22260 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
22261 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
22262 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
22263 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
22264 var EarthControlHandler_1 = require("./component/mouse/EarthControlHandler");
22265 exports.EarthControlHandler = EarthControlHandler_1.EarthControlHandler;
22266 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
22267 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
22268 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
22269 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
22270 var ImageBoundary = require("./component/mouse/ImageBoundary");
22271 exports.ImageBoundary = ImageBoundary;
22272 var Popup_1 = require("./component/popup/popup/Popup");
22273 exports.Popup = Popup_1.Popup;
22274 var PopupComponent_1 = require("./component/popup/PopupComponent");
22275 exports.PopupComponent = PopupComponent_1.PopupComponent;
22276 var NavigationComponent_1 = require("./component/NavigationComponent");
22277 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
22278 var RouteComponent_1 = require("./component/RouteComponent");
22279 exports.RouteComponent = RouteComponent_1.RouteComponent;
22280 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
22281 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
22282 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
22283 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
22284 var SequenceMode_1 = require("./component/sequence/SequenceMode");
22285 exports.SequenceMode = SequenceMode_1.SequenceMode;
22286 var SpatialDataCache_1 = require("./component/spatialdata/SpatialDataCache");
22287 exports.SpatialDataCache = SpatialDataCache_1.SpatialDataCache;
22288 var SpatialDataComponent_1 = require("./component/spatialdata/SpatialDataComponent");
22289 exports.SpatialDataComponent = SpatialDataComponent_1.SpatialDataComponent;
22290 var SpatialDataScene_1 = require("./component/spatialdata/SpatialDataScene");
22291 exports.SpatialDataScene = SpatialDataScene_1.SpatialDataScene;
22292 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
22293 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
22294 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
22295 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
22296 var Shaders_1 = require("./component/shaders/Shaders");
22297 exports.Shaders = Shaders_1.Shaders;
22298 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
22299 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
22300 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
22301 exports.CircleMarker = CircleMarker_1.CircleMarker;
22302 var SliderComponent_1 = require("./component/slider/SliderComponent");
22303 exports.SliderComponent = SliderComponent_1.SliderComponent;
22304 var SliderDOMRenderer_1 = require("./component/slider/SliderDOMRenderer");
22305 exports.SliderDOMRenderer = SliderDOMRenderer_1.SliderDOMRenderer;
22306 var SliderGLRenderer_1 = require("./component/slider/SliderGLRenderer");
22307 exports.SliderGLRenderer = SliderGLRenderer_1.SliderGLRenderer;
22308 var StatsComponent_1 = require("./component/StatsComponent");
22309 exports.StatsComponent = StatsComponent_1.StatsComponent;
22310 var TagHandlerBase_1 = require("./component/tag/handlers/TagHandlerBase");
22311 exports.TagHandlerBase = TagHandlerBase_1.TagHandlerBase;
22312 var CreateHandlerBase_1 = require("./component/tag/handlers/CreateHandlerBase");
22313 exports.CreateHandlerBase = CreateHandlerBase_1.CreateHandlerBase;
22314 var CreatePointHandler_1 = require("./component/tag/handlers/CreatePointHandler");
22315 exports.CreatePointHandler = CreatePointHandler_1.CreatePointHandler;
22316 var CreateVertexHandler_1 = require("./component/tag/handlers/CreateVertexHandler");
22317 exports.CreateVertexHandler = CreateVertexHandler_1.CreateVertexHandler;
22318 var CreatePolygonHandler_1 = require("./component/tag/handlers/CreatePolygonHandler");
22319 exports.CreatePolygonHandler = CreatePolygonHandler_1.CreatePolygonHandler;
22320 var CreateRectHandler_1 = require("./component/tag/handlers/CreateRectHandler");
22321 exports.CreateRectHandler = CreateRectHandler_1.CreateRectHandler;
22322 var CreateRectDragHandler_1 = require("./component/tag/handlers/CreateRectDragHandler");
22323 exports.CreateRectDragHandler = CreateRectDragHandler_1.CreateRectDragHandler;
22324 var EditVertexHandler_1 = require("./component/tag/handlers/EditVertexHandler");
22325 exports.EditVertexHandler = EditVertexHandler_1.EditVertexHandler;
22326 var Tag_1 = require("./component/tag/tag/Tag");
22327 exports.Tag = Tag_1.Tag;
22328 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
22329 exports.OutlineTag = OutlineTag_1.OutlineTag;
22330 var RenderTag_1 = require("./component/tag/tag/RenderTag");
22331 exports.RenderTag = RenderTag_1.RenderTag;
22332 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
22333 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
22334 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
22335 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
22336 var SpotTag_1 = require("./component/tag/tag/SpotTag");
22337 exports.SpotTag = SpotTag_1.SpotTag;
22338 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
22339 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
22340 var TagDomain_1 = require("./component/tag/tag/TagDomain");
22341 exports.TagDomain = TagDomain_1.TagDomain;
22342 var TagComponent_1 = require("./component/tag/TagComponent");
22343 exports.TagComponent = TagComponent_1.TagComponent;
22344 var TagCreator_1 = require("./component/tag/TagCreator");
22345 exports.TagCreator = TagCreator_1.TagCreator;
22346 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
22347 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
22348 var TagMode_1 = require("./component/tag/TagMode");
22349 exports.TagMode = TagMode_1.TagMode;
22350 var TagOperation_1 = require("./component/tag/TagOperation");
22351 exports.TagOperation = TagOperation_1.TagOperation;
22352 var TagScene_1 = require("./component/tag/TagScene");
22353 exports.TagScene = TagScene_1.TagScene;
22354 var TagSet_1 = require("./component/tag/TagSet");
22355 exports.TagSet = TagSet_1.TagSet;
22356 var Geometry_1 = require("./component/tag/geometry/Geometry");
22357 exports.Geometry = Geometry_1.Geometry;
22358 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
22359 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
22360 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
22361 exports.RectGeometry = RectGeometry_1.RectGeometry;
22362 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
22363 exports.PointGeometry = PointGeometry_1.PointGeometry;
22364 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
22365 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
22366 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
22367 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
22368 var ZoomComponent_1 = require("./component/zoom/ZoomComponent");
22369 exports.ZoomComponent = ZoomComponent_1.ZoomComponent;
22370 __export(require("./component/interfaces/interfaces"));
22371
22372 },{"./component/AttributionComponent":289,"./component/BackgroundComponent":290,"./component/BearingComponent":291,"./component/CacheComponent":292,"./component/Component":293,"./component/ComponentService":294,"./component/CoverComponent":295,"./component/DebugComponent":296,"./component/ImageComponent":297,"./component/LoadingComponent":298,"./component/NavigationComponent":299,"./component/RouteComponent":300,"./component/StatsComponent":301,"./component/direction/DirectionComponent":302,"./component/direction/DirectionDOMCalculator":303,"./component/direction/DirectionDOMRenderer":304,"./component/imageplane/ImagePlaneComponent":305,"./component/imageplane/ImagePlaneGLRenderer":306,"./component/interfaces/interfaces":309,"./component/keyboard/KeyPlayHandler":310,"./component/keyboard/KeySequenceNavigationHandler":311,"./component/keyboard/KeySpatialNavigationHandler":312,"./component/keyboard/KeyZoomHandler":313,"./component/keyboard/KeyboardComponent":314,"./component/marker/MarkerComponent":316,"./component/marker/MarkerScene":317,"./component/marker/MarkerSet":318,"./component/marker/marker/CircleMarker":319,"./component/marker/marker/Marker":320,"./component/marker/marker/SimpleMarker":321,"./component/mouse/BounceHandler":322,"./component/mouse/DoubleClickZoomHandler":323,"./component/mouse/DragPanHandler":324,"./component/mouse/EarthControlHandler":325,"./component/mouse/ImageBoundary":326,"./component/mouse/MouseComponent":327,"./component/mouse/ScrollZoomHandler":328,"./component/mouse/TouchZoomHandler":329,"./component/popup/PopupComponent":331,"./component/popup/popup/Popup":332,"./component/sequence/SequenceComponent":333,"./component/sequence/SequenceDOMRenderer":334,"./component/sequence/SequenceMode":335,"./component/shaders/Shaders":336,"./component/slider/SliderComponent":337,"./component/slider/SliderDOMRenderer":338,"./component/slider/SliderGLRenderer":339,"./component/spatialdata/SpatialDataCache":340,"./component/spatialdata/SpatialDataComponent":341,"./component/spatialdata/SpatialDataScene":342,"./component/tag/TagComponent":344,"./component/tag/TagCreator":345,"./component/tag/TagDOMRenderer":346,"./component/tag/TagMode":347,"./component/tag/TagOperation":348,"./component/tag/TagScene":349,"./component/tag/TagSet":350,"./component/tag/error/GeometryTagError":351,"./component/tag/geometry/Geometry":352,"./component/tag/geometry/PointGeometry":353,"./component/tag/geometry/PolygonGeometry":354,"./component/tag/geometry/RectGeometry":355,"./component/tag/geometry/VertexGeometry":356,"./component/tag/handlers/CreateHandlerBase":357,"./component/tag/handlers/CreatePointHandler":358,"./component/tag/handlers/CreatePolygonHandler":359,"./component/tag/handlers/CreateRectDragHandler":360,"./component/tag/handlers/CreateRectHandler":361,"./component/tag/handlers/CreateVertexHandler":362,"./component/tag/handlers/EditVertexHandler":363,"./component/tag/handlers/TagHandlerBase":364,"./component/tag/tag/OutlineCreateTag":365,"./component/tag/tag/OutlineRenderTag":366,"./component/tag/tag/OutlineTag":367,"./component/tag/tag/RenderTag":368,"./component/tag/tag/SpotRenderTag":369,"./component/tag/tag/SpotTag":370,"./component/tag/tag/Tag":371,"./component/tag/tag/TagDomain":372,"./component/utils/ComponentSize":373,"./component/utils/HandlerBase":374,"./component/utils/MeshFactory":375,"./component/utils/MeshScene":376,"./component/utils/MouseOperator":377,"./component/zoom/ZoomComponent":378}],276:[function(require,module,exports){
22373 "use strict";
22374 Object.defineProperty(exports, "__esModule", { value: true });
22375 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
22376 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
22377 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
22378 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
22379 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
22380 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
22381 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
22382 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
22383 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
22384 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
22385
22386 },{"./graph/edge/EdgeCalculator":400,"./graph/edge/EdgeCalculatorCoefficients":401,"./graph/edge/EdgeCalculatorDirections":402,"./graph/edge/EdgeCalculatorSettings":403,"./graph/edge/EdgeDirection":404}],277:[function(require,module,exports){
22387 "use strict";
22388 Object.defineProperty(exports, "__esModule", { value: true });
22389 var AbortMapillaryError_1 = require("./error/AbortMapillaryError");
22390 exports.AbortMapillaryError = AbortMapillaryError_1.AbortMapillaryError;
22391 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
22392 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
22393 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
22394 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
22395 var MapillaryError_1 = require("./error/MapillaryError");
22396 exports.MapillaryError = MapillaryError_1.MapillaryError;
22397
22398 },{"./error/AbortMapillaryError":379,"./error/ArgumentMapillaryError":380,"./error/GraphMapillaryError":381,"./error/MapillaryError":382}],278:[function(require,module,exports){
22399 "use strict";
22400 Object.defineProperty(exports, "__esModule", { value: true });
22401 var Camera_1 = require("./geo/Camera");
22402 exports.Camera = Camera_1.Camera;
22403 var GeoCoords_1 = require("./geo/GeoCoords");
22404 exports.GeoCoords = GeoCoords_1.GeoCoords;
22405 var ViewportCoords_1 = require("./geo/ViewportCoords");
22406 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
22407 var Spatial_1 = require("./geo/Spatial");
22408 exports.Spatial = Spatial_1.Spatial;
22409 var Transform_1 = require("./geo/Transform");
22410 exports.Transform = Transform_1.Transform;
22411 var Geo = require("./geo/Geo");
22412 exports.Geo = Geo;
22413 var Lines = require("./geo/Lines");
22414 exports.Lines = Lines;
22415
22416 },{"./geo/Camera":383,"./geo/Geo":384,"./geo/GeoCoords":385,"./geo/Lines":386,"./geo/Spatial":387,"./geo/Transform":388,"./geo/ViewportCoords":389}],279:[function(require,module,exports){
22417 "use strict";
22418 Object.defineProperty(exports, "__esModule", { value: true });
22419 var FilterCreator_1 = require("./graph/FilterCreator");
22420 exports.FilterCreator = FilterCreator_1.FilterCreator;
22421 var Graph_1 = require("./graph/Graph");
22422 exports.Graph = Graph_1.Graph;
22423 var GraphCalculator_1 = require("./graph/GraphCalculator");
22424 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
22425 var GraphMode_1 = require("./graph/GraphMode");
22426 exports.GraphMode = GraphMode_1.GraphMode;
22427 var GraphService_1 = require("./graph/GraphService");
22428 exports.GraphService = GraphService_1.GraphService;
22429 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
22430 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
22431 var MeshReader_1 = require("./graph/MeshReader");
22432 exports.MeshReader = MeshReader_1.MeshReader;
22433 var Node_1 = require("./graph/Node");
22434 exports.Node = Node_1.Node;
22435 var NodeCache_1 = require("./graph/NodeCache");
22436 exports.NodeCache = NodeCache_1.NodeCache;
22437 var Sequence_1 = require("./graph/Sequence");
22438 exports.Sequence = Sequence_1.Sequence;
22439
22440 },{"./graph/FilterCreator":390,"./graph/Graph":391,"./graph/GraphCalculator":392,"./graph/GraphMode":393,"./graph/GraphService":394,"./graph/ImageLoadingService":395,"./graph/MeshReader":396,"./graph/Node":397,"./graph/NodeCache":398,"./graph/Sequence":399}],280:[function(require,module,exports){
22441 "use strict";
22442 /**
22443  * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
22444  * @name Mapillary
22445  */
22446 function __export(m) {
22447     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22448 }
22449 Object.defineProperty(exports, "__esModule", { value: true });
22450 __export(require("./Support"));
22451 var Edge_1 = require("./Edge");
22452 exports.EdgeDirection = Edge_1.EdgeDirection;
22453 var Error_1 = require("./Error");
22454 exports.AbortMapillaryError = Error_1.AbortMapillaryError;
22455 var Render_1 = require("./Render");
22456 exports.RenderMode = Render_1.RenderMode;
22457 var State_1 = require("./State");
22458 exports.TransitionMode = State_1.TransitionMode;
22459 var Viewer_1 = require("./Viewer");
22460 exports.Alignment = Viewer_1.Alignment;
22461 exports.ImageSize = Viewer_1.ImageSize;
22462 exports.Viewer = Viewer_1.Viewer;
22463 var Component_1 = require("./Component");
22464 exports.SliderMode = Component_1.SliderMode;
22465 exports.ComponentSize = Component_1.ComponentSize;
22466 var TagComponent = require("./component/tag/Tag");
22467 exports.TagComponent = TagComponent;
22468 var MarkerComponent = require("./component/marker/Marker");
22469 exports.MarkerComponent = MarkerComponent;
22470 var PopupComponent = require("./component/popup/Popup");
22471 exports.PopupComponent = PopupComponent;
22472
22473 },{"./Component":275,"./Edge":276,"./Error":277,"./Render":281,"./State":282,"./Support":283,"./Viewer":286,"./component/marker/Marker":315,"./component/popup/Popup":330,"./component/tag/Tag":343}],281:[function(require,module,exports){
22474 "use strict";
22475 Object.defineProperty(exports, "__esModule", { value: true });
22476 var DOMRenderer_1 = require("./render/DOMRenderer");
22477 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
22478 var GLRenderer_1 = require("./render/GLRenderer");
22479 exports.GLRenderer = GLRenderer_1.GLRenderer;
22480 var GLRenderStage_1 = require("./render/GLRenderStage");
22481 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
22482 var RenderCamera_1 = require("./render/RenderCamera");
22483 exports.RenderCamera = RenderCamera_1.RenderCamera;
22484 var RenderMode_1 = require("./render/RenderMode");
22485 exports.RenderMode = RenderMode_1.RenderMode;
22486 var RenderService_1 = require("./render/RenderService");
22487 exports.RenderService = RenderService_1.RenderService;
22488
22489 },{"./render/DOMRenderer":405,"./render/GLRenderStage":406,"./render/GLRenderer":407,"./render/RenderCamera":408,"./render/RenderMode":409,"./render/RenderService":410}],282:[function(require,module,exports){
22490 "use strict";
22491 Object.defineProperty(exports, "__esModule", { value: true });
22492 var FrameGenerator_1 = require("./state/FrameGenerator");
22493 exports.FrameGenerator = FrameGenerator_1.FrameGenerator;
22494 var RotationDelta_1 = require("./state/RotationDelta");
22495 exports.RotationDelta = RotationDelta_1.RotationDelta;
22496 var State_1 = require("./state/State");
22497 exports.State = State_1.State;
22498 var StateBase_1 = require("./state/states/StateBase");
22499 exports.StateBase = StateBase_1.StateBase;
22500 var StateContext_1 = require("./state/StateContext");
22501 exports.StateContext = StateContext_1.StateContext;
22502 var StateService_1 = require("./state/StateService");
22503 exports.StateService = StateService_1.StateService;
22504 var TransitionMode_1 = require("./state/TransitionMode");
22505 exports.TransitionMode = TransitionMode_1.TransitionMode;
22506 var EarthState_1 = require("./state/states/EarthState");
22507 exports.EarthState = EarthState_1.EarthState;
22508 var InteractiveStateBase_1 = require("./state/states/InteractiveStateBase");
22509 exports.InteractiveStateBase = InteractiveStateBase_1.InteractiveStateBase;
22510 var InteractiveWaitingState_1 = require("./state/states/InteractiveWaitingState");
22511 exports.InteractiveWaitingState = InteractiveWaitingState_1.InteractiveWaitingState;
22512 var TraversingState_1 = require("./state/states/TraversingState");
22513 exports.TraversingState = TraversingState_1.TraversingState;
22514 var WaitingState_1 = require("./state/states/WaitingState");
22515 exports.WaitingState = WaitingState_1.WaitingState;
22516
22517 },{"./state/FrameGenerator":411,"./state/RotationDelta":412,"./state/State":413,"./state/StateContext":414,"./state/StateService":415,"./state/TransitionMode":416,"./state/states/EarthState":417,"./state/states/InteractiveStateBase":418,"./state/states/InteractiveWaitingState":419,"./state/states/StateBase":420,"./state/states/TraversingState":421,"./state/states/WaitingState":422}],283:[function(require,module,exports){
22518 "use strict";
22519 Object.defineProperty(exports, "__esModule", { value: true });
22520 var support = require("./utils/Support");
22521 /**
22522  * Test whether the current browser supports the full
22523  * functionality of MapillaryJS.
22524  *
22525  * @description The full functionality includes WebGL rendering.
22526  *
22527  * @return {boolean}
22528  *
22529  * @example `var supported = Mapillary.isSupported();`
22530  */
22531 function isSupported() {
22532     return isFallbackSupported() &&
22533         support.isWebGLSupportedCached();
22534 }
22535 exports.isSupported = isSupported;
22536 /**
22537  * Test whether the current browser supports the fallback
22538  * functionality of MapillaryJS.
22539  *
22540  * @description The fallback functionality does not include WebGL
22541  * rendering, only 2D canvas rendering.
22542  *
22543  * @return {boolean}
22544  *
22545  * @example `var fallbackSupported = Mapillary.isFallbackSupported();`
22546  */
22547 function isFallbackSupported() {
22548     return support.isBrowser() &&
22549         support.isBlobSupported() &&
22550         support.isArraySupported() &&
22551         support.isFunctionSupported() &&
22552         support.isJSONSupported() &&
22553         support.isObjectSupported();
22554 }
22555 exports.isFallbackSupported = isFallbackSupported;
22556
22557 },{"./utils/Support":430}],284:[function(require,module,exports){
22558 "use strict";
22559 Object.defineProperty(exports, "__esModule", { value: true });
22560 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
22561 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
22562 var ImageTileStore_1 = require("./tiles/ImageTileStore");
22563 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
22564 var TextureProvider_1 = require("./tiles/TextureProvider");
22565 exports.TextureProvider = TextureProvider_1.TextureProvider;
22566 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
22567 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
22568
22569 },{"./tiles/ImageTileLoader":423,"./tiles/ImageTileStore":424,"./tiles/RegionOfInterestCalculator":425,"./tiles/TextureProvider":426}],285:[function(require,module,exports){
22570 "use strict";
22571 function __export(m) {
22572     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22573 }
22574 Object.defineProperty(exports, "__esModule", { value: true });
22575 var DOM_1 = require("./utils/DOM");
22576 exports.DOM = DOM_1.DOM;
22577 var EventEmitter_1 = require("./utils/EventEmitter");
22578 exports.EventEmitter = EventEmitter_1.EventEmitter;
22579 var Settings_1 = require("./utils/Settings");
22580 exports.Settings = Settings_1.Settings;
22581 __export(require("./utils/Support"));
22582 var Urls_1 = require("./utils/Urls");
22583 exports.Urls = Urls_1.Urls;
22584
22585 },{"./utils/DOM":427,"./utils/EventEmitter":428,"./utils/Settings":429,"./utils/Support":430,"./utils/Urls":431}],286:[function(require,module,exports){
22586 "use strict";
22587 Object.defineProperty(exports, "__esModule", { value: true });
22588 var Alignment_1 = require("./viewer/Alignment");
22589 exports.Alignment = Alignment_1.Alignment;
22590 var CacheService_1 = require("./viewer/CacheService");
22591 exports.CacheService = CacheService_1.CacheService;
22592 var ComponentController_1 = require("./viewer/ComponentController");
22593 exports.ComponentController = ComponentController_1.ComponentController;
22594 var Container_1 = require("./viewer/Container");
22595 exports.Container = Container_1.Container;
22596 var Observer_1 = require("./viewer/Observer");
22597 exports.Observer = Observer_1.Observer;
22598 var ImageSize_1 = require("./viewer/ImageSize");
22599 exports.ImageSize = ImageSize_1.ImageSize;
22600 var KeyboardService_1 = require("./viewer/KeyboardService");
22601 exports.KeyboardService = KeyboardService_1.KeyboardService;
22602 var LoadingService_1 = require("./viewer/LoadingService");
22603 exports.LoadingService = LoadingService_1.LoadingService;
22604 var MouseService_1 = require("./viewer/MouseService");
22605 exports.MouseService = MouseService_1.MouseService;
22606 var Navigator_1 = require("./viewer/Navigator");
22607 exports.Navigator = Navigator_1.Navigator;
22608 var PlayService_1 = require("./viewer/PlayService");
22609 exports.PlayService = PlayService_1.PlayService;
22610 var Projection_1 = require("./viewer/Projection");
22611 exports.Projection = Projection_1.Projection;
22612 var SpriteService_1 = require("./viewer/SpriteService");
22613 exports.SpriteService = SpriteService_1.SpriteService;
22614 var TouchService_1 = require("./viewer/TouchService");
22615 exports.TouchService = TouchService_1.TouchService;
22616 var Viewer_1 = require("./viewer/Viewer");
22617 exports.Viewer = Viewer_1.Viewer;
22618
22619 },{"./viewer/Alignment":432,"./viewer/CacheService":433,"./viewer/ComponentController":434,"./viewer/Container":435,"./viewer/ImageSize":436,"./viewer/KeyboardService":437,"./viewer/LoadingService":438,"./viewer/MouseService":439,"./viewer/Navigator":440,"./viewer/Observer":441,"./viewer/PlayService":443,"./viewer/Projection":444,"./viewer/SpriteService":445,"./viewer/TouchService":446,"./viewer/Viewer":447}],287:[function(require,module,exports){
22620 "use strict";
22621 Object.defineProperty(exports, "__esModule", { value: true });
22622 var operators_1 = require("rxjs/operators");
22623 var rxjs_1 = require("rxjs");
22624 var API_1 = require("../API");
22625 /**
22626  * @class APIv3
22627  *
22628  * @classdesc Provides methods for access of API v3.
22629  */
22630 var APIv3 = /** @class */ (function () {
22631     /**
22632      * Create a new api v3 instance.
22633      *
22634      * @param {number} clientId - Client id for API requests.
22635      * @param {number} [token] - Optional bearer token for API requests of
22636      * protected resources.
22637      * @param {ModelCreator} [creator] - Optional model creator instance.
22638      */
22639     function APIv3(clientId, token, creator) {
22640         this._clientId = clientId;
22641         this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
22642         this._model = this._modelCreator.createModel(clientId, token);
22643         this._pageCount = 999;
22644         this._pathImageByKey = "imageByKey";
22645         this._pathImageCloseTo = "imageCloseTo";
22646         this._pathImagesByH = "imagesByH";
22647         this._pathImageViewAdd = "imageViewAdd";
22648         this._pathSequenceByKey = "sequenceByKey";
22649         this._pathSequenceViewAdd = "sequenceViewAdd";
22650         this._propertiesCore = [
22651             "cl",
22652             "l",
22653             "sequence_key",
22654         ];
22655         this._propertiesFill = [
22656             "captured_at",
22657             "captured_with_camera_uuid",
22658             "user",
22659             "organization_key",
22660             "private",
22661             "project",
22662         ];
22663         this._propertiesKey = [
22664             "key",
22665         ];
22666         this._propertiesSequence = [
22667             "keys",
22668         ];
22669         this._propertiesSpatial = [
22670             "atomic_scale",
22671             "c_rotation",
22672             "ca",
22673             "calt",
22674             "camera_projection_type",
22675             "cca",
22676             "cfocal",
22677             "ck1",
22678             "ck2",
22679             "gpano",
22680             "height",
22681             "merge_cc",
22682             "merge_version",
22683             "orientation",
22684             "width",
22685         ];
22686         this._propertiesUser = [
22687             "username",
22688         ];
22689     }
22690     APIv3.prototype.imageByKeyFill$ = function (keys) {
22691         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
22692             this._pathImageByKey,
22693             keys,
22694             this._propertiesKey
22695                 .concat(this._propertiesFill)
22696                 .concat(this._propertiesSpatial),
22697             this._propertiesKey
22698                 .concat(this._propertiesUser)
22699         ])).pipe(operators_1.map(function (value) {
22700             if (!value) {
22701                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
22702             }
22703             return value.json.imageByKey;
22704         })), this._pathImageByKey, keys);
22705     };
22706     APIv3.prototype.imageByKeyFull$ = function (keys) {
22707         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
22708             this._pathImageByKey,
22709             keys,
22710             this._propertiesKey
22711                 .concat(this._propertiesCore)
22712                 .concat(this._propertiesFill)
22713                 .concat(this._propertiesSpatial),
22714             this._propertiesKey
22715                 .concat(this._propertiesUser)
22716         ])).pipe(operators_1.map(function (value) {
22717             if (!value) {
22718                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
22719             }
22720             return value.json.imageByKey;
22721         })), this._pathImageByKey, keys);
22722     };
22723     APIv3.prototype.imageCloseTo$ = function (lat, lon) {
22724         var lonLat = lon + ":" + lat;
22725         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
22726             this._pathImageCloseTo,
22727             [lonLat],
22728             this._propertiesKey
22729                 .concat(this._propertiesCore)
22730                 .concat(this._propertiesFill)
22731                 .concat(this._propertiesSpatial),
22732             this._propertiesKey
22733                 .concat(this._propertiesUser)
22734         ])).pipe(operators_1.map(function (value) {
22735             return value != null ? value.json.imageCloseTo[lonLat] : null;
22736         })), this._pathImageCloseTo, [lonLat]);
22737     };
22738     APIv3.prototype.imagesByH$ = function (hs) {
22739         var _this = this;
22740         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
22741             this._pathImagesByH,
22742             hs,
22743             { from: 0, to: this._pageCount },
22744             this._propertiesKey
22745                 .concat(this._propertiesCore)
22746         ])).pipe(operators_1.map(function (value) {
22747             if (!value) {
22748                 value = { json: { imagesByH: {} } };
22749                 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
22750                     var h = hs_1[_i];
22751                     value.json.imagesByH[h] = {};
22752                     for (var i = 0; i <= _this._pageCount; i++) {
22753                         value.json.imagesByH[h][i] = null;
22754                     }
22755                 }
22756             }
22757             return value.json.imagesByH;
22758         })), this._pathImagesByH, hs);
22759     };
22760     APIv3.prototype.imageViewAdd$ = function (keys) {
22761         return this._catchInvalidateCall$(this._wrapCallModelResponse$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
22762     };
22763     APIv3.prototype.invalidateImageByKey = function (keys) {
22764         this._invalidateGet(this._pathImageByKey, keys);
22765     };
22766     APIv3.prototype.invalidateImagesByH = function (hs) {
22767         this._invalidateGet(this._pathImagesByH, hs);
22768     };
22769     APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
22770         this._invalidateGet(this._pathSequenceByKey, sKeys);
22771     };
22772     APIv3.prototype.setToken = function (token) {
22773         this._model.invalidate([]);
22774         this._model = null;
22775         this._model = this._modelCreator.createModel(this._clientId, token);
22776     };
22777     APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
22778         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
22779             this._pathSequenceByKey,
22780             sequenceKeys,
22781             this._propertiesKey
22782                 .concat(this._propertiesSequence)
22783         ])).pipe(operators_1.map(function (value) {
22784             if (!value) {
22785                 value = { json: { sequenceByKey: {} } };
22786             }
22787             for (var _i = 0, sequenceKeys_1 = sequenceKeys; _i < sequenceKeys_1.length; _i++) {
22788                 var sequenceKey = sequenceKeys_1[_i];
22789                 if (!(sequenceKey in value.json.sequenceByKey)) {
22790                     console.warn("Sequence data missing (" + sequenceKey + ")");
22791                     value.json.sequenceByKey[sequenceKey] = { key: sequenceKey, keys: [] };
22792                 }
22793             }
22794             return value.json.sequenceByKey;
22795         })), this._pathSequenceByKey, sequenceKeys);
22796     };
22797     APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
22798         return this._catchInvalidateCall$(this._wrapCallModelResponse$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
22799     };
22800     Object.defineProperty(APIv3.prototype, "clientId", {
22801         get: function () {
22802             return this._clientId;
22803         },
22804         enumerable: true,
22805         configurable: true
22806     });
22807     APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
22808         var _this = this;
22809         return observable.pipe(operators_1.catchError(function (error) {
22810             _this._invalidateGet(path, paths);
22811             throw error;
22812         }));
22813     };
22814     APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
22815         var _this = this;
22816         return observable.pipe(operators_1.catchError(function (error) {
22817             _this._invalidateCall(path, paths);
22818             throw error;
22819         }));
22820     };
22821     APIv3.prototype._invalidateGet = function (path, paths) {
22822         this._model.invalidate([path, paths]);
22823     };
22824     APIv3.prototype._invalidateCall = function (path, paths) {
22825         this._model.invalidate([path], [paths]);
22826     };
22827     APIv3.prototype._wrapModelResponse$ = function (modelResponse) {
22828         return rxjs_1.Observable
22829             .create(function (subscriber) {
22830             modelResponse
22831                 .then(function (value) {
22832                 subscriber.next(value);
22833                 subscriber.complete();
22834             }, function (error) {
22835                 subscriber.error(error);
22836             });
22837         });
22838     };
22839     APIv3.prototype._wrapCallModelResponse$ = function (modelResponse) {
22840         return this._wrapModelResponse$(modelResponse).pipe(operators_1.map(function (value) {
22841             return;
22842         }));
22843     };
22844     return APIv3;
22845 }());
22846 exports.APIv3 = APIv3;
22847 exports.default = APIv3;
22848
22849 },{"../API":274,"rxjs":27,"rxjs/operators":225}],288:[function(require,module,exports){
22850 "use strict";
22851 Object.defineProperty(exports, "__esModule", { value: true });
22852 var falcor = require("falcor");
22853 var falcor_http_datasource_1 = require("falcor-http-datasource");
22854 var Utils_1 = require("../Utils");
22855 /**
22856  * @class ModelCreator
22857  *
22858  * @classdesc Creates API models.
22859  */
22860 var ModelCreator = /** @class */ (function () {
22861     function ModelCreator() {
22862     }
22863     /**
22864      * Creates a Falcor model.
22865      *
22866      * @description Max cache size will be set to 16 MB. Authorization
22867      * header will be added if bearer token is supplied.
22868      *
22869      * @param {number} clientId - Client id for API requests.
22870      * @param {number} [token] - Optional bearer token for API requests of
22871      * protected resources.
22872      * @returns {falcor.Model} Falcor model for HTTP requests.
22873      */
22874     ModelCreator.prototype.createModel = function (clientId, token) {
22875         var configuration = {
22876             crossDomain: true,
22877             withCredentials: false,
22878         };
22879         if (token != null) {
22880             configuration.headers = { "Authorization": "Bearer " + token };
22881         }
22882         return new falcor.Model({
22883             maxSize: 16 * 1024 * 1024,
22884             source: new falcor_http_datasource_1.default(Utils_1.Urls.falcorModel(clientId), configuration),
22885         });
22886     };
22887     return ModelCreator;
22888 }());
22889 exports.ModelCreator = ModelCreator;
22890 exports.default = ModelCreator;
22891
22892 },{"../Utils":285,"falcor":15,"falcor-http-datasource":10}],289:[function(require,module,exports){
22893 "use strict";
22894 var __extends = (this && this.__extends) || (function () {
22895     var extendStatics = function (d, b) {
22896         extendStatics = Object.setPrototypeOf ||
22897             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22898             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22899         return extendStatics(d, b);
22900     }
22901     return function (d, b) {
22902         extendStatics(d, b);
22903         function __() { this.constructor = d; }
22904         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22905     };
22906 })();
22907 Object.defineProperty(exports, "__esModule", { value: true });
22908 var rxjs_1 = require("rxjs");
22909 var operators_1 = require("rxjs/operators");
22910 var vd = require("virtual-dom");
22911 var Component_1 = require("../Component");
22912 var Utils_1 = require("../Utils");
22913 var AttributionComponent = /** @class */ (function (_super) {
22914     __extends(AttributionComponent, _super);
22915     function AttributionComponent(name, container, navigator) {
22916         return _super.call(this, name, container, navigator) || this;
22917     }
22918     AttributionComponent.prototype._activate = function () {
22919         var _this = this;
22920         this._disposable = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
22921             var node = _a[0], size = _a[1];
22922             return {
22923                 name: _this._name,
22924                 vnode: _this._getAttributionNode(node.username, node.key, node.capturedAt, size.width),
22925             };
22926         }))
22927             .subscribe(this._container.domRenderer.render$);
22928     };
22929     AttributionComponent.prototype._deactivate = function () {
22930         this._disposable.unsubscribe();
22931     };
22932     AttributionComponent.prototype._getDefaultConfiguration = function () {
22933         return {};
22934     };
22935     AttributionComponent.prototype._getAttributionNode = function (username, key, capturedAt, width) {
22936         var compact = width <= 640;
22937         var mapillaryIcon = vd.h("div.AttributionMapillaryLogo", []);
22938         var mapillaryLink = vd.h("a.AttributionIconContainer", { href: Utils_1.Urls.explore, target: "_blank" }, [mapillaryIcon]);
22939         var imageBy = compact ? "" + username : "image by " + username;
22940         var imageByContent = vd.h("div.AttributionUsername", { textContent: imageBy }, []);
22941         var date = new Date(capturedAt).toDateString().split(" ");
22942         var formatted = (date.length > 3 ?
22943             compact ?
22944                 [date[3]] :
22945                 [date[1], date[2] + ",", date[3]] :
22946             date).join(" ");
22947         var dateContent = vd.h("div.AttributionDate", { textContent: formatted }, []);
22948         var imageLink = vd.h("a.AttributionImageContainer", { href: Utils_1.Urls.exporeImage(key), target: "_blank" }, [imageByContent, dateContent]);
22949         var compactClass = compact ? ".AttributionCompact" : "";
22950         return vd.h("div.AttributionContainer" + compactClass, {}, [mapillaryLink, imageLink]);
22951     };
22952     AttributionComponent.componentName = "attribution";
22953     return AttributionComponent;
22954 }(Component_1.Component));
22955 exports.AttributionComponent = AttributionComponent;
22956 Component_1.ComponentService.register(AttributionComponent);
22957 exports.default = AttributionComponent;
22958
22959 },{"../Component":275,"../Utils":285,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],290:[function(require,module,exports){
22960 "use strict";
22961 var __extends = (this && this.__extends) || (function () {
22962     var extendStatics = function (d, b) {
22963         extendStatics = Object.setPrototypeOf ||
22964             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22965             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22966         return extendStatics(d, b);
22967     }
22968     return function (d, b) {
22969         extendStatics(d, b);
22970         function __() { this.constructor = d; }
22971         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22972     };
22973 })();
22974 Object.defineProperty(exports, "__esModule", { value: true });
22975 var vd = require("virtual-dom");
22976 var Component_1 = require("../Component");
22977 var BackgroundComponent = /** @class */ (function (_super) {
22978     __extends(BackgroundComponent, _super);
22979     function BackgroundComponent(name, container, navigator) {
22980         return _super.call(this, name, container, navigator) || this;
22981     }
22982     BackgroundComponent.prototype._activate = function () {
22983         this._container.domRenderer.render$
22984             .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given image.") });
22985     };
22986     BackgroundComponent.prototype._deactivate = function () {
22987         return;
22988     };
22989     BackgroundComponent.prototype._getDefaultConfiguration = function () {
22990         return {};
22991     };
22992     BackgroundComponent.prototype._getBackgroundNode = function (notice) {
22993         // todo: add condition for when to display the DOM node
22994         return vd.h("div.BackgroundWrapper", {}, [
22995             vd.h("p", { textContent: notice }, []),
22996         ]);
22997     };
22998     BackgroundComponent.componentName = "background";
22999     return BackgroundComponent;
23000 }(Component_1.Component));
23001 exports.BackgroundComponent = BackgroundComponent;
23002 Component_1.ComponentService.register(BackgroundComponent);
23003 exports.default = BackgroundComponent;
23004
23005 },{"../Component":275,"virtual-dom":231}],291:[function(require,module,exports){
23006 "use strict";
23007 var __extends = (this && this.__extends) || (function () {
23008     var extendStatics = function (d, b) {
23009         extendStatics = Object.setPrototypeOf ||
23010             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23011             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23012         return extendStatics(d, b);
23013     }
23014     return function (d, b) {
23015         extendStatics(d, b);
23016         function __() { this.constructor = d; }
23017         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23018     };
23019 })();
23020 Object.defineProperty(exports, "__esModule", { value: true });
23021 var operators_1 = require("rxjs/operators");
23022 var vd = require("virtual-dom");
23023 var UnitBezier = require("@mapbox/unitbezier");
23024 var rxjs_1 = require("rxjs");
23025 var Component_1 = require("../Component");
23026 var Geo_1 = require("../Geo");
23027 var ViewportCoords_1 = require("../geo/ViewportCoords");
23028 var ComponentSize_1 = require("./utils/ComponentSize");
23029 /**
23030  * @class BearingComponent
23031  *
23032  * @classdesc Component for indicating bearing and field of view.
23033  *
23034  * @example
23035  * ```
23036  * var viewer = new Mapillary.Viewer(
23037  *     "<element-id>",
23038  *     "<client-id>",
23039  *     "<my key>");
23040  *
23041  * var bearingComponent = viewer.getComponent("bearing");
23042  * bearingComponent.configure({ size: Mapillary.ComponentSize.Small });
23043  * ```
23044  */
23045 var BearingComponent = /** @class */ (function (_super) {
23046     __extends(BearingComponent, _super);
23047     function BearingComponent(name, container, navigator) {
23048         var _this = _super.call(this, name, container, navigator) || this;
23049         _this._spatial = new Geo_1.Spatial();
23050         _this._viewportCoords = new ViewportCoords_1.default();
23051         _this._svgNamespace = "http://www.w3.org/2000/svg";
23052         _this._distinctThreshold = Math.PI / 360;
23053         _this._animationSpeed = 0.075;
23054         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
23055         return _this;
23056     }
23057     BearingComponent.prototype._activate = function () {
23058         var _this = this;
23059         var cameraBearingFov$ = this._container.renderService.renderCamera$.pipe(operators_1.map(function (rc) {
23060             var vFov = _this._spatial.degToRad(rc.perspective.fov);
23061             var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
23062                 Math.PI :
23063                 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
23064             return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
23065         }), operators_1.distinctUntilChanged(function (a1, a2) {
23066             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
23067                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
23068         }));
23069         var nodeFov$ = rxjs_1.combineLatest(this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
23070             return frame.state.currentNode.key;
23071         })), this._navigator.panService.panNodes$).pipe(operators_1.map(function (_a) {
23072             var frame = _a[0], panNodes = _a[1];
23073             var node = frame.state.currentNode;
23074             var transform = frame.state.currentTransform;
23075             if (node.pano) {
23076                 var panoHFov = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
23077                 return [panoHFov / 2, panoHFov / 2];
23078             }
23079             var currentProjectedPoints = _this._computeProjectedPoints(transform);
23080             var hFov = _this._spatial.degToRad(_this._computeHorizontalFov(currentProjectedPoints));
23081             var hFovLeft = hFov / 2;
23082             var hFovRight = hFov / 2;
23083             for (var _i = 0, panNodes_1 = panNodes; _i < panNodes_1.length; _i++) {
23084                 var _b = panNodes_1[_i], n = _b[0], f = _b[2];
23085                 var diff = _this._spatial.wrap(n.ca - node.ca, -180, 180);
23086                 if (diff < 0) {
23087                     hFovLeft = _this._spatial.degToRad(Math.abs(diff)) + f / 2;
23088                 }
23089                 else {
23090                     hFovRight = _this._spatial.degToRad(Math.abs(diff)) + f / 2;
23091                 }
23092             }
23093             return [hFovLeft, hFovRight];
23094         }), operators_1.distinctUntilChanged(function (_a, _b) {
23095             var hFovLeft1 = _a[0], hFovRight1 = _a[1];
23096             var hFovLeft2 = _b[0], hFovRight2 = _b[1];
23097             return Math.abs(hFovLeft2 - hFovLeft1) < _this._distinctThreshold &&
23098                 Math.abs(hFovRight2 - hFovRight1) < _this._distinctThreshold;
23099         }));
23100         var offset$ = rxjs_1.combineLatest(this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
23101             return frame.state.currentNode.key;
23102         })), this._container.renderService.bearing$).pipe(operators_1.map(function (_a) {
23103             var frame = _a[0], bearing = _a[1];
23104             var offset = _this._spatial.degToRad(frame.state.currentNode.ca - bearing);
23105             return offset;
23106         }));
23107         var nodeFovOperation$ = new rxjs_1.Subject();
23108         var smoothNodeFov$ = nodeFovOperation$.pipe(operators_1.scan(function (state, operation) {
23109             return operation(state);
23110         }, { alpha: 0, curr: [0, 0, 0], prev: [0, 0, 0] }), operators_1.map(function (state) {
23111             var alpha = _this._unitBezier.solve(state.alpha);
23112             var curr = state.curr;
23113             var prev = state.prev;
23114             return [
23115                 _this._interpolate(prev[0], curr[0], alpha),
23116                 _this._interpolate(prev[1], curr[1], alpha),
23117             ];
23118         }));
23119         this._fovSubscription = nodeFov$.pipe(operators_1.map(function (nbf) {
23120             return function (state) {
23121                 var a = _this._unitBezier.solve(state.alpha);
23122                 var c = state.curr;
23123                 var p = state.prev;
23124                 var prev = [
23125                     _this._interpolate(p[0], c[0], a),
23126                     _this._interpolate(p[1], c[1], a),
23127                 ];
23128                 var curr = nbf.slice();
23129                 return {
23130                     alpha: 0,
23131                     curr: curr,
23132                     prev: prev,
23133                 };
23134             };
23135         }))
23136             .subscribe(nodeFovOperation$);
23137         this._fovAnimationSubscription = nodeFov$.pipe(operators_1.switchMap(function () {
23138             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.skip(1), operators_1.scan(function (alpha) {
23139                 return alpha + _this._animationSpeed;
23140             }, 0), operators_1.takeWhile(function (alpha) {
23141                 return alpha <= 1 + _this._animationSpeed;
23142             }), operators_1.map(function (alpha) {
23143                 return Math.min(alpha, 1);
23144             }));
23145         }), operators_1.map(function (alpha) {
23146             return function (nbfState) {
23147                 return {
23148                     alpha: alpha,
23149                     curr: nbfState.curr.slice(),
23150                     prev: nbfState.prev.slice(),
23151                 };
23152             };
23153         }))
23154             .subscribe(nodeFovOperation$);
23155         var nodeBearingFov$ = rxjs_1.combineLatest(offset$, smoothNodeFov$).pipe(operators_1.map(function (_a) {
23156             var offset = _a[0], fov = _a[1];
23157             return [offset, fov[0], fov[1]];
23158         }));
23159         this._renderSubscription = rxjs_1.combineLatest(cameraBearingFov$, nodeBearingFov$, this._configuration$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
23160             var _b = _a[0], cb = _b[0], cf = _b[1], _c = _a[1], no = _c[0], nfl = _c[1], nfr = _c[2], configuration = _a[2], size = _a[3];
23161             var background = _this._createBackground(cb);
23162             var fovIndicator = _this._createFovIndicator(nfl, nfr, no);
23163             var north = _this._createNorth(cb);
23164             var cameraSector = _this._createCircleSectorCompass(_this._createCircleSector(Math.max(Math.PI / 20, cf), "#FFF"));
23165             var compact = configuration.size === ComponentSize_1.default.Small ||
23166                 configuration.size === ComponentSize_1.default.Automatic && size.width < 640 ?
23167                 ".BearingCompact" : "";
23168             return {
23169                 name: _this._name,
23170                 vnode: vd.h("div.BearingIndicatorContainer" + compact, { oncontextmenu: function (event) { event.preventDefault(); } }, [
23171                     background,
23172                     fovIndicator,
23173                     north,
23174                     cameraSector,
23175                 ]),
23176             };
23177         }))
23178             .subscribe(this._container.domRenderer.render$);
23179     };
23180     BearingComponent.prototype._deactivate = function () {
23181         this._renderSubscription.unsubscribe();
23182         this._fovSubscription.unsubscribe();
23183         this._fovAnimationSubscription.unsubscribe();
23184     };
23185     BearingComponent.prototype._getDefaultConfiguration = function () {
23186         return { size: ComponentSize_1.default.Automatic };
23187     };
23188     BearingComponent.prototype._createFovIndicator = function (fovLeft, fovRigth, offset) {
23189         var arc = this._createFovArc(fovLeft, fovRigth);
23190         var group = vd.h("g", {
23191             attributes: { transform: "translate(18,18)" },
23192             namespace: this._svgNamespace,
23193         }, [arc]);
23194         var svg = vd.h("svg", {
23195             attributes: { viewBox: "0 0 36 36" },
23196             namespace: this._svgNamespace,
23197             style: {
23198                 height: "36px",
23199                 left: "2px",
23200                 position: "absolute",
23201                 top: "2px",
23202                 transform: "rotateZ(" + this._spatial.radToDeg(offset) + "deg)",
23203                 width: "36px",
23204             },
23205         }, [group]);
23206         return svg;
23207     };
23208     BearingComponent.prototype._createFovArc = function (fovLeft, fovRigth) {
23209         var radius = 16.75;
23210         var strokeWidth = 2.5;
23211         var fov = fovLeft + fovRigth;
23212         if (fov > 2 * Math.PI - Math.PI / 90) {
23213             return vd.h("circle", {
23214                 attributes: {
23215                     cx: "0",
23216                     cy: "0",
23217                     "fill-opacity": "0",
23218                     r: "" + radius,
23219                     stroke: "#FFF",
23220                     "stroke-width": "" + strokeWidth,
23221                 },
23222                 namespace: this._svgNamespace,
23223             }, []);
23224         }
23225         var arcStart = -Math.PI / 2 - fovLeft;
23226         var arcEnd = arcStart + fov;
23227         var startX = radius * Math.cos(arcStart);
23228         var startY = radius * Math.sin(arcStart);
23229         var endX = radius * Math.cos(arcEnd);
23230         var endY = radius * Math.sin(arcEnd);
23231         var largeArc = fov >= Math.PI ? 1 : 0;
23232         var description = "M " + startX + " " + startY + " A " + radius + " " + radius + " 0 " + largeArc + " 1 " + endX + " " + endY;
23233         return vd.h("path", {
23234             attributes: {
23235                 d: description,
23236                 "fill-opacity": "0",
23237                 stroke: "#FFF",
23238                 "stroke-width": "" + strokeWidth,
23239             },
23240             namespace: this._svgNamespace,
23241         }, []);
23242     };
23243     BearingComponent.prototype._createCircleSectorCompass = function (cameraSector) {
23244         var group = vd.h("g", {
23245             attributes: { transform: "translate(1,1)" },
23246             namespace: this._svgNamespace,
23247         }, [cameraSector]);
23248         var svg = vd.h("svg", {
23249             attributes: { viewBox: "0 0 2 2" },
23250             namespace: this._svgNamespace,
23251             style: {
23252                 height: "26px",
23253                 left: "7px",
23254                 position: "absolute",
23255                 top: "7px",
23256                 width: "26px",
23257             },
23258         }, [group]);
23259         return svg;
23260     };
23261     BearingComponent.prototype._createCircleSector = function (fov, fill) {
23262         if (fov > 2 * Math.PI - Math.PI / 90) {
23263             return vd.h("circle", {
23264                 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
23265                 namespace: this._svgNamespace,
23266             }, []);
23267         }
23268         var arcStart = -Math.PI / 2 - fov / 2;
23269         var arcEnd = arcStart + fov;
23270         var startX = Math.cos(arcStart);
23271         var startY = Math.sin(arcStart);
23272         var endX = Math.cos(arcEnd);
23273         var endY = Math.sin(arcEnd);
23274         var largeArc = fov >= Math.PI ? 1 : 0;
23275         var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
23276         return vd.h("path", {
23277             attributes: { d: description, fill: fill },
23278             namespace: this._svgNamespace,
23279         }, []);
23280     };
23281     BearingComponent.prototype._createNorth = function (bearing) {
23282         var north = vd.h("div.BearingNorth", []);
23283         var container = vd.h("div.BearingNorthContainer", { style: { transform: "rotateZ(" + this._spatial.radToDeg(-bearing) + "deg)" } }, [north]);
23284         return container;
23285     };
23286     BearingComponent.prototype._createBackground = function (bearing) {
23287         return vd.h("div.BearingIndicatorBackground", { style: { transform: "rotateZ(" + this._spatial.radToDeg(-bearing) + "deg)" } }, [
23288             vd.h("div.BearingIndicatorBackgroundCircle", []),
23289             vd.h("div.BearingIndicatorBackgroundArrowContainer", [
23290                 vd.h("div.BearingIndicatorBackgroundArrow", []),
23291             ]),
23292         ]);
23293     };
23294     BearingComponent.prototype._computeProjectedPoints = function (transform) {
23295         var vertices = [[1, 0]];
23296         var directions = [[0, 0.5]];
23297         var pointsPerLine = 12;
23298         return Geo_1.Geo.computeProjectedPoints(transform, vertices, directions, pointsPerLine, this._viewportCoords);
23299     };
23300     BearingComponent.prototype._computeHorizontalFov = function (projectedPoints) {
23301         var _this = this;
23302         var fovs = projectedPoints
23303             .map(function (projectedPoint) {
23304             return _this._coordToFov(projectedPoint[0]);
23305         });
23306         var fov = Math.min.apply(Math, fovs);
23307         return fov;
23308     };
23309     BearingComponent.prototype._coordToFov = function (x) {
23310         return this._spatial.radToDeg(2 * Math.atan(x));
23311     };
23312     BearingComponent.prototype._interpolate = function (x1, x2, alpha) {
23313         return (1 - alpha) * x1 + alpha * x2;
23314     };
23315     BearingComponent.componentName = "bearing";
23316     return BearingComponent;
23317 }(Component_1.Component));
23318 exports.BearingComponent = BearingComponent;
23319 Component_1.ComponentService.register(BearingComponent);
23320 exports.default = BearingComponent;
23321
23322
23323 },{"../Component":275,"../Geo":278,"../geo/ViewportCoords":389,"./utils/ComponentSize":373,"@mapbox/unitbezier":2,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],292:[function(require,module,exports){
23324 "use strict";
23325 var __extends = (this && this.__extends) || (function () {
23326     var extendStatics = function (d, b) {
23327         extendStatics = Object.setPrototypeOf ||
23328             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23329             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23330         return extendStatics(d, b);
23331     }
23332     return function (d, b) {
23333         extendStatics(d, b);
23334         function __() { this.constructor = d; }
23335         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23336     };
23337 })();
23338 Object.defineProperty(exports, "__esModule", { value: true });
23339 var rxjs_1 = require("rxjs");
23340 var operators_1 = require("rxjs/operators");
23341 var Edge_1 = require("../Edge");
23342 var Component_1 = require("../Component");
23343 var CacheComponent = /** @class */ (function (_super) {
23344     __extends(CacheComponent, _super);
23345     function CacheComponent(name, container, navigator) {
23346         return _super.call(this, name, container, navigator) || this;
23347     }
23348     /**
23349      * Set the cache depth.
23350      *
23351      * Configures the cache depth. The cache depth can be different for
23352      * different edge direction types.
23353      *
23354      * @param {ICacheDepth} depth - Cache depth structure.
23355      */
23356     CacheComponent.prototype.setDepth = function (depth) {
23357         this.configure({ depth: depth });
23358     };
23359     CacheComponent.prototype._activate = function () {
23360         var _this = this;
23361         this._sequenceSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
23362             return node.sequenceEdges$;
23363         }), operators_1.filter(function (status) {
23364             return status.cached;
23365         })), this._configuration$).pipe(operators_1.switchMap(function (nc) {
23366             var status = nc[0];
23367             var configuration = nc[1];
23368             var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
23369             var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
23370             var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
23371             return rxjs_1.merge(next$, prev$).pipe(operators_1.catchError(function (error, caught) {
23372                 console.error("Failed to cache sequence edges.", error);
23373                 return rxjs_1.empty();
23374             }));
23375         }))
23376             .subscribe(function () { });
23377         this._spatialSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
23378             return rxjs_1.combineLatest(rxjs_1.of(node), node.spatialEdges$.pipe(operators_1.filter(function (status) {
23379                 return status.cached;
23380             })));
23381         })), this._configuration$).pipe(operators_1.switchMap(function (_a) {
23382             var _b = _a[0], node = _b[0], edgeStatus = _b[1], configuration = _a[1];
23383             var edges = edgeStatus.edges;
23384             var depth = configuration.depth;
23385             var panoDepth = Math.max(0, Math.min(2, depth.pano));
23386             var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
23387             var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
23388             var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
23389             var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
23390             var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
23391             var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
23392             var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
23393             var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
23394             var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
23395             var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
23396             return rxjs_1.merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$).pipe(operators_1.catchError(function (error, caught) {
23397                 console.error("Failed to cache spatial edges.", error);
23398                 return rxjs_1.empty();
23399             }));
23400         }))
23401             .subscribe(function () { });
23402     };
23403     CacheComponent.prototype._deactivate = function () {
23404         this._sequenceSubscription.unsubscribe();
23405         this._spatialSubscription.unsubscribe();
23406     };
23407     CacheComponent.prototype._getDefaultConfiguration = function () {
23408         return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
23409     };
23410     CacheComponent.prototype._cache$ = function (edges, direction, depth) {
23411         var _this = this;
23412         return rxjs_1.zip(rxjs_1.of(edges), rxjs_1.of(depth)).pipe(operators_1.expand(function (ed) {
23413             var es = ed[0];
23414             var d = ed[1];
23415             var edgesDepths$ = [];
23416             if (d > 0) {
23417                 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
23418                     var edge = es_1[_i];
23419                     if (edge.data.direction === direction) {
23420                         edgesDepths$.push(rxjs_1.zip(_this._navigator.graphService.cacheNode$(edge.to).pipe(operators_1.mergeMap(function (n) {
23421                             return _this._nodeToEdges$(n, direction);
23422                         })), rxjs_1.of(d - 1)));
23423                     }
23424                 }
23425             }
23426             return rxjs_1.from(edgesDepths$).pipe(operators_1.mergeAll());
23427         }), operators_1.skip(1));
23428     };
23429     CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
23430         return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
23431             node.sequenceEdges$ :
23432             node.spatialEdges$).pipe(operators_1.first(function (status) {
23433             return status.cached;
23434         }), operators_1.map(function (status) {
23435             return status.edges;
23436         }));
23437     };
23438     CacheComponent.componentName = "cache";
23439     return CacheComponent;
23440 }(Component_1.Component));
23441 exports.CacheComponent = CacheComponent;
23442 Component_1.ComponentService.register(CacheComponent);
23443 exports.default = CacheComponent;
23444
23445 },{"../Component":275,"../Edge":276,"rxjs":27,"rxjs/operators":225}],293:[function(require,module,exports){
23446 "use strict";
23447 var __extends = (this && this.__extends) || (function () {
23448     var extendStatics = function (d, b) {
23449         extendStatics = Object.setPrototypeOf ||
23450             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23451             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23452         return extendStatics(d, b);
23453     }
23454     return function (d, b) {
23455         extendStatics(d, b);
23456         function __() { this.constructor = d; }
23457         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23458     };
23459 })();
23460 Object.defineProperty(exports, "__esModule", { value: true });
23461 var operators_1 = require("rxjs/operators");
23462 var rxjs_1 = require("rxjs");
23463 var Utils_1 = require("../Utils");
23464 var Component = /** @class */ (function (_super) {
23465     __extends(Component, _super);
23466     function Component(name, container, navigator) {
23467         var _this = _super.call(this) || this;
23468         _this._activated$ = new rxjs_1.BehaviorSubject(false);
23469         _this._configurationSubject$ = new rxjs_1.Subject();
23470         _this._activated = false;
23471         _this._container = container;
23472         _this._name = name;
23473         _this._navigator = navigator;
23474         _this._configuration$ =
23475             _this._configurationSubject$.pipe(operators_1.startWith(_this.defaultConfiguration), operators_1.scan(function (conf, newConf) {
23476                 for (var key in newConf) {
23477                     if (newConf.hasOwnProperty(key)) {
23478                         conf[key] = newConf[key];
23479                     }
23480                 }
23481                 return conf;
23482             }), operators_1.publishReplay(1), operators_1.refCount());
23483         _this._configuration$.subscribe(function () { });
23484         return _this;
23485     }
23486     Object.defineProperty(Component.prototype, "activated", {
23487         get: function () {
23488             return this._activated;
23489         },
23490         enumerable: true,
23491         configurable: true
23492     });
23493     Object.defineProperty(Component.prototype, "activated$", {
23494         /** @ignore */
23495         get: function () {
23496             return this._activated$;
23497         },
23498         enumerable: true,
23499         configurable: true
23500     });
23501     Object.defineProperty(Component.prototype, "defaultConfiguration", {
23502         /**
23503          * Get default configuration.
23504          *
23505          * @returns {TConfiguration} Default configuration for component.
23506          */
23507         get: function () {
23508             return this._getDefaultConfiguration();
23509         },
23510         enumerable: true,
23511         configurable: true
23512     });
23513     Object.defineProperty(Component.prototype, "configuration$", {
23514         /** @ignore */
23515         get: function () {
23516             return this._configuration$;
23517         },
23518         enumerable: true,
23519         configurable: true
23520     });
23521     Object.defineProperty(Component.prototype, "name", {
23522         /**
23523          * Get name.
23524          *
23525          * @description The name of the component. Used when interacting with the
23526          * component through the Viewer's API.
23527          */
23528         get: function () {
23529             return this._name;
23530         },
23531         enumerable: true,
23532         configurable: true
23533     });
23534     Component.prototype.activate = function (conf) {
23535         if (this._activated) {
23536             return;
23537         }
23538         if (conf !== undefined) {
23539             this._configurationSubject$.next(conf);
23540         }
23541         this._activated = true;
23542         this._activate();
23543         this._activated$.next(true);
23544     };
23545     Component.prototype.configure = function (conf) {
23546         this._configurationSubject$.next(conf);
23547     };
23548     Component.prototype.deactivate = function () {
23549         if (!this._activated) {
23550             return;
23551         }
23552         this._activated = false;
23553         this._deactivate();
23554         this._container.domRenderer.clear(this._name);
23555         this._container.glRenderer.clear(this._name);
23556         this._activated$.next(false);
23557     };
23558     /**
23559      * Detect the viewer's new width and height and resize the component's
23560      * rendered elements accordingly if applicable.
23561      *
23562      * @ignore
23563      */
23564     Component.prototype.resize = function () { return; };
23565     Component.componentName = "not_worthy";
23566     return Component;
23567 }(Utils_1.EventEmitter));
23568 exports.Component = Component;
23569 exports.default = Component;
23570
23571 },{"../Utils":285,"rxjs":27,"rxjs/operators":225}],294:[function(require,module,exports){
23572 "use strict";
23573 Object.defineProperty(exports, "__esModule", { value: true });
23574 var Error_1 = require("../Error");
23575 var ComponentService = /** @class */ (function () {
23576     function ComponentService(container, navigator) {
23577         this._components = {};
23578         for (var componentName in ComponentService.registeredComponents) {
23579             if (!ComponentService.registeredComponents.hasOwnProperty(componentName)) {
23580                 continue;
23581             }
23582             var component = ComponentService.registeredComponents[componentName];
23583             this._components[componentName] = {
23584                 active: false,
23585                 component: new component(componentName, container, navigator),
23586             };
23587         }
23588         this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
23589         this._coverComponent.activate();
23590         this._coverActivated = true;
23591     }
23592     ComponentService.register = function (component) {
23593         if (ComponentService.registeredComponents[component.componentName] === undefined) {
23594             ComponentService.registeredComponents[component.componentName] = component;
23595         }
23596     };
23597     ComponentService.registerCover = function (coverComponent) {
23598         ComponentService.registeredCoverComponent = coverComponent;
23599     };
23600     Object.defineProperty(ComponentService.prototype, "coverActivated", {
23601         get: function () {
23602             return this._coverActivated;
23603         },
23604         enumerable: true,
23605         configurable: true
23606     });
23607     ComponentService.prototype.activateCover = function () {
23608         if (this._coverActivated) {
23609             return;
23610         }
23611         this._coverActivated = true;
23612         for (var componentName in this._components) {
23613             if (!this._components.hasOwnProperty(componentName)) {
23614                 continue;
23615             }
23616             var component = this._components[componentName];
23617             if (component.active) {
23618                 component.component.deactivate();
23619             }
23620         }
23621     };
23622     ComponentService.prototype.deactivateCover = function () {
23623         if (!this._coverActivated) {
23624             return;
23625         }
23626         this._coverActivated = false;
23627         for (var componentName in this._components) {
23628             if (!this._components.hasOwnProperty(componentName)) {
23629                 continue;
23630             }
23631             var component = this._components[componentName];
23632             if (component.active) {
23633                 component.component.activate();
23634             }
23635         }
23636     };
23637     ComponentService.prototype.activate = function (name) {
23638         this._checkName(name);
23639         this._components[name].active = true;
23640         if (!this._coverActivated) {
23641             this.get(name).activate();
23642         }
23643     };
23644     ComponentService.prototype.configure = function (name, conf) {
23645         this._checkName(name);
23646         this.get(name).configure(conf);
23647     };
23648     ComponentService.prototype.deactivate = function (name) {
23649         this._checkName(name);
23650         this._components[name].active = false;
23651         if (!this._coverActivated) {
23652             this.get(name).deactivate();
23653         }
23654     };
23655     ComponentService.prototype.get = function (name) {
23656         return this._components[name].component;
23657     };
23658     ComponentService.prototype.getCover = function () {
23659         return this._coverComponent;
23660     };
23661     ComponentService.prototype._checkName = function (name) {
23662         if (!(name in this._components)) {
23663             throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
23664         }
23665     };
23666     ComponentService.registeredComponents = {};
23667     return ComponentService;
23668 }());
23669 exports.ComponentService = ComponentService;
23670 exports.default = ComponentService;
23671
23672 },{"../Error":277}],295:[function(require,module,exports){
23673 "use strict";
23674 var __extends = (this && this.__extends) || (function () {
23675     var extendStatics = function (d, b) {
23676         extendStatics = Object.setPrototypeOf ||
23677             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23678             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23679         return extendStatics(d, b);
23680     }
23681     return function (d, b) {
23682         extendStatics(d, b);
23683         function __() { this.constructor = d; }
23684         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23685     };
23686 })();
23687 Object.defineProperty(exports, "__esModule", { value: true });
23688 var rxjs_1 = require("rxjs");
23689 var operators_1 = require("rxjs/operators");
23690 var vd = require("virtual-dom");
23691 var Component_1 = require("../Component");
23692 var Utils_1 = require("../Utils");
23693 var Viewer_1 = require("../Viewer");
23694 var CoverComponent = /** @class */ (function (_super) {
23695     __extends(CoverComponent, _super);
23696     function CoverComponent(name, container, navigator) {
23697         return _super.call(this, name, container, navigator) || this;
23698     }
23699     CoverComponent.prototype._activate = function () {
23700         var _this = this;
23701         this._configuration$.pipe(operators_1.distinctUntilChanged(undefined, function (configuration) {
23702             return configuration.state;
23703         }), operators_1.switchMap(function (configuration) {
23704             return rxjs_1.combineLatest(rxjs_1.of(configuration.state), _this._navigator.stateService.currentNode$);
23705         }), operators_1.switchMap(function (_a) {
23706             var state = _a[0], node = _a[1];
23707             var keySrc$ = rxjs_1.combineLatest(rxjs_1.of(node.key), node.image$.pipe(operators_1.filter(function (image) {
23708                 return !!image;
23709             }), operators_1.map(function (image) {
23710                 return image.src;
23711             })));
23712             return state === Component_1.CoverState.Visible ? keySrc$.pipe(operators_1.first()) : keySrc$;
23713         }), operators_1.distinctUntilChanged(function (_a, _b) {
23714             var k1 = _a[0], s1 = _a[1];
23715             var k2 = _b[0], s2 = _b[1];
23716             return k1 === k2 && s1 === s2;
23717         }), operators_1.map(function (_a) {
23718             var key = _a[0], src = _a[1];
23719             return { key: key, src: src };
23720         }))
23721             .subscribe(this._configurationSubject$);
23722         this._renderSubscription = rxjs_1.combineLatest(this._configuration$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
23723             var configuration = _a[0], size = _a[1];
23724             if (!configuration.key) {
23725                 return { name: _this._name, vnode: vd.h("div", []) };
23726             }
23727             var compactClass = size.width <= 640 || size.height <= 480 ? ".CoverCompact" : "";
23728             if (configuration.state === Component_1.CoverState.Hidden) {
23729                 var doneContainer = vd.h("div.CoverContainer.CoverDone" + compactClass, [_this._getCoverBackgroundVNode(configuration)]);
23730                 return { name: _this._name, vnode: doneContainer };
23731             }
23732             var container = vd.h("div.CoverContainer" + compactClass, [_this._getCoverButtonVNode(configuration)]);
23733             return { name: _this._name, vnode: container };
23734         }))
23735             .subscribe(this._container.domRenderer.render$);
23736     };
23737     CoverComponent.prototype._deactivate = function () {
23738         this._renderSubscription.unsubscribe();
23739         this._keySubscription.unsubscribe();
23740     };
23741     CoverComponent.prototype._getDefaultConfiguration = function () {
23742         return { state: Component_1.CoverState.Visible };
23743     };
23744     CoverComponent.prototype._getCoverButtonVNode = function (configuration) {
23745         var _this = this;
23746         var cover = configuration.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover";
23747         var coverButton = vd.h("div.CoverButton", [vd.h("div.CoverButtonIcon", [])]);
23748         var coverLogo = vd.h("a.CoverLogo", { href: Utils_1.Urls.explore, target: "_blank" }, []);
23749         var coverIndicator = vd.h("div.CoverIndicator", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, []);
23750         return vd.h(cover, [
23751             this._getCoverBackgroundVNode(configuration),
23752             coverIndicator,
23753             coverButton,
23754             coverLogo,
23755         ]);
23756     };
23757     CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
23758         var url = conf.src != null ?
23759             conf.src : Utils_1.Urls.thumbnail(conf.key, Viewer_1.ImageSize.Size640);
23760         var properties = { style: { backgroundImage: "url(" + url + ")" } };
23761         var children = [];
23762         if (conf.state === Component_1.CoverState.Loading) {
23763             children.push(vd.h("div.Spinner", {}, []));
23764         }
23765         return vd.h("div.CoverBackground", properties, children);
23766     };
23767     CoverComponent.componentName = "cover";
23768     return CoverComponent;
23769 }(Component_1.Component));
23770 exports.CoverComponent = CoverComponent;
23771 Component_1.ComponentService.registerCover(CoverComponent);
23772 exports.default = CoverComponent;
23773
23774 },{"../Component":275,"../Utils":285,"../Viewer":286,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],296:[function(require,module,exports){
23775 "use strict";
23776 var __extends = (this && this.__extends) || (function () {
23777     var extendStatics = function (d, b) {
23778         extendStatics = Object.setPrototypeOf ||
23779             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23780             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23781         return extendStatics(d, b);
23782     }
23783     return function (d, b) {
23784         extendStatics(d, b);
23785         function __() { this.constructor = d; }
23786         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23787     };
23788 })();
23789 Object.defineProperty(exports, "__esModule", { value: true });
23790 var rxjs_1 = require("rxjs");
23791 var operators_1 = require("rxjs/operators");
23792 var vd = require("virtual-dom");
23793 var Component_1 = require("../Component");
23794 var DebugComponent = /** @class */ (function (_super) {
23795     __extends(DebugComponent, _super);
23796     function DebugComponent() {
23797         var _this = _super !== null && _super.apply(this, arguments) || this;
23798         _this._open$ = new rxjs_1.BehaviorSubject(false);
23799         return _this;
23800     }
23801     DebugComponent.prototype._activate = function () {
23802         var _this = this;
23803         this._disposable = rxjs_1.combineLatest(this._navigator.stateService.currentState$, this._open$, this._navigator.imageLoadingService.loadstatus$).pipe(operators_1.map(function (_a) {
23804             var frame = _a[0], open = _a[1], loadStatus = _a[2];
23805             return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
23806         }))
23807             .subscribe(this._container.domRenderer.render$);
23808     };
23809     DebugComponent.prototype._deactivate = function () {
23810         this._disposable.unsubscribe();
23811     };
23812     DebugComponent.prototype._getDefaultConfiguration = function () {
23813         return {};
23814     };
23815     DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
23816         var ret = [];
23817         ret.push(vd.h("h2", "Node"));
23818         if (frame.state.currentNode) {
23819             ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
23820         }
23821         if (frame.state.previousNode) {
23822             ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
23823         }
23824         ret.push(vd.h("h2", "Loading"));
23825         var total = 0;
23826         var loaded = 0;
23827         var loading = 0;
23828         for (var key in loadStatus) {
23829             if (!loadStatus.hasOwnProperty(key)) {
23830                 continue;
23831             }
23832             var status_1 = loadStatus[key];
23833             total += status_1.loaded;
23834             if (status_1.loaded !== status_1.total) {
23835                 loading++;
23836             }
23837             else {
23838                 loaded++;
23839             }
23840         }
23841         ret.push(vd.h("p", "Loaded Images: " + loaded));
23842         ret.push(vd.h("p", "Loading Images: " + loading));
23843         ret.push(vd.h("p", "Total bytes loaded: " + total));
23844         ret.push(vd.h("h2", "Camera"));
23845         ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
23846         ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
23847         ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
23848         ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
23849         ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
23850         ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
23851         ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
23852         ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
23853         ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
23854         return ret;
23855     };
23856     DebugComponent.prototype._getDebugVNode = function (open, info) {
23857         if (open) {
23858             return vd.h("div.Debug", {}, [
23859                 vd.h("h2", {}, ["Debug"]),
23860                 this._getDebugVNodeButton(open),
23861                 vd.h("pre", {}, info),
23862             ]);
23863         }
23864         else {
23865             return this._getDebugVNodeButton(open);
23866         }
23867     };
23868     DebugComponent.prototype._getDebugVNodeButton = function (open) {
23869         var buttonText = open ? "Disable Debug" : "D";
23870         var buttonCssClass = open ? "" : ".DebugButtonFixed";
23871         if (open) {
23872             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
23873         }
23874         else {
23875             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
23876         }
23877     };
23878     DebugComponent.prototype._closeDebugElement = function (open) {
23879         this._open$.next(false);
23880     };
23881     DebugComponent.prototype._openDebugElement = function () {
23882         this._open$.next(true);
23883     };
23884     DebugComponent.componentName = "debug";
23885     return DebugComponent;
23886 }(Component_1.Component));
23887 exports.DebugComponent = DebugComponent;
23888 Component_1.ComponentService.register(DebugComponent);
23889 exports.default = DebugComponent;
23890
23891 },{"../Component":275,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],297:[function(require,module,exports){
23892 "use strict";
23893 var __extends = (this && this.__extends) || (function () {
23894     var extendStatics = function (d, b) {
23895         extendStatics = Object.setPrototypeOf ||
23896             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23897             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23898         return extendStatics(d, b);
23899     }
23900     return function (d, b) {
23901         extendStatics(d, b);
23902         function __() { this.constructor = d; }
23903         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23904     };
23905 })();
23906 Object.defineProperty(exports, "__esModule", { value: true });
23907 var rxjs_1 = require("rxjs");
23908 var operators_1 = require("rxjs/operators");
23909 var vd = require("virtual-dom");
23910 var Component_1 = require("../Component");
23911 var Utils_1 = require("../Utils");
23912 var ImageComponent = /** @class */ (function (_super) {
23913     __extends(ImageComponent, _super);
23914     function ImageComponent(name, container, navigator, dom) {
23915         var _this = _super.call(this, name, container, navigator) || this;
23916         _this._canvasId = container.id + "-" + _this._name;
23917         _this._dom = !!dom ? dom : new Utils_1.DOM();
23918         return _this;
23919     }
23920     ImageComponent.prototype._activate = function () {
23921         var _this = this;
23922         var canvasSize$ = this._container.domRenderer.element$.pipe(operators_1.map(function (element) {
23923             return _this._dom.document.getElementById(_this._canvasId);
23924         }), operators_1.filter(function (canvas) {
23925             return !!canvas;
23926         }), operators_1.map(function (canvas) {
23927             var adaptableDomRenderer = canvas.parentElement;
23928             var width = adaptableDomRenderer.offsetWidth;
23929             var height = adaptableDomRenderer.offsetHeight;
23930             return [canvas, { height: height, width: width }];
23931         }), operators_1.distinctUntilChanged(function (s1, s2) {
23932             return s1.height === s2.height && s1.width === s2.width;
23933         }, function (_a) {
23934             var canvas = _a[0], size = _a[1];
23935             return size;
23936         }));
23937         this.drawSubscription = rxjs_1.combineLatest(canvasSize$, this._navigator.stateService.currentNode$)
23938             .subscribe(function (_a) {
23939             var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1];
23940             canvas.width = size.width;
23941             canvas.height = size.height;
23942             canvas
23943                 .getContext("2d")
23944                 .drawImage(node.image, 0, 0, size.width, size.height);
23945         });
23946         this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
23947     };
23948     ImageComponent.prototype._deactivate = function () {
23949         this.drawSubscription.unsubscribe();
23950     };
23951     ImageComponent.prototype._getDefaultConfiguration = function () {
23952         return {};
23953     };
23954     ImageComponent.componentName = "image";
23955     return ImageComponent;
23956 }(Component_1.Component));
23957 exports.ImageComponent = ImageComponent;
23958 Component_1.ComponentService.register(ImageComponent);
23959 exports.default = ImageComponent;
23960
23961
23962 },{"../Component":275,"../Utils":285,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],298:[function(require,module,exports){
23963 "use strict";
23964 var __extends = (this && this.__extends) || (function () {
23965     var extendStatics = function (d, b) {
23966         extendStatics = Object.setPrototypeOf ||
23967             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23968             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23969         return extendStatics(d, b);
23970     }
23971     return function (d, b) {
23972         extendStatics(d, b);
23973         function __() { this.constructor = d; }
23974         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23975     };
23976 })();
23977 Object.defineProperty(exports, "__esModule", { value: true });
23978 var rxjs_1 = require("rxjs");
23979 var operators_1 = require("rxjs/operators");
23980 var vd = require("virtual-dom");
23981 var Component_1 = require("../Component");
23982 var LoadingComponent = /** @class */ (function (_super) {
23983     __extends(LoadingComponent, _super);
23984     function LoadingComponent(name, container, navigator) {
23985         return _super.call(this, name, container, navigator) || this;
23986     }
23987     LoadingComponent.prototype._activate = function () {
23988         var _this = this;
23989         this._loadingSubscription = this._navigator.loadingService.loading$.pipe(operators_1.switchMap(function (loading) {
23990             return loading ?
23991                 _this._navigator.imageLoadingService.loadstatus$ :
23992                 rxjs_1.of({});
23993         }), operators_1.map(function (loadStatus) {
23994             var total = 0;
23995             var loaded = 0;
23996             for (var key in loadStatus) {
23997                 if (!loadStatus.hasOwnProperty(key)) {
23998                     continue;
23999                 }
24000                 var status_1 = loadStatus[key];
24001                 if (status_1.loaded !== status_1.total) {
24002                     loaded += status_1.loaded;
24003                     total += status_1.total;
24004                 }
24005             }
24006             var percentage = 100;
24007             if (total !== 0) {
24008                 percentage = (loaded / total) * 100;
24009             }
24010             return { name: _this._name, vnode: _this._getBarVNode(percentage) };
24011         }))
24012             .subscribe(this._container.domRenderer.render$);
24013     };
24014     LoadingComponent.prototype._deactivate = function () {
24015         this._loadingSubscription.unsubscribe();
24016     };
24017     LoadingComponent.prototype._getDefaultConfiguration = function () {
24018         return {};
24019     };
24020     LoadingComponent.prototype._getBarVNode = function (percentage) {
24021         var loadingBarStyle = {};
24022         var loadingContainerStyle = {};
24023         if (percentage !== 100) {
24024             loadingBarStyle.width = percentage.toFixed(0) + "%";
24025             loadingBarStyle.opacity = "1";
24026         }
24027         else {
24028             loadingBarStyle.width = "100%";
24029             loadingBarStyle.opacity = "0";
24030         }
24031         return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
24032     };
24033     LoadingComponent.componentName = "loading";
24034     return LoadingComponent;
24035 }(Component_1.Component));
24036 exports.LoadingComponent = LoadingComponent;
24037 Component_1.ComponentService.register(LoadingComponent);
24038 exports.default = LoadingComponent;
24039
24040 },{"../Component":275,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],299:[function(require,module,exports){
24041 "use strict";
24042 var __extends = (this && this.__extends) || (function () {
24043     var extendStatics = function (d, b) {
24044         extendStatics = Object.setPrototypeOf ||
24045             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24046             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24047         return extendStatics(d, b);
24048     }
24049     return function (d, b) {
24050         extendStatics(d, b);
24051         function __() { this.constructor = d; }
24052         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24053     };
24054 })();
24055 Object.defineProperty(exports, "__esModule", { value: true });
24056 var rxjs_1 = require("rxjs");
24057 var operators_1 = require("rxjs/operators");
24058 var vd = require("virtual-dom");
24059 var Edge_1 = require("../Edge");
24060 var Error_1 = require("../Error");
24061 var Component_1 = require("../Component");
24062 /**
24063  * @class NavigationComponent
24064  *
24065  * @classdesc Fallback navigation component for environments without WebGL support.
24066  *
24067  * Replaces the functionality in the Direction and Sequence components.
24068  */
24069 var NavigationComponent = /** @class */ (function (_super) {
24070     __extends(NavigationComponent, _super);
24071     /** @ignore */
24072     function NavigationComponent(name, container, navigator) {
24073         var _this = _super.call(this, name, container, navigator) || this;
24074         _this._seqNames = {};
24075         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev";
24076         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next";
24077         _this._spaTopNames = {};
24078         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft";
24079         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left";
24080         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward";
24081         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right";
24082         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright";
24083         _this._spaBottomNames = {};
24084         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround";
24085         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward";
24086         return _this;
24087     }
24088     NavigationComponent.prototype._activate = function () {
24089         var _this = this;
24090         this._renderSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, this._configuration$).pipe(operators_1.switchMap(function (_a) {
24091             var node = _a[0], configuration = _a[1];
24092             var sequenceEdges$ = configuration.sequence ?
24093                 node.sequenceEdges$.pipe(operators_1.map(function (status) {
24094                     return status.edges
24095                         .map(function (edge) {
24096                         return edge.data.direction;
24097                     });
24098                 })) :
24099                 rxjs_1.of([]);
24100             var spatialEdges$ = !node.pano && configuration.spatial ?
24101                 node.spatialEdges$.pipe(operators_1.map(function (status) {
24102                     return status.edges
24103                         .map(function (edge) {
24104                         return edge.data.direction;
24105                     });
24106                 })) :
24107                 rxjs_1.of([]);
24108             return rxjs_1.combineLatest(sequenceEdges$, spatialEdges$).pipe(operators_1.map(function (_a) {
24109                 var seq = _a[0], spa = _a[1];
24110                 return seq.concat(spa);
24111             }));
24112         }), operators_1.map(function (edgeDirections) {
24113             var seqs = _this._createArrowRow(_this._seqNames, edgeDirections);
24114             var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections);
24115             var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections);
24116             var seqContainer = vd.h("div.NavigationSequence", seqs);
24117             var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops);
24118             var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms);
24119             var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]);
24120             return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) };
24121         }))
24122             .subscribe(this._container.domRenderer.render$);
24123     };
24124     NavigationComponent.prototype._deactivate = function () {
24125         this._renderSubscription.unsubscribe();
24126     };
24127     NavigationComponent.prototype._getDefaultConfiguration = function () {
24128         return { sequence: true, spatial: true };
24129     };
24130     NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) {
24131         var arrows = [];
24132         for (var arrowName in arrowNames) {
24133             if (!(arrowNames.hasOwnProperty(arrowName))) {
24134                 continue;
24135             }
24136             var direction = Edge_1.EdgeDirection[arrowName];
24137             if (edgeDirections.indexOf(direction) !== -1) {
24138                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible"));
24139             }
24140             else {
24141                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden"));
24142             }
24143         }
24144         return arrows;
24145     };
24146     NavigationComponent.prototype._createVNode = function (direction, name, visibility) {
24147         var _this = this;
24148         return vd.h("span.Direction.Direction" + name, {
24149             onclick: function (ev) {
24150                 _this._navigator.moveDir$(direction)
24151                     .subscribe(undefined, function (error) {
24152                     if (!(error instanceof Error_1.AbortMapillaryError)) {
24153                         console.error(error);
24154                     }
24155                 });
24156             },
24157             style: {
24158                 visibility: visibility,
24159             },
24160         }, []);
24161     };
24162     NavigationComponent.componentName = "navigation";
24163     return NavigationComponent;
24164 }(Component_1.Component));
24165 exports.NavigationComponent = NavigationComponent;
24166 Component_1.ComponentService.register(NavigationComponent);
24167 exports.default = NavigationComponent;
24168
24169 },{"../Component":275,"../Edge":276,"../Error":277,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],300:[function(require,module,exports){
24170 "use strict";
24171 var __extends = (this && this.__extends) || (function () {
24172     var extendStatics = function (d, b) {
24173         extendStatics = Object.setPrototypeOf ||
24174             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24175             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24176         return extendStatics(d, b);
24177     }
24178     return function (d, b) {
24179         extendStatics(d, b);
24180         function __() { this.constructor = d; }
24181         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24182     };
24183 })();
24184 Object.defineProperty(exports, "__esModule", { value: true });
24185 var rxjs_1 = require("rxjs");
24186 var operators_1 = require("rxjs/operators");
24187 var vd = require("virtual-dom");
24188 var Component_1 = require("../Component");
24189 var DescriptionState = /** @class */ (function () {
24190     function DescriptionState() {
24191     }
24192     return DescriptionState;
24193 }());
24194 var RouteState = /** @class */ (function () {
24195     function RouteState() {
24196     }
24197     return RouteState;
24198 }());
24199 var RouteTrack = /** @class */ (function () {
24200     function RouteTrack() {
24201         this.nodeInstructions = [];
24202         this.nodeInstructionsOrdered = [];
24203     }
24204     return RouteTrack;
24205 }());
24206 var RouteComponent = /** @class */ (function (_super) {
24207     __extends(RouteComponent, _super);
24208     function RouteComponent(name, container, navigator) {
24209         return _super.call(this, name, container, navigator) || this;
24210     }
24211     RouteComponent.prototype._activate = function () {
24212         var _this = this;
24213         var slowedStream$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
24214             return (frame.id % 2) === 0;
24215         }), operators_1.filter(function (frame) {
24216             return frame.state.nodesAhead < 15;
24217         }), operators_1.distinctUntilChanged(undefined, function (frame) {
24218             return frame.state.lastNode.key;
24219         }));
24220         var routeTrack$ = rxjs_1.combineLatest(this.configuration$.pipe(operators_1.mergeMap(function (conf) {
24221             return rxjs_1.from(conf.paths);
24222         }), operators_1.distinct(function (p) {
24223             return p.sequenceKey;
24224         }), operators_1.mergeMap(function (path) {
24225             return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey]).pipe(operators_1.map(function (sequenceByKey) {
24226                 return sequenceByKey[path.sequenceKey];
24227             }));
24228         })), this.configuration$).pipe(operators_1.map(function (_a) {
24229             var sequence = _a[0], conf = _a[1];
24230             var i = 0;
24231             var instructionPlaces = [];
24232             for (var _i = 0, _b = conf.paths; _i < _b.length; _i++) {
24233                 var path = _b[_i];
24234                 if (path.sequenceKey === sequence.key) {
24235                     var nodeInstructions = [];
24236                     var saveKey = false;
24237                     for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
24238                         var key = _d[_c];
24239                         if (path.startKey === key) {
24240                             saveKey = true;
24241                         }
24242                         if (saveKey) {
24243                             var description = null;
24244                             for (var _e = 0, _f = path.infoKeys; _e < _f.length; _e++) {
24245                                 var infoKey = _f[_e];
24246                                 if (infoKey.key === key) {
24247                                     description = infoKey.description;
24248                                 }
24249                             }
24250                             nodeInstructions.push({ description: description, key: key });
24251                         }
24252                         if (path.stopKey === key) {
24253                             saveKey = false;
24254                         }
24255                     }
24256                     instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
24257                 }
24258                 i++;
24259             }
24260             return instructionPlaces;
24261         }), operators_1.scan(function (routeTrack, instructionPlaces) {
24262             for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
24263                 var instructionPlace = instructionPlaces_1[_i];
24264                 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
24265             }
24266             for (var place in routeTrack.nodeInstructionsOrdered) {
24267                 if (!routeTrack.nodeInstructionsOrdered.hasOwnProperty(place)) {
24268                     continue;
24269                 }
24270                 var instructionGroup = routeTrack.nodeInstructionsOrdered[place];
24271                 for (var _a = 0, instructionGroup_1 = instructionGroup; _a < instructionGroup_1.length; _a++) {
24272                     var instruction = instructionGroup_1[_a];
24273                     routeTrack.nodeInstructions.push(instruction);
24274                 }
24275             }
24276             return routeTrack;
24277         }, new RouteTrack()));
24278         var cacheNode$ = rxjs_1.combineLatest(slowedStream$, routeTrack$, this.configuration$).pipe(operators_1.map(function (_a) {
24279             var frame = _a[0], routeTrack = _a[1], conf = _a[2];
24280             return { conf: conf, frame: frame, routeTrack: routeTrack };
24281         }), operators_1.scan(function (routeState, rtAndFrame) {
24282             if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
24283                 routeState.routeTrack = rtAndFrame.routeTrack;
24284                 routeState.currentNode = rtAndFrame.frame.state.currentNode;
24285                 routeState.lastNode = rtAndFrame.frame.state.lastNode;
24286                 routeState.playing = true;
24287             }
24288             else {
24289                 _this._navigator.stateService.cutNodes();
24290                 routeState.playing = false;
24291             }
24292             return routeState;
24293         }, new RouteState()), operators_1.filter(function (routeState) {
24294             return routeState.playing;
24295         }), operators_1.filter(function (routeState) {
24296             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
24297                 var nodeInstruction = _a[_i];
24298                 if (!nodeInstruction) {
24299                     continue;
24300                 }
24301                 if (nodeInstruction.key === routeState.lastNode.key) {
24302                     return true;
24303                 }
24304             }
24305             return false;
24306         }), operators_1.distinctUntilChanged(undefined, function (routeState) {
24307             return routeState.lastNode.key;
24308         }), operators_1.mergeMap(function (routeState) {
24309             var i = 0;
24310             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
24311                 var nodeInstruction = _a[_i];
24312                 if (nodeInstruction.key === routeState.lastNode.key) {
24313                     break;
24314                 }
24315                 i++;
24316             }
24317             var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
24318             if (!nextInstruction) {
24319                 return rxjs_1.of(null);
24320             }
24321             return _this._navigator.graphService.cacheNode$(nextInstruction.key);
24322         }));
24323         this._disposable = rxjs_1.combineLatest(cacheNode$, this.configuration$).pipe(operators_1.map(function (_a) {
24324             var node = _a[0], conf = _a[1];
24325             return { conf: conf, node: node };
24326         }), operators_1.filter(function (cAN) {
24327             return cAN.node !== null && cAN.conf.playing;
24328         }), operators_1.pluck("node"))
24329             .subscribe(this._navigator.stateService.appendNode$);
24330         this._disposableDescription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, routeTrack$, this.configuration$).pipe(operators_1.map(function (_a) {
24331             var node = _a[0], routeTrack = _a[1], conf = _a[2];
24332             if (conf.playing !== undefined && !conf.playing) {
24333                 return "quit";
24334             }
24335             var description = null;
24336             for (var _i = 0, _b = routeTrack.nodeInstructions; _i < _b.length; _i++) {
24337                 var nodeInstruction = _b[_i];
24338                 if (nodeInstruction.key === node.key) {
24339                     description = nodeInstruction.description;
24340                     break;
24341                 }
24342             }
24343             return description;
24344         }), operators_1.scan(function (descriptionState, description) {
24345             if (description !== descriptionState.description && description !== null) {
24346                 descriptionState.description = description;
24347                 descriptionState.showsLeft = 6;
24348             }
24349             else {
24350                 descriptionState.showsLeft--;
24351             }
24352             if (description === "quit") {
24353                 descriptionState.description = null;
24354             }
24355             return descriptionState;
24356         }, new DescriptionState()), operators_1.map(function (descriptionState) {
24357             if (descriptionState.showsLeft > 0 && descriptionState.description) {
24358                 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
24359             }
24360             else {
24361                 return { name: _this._name, vnode: vd.h("div", []) };
24362             }
24363         }))
24364             .subscribe(this._container.domRenderer.render$);
24365     };
24366     RouteComponent.prototype._deactivate = function () {
24367         this._disposable.unsubscribe();
24368         this._disposableDescription.unsubscribe();
24369     };
24370     RouteComponent.prototype._getDefaultConfiguration = function () {
24371         return {};
24372     };
24373     RouteComponent.prototype.play = function () {
24374         this.configure({ playing: true });
24375     };
24376     RouteComponent.prototype.stop = function () {
24377         this.configure({ playing: false });
24378     };
24379     RouteComponent.prototype._getRouteAnnotationNode = function (description) {
24380         return vd.h("div.RouteFrame", {}, [
24381             vd.h("p", { textContent: description }, []),
24382         ]);
24383     };
24384     RouteComponent.componentName = "route";
24385     return RouteComponent;
24386 }(Component_1.Component));
24387 exports.RouteComponent = RouteComponent;
24388 Component_1.ComponentService.register(RouteComponent);
24389 exports.default = RouteComponent;
24390
24391 },{"../Component":275,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],301:[function(require,module,exports){
24392 "use strict";
24393 var __extends = (this && this.__extends) || (function () {
24394     var extendStatics = function (d, b) {
24395         extendStatics = Object.setPrototypeOf ||
24396             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24397             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24398         return extendStatics(d, b);
24399     }
24400     return function (d, b) {
24401         extendStatics(d, b);
24402         function __() { this.constructor = d; }
24403         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24404     };
24405 })();
24406 Object.defineProperty(exports, "__esModule", { value: true });
24407 var rxjs_1 = require("rxjs");
24408 var operators_1 = require("rxjs/operators");
24409 var Component_1 = require("../Component");
24410 var StatsComponent = /** @class */ (function (_super) {
24411     __extends(StatsComponent, _super);
24412     function StatsComponent(name, container, navigator, scheduler) {
24413         var _this = _super.call(this, name, container, navigator) || this;
24414         _this._scheduler = scheduler;
24415         return _this;
24416     }
24417     StatsComponent.prototype._activate = function () {
24418         var _this = this;
24419         this._sequenceSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.scan(function (keys, node) {
24420             var sKey = node.sequenceKey;
24421             keys.report = [];
24422             if (!(sKey in keys.reported)) {
24423                 keys.report = [sKey];
24424                 keys.reported[sKey] = true;
24425             }
24426             return keys;
24427         }, { report: [], reported: {} }), operators_1.filter(function (keys) {
24428             return keys.report.length > 0;
24429         }), operators_1.mergeMap(function (keys) {
24430             return _this._navigator.apiV3.sequenceViewAdd$(keys.report).pipe(operators_1.catchError(function (error, caught) {
24431                 console.error("Failed to report sequence stats (" + keys.report + ")", error);
24432                 return rxjs_1.empty();
24433             }));
24434         }))
24435             .subscribe(function () { });
24436         this._imageSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
24437             return node.key;
24438         })).pipe(operators_1.buffer(this._navigator.stateService.currentNode$.pipe(operators_1.debounceTime(5000, this._scheduler))), operators_1.scan(function (keys, newKeys) {
24439             keys.report = [];
24440             for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
24441                 var key = newKeys_1[_i];
24442                 if (!(key in keys.reported)) {
24443                     keys.report.push(key);
24444                     keys.reported[key] = true;
24445                 }
24446             }
24447             return keys;
24448         }, { report: [], reported: {} }), operators_1.filter(function (keys) {
24449             return keys.report.length > 0;
24450         }), operators_1.mergeMap(function (keys) {
24451             return _this._navigator.apiV3.imageViewAdd$(keys.report).pipe(operators_1.catchError(function (error, caught) {
24452                 console.error("Failed to report image stats (" + keys.report + ")", error);
24453                 return rxjs_1.empty();
24454             }));
24455         }))
24456             .subscribe(function () { });
24457     };
24458     StatsComponent.prototype._deactivate = function () {
24459         this._sequenceSubscription.unsubscribe();
24460         this._imageSubscription.unsubscribe();
24461     };
24462     StatsComponent.prototype._getDefaultConfiguration = function () {
24463         return {};
24464     };
24465     StatsComponent.componentName = "stats";
24466     return StatsComponent;
24467 }(Component_1.Component));
24468 exports.StatsComponent = StatsComponent;
24469 Component_1.ComponentService.register(StatsComponent);
24470 exports.default = StatsComponent;
24471
24472 },{"../Component":275,"rxjs":27,"rxjs/operators":225}],302:[function(require,module,exports){
24473 "use strict";
24474 var __extends = (this && this.__extends) || (function () {
24475     var extendStatics = function (d, b) {
24476         extendStatics = Object.setPrototypeOf ||
24477             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24478             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24479         return extendStatics(d, b);
24480     }
24481     return function (d, b) {
24482         extendStatics(d, b);
24483         function __() { this.constructor = d; }
24484         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24485     };
24486 })();
24487 Object.defineProperty(exports, "__esModule", { value: true });
24488 var vd = require("virtual-dom");
24489 var rxjs_1 = require("rxjs");
24490 var operators_1 = require("rxjs/operators");
24491 var Component_1 = require("../../Component");
24492 /**
24493  * @class DirectionComponent
24494  * @classdesc Component showing navigation arrows for steps and turns.
24495  */
24496 var DirectionComponent = /** @class */ (function (_super) {
24497     __extends(DirectionComponent, _super);
24498     function DirectionComponent(name, container, navigator, directionDOMRenderer) {
24499         var _this = _super.call(this, name, container, navigator) || this;
24500         _this._renderer = !!directionDOMRenderer ?
24501             directionDOMRenderer :
24502             new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, { height: container.element.offsetHeight, width: container.element.offsetWidth });
24503         _this._hoveredKeySubject$ = new rxjs_1.Subject();
24504         _this._hoveredKey$ = _this._hoveredKeySubject$.pipe(operators_1.share());
24505         return _this;
24506     }
24507     Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
24508         /**
24509          * Get hovered key observable.
24510          *
24511          * @description An observable emitting the key of the node for the direction
24512          * arrow that is being hovered. When the mouse leaves a direction arrow null
24513          * is emitted.
24514          *
24515          * @returns {Observable<string>}
24516          */
24517         get: function () {
24518             return this._hoveredKey$;
24519         },
24520         enumerable: true,
24521         configurable: true
24522     });
24523     /**
24524      * Set highlight key.
24525      *
24526      * @description The arrow pointing towards the node corresponding to the
24527      * highlight key will be highlighted.
24528      *
24529      * @param {string} highlightKey Key of node to be highlighted if existing
24530      * among arrows.
24531      */
24532     DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
24533         this.configure({ highlightKey: highlightKey });
24534     };
24535     /**
24536      * Set min width of container element.
24537      *
24538      * @description  Set min width of the non transformed container element holding
24539      * the navigation arrows. If the min width is larger than the max width the
24540      * min width value will be used.
24541      *
24542      * The container element is automatically resized when the resize
24543      * method on the Viewer class is called.
24544      *
24545      * @param {number} minWidth
24546      */
24547     DirectionComponent.prototype.setMinWidth = function (minWidth) {
24548         this.configure({ minWidth: minWidth });
24549     };
24550     /**
24551      * Set max width of container element.
24552      *
24553      * @description Set max width of the non transformed container element holding
24554      * the navigation arrows. If the min width is larger than the max width the
24555      * min width value will be used.
24556      *
24557      * The container element is automatically resized when the resize
24558      * method on the Viewer class is called.
24559      *
24560      * @param {number} minWidth
24561      */
24562     DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
24563         this.configure({ maxWidth: maxWidth });
24564     };
24565     DirectionComponent.prototype._activate = function () {
24566         var _this = this;
24567         this._configurationSubscription = this._configuration$
24568             .subscribe(function (configuration) {
24569             _this._renderer.setConfiguration(configuration);
24570         });
24571         this._resizeSubscription = this._container.renderService.size$
24572             .subscribe(function (size) {
24573             _this._renderer.resize(size);
24574         });
24575         this._nodeSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.tap(function (node) {
24576             _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
24577             _this._renderer.setNode(node);
24578         }), operators_1.withLatestFrom(this._configuration$), operators_1.switchMap(function (_a) {
24579             var node = _a[0], configuration = _a[1];
24580             return rxjs_1.combineLatest(node.spatialEdges$, configuration.distinguishSequence ?
24581                 _this._navigator.graphService
24582                     .cacheSequence$(node.sequenceKey).pipe(operators_1.catchError(function (error, caught) {
24583                     console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
24584                     return rxjs_1.of(null);
24585                 })) :
24586                 rxjs_1.of(null));
24587         }))
24588             .subscribe(function (_a) {
24589             var edgeStatus = _a[0], sequence = _a[1];
24590             _this._renderer.setEdges(edgeStatus, sequence);
24591         });
24592         this._renderCameraSubscription = this._container.renderService.renderCameraFrame$.pipe(operators_1.tap(function (renderCamera) {
24593             _this._renderer.setRenderCamera(renderCamera);
24594         }), operators_1.map(function () {
24595             return _this._renderer;
24596         }), operators_1.filter(function (renderer) {
24597             return renderer.needsRender;
24598         }), operators_1.map(function (renderer) {
24599             return { name: _this._name, vnode: renderer.render(_this._navigator) };
24600         }))
24601             .subscribe(this._container.domRenderer.render$);
24602         this._hoveredKeySubscription = rxjs_1.combineLatest(this._container.domRenderer.element$, this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$.pipe(operators_1.startWith(null)), this._container.mouseService.mouseUp$.pipe(operators_1.startWith(null))).pipe(operators_1.map(function (_a) {
24603             var element = _a[0];
24604             var elements = element.getElementsByClassName("DirectionsPerspective");
24605             for (var i = 0; i < elements.length; i++) {
24606                 var hovered = elements.item(i).querySelector(":hover");
24607                 if (hovered != null && hovered.hasAttribute("data-key")) {
24608                     return hovered.getAttribute("data-key");
24609                 }
24610             }
24611             return null;
24612         }), operators_1.distinctUntilChanged())
24613             .subscribe(this._hoveredKeySubject$);
24614         this._emitHoveredKeySubscription = this._hoveredKey$
24615             .subscribe(function (key) {
24616             _this.fire(DirectionComponent.hoveredkeychanged, key);
24617         });
24618     };
24619     DirectionComponent.prototype._deactivate = function () {
24620         this._configurationSubscription.unsubscribe();
24621         this._emitHoveredKeySubscription.unsubscribe();
24622         this._hoveredKeySubscription.unsubscribe();
24623         this._nodeSubscription.unsubscribe();
24624         this._renderCameraSubscription.unsubscribe();
24625     };
24626     DirectionComponent.prototype._getDefaultConfiguration = function () {
24627         return {
24628             distinguishSequence: false,
24629             maxWidth: 460,
24630             minWidth: 260,
24631         };
24632     };
24633     /** @inheritdoc */
24634     DirectionComponent.componentName = "direction";
24635     /**
24636      * Event fired when the hovered key changes.
24637      *
24638      * @description Emits the key of the node for the direction
24639      * arrow that is being hovered. When the mouse leaves a
24640      * direction arrow null is emitted.
24641      *
24642      * @event DirectionComponent#hoveredkeychanged
24643      * @type {string} The hovered key, null if no key is hovered.
24644      */
24645     DirectionComponent.hoveredkeychanged = "hoveredkeychanged";
24646     return DirectionComponent;
24647 }(Component_1.Component));
24648 exports.DirectionComponent = DirectionComponent;
24649 Component_1.ComponentService.register(DirectionComponent);
24650 exports.default = DirectionComponent;
24651
24652
24653 },{"../../Component":275,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],303:[function(require,module,exports){
24654 "use strict";
24655 Object.defineProperty(exports, "__esModule", { value: true });
24656 var Geo_1 = require("../../Geo");
24657 /**
24658  * @class DirectionDOMCalculator
24659  * @classdesc Helper class for calculating DOM CSS properties.
24660  */
24661 var DirectionDOMCalculator = /** @class */ (function () {
24662     function DirectionDOMCalculator(configuration, size) {
24663         this._spatial = new Geo_1.Spatial();
24664         this._minThresholdWidth = 320;
24665         this._maxThresholdWidth = 1480;
24666         this._minThresholdHeight = 240;
24667         this._maxThresholdHeight = 820;
24668         this._configure(configuration);
24669         this._resize(size);
24670         this._reset();
24671     }
24672     Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
24673         get: function () {
24674             return this._minWidth;
24675         },
24676         enumerable: true,
24677         configurable: true
24678     });
24679     Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
24680         get: function () {
24681             return this._maxWidth;
24682         },
24683         enumerable: true,
24684         configurable: true
24685     });
24686     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
24687         get: function () {
24688             return this._containerWidth;
24689         },
24690         enumerable: true,
24691         configurable: true
24692     });
24693     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
24694         get: function () {
24695             return this._containerWidthCss;
24696         },
24697         enumerable: true,
24698         configurable: true
24699     });
24700     Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
24701         get: function () {
24702             return this._containerMarginCss;
24703         },
24704         enumerable: true,
24705         configurable: true
24706     });
24707     Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
24708         get: function () {
24709             return this._containerLeftCss;
24710         },
24711         enumerable: true,
24712         configurable: true
24713     });
24714     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
24715         get: function () {
24716             return this._containerHeight;
24717         },
24718         enumerable: true,
24719         configurable: true
24720     });
24721     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
24722         get: function () {
24723             return this._containerHeightCss;
24724         },
24725         enumerable: true,
24726         configurable: true
24727     });
24728     Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
24729         get: function () {
24730             return this._containerBottomCss;
24731         },
24732         enumerable: true,
24733         configurable: true
24734     });
24735     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
24736         get: function () {
24737             return this._stepCircleSize;
24738         },
24739         enumerable: true,
24740         configurable: true
24741     });
24742     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
24743         get: function () {
24744             return this._stepCircleSizeCss;
24745         },
24746         enumerable: true,
24747         configurable: true
24748     });
24749     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
24750         get: function () {
24751             return this._stepCircleMarginCss;
24752         },
24753         enumerable: true,
24754         configurable: true
24755     });
24756     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
24757         get: function () {
24758             return this._turnCircleSize;
24759         },
24760         enumerable: true,
24761         configurable: true
24762     });
24763     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
24764         get: function () {
24765             return this._turnCircleSizeCss;
24766         },
24767         enumerable: true,
24768         configurable: true
24769     });
24770     Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
24771         get: function () {
24772             return this._outerRadius;
24773         },
24774         enumerable: true,
24775         configurable: true
24776     });
24777     Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
24778         get: function () {
24779             return this._innerRadius;
24780         },
24781         enumerable: true,
24782         configurable: true
24783     });
24784     Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
24785         get: function () {
24786             return this._shadowOffset;
24787         },
24788         enumerable: true,
24789         configurable: true
24790     });
24791     /**
24792      * Configures the min and max width values.
24793      *
24794      * @param {IDirectionConfiguration} configuration Configuration
24795      * with min and max width values.
24796      */
24797     DirectionDOMCalculator.prototype.configure = function (configuration) {
24798         this._configure(configuration);
24799         this._reset();
24800     };
24801     /**
24802      * Resizes all properties according to the width and height
24803      * of the size object.
24804      *
24805      * @param {ISize} size The size of the container element.
24806      */
24807     DirectionDOMCalculator.prototype.resize = function (size) {
24808         this._resize(size);
24809         this._reset();
24810     };
24811     /**
24812      * Calculates the coordinates on the unit circle for an angle.
24813      *
24814      * @param {number} angle Angle in radians.
24815      * @returns {Array<number>} The x and y coordinates on the unit circle.
24816      */
24817     DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
24818         return [Math.cos(angle), Math.sin(angle)];
24819     };
24820     /**
24821      * Calculates the coordinates on the unit circle for the
24822      * relative angle between the first and second angle.
24823      *
24824      * @param {number} first Angle in radians.
24825      * @param {number} second Angle in radians.
24826      * @returns {Array<number>} The x and y coordinates on the unit circle
24827      * for the relative angle between the first and second angle.
24828      */
24829     DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
24830         var relativeAngle = this._spatial.wrapAngle(first - second);
24831         return this.angleToCoordinates(relativeAngle);
24832     };
24833     DirectionDOMCalculator.prototype._configure = function (configuration) {
24834         this._minWidth = configuration.minWidth;
24835         this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
24836     };
24837     DirectionDOMCalculator.prototype._resize = function (size) {
24838         this._elementWidth = size.width;
24839         this._elementHeight = size.height;
24840     };
24841     DirectionDOMCalculator.prototype._reset = function () {
24842         this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
24843         this._containerHeight = this._getContainerHeight(this.containerWidth);
24844         this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
24845         this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
24846         this._outerRadius = this._getOuterRadius(this._containerHeight);
24847         this._innerRadius = this._getInnerRadius(this._containerHeight);
24848         this._shadowOffset = 3;
24849         this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
24850         this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
24851         this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
24852         this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
24853         this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
24854         this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
24855         this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
24856         this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
24857     };
24858     DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
24859         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
24860         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
24861         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
24862         coeff = 0.04 * Math.round(25 * coeff);
24863         return this._minWidth + coeff * (this._maxWidth - this._minWidth);
24864     };
24865     DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
24866         return 0.77 * containerWidth;
24867     };
24868     DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
24869         return 0.34 * containerHeight;
24870     };
24871     DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
24872         return 0.3 * containerHeight;
24873     };
24874     DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
24875         return 0.31 * containerHeight;
24876     };
24877     DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
24878         return 0.125 * containerHeight;
24879     };
24880     DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
24881         return value + "px";
24882     };
24883     DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
24884         return value > minWidth ? value : minWidth;
24885     };
24886     return DirectionDOMCalculator;
24887 }());
24888 exports.DirectionDOMCalculator = DirectionDOMCalculator;
24889 exports.default = DirectionDOMCalculator;
24890
24891
24892 },{"../../Geo":278}],304:[function(require,module,exports){
24893 "use strict";
24894 Object.defineProperty(exports, "__esModule", { value: true });
24895 var vd = require("virtual-dom");
24896 var Component_1 = require("../../Component");
24897 var Edge_1 = require("../../Edge");
24898 var Error_1 = require("../../Error");
24899 var Geo_1 = require("../../Geo");
24900 /**
24901  * @class DirectionDOMRenderer
24902  * @classdesc DOM renderer for direction arrows.
24903  */
24904 var DirectionDOMRenderer = /** @class */ (function () {
24905     function DirectionDOMRenderer(configuration, size) {
24906         this._isEdge = false;
24907         this._spatial = new Geo_1.Spatial();
24908         this._calculator = new Component_1.DirectionDOMCalculator(configuration, size);
24909         this._node = null;
24910         this._rotation = { phi: 0, theta: 0 };
24911         this._epsilon = 0.5 * Math.PI / 180;
24912         this._highlightKey = null;
24913         this._distinguishSequence = false;
24914         this._needsRender = false;
24915         this._stepEdges = [];
24916         this._turnEdges = [];
24917         this._panoEdges = [];
24918         this._sequenceEdgeKeys = [];
24919         this._stepDirections = [
24920             Edge_1.EdgeDirection.StepForward,
24921             Edge_1.EdgeDirection.StepBackward,
24922             Edge_1.EdgeDirection.StepLeft,
24923             Edge_1.EdgeDirection.StepRight,
24924         ];
24925         this._turnDirections = [
24926             Edge_1.EdgeDirection.TurnLeft,
24927             Edge_1.EdgeDirection.TurnRight,
24928             Edge_1.EdgeDirection.TurnU,
24929         ];
24930         this._turnNames = {};
24931         this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
24932         this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
24933         this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
24934         // detects IE 8-11, then Edge 20+.
24935         var isIE = !!document.documentMode;
24936         this._isEdge = !isIE && !!window.StyleMedia;
24937     }
24938     Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
24939         /**
24940          * Get needs render.
24941          *
24942          * @returns {boolean} Value indicating whether render should be called.
24943          */
24944         get: function () {
24945             return this._needsRender;
24946         },
24947         enumerable: true,
24948         configurable: true
24949     });
24950     /**
24951      * Renders virtual DOM elements.
24952      *
24953      * @description Calling render resets the needs render property.
24954      */
24955     DirectionDOMRenderer.prototype.render = function (navigator) {
24956         this._needsRender = false;
24957         var rotation = this._rotation;
24958         var steps = [];
24959         var turns = [];
24960         if (this._node.pano) {
24961             steps = steps.concat(this._createPanoArrows(navigator, rotation));
24962         }
24963         else {
24964             steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
24965             steps = steps.concat(this._createStepArrows(navigator, rotation));
24966             turns = turns.concat(this._createTurnArrows(navigator));
24967         }
24968         return this._getContainer(steps, turns, rotation);
24969     };
24970     DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
24971         this._setEdges(edgeStatus, sequence);
24972         this._setNeedsRender();
24973     };
24974     /**
24975      * Set node for which to show edges.
24976      *
24977      * @param {Node} node
24978      */
24979     DirectionDOMRenderer.prototype.setNode = function (node) {
24980         this._node = node;
24981         this._clearEdges();
24982         this._setNeedsRender();
24983     };
24984     /**
24985      * Set the render camera to use for calculating rotations.
24986      *
24987      * @param {RenderCamera} renderCamera
24988      */
24989     DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
24990         var rotation = renderCamera.rotation;
24991         if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
24992             return;
24993         }
24994         this._rotation = rotation;
24995         this._setNeedsRender();
24996     };
24997     /**
24998      * Set configuration values.
24999      *
25000      * @param {IDirectionConfiguration} configuration
25001      */
25002     DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
25003         var needsRender = false;
25004         if (this._highlightKey !== configuration.highlightKey ||
25005             this._distinguishSequence !== configuration.distinguishSequence) {
25006             this._highlightKey = configuration.highlightKey;
25007             this._distinguishSequence = configuration.distinguishSequence;
25008             needsRender = true;
25009         }
25010         if (this._calculator.minWidth !== configuration.minWidth ||
25011             this._calculator.maxWidth !== configuration.maxWidth) {
25012             this._calculator.configure(configuration);
25013             needsRender = true;
25014         }
25015         if (needsRender) {
25016             this._setNeedsRender();
25017         }
25018     };
25019     /**
25020      * Detect the element's width and height and resize
25021      * elements accordingly.
25022      *
25023      * @param {ISize} size Size of vßiewer container element.
25024      */
25025     DirectionDOMRenderer.prototype.resize = function (size) {
25026         this._calculator.resize(size);
25027         this._setNeedsRender();
25028     };
25029     DirectionDOMRenderer.prototype._setNeedsRender = function () {
25030         if (this._node != null) {
25031             this._needsRender = true;
25032         }
25033     };
25034     DirectionDOMRenderer.prototype._clearEdges = function () {
25035         this._stepEdges = [];
25036         this._turnEdges = [];
25037         this._panoEdges = [];
25038         this._sequenceEdgeKeys = [];
25039     };
25040     DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
25041         this._stepEdges = [];
25042         this._turnEdges = [];
25043         this._panoEdges = [];
25044         this._sequenceEdgeKeys = [];
25045         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25046             var edge = _a[_i];
25047             var direction = edge.data.direction;
25048             if (this._stepDirections.indexOf(direction) > -1) {
25049                 this._stepEdges.push(edge);
25050                 continue;
25051             }
25052             if (this._turnDirections.indexOf(direction) > -1) {
25053                 this._turnEdges.push(edge);
25054                 continue;
25055             }
25056             if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
25057                 this._panoEdges.push(edge);
25058             }
25059         }
25060         if (this._distinguishSequence && sequence != null) {
25061             var edges = this._panoEdges
25062                 .concat(this._stepEdges)
25063                 .concat(this._turnEdges);
25064             for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
25065                 var edge = edges_1[_b];
25066                 var edgeKey = edge.to;
25067                 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
25068                     var sequenceKey = _d[_c];
25069                     if (sequenceKey === edgeKey) {
25070                         this._sequenceEdgeKeys.push(edgeKey);
25071                         break;
25072                     }
25073                 }
25074             }
25075         }
25076     };
25077     DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
25078         var arrows = [];
25079         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
25080             var panoEdge = _a[_i];
25081             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
25082         }
25083         for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
25084             var stepEdge = _c[_b];
25085             arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
25086         }
25087         return arrows;
25088     };
25089     DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
25090         var threshold = Math.PI / 8;
25091         var relativePhi = rotation.phi;
25092         switch (direction) {
25093             case Edge_1.EdgeDirection.StepBackward:
25094                 relativePhi = rotation.phi - Math.PI;
25095                 break;
25096             case Edge_1.EdgeDirection.StepLeft:
25097                 relativePhi = rotation.phi + Math.PI / 2;
25098                 break;
25099             case Edge_1.EdgeDirection.StepRight:
25100                 relativePhi = rotation.phi - Math.PI / 2;
25101                 break;
25102             default:
25103                 break;
25104         }
25105         if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
25106             return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
25107         }
25108         return this._createVNodeDisabled(key, azimuth, rotation);
25109     };
25110     DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
25111         var arrows = [];
25112         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
25113             var panoEdge = _a[_i];
25114             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
25115         }
25116         return arrows;
25117     };
25118     DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
25119         var arrows = [];
25120         for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
25121             var stepEdge = _a[_i];
25122             arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
25123         }
25124         return arrows;
25125     };
25126     DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
25127         var turns = [];
25128         for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
25129             var turnEdge = _a[_i];
25130             var direction = turnEdge.data.direction;
25131             var name_1 = this._turnNames[direction];
25132             turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
25133         }
25134         return turns;
25135     };
25136     DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
25137         var onClick = function (e) {
25138             navigator.moveToKey$(key)
25139                 .subscribe(undefined, function (error) {
25140                 if (!(error instanceof Error_1.AbortMapillaryError)) {
25141                     console.error(error);
25142                 }
25143             });
25144         };
25145         return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
25146     };
25147     DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
25148         var onClick = function (e) {
25149             navigator.moveDir$(direction)
25150                 .subscribe(undefined, function (error) {
25151                 if (!(error instanceof Error_1.AbortMapillaryError)) {
25152                     console.error(error);
25153                 }
25154             });
25155         };
25156         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
25157     };
25158     DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
25159         var onClick = function (e) {
25160             navigator.moveDir$(direction)
25161                 .subscribe(undefined, function (error) {
25162                 if (!(error instanceof Error_1.AbortMapillaryError)) {
25163                     console.error(error);
25164                 }
25165             });
25166         };
25167         var style = {
25168             height: this._calculator.turnCircleSizeCss,
25169             transform: "rotate(0)",
25170             width: this._calculator.turnCircleSizeCss,
25171         };
25172         switch (direction) {
25173             case Edge_1.EdgeDirection.TurnLeft:
25174                 style.left = "5px";
25175                 style.top = "5px";
25176                 break;
25177             case Edge_1.EdgeDirection.TurnRight:
25178                 style.right = "5px";
25179                 style.top = "5px";
25180                 break;
25181             case Edge_1.EdgeDirection.TurnU:
25182                 style.left = "5px";
25183                 style.bottom = "5px";
25184                 break;
25185             default:
25186                 break;
25187         }
25188         var circleProperties = {
25189             attributes: {
25190                 "data-key": key,
25191             },
25192             onclick: onClick,
25193             style: style,
25194         };
25195         var circleClassName = "TurnCircle";
25196         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
25197             circleClassName += "Sequence";
25198         }
25199         if (this._highlightKey === key) {
25200             circleClassName += "Highlight";
25201         }
25202         var turn = vd.h("div." + className, {}, []);
25203         return vd.h("div." + circleClassName, circleProperties, [turn]);
25204     };
25205     DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
25206         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
25207     };
25208     DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
25209         var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
25210         // rotate 90 degrees clockwise and flip over X-axis
25211         var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
25212         var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
25213         var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
25214         var shadowOffset = this._calculator.shadowOffset;
25215         var shadowTranslationX = -shadowOffset * shadowTranslation[1];
25216         var shadowTranslationY = shadowOffset * shadowTranslation[0];
25217         var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
25218         var properties = {
25219             style: {
25220                 "-webkit-filter": filter,
25221                 filter: filter,
25222             },
25223         };
25224         var chevron = vd.h("div." + className, properties, []);
25225         var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
25226         var circleTransform = shiftVertically ?
25227             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
25228             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
25229         var circleProperties = {
25230             attributes: { "data-key": key },
25231             onclick: onClick,
25232             style: {
25233                 height: this._calculator.stepCircleSizeCss,
25234                 marginLeft: this._calculator.stepCircleMarginCss,
25235                 marginTop: this._calculator.stepCircleMarginCss,
25236                 transform: circleTransform,
25237                 width: this._calculator.stepCircleSizeCss,
25238             },
25239         };
25240         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
25241             circleClassName += "Sequence";
25242         }
25243         if (this._highlightKey === key) {
25244             circleClassName += "Highlight";
25245         }
25246         return vd.h("div." + circleClassName, circleProperties, [chevron]);
25247     };
25248     DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
25249         // edge does not handle hover on perspective transforms.
25250         var transform = this._isEdge ?
25251             "rotateX(60deg)" :
25252             "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
25253         var properties = {
25254             oncontextmenu: function (event) { event.preventDefault(); },
25255             style: {
25256                 bottom: this._calculator.containerBottomCss,
25257                 height: this._calculator.containerHeightCss,
25258                 left: this._calculator.containerLeftCss,
25259                 marginLeft: this._calculator.containerMarginCss,
25260                 transform: transform,
25261                 width: this._calculator.containerWidthCss,
25262             },
25263         };
25264         return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
25265     };
25266     return DirectionDOMRenderer;
25267 }());
25268 exports.DirectionDOMRenderer = DirectionDOMRenderer;
25269 exports.default = DirectionDOMRenderer;
25270
25271
25272 },{"../../Component":275,"../../Edge":276,"../../Error":277,"../../Geo":278,"virtual-dom":231}],305:[function(require,module,exports){
25273 "use strict";
25274 var __extends = (this && this.__extends) || (function () {
25275     var extendStatics = function (d, b) {
25276         extendStatics = Object.setPrototypeOf ||
25277             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25278             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25279         return extendStatics(d, b);
25280     }
25281     return function (d, b) {
25282         extendStatics(d, b);
25283         function __() { this.constructor = d; }
25284         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25285     };
25286 })();
25287 Object.defineProperty(exports, "__esModule", { value: true });
25288 var rxjs_1 = require("rxjs");
25289 var operators_1 = require("rxjs/operators");
25290 var Component_1 = require("../../Component");
25291 var Viewer_1 = require("../../Viewer");
25292 var Render_1 = require("../../Render");
25293 var Tiles_1 = require("../../Tiles");
25294 var Utils_1 = require("../../Utils");
25295 var ViewportCoords_1 = require("../../geo/ViewportCoords");
25296 var Spatial_1 = require("../../geo/Spatial");
25297 var ImagePlaneComponent = /** @class */ (function (_super) {
25298     __extends(ImagePlaneComponent, _super);
25299     function ImagePlaneComponent(name, container, navigator) {
25300         var _this = _super.call(this, name, container, navigator) || this;
25301         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
25302         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
25303         _this._rendererOperation$ = new rxjs_1.Subject();
25304         _this._rendererCreator$ = new rxjs_1.Subject();
25305         _this._rendererDisposer$ = new rxjs_1.Subject();
25306         _this._renderer$ = _this._rendererOperation$.pipe(operators_1.scan(function (renderer, operation) {
25307             return operation(renderer);
25308         }, null), operators_1.filter(function (renderer) {
25309             return renderer != null;
25310         }), operators_1.distinctUntilChanged(undefined, function (renderer) {
25311             return renderer.frameId;
25312         }));
25313         _this._rendererCreator$.pipe(operators_1.map(function () {
25314             return function (renderer) {
25315                 if (renderer != null) {
25316                     throw new Error("Multiple image plane states can not be created at the same time");
25317                 }
25318                 return new Component_1.ImagePlaneGLRenderer();
25319             };
25320         }))
25321             .subscribe(_this._rendererOperation$);
25322         _this._rendererDisposer$.pipe(operators_1.map(function () {
25323             return function (renderer) {
25324                 renderer.dispose();
25325                 return null;
25326             };
25327         }))
25328             .subscribe(_this._rendererOperation$);
25329         return _this;
25330     }
25331     ImagePlaneComponent.prototype._activate = function () {
25332         var _this = this;
25333         this._rendererSubscription = this._renderer$.pipe(operators_1.map(function (renderer) {
25334             var renderHash = {
25335                 name: _this._name,
25336                 render: {
25337                     frameId: renderer.frameId,
25338                     needsRender: renderer.needsRender,
25339                     render: renderer.render.bind(renderer),
25340                     stage: Render_1.GLRenderStage.Background,
25341                 },
25342             };
25343             renderer.clearNeedsRender();
25344             return renderHash;
25345         }))
25346             .subscribe(this._container.glRenderer.render$);
25347         this._rendererCreator$.next(null);
25348         this._stateSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
25349             return function (renderer) {
25350                 renderer.updateFrame(frame);
25351                 return renderer;
25352             };
25353         }))
25354             .subscribe(this._rendererOperation$);
25355         var textureProvider$ = this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
25356             return frame.state.currentNode.key;
25357         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
25358             var frame = _a[0], renderer = _a[1], size = _a[2];
25359             var state = frame.state;
25360             var viewportSize = Math.max(size.width, size.height);
25361             var currentNode = state.currentNode;
25362             var currentTransform = state.currentTransform;
25363             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
25364             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
25365         }), operators_1.publishReplay(1), operators_1.refCount());
25366         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
25367         this._setTextureProviderSubscription = textureProvider$.pipe(operators_1.map(function (provider) {
25368             return function (renderer) {
25369                 renderer.setTextureProvider(provider.key, provider);
25370                 return renderer;
25371             };
25372         }))
25373             .subscribe(this._rendererOperation$);
25374         this._setTileSizeSubscription = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
25375             return rxjs_1.combineLatest(textureProvider$, rxjs_1.of(size)).pipe(operators_1.first());
25376         }))
25377             .subscribe(function (_a) {
25378             var provider = _a[0], size = _a[1];
25379             var viewportSize = Math.max(size.width, size.height);
25380             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
25381             provider.setTileSize(tileSize);
25382         });
25383         this._abortTextureProviderSubscription = textureProvider$.pipe(operators_1.pairwise())
25384             .subscribe(function (pair) {
25385             var previous = pair[0];
25386             previous.abort();
25387         });
25388         var roiTrigger$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
25389             var camera = _a[0], size = _a[1];
25390             return [
25391                 camera.camera.position.clone(),
25392                 camera.camera.lookat.clone(),
25393                 camera.zoom.valueOf(),
25394                 size.height.valueOf(),
25395                 size.width.valueOf()
25396             ];
25397         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
25398             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
25399         }), operators_1.map(function (pls) {
25400             var samePosition = pls[0][0].equals(pls[1][0]);
25401             var sameLookat = pls[0][1].equals(pls[1][1]);
25402             var sameZoom = pls[0][2] === pls[1][2];
25403             var sameHeight = pls[0][3] === pls[1][3];
25404             var sameWidth = pls[0][4] === pls[1][4];
25405             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
25406         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
25407             return stalled;
25408         }), operators_1.switchMap(function (stalled) {
25409             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
25410         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
25411         this._setRegionOfInterestSubscription = textureProvider$.pipe(operators_1.switchMap(function (provider) {
25412             return roiTrigger$.pipe(operators_1.map(function (_a) {
25413                 var camera = _a[0], size = _a[1], transform = _a[2];
25414                 var basic = new ViewportCoords_1.default().viewportToBasic(0, 0, transform, camera.perspective);
25415                 if (basic[0] < 0 || basic[1] < 0 || basic[0] > 1 || basic[1] > 1) {
25416                     return undefined;
25417                 }
25418                 return [
25419                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
25420                     provider,
25421                 ];
25422             }), operators_1.filter(function (args) {
25423                 return !!args;
25424             }));
25425         }), operators_1.filter(function (args) {
25426             return !args[1].disposed;
25427         }))
25428             .subscribe(function (args) {
25429             var roi = args[0];
25430             var provider = args[1];
25431             provider.setRegionOfInterest(roi);
25432         });
25433         var hasTexture$ = textureProvider$.pipe(operators_1.switchMap(function (provider) {
25434             return provider.hasTexture$;
25435         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
25436         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
25437         var nodeImage$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
25438             return frame.state.nodesAhead === 0;
25439         }), operators_1.map(function (frame) {
25440             return frame.state.currentNode;
25441         }), operators_1.distinctUntilChanged(undefined, function (node) {
25442             return node.key;
25443         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexture$), operators_1.filter(function (args) {
25444             return !args[1];
25445         }), operators_1.map(function (args) {
25446             return args[0];
25447         }), operators_1.filter(function (node) {
25448             return node.pano ?
25449                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
25450                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
25451         }), operators_1.switchMap(function (node) {
25452             var baseImageSize = node.pano ?
25453                 Utils_1.Settings.basePanoramaSize :
25454                 Utils_1.Settings.baseImageSize;
25455             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
25456                 return rxjs_1.empty();
25457             }
25458             var image$ = node
25459                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
25460                 return [n.image, n];
25461             }));
25462             return image$.pipe(operators_1.takeUntil(hasTexture$.pipe(operators_1.filter(function (hasTexture) {
25463                 return hasTexture;
25464             }))), operators_1.catchError(function (error, caught) {
25465                 console.error("Failed to fetch high res image (" + node.key + ")", error);
25466                 return rxjs_1.empty();
25467             }));
25468         })).pipe(operators_1.publish(), operators_1.refCount());
25469         this._updateBackgroundSubscription = nodeImage$.pipe(operators_1.withLatestFrom(textureProvider$))
25470             .subscribe(function (args) {
25471             if (args[0][1].key !== args[1].key ||
25472                 args[1].disposed) {
25473                 return;
25474             }
25475             args[1].updateBackground(args[0][0]);
25476         });
25477         this._updateTextureImageSubscription = nodeImage$.pipe(operators_1.map(function (imn) {
25478             return function (renderer) {
25479                 renderer.updateTextureImage(imn[0], imn[1]);
25480                 return renderer;
25481             };
25482         }))
25483             .subscribe(this._rendererOperation$);
25484         this._clearPeripheryPlaneSubscription = this._navigator.panService.panNodes$.pipe(operators_1.filter(function (panNodes) {
25485             return panNodes.length === 0;
25486         }), operators_1.map(function () {
25487             return function (renderer) {
25488                 renderer.clearPeripheryPlanes();
25489                 return renderer;
25490             };
25491         }))
25492             .subscribe(this._rendererOperation$);
25493         var cachedPanNodes$ = this._navigator.panService.panNodes$.pipe(operators_1.switchMap(function (nts) {
25494             return rxjs_1.from(nts).pipe(operators_1.mergeMap(function (_a) {
25495                 var n = _a[0], t = _a[1];
25496                 return rxjs_1.combineLatest(_this._navigator.graphService.cacheNode$(n.key).pipe(operators_1.catchError(function (error) {
25497                     console.error("Failed to cache periphery node (" + n.key + ")", error);
25498                     return rxjs_1.empty();
25499                 })), rxjs_1.of(t));
25500             }));
25501         }), operators_1.share());
25502         this._addPeripheryPlaneSubscription = cachedPanNodes$.pipe(operators_1.map(function (_a) {
25503             var n = _a[0], t = _a[1];
25504             return function (renderer) {
25505                 renderer.addPeripheryPlane(n, t);
25506                 return renderer;
25507             };
25508         }))
25509             .subscribe(this._rendererOperation$);
25510         this._updatePeripheryPlaneTextureSubscription = cachedPanNodes$.pipe(operators_1.mergeMap(function (_a) {
25511             var n = _a[0];
25512             return Viewer_1.ImageSize.Size2048 > Math.max(n.image.width, n.image.height) ?
25513                 n.cacheImage$(Viewer_1.ImageSize.Size2048).pipe(operators_1.catchError(function () {
25514                     return rxjs_1.empty();
25515                 })) :
25516                 rxjs_1.empty();
25517         }), operators_1.map(function (n) {
25518             return function (renderer) {
25519                 renderer.updateTextureImage(n.image, n);
25520                 return renderer;
25521             };
25522         }))
25523             .subscribe(this._rendererOperation$);
25524         var inTransition$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
25525             return frame.state.alpha < 1;
25526         }), operators_1.distinctUntilChanged());
25527         var panTrigger$ = rxjs_1.combineLatest(this._container.mouseService.active$, this._container.touchService.active$, this._navigator.stateService.inMotion$, inTransition$).pipe(operators_1.map(function (_a) {
25528             var mouseActive = _a[0], touchActive = _a[1], inMotion = _a[2], inTransition = _a[3];
25529             return !(mouseActive || touchActive || inMotion || inTransition);
25530         }), operators_1.filter(function (trigger) {
25531             return trigger;
25532         }));
25533         this._moveToPeripheryNodeSubscription = this._navigator.panService.panNodes$.pipe(operators_1.switchMap(function (nts) {
25534             return panTrigger$.pipe(operators_1.withLatestFrom(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentNode$, _this._navigator.stateService.currentTransform$), operators_1.mergeMap(function (_a) {
25535                 var renderCamera = _a[1], currentNode = _a[2], currentTransform = _a[3];
25536                 return rxjs_1.of([
25537                     renderCamera,
25538                     currentNode,
25539                     currentTransform,
25540                     nts,
25541                 ]);
25542             }));
25543         }), operators_1.switchMap(function (_a) {
25544             var camera = _a[0], cn = _a[1], ct = _a[2], nts = _a[3];
25545             var direction = camera.camera.lookat.clone().sub(camera.camera.position);
25546             var cd = new Spatial_1.default().viewingDirection(cn.rotation);
25547             var ca = cd.angleTo(direction);
25548             var closest = [ca, undefined];
25549             var basic = new ViewportCoords_1.default().viewportToBasic(0, 0, ct, camera.perspective);
25550             if (basic[0] >= 0 && basic[0] <= 1 && basic[1] >= 0 && basic[1] <= 1) {
25551                 closest[0] = Number.NEGATIVE_INFINITY;
25552             }
25553             for (var _i = 0, nts_1 = nts; _i < nts_1.length; _i++) {
25554                 var n = nts_1[_i][0];
25555                 var d = new Spatial_1.default().viewingDirection(n.rotation);
25556                 var a = d.angleTo(direction);
25557                 if (a < closest[0]) {
25558                     closest[0] = a;
25559                     closest[1] = n.key;
25560                 }
25561             }
25562             if (!closest[1]) {
25563                 return rxjs_1.empty();
25564             }
25565             return _this._navigator.moveToKey$(closest[1]).pipe(operators_1.catchError(function () {
25566                 return rxjs_1.empty();
25567             }));
25568         }))
25569             .subscribe();
25570     };
25571     ImagePlaneComponent.prototype._deactivate = function () {
25572         this._rendererDisposer$.next(null);
25573         this._abortTextureProviderSubscription.unsubscribe();
25574         this._hasTextureSubscription.unsubscribe();
25575         this._rendererSubscription.unsubscribe();
25576         this._setRegionOfInterestSubscription.unsubscribe();
25577         this._setTextureProviderSubscription.unsubscribe();
25578         this._setTileSizeSubscription.unsubscribe();
25579         this._stateSubscription.unsubscribe();
25580         this._textureProviderSubscription.unsubscribe();
25581         this._updateBackgroundSubscription.unsubscribe();
25582         this._updateTextureImageSubscription.unsubscribe();
25583         this._clearPeripheryPlaneSubscription.unsubscribe();
25584         this._addPeripheryPlaneSubscription.unsubscribe();
25585         this._updatePeripheryPlaneTextureSubscription.unsubscribe();
25586         this._moveToPeripheryNodeSubscription.unsubscribe();
25587     };
25588     ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
25589         return {};
25590     };
25591     ImagePlaneComponent.componentName = "imagePlane";
25592     return ImagePlaneComponent;
25593 }(Component_1.Component));
25594 exports.ImagePlaneComponent = ImagePlaneComponent;
25595 Component_1.ComponentService.register(ImagePlaneComponent);
25596 exports.default = ImagePlaneComponent;
25597
25598 },{"../../Component":275,"../../Render":281,"../../Tiles":284,"../../Utils":285,"../../Viewer":286,"../../geo/Spatial":387,"../../geo/ViewportCoords":389,"rxjs":27,"rxjs/operators":225}],306:[function(require,module,exports){
25599 "use strict";
25600 Object.defineProperty(exports, "__esModule", { value: true });
25601 var Component_1 = require("../../Component");
25602 var ImagePlaneGLRenderer = /** @class */ (function () {
25603     function ImagePlaneGLRenderer() {
25604         this._factory = new Component_1.MeshFactory();
25605         this._scene = new Component_1.MeshScene();
25606         this._alpha = 0;
25607         this._alphaOld = 0;
25608         this._fadeOutSpeed = 0.05;
25609         this._currentKey = null;
25610         this._previousKey = null;
25611         this._providerDisposers = {};
25612         this._frameId = 0;
25613         this._needsRender = false;
25614     }
25615     Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
25616         get: function () {
25617             return this._frameId;
25618         },
25619         enumerable: true,
25620         configurable: true
25621     });
25622     Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
25623         get: function () {
25624             return this._needsRender;
25625         },
25626         enumerable: true,
25627         configurable: true
25628     });
25629     ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
25630         this._needsRender = true;
25631     };
25632     ImagePlaneGLRenderer.prototype.addPeripheryPlane = function (node, transform) {
25633         var mesh = this._factory.createMesh(node, transform);
25634         var planes = {};
25635         planes[node.key] = mesh;
25636         this._scene.addPeripheryPlanes(planes);
25637         this._needsRender = true;
25638     };
25639     ImagePlaneGLRenderer.prototype.clearPeripheryPlanes = function () {
25640         this._scene.setPeripheryPlanes({});
25641         this._needsRender = true;
25642     };
25643     ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
25644         this._updateFrameId(frame.id);
25645         this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
25646         this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
25647         this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
25648     };
25649     ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
25650         var _this = this;
25651         if (key !== this._currentKey) {
25652             return;
25653         }
25654         var createdSubscription = provider.textureCreated$
25655             .subscribe(function (texture) {
25656             _this._updateTexture(texture);
25657         });
25658         var updatedSubscription = provider.textureUpdated$
25659             .subscribe(function (updated) {
25660             _this._needsRender = true;
25661         });
25662         var dispose = function () {
25663             createdSubscription.unsubscribe();
25664             updatedSubscription.unsubscribe();
25665             provider.dispose();
25666         };
25667         if (key in this._providerDisposers) {
25668             var disposeProvider = this._providerDisposers[key];
25669             disposeProvider();
25670             delete this._providerDisposers[key];
25671         }
25672         this._providerDisposers[key] = dispose;
25673     };
25674     ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
25675         this._needsRender = true;
25676         var planes = this._extend({}, this._scene.planes, this._scene.planesOld, this._scene.planesPeriphery);
25677         for (var key in planes) {
25678             if (!planes.hasOwnProperty(key)) {
25679                 continue;
25680             }
25681             if (key !== node.key) {
25682                 continue;
25683             }
25684             var plane = planes[key];
25685             var material = plane.material;
25686             var texture = material.uniforms.projectorTex.value;
25687             texture.image = image;
25688             texture.needsUpdate = true;
25689         }
25690     };
25691     ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
25692         var planes = this._scene.planes;
25693         var planesOld = this._scene.planesOld;
25694         var planesPeriphery = this._scene.planesPeriphery;
25695         var planeAlpha = Object.keys(planesOld).length ? 1 : this._alpha;
25696         var peripheryAlpha = Object.keys(planesOld).length ? 1 : Math.floor(this._alpha);
25697         for (var key in planes) {
25698             if (!planes.hasOwnProperty(key)) {
25699                 continue;
25700             }
25701             var plane = planes[key];
25702             plane.material.uniforms.opacity.value = planeAlpha;
25703         }
25704         for (var key in planesOld) {
25705             if (!planesOld.hasOwnProperty(key)) {
25706                 continue;
25707             }
25708             var plane = planesOld[key];
25709             plane.material.uniforms.opacity.value = this._alphaOld;
25710         }
25711         for (var key in planesPeriphery) {
25712             if (!planesPeriphery.hasOwnProperty(key)) {
25713                 continue;
25714             }
25715             var plane = planesPeriphery[key];
25716             plane.material.uniforms.opacity.value = peripheryAlpha;
25717         }
25718         renderer.render(this._scene.scenePeriphery, perspectiveCamera);
25719         renderer.render(this._scene.scene, perspectiveCamera);
25720         renderer.render(this._scene.sceneOld, perspectiveCamera);
25721         for (var key in planes) {
25722             if (!planes.hasOwnProperty(key)) {
25723                 continue;
25724             }
25725             var plane = planes[key];
25726             plane.material.uniforms.opacity.value = this._alpha;
25727         }
25728         renderer.render(this._scene.scene, perspectiveCamera);
25729     };
25730     ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
25731         this._needsRender = false;
25732     };
25733     ImagePlaneGLRenderer.prototype.dispose = function () {
25734         this._scene.clear();
25735     };
25736     ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
25737         this._frameId = frameId;
25738     };
25739     ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
25740         if (alpha === this._alpha) {
25741             return false;
25742         }
25743         this._alpha = alpha;
25744         return true;
25745     };
25746     ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
25747         if (alpha < 1 || this._alphaOld === 0) {
25748             return false;
25749         }
25750         this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
25751         return true;
25752     };
25753     ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
25754         if (state.currentNode == null || state.currentNode.key === this._currentKey) {
25755             return false;
25756         }
25757         var previousKey = state.previousNode != null ? state.previousNode.key : null;
25758         var currentKey = state.currentNode.key;
25759         if (this._previousKey !== previousKey &&
25760             this._previousKey !== currentKey &&
25761             this._previousKey in this._providerDisposers) {
25762             var disposeProvider = this._providerDisposers[this._previousKey];
25763             disposeProvider();
25764             delete this._providerDisposers[this._previousKey];
25765         }
25766         if (previousKey != null) {
25767             if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
25768                 var previousMesh = this._factory.createMesh(state.previousNode, state.previousTransform);
25769                 var previousPlanes = {};
25770                 previousPlanes[previousKey] = previousMesh;
25771                 this._scene.updateImagePlanes(previousPlanes);
25772             }
25773             this._previousKey = previousKey;
25774         }
25775         this._currentKey = currentKey;
25776         var currentMesh = this._factory.createMesh(state.currentNode, state.currentTransform);
25777         var planes = {};
25778         planes[currentKey] = currentMesh;
25779         this._scene.updateImagePlanes(planes);
25780         this._alphaOld = 1;
25781         return true;
25782     };
25783     ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
25784         this._needsRender = true;
25785         var planes = this._scene.planes;
25786         for (var key in planes) {
25787             if (!planes.hasOwnProperty(key)) {
25788                 continue;
25789             }
25790             var plane = planes[key];
25791             var material = plane.material;
25792             var oldTexture = material.uniforms.projectorTex.value;
25793             material.uniforms.projectorTex.value = null;
25794             oldTexture.dispose();
25795             material.uniforms.projectorTex.value = texture;
25796         }
25797     };
25798     ImagePlaneGLRenderer.prototype._extend = function (dest) {
25799         var sources = [];
25800         for (var _i = 1; _i < arguments.length; _i++) {
25801             sources[_i - 1] = arguments[_i];
25802         }
25803         for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
25804             var src = sources_1[_a];
25805             for (var k in src) {
25806                 if (!src.hasOwnProperty(k)) {
25807                     continue;
25808                 }
25809                 dest[k] = src[k];
25810             }
25811         }
25812         return dest;
25813     };
25814     return ImagePlaneGLRenderer;
25815 }());
25816 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
25817 exports.default = ImagePlaneGLRenderer;
25818
25819 },{"../../Component":275}],307:[function(require,module,exports){
25820 "use strict";
25821 Object.defineProperty(exports, "__esModule", { value: true });
25822 var CoverState;
25823 (function (CoverState) {
25824     CoverState[CoverState["Hidden"] = 0] = "Hidden";
25825     CoverState[CoverState["Loading"] = 1] = "Loading";
25826     CoverState[CoverState["Visible"] = 2] = "Visible";
25827 })(CoverState = exports.CoverState || (exports.CoverState = {}));
25828
25829 },{}],308:[function(require,module,exports){
25830 "use strict";
25831 Object.defineProperty(exports, "__esModule", { value: true });
25832 /**
25833  * Enumeration for slider mode.
25834  *
25835  * @enum {number}
25836  * @readonly
25837  *
25838  * @description Modes for specifying how transitions
25839  * between nodes are performed in slider mode. Only
25840  * applicable when the slider component determines
25841  * that transitions with motion is possilble. When it
25842  * is not, the stationary mode will be applied.
25843  */
25844 var SliderMode;
25845 (function (SliderMode) {
25846     /**
25847      * Transitions with motion.
25848      *
25849      * @description The slider component moves the
25850      * camera between the node origins.
25851      *
25852      * In this mode it is not possible to zoom or pan.
25853      *
25854      * The slider component falls back to stationary
25855      * mode when it determines that the pair of nodes
25856      * does not have a strong enough relation.
25857      */
25858     SliderMode[SliderMode["Motion"] = 0] = "Motion";
25859     /**
25860      * Stationary transitions.
25861      *
25862      * @description The camera is stationary.
25863      *
25864      * In this mode it is possible to zoom and pan.
25865      */
25866     SliderMode[SliderMode["Stationary"] = 1] = "Stationary";
25867 })(SliderMode = exports.SliderMode || (exports.SliderMode = {}));
25868
25869 },{}],309:[function(require,module,exports){
25870 "use strict";
25871 Object.defineProperty(exports, "__esModule", { value: true });
25872 var ICoverConfiguration_1 = require("./ICoverConfiguration");
25873 exports.CoverState = ICoverConfiguration_1.CoverState;
25874 var ISliderConfiguration_1 = require("./ISliderConfiguration");
25875 exports.SliderMode = ISliderConfiguration_1.SliderMode;
25876
25877 },{"./ICoverConfiguration":307,"./ISliderConfiguration":308}],310:[function(require,module,exports){
25878 "use strict";
25879 var __extends = (this && this.__extends) || (function () {
25880     var extendStatics = function (d, b) {
25881         extendStatics = Object.setPrototypeOf ||
25882             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25883             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25884         return extendStatics(d, b);
25885     }
25886     return function (d, b) {
25887         extendStatics(d, b);
25888         function __() { this.constructor = d; }
25889         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25890     };
25891 })();
25892 Object.defineProperty(exports, "__esModule", { value: true });
25893 var operators_1 = require("rxjs/operators");
25894 var Component_1 = require("../../Component");
25895 var Edge_1 = require("../../Edge");
25896 /**
25897  * The `KeyPlayHandler` allows the user to control the play behavior
25898  * using the following key commands:
25899  *
25900  * `Spacebar`: Start or stop playing.
25901  * `SHIFT` + `D`: Switch direction.
25902  * `<`: Decrease speed.
25903  * `>`: Increase speed.
25904  *
25905  * @example
25906  * ```
25907  * var keyboardComponent = viewer.getComponent("keyboard");
25908  *
25909  * keyboardComponent.keyPlay.disable();
25910  * keyboardComponent.keyPlay.enable();
25911  *
25912  * var isEnabled = keyboardComponent.keyPlay.isEnabled;
25913  * ```
25914  */
25915 var KeyPlayHandler = /** @class */ (function (_super) {
25916     __extends(KeyPlayHandler, _super);
25917     function KeyPlayHandler() {
25918         return _super !== null && _super.apply(this, arguments) || this;
25919     }
25920     KeyPlayHandler.prototype._enable = function () {
25921         var _this = this;
25922         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(this._navigator.playService.playing$, this._navigator.playService.direction$, this._navigator.playService.speed$, this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
25923             return node.sequenceEdges$;
25924         }))))
25925             .subscribe(function (_a) {
25926             var event = _a[0], playing = _a[1], direction = _a[2], speed = _a[3], status = _a[4];
25927             if (event.altKey || event.ctrlKey || event.metaKey) {
25928                 return;
25929             }
25930             switch (event.key) {
25931                 case "D":
25932                     if (!event.shiftKey) {
25933                         return;
25934                     }
25935                     var newDirection = playing ?
25936                         null : direction === Edge_1.EdgeDirection.Next ?
25937                         Edge_1.EdgeDirection.Prev : direction === Edge_1.EdgeDirection.Prev ?
25938                         Edge_1.EdgeDirection.Next : null;
25939                     if (newDirection != null) {
25940                         _this._navigator.playService.setDirection(newDirection);
25941                     }
25942                     break;
25943                 case " ":
25944                     if (event.shiftKey) {
25945                         return;
25946                     }
25947                     if (playing) {
25948                         _this._navigator.playService.stop();
25949                     }
25950                     else {
25951                         for (var _i = 0, _b = status.edges; _i < _b.length; _i++) {
25952                             var edge = _b[_i];
25953                             if (edge.data.direction === direction) {
25954                                 _this._navigator.playService.play();
25955                             }
25956                         }
25957                     }
25958                     break;
25959                 case "<":
25960                     _this._navigator.playService.setSpeed(speed - 0.05);
25961                     break;
25962                 case ">":
25963                     _this._navigator.playService.setSpeed(speed + 0.05);
25964                     break;
25965                 default:
25966                     return;
25967             }
25968             event.preventDefault();
25969         });
25970     };
25971     KeyPlayHandler.prototype._disable = function () {
25972         this._keyDownSubscription.unsubscribe();
25973     };
25974     KeyPlayHandler.prototype._getConfiguration = function (enable) {
25975         return { keyZoom: enable };
25976     };
25977     return KeyPlayHandler;
25978 }(Component_1.HandlerBase));
25979 exports.KeyPlayHandler = KeyPlayHandler;
25980 exports.default = KeyPlayHandler;
25981
25982 },{"../../Component":275,"../../Edge":276,"rxjs/operators":225}],311:[function(require,module,exports){
25983 "use strict";
25984 var __extends = (this && this.__extends) || (function () {
25985     var extendStatics = function (d, b) {
25986         extendStatics = Object.setPrototypeOf ||
25987             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25988             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25989         return extendStatics(d, b);
25990     }
25991     return function (d, b) {
25992         extendStatics(d, b);
25993         function __() { this.constructor = d; }
25994         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25995     };
25996 })();
25997 Object.defineProperty(exports, "__esModule", { value: true });
25998 var operators_1 = require("rxjs/operators");
25999 var Component_1 = require("../../Component");
26000 var Edge_1 = require("../../Edge");
26001 var Error_1 = require("../../Error");
26002 /**
26003  * The `KeySequenceNavigationHandler` allows the user to navigate through a sequence using the
26004  * following key commands:
26005  *
26006  * `ALT` + `Up Arrow`: Navigate to next image in the sequence.
26007  * `ALT` + `Down Arrow`: Navigate to previous image in sequence.
26008  *
26009  * @example
26010  * ```
26011  * var keyboardComponent = viewer.getComponent("keyboard");
26012  *
26013  * keyboardComponent.keySequenceNavigation.disable();
26014  * keyboardComponent.keySequenceNavigation.enable();
26015  *
26016  * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled;
26017  * ```
26018  */
26019 var KeySequenceNavigationHandler = /** @class */ (function (_super) {
26020     __extends(KeySequenceNavigationHandler, _super);
26021     function KeySequenceNavigationHandler() {
26022         return _super !== null && _super.apply(this, arguments) || this;
26023     }
26024     KeySequenceNavigationHandler.prototype._enable = function () {
26025         var _this = this;
26026         var sequenceEdges$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
26027             return node.sequenceEdges$;
26028         }));
26029         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(sequenceEdges$))
26030             .subscribe(function (_a) {
26031             var event = _a[0], edgeStatus = _a[1];
26032             var direction = null;
26033             switch (event.keyCode) {
26034                 case 38: // up
26035                     direction = Edge_1.EdgeDirection.Next;
26036                     break;
26037                 case 40: // down
26038                     direction = Edge_1.EdgeDirection.Prev;
26039                     break;
26040                 default:
26041                     return;
26042             }
26043             event.preventDefault();
26044             if (!event.altKey || event.shiftKey || !edgeStatus.cached) {
26045                 return;
26046             }
26047             for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
26048                 var edge = _b[_i];
26049                 if (edge.data.direction === direction) {
26050                     _this._navigator.moveToKey$(edge.to)
26051                         .subscribe(undefined, function (error) {
26052                         if (!(error instanceof Error_1.AbortMapillaryError)) {
26053                             console.error(error);
26054                         }
26055                     });
26056                     return;
26057                 }
26058             }
26059         });
26060     };
26061     KeySequenceNavigationHandler.prototype._disable = function () {
26062         this._keyDownSubscription.unsubscribe();
26063     };
26064     KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) {
26065         return { keySequenceNavigation: enable };
26066     };
26067     return KeySequenceNavigationHandler;
26068 }(Component_1.HandlerBase));
26069 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler;
26070 exports.default = KeySequenceNavigationHandler;
26071
26072 },{"../../Component":275,"../../Edge":276,"../../Error":277,"rxjs/operators":225}],312:[function(require,module,exports){
26073 "use strict";
26074 var __extends = (this && this.__extends) || (function () {
26075     var extendStatics = function (d, b) {
26076         extendStatics = Object.setPrototypeOf ||
26077             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26078             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26079         return extendStatics(d, b);
26080     }
26081     return function (d, b) {
26082         extendStatics(d, b);
26083         function __() { this.constructor = d; }
26084         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26085     };
26086 })();
26087 Object.defineProperty(exports, "__esModule", { value: true });
26088 var operators_1 = require("rxjs/operators");
26089 var Component_1 = require("../../Component");
26090 var Edge_1 = require("../../Edge");
26091 var Error_1 = require("../../Error");
26092 /**
26093  * The `KeySpatialNavigationHandler` allows the user to navigate through a sequence using the
26094  * following key commands:
26095  *
26096  * `Up Arrow`: Step forward.
26097  * `Down Arrow`: Step backward.
26098  * `Left Arrow`: Step to the left.
26099  * `Rigth Arrow`: Step to the right.
26100  * `SHIFT` + `Down Arrow`: Turn around.
26101  * `SHIFT` + `Left Arrow`: Turn to the left.
26102  * `SHIFT` + `Rigth Arrow`: Turn to the right.
26103  *
26104  * @example
26105  * ```
26106  * var keyboardComponent = viewer.getComponent("keyboard");
26107  *
26108  * keyboardComponent.keySpatialNavigation.disable();
26109  * keyboardComponent.keySpatialNavigation.enable();
26110  *
26111  * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled;
26112  * ```
26113  */
26114 var KeySpatialNavigationHandler = /** @class */ (function (_super) {
26115     __extends(KeySpatialNavigationHandler, _super);
26116     /** @ignore */
26117     function KeySpatialNavigationHandler(component, container, navigator, spatial) {
26118         var _this = _super.call(this, component, container, navigator) || this;
26119         _this._spatial = spatial;
26120         return _this;
26121     }
26122     KeySpatialNavigationHandler.prototype._enable = function () {
26123         var _this = this;
26124         var spatialEdges$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
26125             return node.spatialEdges$;
26126         }));
26127         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$))
26128             .subscribe(function (_a) {
26129             var event = _a[0], edgeStatus = _a[1], frame = _a[2];
26130             var pano = frame.state.currentNode.pano;
26131             var direction = null;
26132             switch (event.keyCode) {
26133                 case 37: // left
26134                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
26135                     break;
26136                 case 38: // up
26137                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
26138                     break;
26139                 case 39: // right
26140                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
26141                     break;
26142                 case 40: // down
26143                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
26144                     break;
26145                 default:
26146                     return;
26147             }
26148             event.preventDefault();
26149             if (event.altKey || !edgeStatus.cached ||
26150                 (event.shiftKey && pano)) {
26151                 return;
26152             }
26153             if (!pano) {
26154                 _this._moveDir(direction, edgeStatus);
26155             }
26156             else {
26157                 var shifts = {};
26158                 shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI;
26159                 shifts[Edge_1.EdgeDirection.StepForward] = 0;
26160                 shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2;
26161                 shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2;
26162                 var phi = _this._rotationFromCamera(frame.state.camera).phi;
26163                 var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]);
26164                 var threshold = Math.PI / 4;
26165                 var edges = edgeStatus.edges.filter(function (e) {
26166                     return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction;
26167                 });
26168                 var smallestAngle = Number.MAX_VALUE;
26169                 var toKey = null;
26170                 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
26171                     var edge = edges_1[_i];
26172                     var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
26173                     if (angle < Math.min(smallestAngle, threshold)) {
26174                         smallestAngle = angle;
26175                         toKey = edge.to;
26176                     }
26177                 }
26178                 if (toKey == null) {
26179                     return;
26180                 }
26181                 _this._moveToKey(toKey);
26182             }
26183         });
26184     };
26185     KeySpatialNavigationHandler.prototype._disable = function () {
26186         this._keyDownSubscription.unsubscribe();
26187     };
26188     KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) {
26189         return { keySpatialNavigation: enable };
26190     };
26191     KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) {
26192         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26193             var edge = _a[_i];
26194             if (edge.data.direction === direction) {
26195                 this._moveToKey(edge.to);
26196                 return;
26197             }
26198         }
26199     };
26200     KeySpatialNavigationHandler.prototype._moveToKey = function (key) {
26201         this._navigator.moveToKey$(key)
26202             .subscribe(undefined, function (error) {
26203             if (!(error instanceof Error_1.AbortMapillaryError)) {
26204                 console.error(error);
26205             }
26206         });
26207     };
26208     KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) {
26209         var direction = camera.lookat.clone().sub(camera.position);
26210         var upProjection = direction.clone().dot(camera.up);
26211         var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
26212         var phi = Math.atan2(planeProjection.y, planeProjection.x);
26213         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
26214         return { phi: phi, theta: theta };
26215     };
26216     return KeySpatialNavigationHandler;
26217 }(Component_1.HandlerBase));
26218 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler;
26219 exports.default = KeySpatialNavigationHandler;
26220
26221 },{"../../Component":275,"../../Edge":276,"../../Error":277,"rxjs/operators":225}],313:[function(require,module,exports){
26222 "use strict";
26223 var __extends = (this && this.__extends) || (function () {
26224     var extendStatics = function (d, b) {
26225         extendStatics = Object.setPrototypeOf ||
26226             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26227             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26228         return extendStatics(d, b);
26229     }
26230     return function (d, b) {
26231         extendStatics(d, b);
26232         function __() { this.constructor = d; }
26233         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26234     };
26235 })();
26236 Object.defineProperty(exports, "__esModule", { value: true });
26237 var operators_1 = require("rxjs/operators");
26238 var Component_1 = require("../../Component");
26239 /**
26240  * The `KeyZoomHandler` allows the user to zoom in and out using the
26241  * following key commands:
26242  *
26243  * `+`: Zoom in.
26244  * `-`: Zoom out.
26245  *
26246  * @example
26247  * ```
26248  * var keyboardComponent = viewer.getComponent("keyboard");
26249  *
26250  * keyboardComponent.keyZoom.disable();
26251  * keyboardComponent.keyZoom.enable();
26252  *
26253  * var isEnabled = keyboardComponent.keyZoom.isEnabled;
26254  * ```
26255  */
26256 var KeyZoomHandler = /** @class */ (function (_super) {
26257     __extends(KeyZoomHandler, _super);
26258     /** @ignore */
26259     function KeyZoomHandler(component, container, navigator, viewportCoords) {
26260         var _this = _super.call(this, component, container, navigator) || this;
26261         _this._viewportCoords = viewportCoords;
26262         return _this;
26263     }
26264     KeyZoomHandler.prototype._enable = function () {
26265         var _this = this;
26266         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
26267             .subscribe(function (_a) {
26268             var event = _a[0], render = _a[1], transform = _a[2];
26269             if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
26270                 return;
26271             }
26272             var delta = 0;
26273             switch (event.key) {
26274                 case "+":
26275                     delta = 1;
26276                     break;
26277                 case "-":
26278                     delta = -1;
26279                     break;
26280                 default:
26281                     return;
26282             }
26283             event.preventDefault();
26284             var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
26285             var reference = transform.projectBasic(unprojected.toArray());
26286             _this._navigator.stateService.zoomIn(delta, reference);
26287         });
26288     };
26289     KeyZoomHandler.prototype._disable = function () {
26290         this._keyDownSubscription.unsubscribe();
26291     };
26292     KeyZoomHandler.prototype._getConfiguration = function (enable) {
26293         return { keyZoom: enable };
26294     };
26295     return KeyZoomHandler;
26296 }(Component_1.HandlerBase));
26297 exports.KeyZoomHandler = KeyZoomHandler;
26298 exports.default = KeyZoomHandler;
26299
26300 },{"../../Component":275,"rxjs/operators":225}],314:[function(require,module,exports){
26301 "use strict";
26302 var __extends = (this && this.__extends) || (function () {
26303     var extendStatics = function (d, b) {
26304         extendStatics = Object.setPrototypeOf ||
26305             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26306             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26307         return extendStatics(d, b);
26308     }
26309     return function (d, b) {
26310         extendStatics(d, b);
26311         function __() { this.constructor = d; }
26312         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26313     };
26314 })();
26315 Object.defineProperty(exports, "__esModule", { value: true });
26316 var Component_1 = require("../../Component");
26317 var Geo_1 = require("../../Geo");
26318 /**
26319  * @class KeyboardComponent
26320  *
26321  * @classdesc Component for keyboard event handling.
26322  *
26323  * To retrive and use the keyboard component
26324  *
26325  * @example
26326  * ```
26327  * var viewer = new Mapillary.Viewer(
26328  *     "<element-id>",
26329  *     "<client-id>",
26330  *     "<my key>");
26331  *
26332  * var keyboardComponent = viewer.getComponent("keyboard");
26333  * ```
26334  */
26335 var KeyboardComponent = /** @class */ (function (_super) {
26336     __extends(KeyboardComponent, _super);
26337     /** @ignore */
26338     function KeyboardComponent(name, container, navigator) {
26339         var _this = _super.call(this, name, container, navigator) || this;
26340         _this._keyPlayHandler = new Component_1.KeyPlayHandler(_this, container, navigator);
26341         _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator);
26342         _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial());
26343         _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords());
26344         return _this;
26345     }
26346     Object.defineProperty(KeyboardComponent.prototype, "keyPlay", {
26347         /**
26348          * Get key play.
26349          *
26350          * @returns {KeyPlayHandler} The key play handler.
26351          */
26352         get: function () {
26353             return this._keyPlayHandler;
26354         },
26355         enumerable: true,
26356         configurable: true
26357     });
26358     Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", {
26359         /**
26360          * Get key sequence navigation.
26361          *
26362          * @returns {KeySequenceNavigationHandler} The key sequence navigation handler.
26363          */
26364         get: function () {
26365             return this._keySequenceNavigationHandler;
26366         },
26367         enumerable: true,
26368         configurable: true
26369     });
26370     Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", {
26371         /**
26372          * Get spatial.
26373          *
26374          * @returns {KeySpatialNavigationHandler} The spatial handler.
26375          */
26376         get: function () {
26377             return this._keySpatialNavigationHandler;
26378         },
26379         enumerable: true,
26380         configurable: true
26381     });
26382     Object.defineProperty(KeyboardComponent.prototype, "keyZoom", {
26383         /**
26384          * Get key zoom.
26385          *
26386          * @returns {KeyZoomHandler} The key zoom handler.
26387          */
26388         get: function () {
26389             return this._keyZoomHandler;
26390         },
26391         enumerable: true,
26392         configurable: true
26393     });
26394     KeyboardComponent.prototype._activate = function () {
26395         var _this = this;
26396         this._configurationSubscription = this._configuration$
26397             .subscribe(function (configuration) {
26398             if (configuration.keyPlay) {
26399                 _this._keyPlayHandler.enable();
26400             }
26401             else {
26402                 _this._keyPlayHandler.disable();
26403             }
26404             if (configuration.keySequenceNavigation) {
26405                 _this._keySequenceNavigationHandler.enable();
26406             }
26407             else {
26408                 _this._keySequenceNavigationHandler.disable();
26409             }
26410             if (configuration.keySpatialNavigation) {
26411                 _this._keySpatialNavigationHandler.enable();
26412             }
26413             else {
26414                 _this._keySpatialNavigationHandler.disable();
26415             }
26416             if (configuration.keyZoom) {
26417                 _this._keyZoomHandler.enable();
26418             }
26419             else {
26420                 _this._keyZoomHandler.disable();
26421             }
26422         });
26423     };
26424     KeyboardComponent.prototype._deactivate = function () {
26425         this._configurationSubscription.unsubscribe();
26426         this._keyPlayHandler.disable();
26427         this._keySequenceNavigationHandler.disable();
26428         this._keySpatialNavigationHandler.disable();
26429         this._keyZoomHandler.disable();
26430     };
26431     KeyboardComponent.prototype._getDefaultConfiguration = function () {
26432         return { keyPlay: true, keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true };
26433     };
26434     KeyboardComponent.componentName = "keyboard";
26435     return KeyboardComponent;
26436 }(Component_1.Component));
26437 exports.KeyboardComponent = KeyboardComponent;
26438 Component_1.ComponentService.register(KeyboardComponent);
26439 exports.default = KeyboardComponent;
26440
26441 },{"../../Component":275,"../../Geo":278}],315:[function(require,module,exports){
26442 "use strict";
26443 Object.defineProperty(exports, "__esModule", { value: true });
26444 var MarkerComponent_1 = require("./MarkerComponent");
26445 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
26446 var SimpleMarker_1 = require("./marker/SimpleMarker");
26447 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
26448 var CircleMarker_1 = require("./marker/CircleMarker");
26449 exports.CircleMarker = CircleMarker_1.CircleMarker;
26450
26451 },{"./MarkerComponent":316,"./marker/CircleMarker":319,"./marker/SimpleMarker":321}],316:[function(require,module,exports){
26452 "use strict";
26453 var __extends = (this && this.__extends) || (function () {
26454     var extendStatics = function (d, b) {
26455         extendStatics = Object.setPrototypeOf ||
26456             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26457             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26458         return extendStatics(d, b);
26459     }
26460     return function (d, b) {
26461         extendStatics(d, b);
26462         function __() { this.constructor = d; }
26463         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26464     };
26465 })();
26466 Object.defineProperty(exports, "__esModule", { value: true });
26467 var rxjs_1 = require("rxjs");
26468 var operators_1 = require("rxjs/operators");
26469 var THREE = require("three");
26470 var when = require("when");
26471 var Component_1 = require("../../Component");
26472 var Render_1 = require("../../Render");
26473 var Graph_1 = require("../../Graph");
26474 var Geo_1 = require("../../Geo");
26475 /**
26476  * @class MarkerComponent
26477  *
26478  * @classdesc Component for showing and editing 3D marker objects.
26479  *
26480  * The `add` method is used for adding new markers or replacing
26481  * markers already in the set.
26482  *
26483  * If a marker already in the set has the same
26484  * id as one of the markers added, the old marker will be removed and
26485  * the added marker will take its place.
26486  *
26487  * It is not possible to update markers in the set by updating any properties
26488  * directly on the marker object. Markers need to be replaced by
26489  * re-adding them for updates to geographic position or configuration
26490  * to be reflected.
26491  *
26492  * Markers added to the marker component can be either interactive
26493  * or non-interactive. Different marker types define their behavior.
26494  * Markers with interaction support can be configured with options
26495  * to respond to dragging inside the viewer and be detected when
26496  * retrieving markers from pixel points with the `getMarkerIdAt` method.
26497  *
26498  * To retrive and use the marker component
26499  *
26500  * @example
26501  * ```
26502  * var viewer = new Mapillary.Viewer(
26503  *     "<element-id>",
26504  *     "<client-id>",
26505  *     "<my key>",
26506  *     { component: { marker: true } });
26507  *
26508  * var markerComponent = viewer.getComponent("marker");
26509  * ```
26510  */
26511 var MarkerComponent = /** @class */ (function (_super) {
26512     __extends(MarkerComponent, _super);
26513     /** @ignore */
26514     function MarkerComponent(name, container, navigator) {
26515         var _this = _super.call(this, name, container, navigator) || this;
26516         _this._relativeGroundAltitude = -2;
26517         _this._geoCoords = new Geo_1.GeoCoords();
26518         _this._graphCalculator = new Graph_1.GraphCalculator();
26519         _this._markerScene = new Component_1.MarkerScene();
26520         _this._markerSet = new Component_1.MarkerSet();
26521         _this._viewportCoords = new Geo_1.ViewportCoords();
26522         return _this;
26523     }
26524     /**
26525      * Add markers to the marker set or replace markers in the marker set.
26526      *
26527      * @description If a marker already in the set has the same
26528      * id as one of the markers added, the old marker will be removed
26529      * the added marker will take its place.
26530      *
26531      * Any marker inside the visible bounding bbox
26532      * will be initialized and placed in the viewer.
26533      *
26534      * @param {Array<Marker>} markers - Markers to add.
26535      *
26536      * @example ```markerComponent.add([marker1, marker2]);```
26537      */
26538     MarkerComponent.prototype.add = function (markers) {
26539         this._markerSet.add(markers);
26540     };
26541     /**
26542      * Returns the marker in the marker set with the specified id, or
26543      * undefined if the id matches no marker.
26544      *
26545      * @param {string} markerId - Id of the marker.
26546      *
26547      * @example ```var marker = markerComponent.get("markerId");```
26548      *
26549      */
26550     MarkerComponent.prototype.get = function (markerId) {
26551         return this._markerSet.get(markerId);
26552     };
26553     /**
26554      * Returns an array of all markers.
26555      *
26556      * @example ```var markers = markerComponent.getAll();```
26557      */
26558     MarkerComponent.prototype.getAll = function () {
26559         return this._markerSet.getAll();
26560     };
26561     /**
26562      * Returns the id of the interactive marker closest to the current camera
26563      * position at the specified point.
26564      *
26565      * @description Notice that the pixelPoint argument requires x, y
26566      * coordinates from pixel space.
26567      *
26568      * With this function, you can use the coordinates provided by mouse
26569      * events to get information out of the marker component.
26570      *
26571      * If no interactive geometry of an interactive marker exist at the pixel
26572      * point, `null` will be returned.
26573      *
26574      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
26575      * @returns {string} Id of the interactive marker closest to the camera. If no
26576      * interactive marker exist at the pixel point, `null` will be returned.
26577      *
26578      * @example
26579      * ```
26580      * markerComponent.getMarkerIdAt([100, 100])
26581      *     .then((markerId) => { console.log(markerId); });
26582      * ```
26583      */
26584     MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
26585         var _this = this;
26586         return when.promise(function (resolve, reject) {
26587             _this._container.renderService.renderCamera$.pipe(operators_1.first(), operators_1.map(function (render) {
26588                 var viewport = _this._viewportCoords
26589                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
26590                 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
26591                 return id;
26592             }))
26593                 .subscribe(function (id) {
26594                 resolve(id);
26595             }, function (error) {
26596                 reject(error);
26597             });
26598         });
26599     };
26600     /**
26601      * Check if a marker exist in the marker set.
26602      *
26603      * @param {string} markerId - Id of the marker.
26604      *
26605      * @example ```var markerExists = markerComponent.has("markerId");```
26606      */
26607     MarkerComponent.prototype.has = function (markerId) {
26608         return this._markerSet.has(markerId);
26609     };
26610     /**
26611      * Remove markers with the specified ids from the marker set.
26612      *
26613      * @param {Array<string>} markerIds - Ids for markers to remove.
26614      *
26615      * @example ```markerComponent.remove(["id-1", "id-2"]);```
26616      */
26617     MarkerComponent.prototype.remove = function (markerIds) {
26618         this._markerSet.remove(markerIds);
26619     };
26620     /**
26621      * Remove all markers from the marker set.
26622      *
26623      * @example ```markerComponent.removeAll();```
26624      */
26625     MarkerComponent.prototype.removeAll = function () {
26626         this._markerSet.removeAll();
26627     };
26628     MarkerComponent.prototype._activate = function () {
26629         var _this = this;
26630         var groundAltitude$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
26631             return frame.state.camera.position.z + _this._relativeGroundAltitude;
26632         }), operators_1.distinctUntilChanged(function (a1, a2) {
26633             return Math.abs(a1 - a2) < 0.01;
26634         }), operators_1.publishReplay(1), operators_1.refCount());
26635         var geoInitiated$ = rxjs_1.combineLatest(groundAltitude$, this._navigator.stateService.reference$).pipe(operators_1.first(), operators_1.map(function () { }), operators_1.publishReplay(1), operators_1.refCount());
26636         var clampedConfiguration$ = this._configuration$.pipe(operators_1.map(function (configuration) {
26637             return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
26638         }));
26639         var currentlatLon$ = this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) { return node.latLon; }), operators_1.publishReplay(1), operators_1.refCount());
26640         var visibleBBox$ = rxjs_1.combineLatest(clampedConfiguration$, currentlatLon$).pipe(operators_1.map(function (_a) {
26641             var configuration = _a[0], latLon = _a[1];
26642             return _this._graphCalculator
26643                 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
26644         }), operators_1.publishReplay(1), operators_1.refCount());
26645         var visibleMarkers$ = rxjs_1.combineLatest(rxjs_1.concat(rxjs_1.of(this._markerSet), this._markerSet.changed$), visibleBBox$).pipe(operators_1.map(function (_a) {
26646             var set = _a[0], bbox = _a[1];
26647             return set.search(bbox);
26648         }));
26649         this._setChangedSubscription = geoInitiated$.pipe(operators_1.switchMap(function () {
26650             return visibleMarkers$.pipe(operators_1.withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$));
26651         }))
26652             .subscribe(function (_a) {
26653             var markers = _a[0], reference = _a[1], alt = _a[2];
26654             var geoCoords = _this._geoCoords;
26655             var markerScene = _this._markerScene;
26656             var sceneMarkers = markerScene.markers;
26657             var markersToRemove = Object.assign({}, sceneMarkers);
26658             for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
26659                 var marker = markers_1[_i];
26660                 if (marker.id in sceneMarkers) {
26661                     delete markersToRemove[marker.id];
26662                 }
26663                 else {
26664                     var point3d = geoCoords
26665                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26666                     markerScene.add(marker, point3d);
26667                 }
26668             }
26669             for (var id in markersToRemove) {
26670                 if (!markersToRemove.hasOwnProperty(id)) {
26671                     continue;
26672                 }
26673                 markerScene.remove(id);
26674             }
26675         });
26676         this._markersUpdatedSubscription = geoInitiated$.pipe(operators_1.switchMap(function () {
26677             return _this._markerSet.updated$.pipe(operators_1.withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$));
26678         }))
26679             .subscribe(function (_a) {
26680             var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
26681             var geoCoords = _this._geoCoords;
26682             var markerScene = _this._markerScene;
26683             for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
26684                 var marker = markers_2[_i];
26685                 var exists = markerScene.has(marker.id);
26686                 var visible = marker.latLon.lat > sw.lat &&
26687                     marker.latLon.lat < ne.lat &&
26688                     marker.latLon.lon > sw.lon &&
26689                     marker.latLon.lon < ne.lon;
26690                 if (visible) {
26691                     var point3d = geoCoords
26692                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26693                     markerScene.add(marker, point3d);
26694                 }
26695                 else if (!visible && exists) {
26696                     markerScene.remove(marker.id);
26697                 }
26698             }
26699         });
26700         this._referenceSubscription = this._navigator.stateService.reference$.pipe(operators_1.skip(1), operators_1.withLatestFrom(groundAltitude$))
26701             .subscribe(function (_a) {
26702             var reference = _a[0], alt = _a[1];
26703             var geoCoords = _this._geoCoords;
26704             var markerScene = _this._markerScene;
26705             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
26706                 var marker = _b[_i];
26707                 var point3d = geoCoords
26708                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26709                 markerScene.update(marker.id, point3d);
26710             }
26711         });
26712         this._adjustHeightSubscription = groundAltitude$.pipe(operators_1.skip(1), operators_1.withLatestFrom(this._navigator.stateService.reference$, currentlatLon$))
26713             .subscribe(function (_a) {
26714             var alt = _a[0], reference = _a[1], latLon = _a[2];
26715             var geoCoords = _this._geoCoords;
26716             var markerScene = _this._markerScene;
26717             var position = geoCoords
26718                 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26719             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
26720                 var marker = _b[_i];
26721                 var point3d = geoCoords
26722                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26723                 var distanceX = point3d[0] - position[0];
26724                 var distanceY = point3d[1] - position[1];
26725                 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
26726                 if (groundDistance > 50) {
26727                     continue;
26728                 }
26729                 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
26730             }
26731         });
26732         this._renderSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
26733             var scene = _this._markerScene;
26734             return {
26735                 name: _this._name,
26736                 render: {
26737                     frameId: frame.id,
26738                     needsRender: scene.needsRender,
26739                     render: scene.render.bind(scene),
26740                     stage: Render_1.GLRenderStage.Foreground,
26741                 },
26742             };
26743         }))
26744             .subscribe(this._container.glRenderer.render$);
26745         var hoveredMarkerId$ = rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$).pipe(operators_1.map(function (_a) {
26746             var render = _a[0], event = _a[1];
26747             var element = _this._container.element;
26748             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
26749             var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
26750             var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
26751             return markerId;
26752         }), operators_1.publishReplay(1), operators_1.refCount());
26753         var draggingStarted$ = this._container.mouseService
26754             .filtered$(this._name, this._container.mouseService.mouseDragStart$).pipe(operators_1.map(function (event) {
26755             return true;
26756         }));
26757         var draggingStopped$ = this._container.mouseService
26758             .filtered$(this._name, this._container.mouseService.mouseDragEnd$).pipe(operators_1.map(function (event) {
26759             return false;
26760         }));
26761         var filteredDragging$ = rxjs_1.merge(draggingStarted$, draggingStopped$).pipe(operators_1.startWith(false));
26762         this._dragEventSubscription = rxjs_1.merge(draggingStarted$.pipe(operators_1.withLatestFrom(hoveredMarkerId$)), rxjs_1.combineLatest(draggingStopped$, rxjs_1.of(null))).pipe(operators_1.startWith([false, null]), operators_1.pairwise())
26763             .subscribe(function (_a) {
26764             var previous = _a[0], current = _a[1];
26765             var dragging = current[0];
26766             var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
26767             var id = dragging ? current[1] : previous[1];
26768             var marker = _this._markerScene.get(id);
26769             var markerEvent = { marker: marker, target: _this, type: eventType };
26770             _this.fire(eventType, markerEvent);
26771         });
26772         var mouseDown$ = rxjs_1.merge(this._container.mouseService.mouseDown$.pipe(operators_1.map(function (event) { return true; })), this._container.mouseService.documentMouseUp$.pipe(operators_1.map(function (event) { return false; }))).pipe(operators_1.startWith(false));
26773         this._mouseClaimSubscription = rxjs_1.combineLatest(this._container.mouseService.active$, hoveredMarkerId$.pipe(operators_1.distinctUntilChanged()), mouseDown$, filteredDragging$).pipe(operators_1.map(function (_a) {
26774             var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3];
26775             return (!active && markerId != null && mouseDown) || filteredDragging;
26776         }), operators_1.distinctUntilChanged())
26777             .subscribe(function (claim) {
26778             if (claim) {
26779                 _this._container.mouseService.claimMouse(_this._name, 1);
26780                 _this._container.mouseService.claimWheel(_this._name, 1);
26781             }
26782             else {
26783                 _this._container.mouseService.unclaimMouse(_this._name);
26784                 _this._container.mouseService.unclaimWheel(_this._name);
26785             }
26786         });
26787         var offset$ = this._container.mouseService
26788             .filtered$(this._name, this._container.mouseService.mouseDragStart$).pipe(operators_1.withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$), operators_1.map(function (_a) {
26789             var e = _a[0], id = _a[1], r = _a[2];
26790             var marker = _this._markerScene.get(id);
26791             var element = _this._container.element;
26792             var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
26793             var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
26794             var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
26795             return [marker, offset, r];
26796         }), operators_1.publishReplay(1), operators_1.refCount());
26797         this._updateMarkerSubscription = this._container.mouseService
26798             .filtered$(this._name, this._container.mouseService.mouseDrag$).pipe(operators_1.withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$))
26799             .subscribe(function (_a) {
26800             var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
26801             if (!_this._markerScene.has(marker.id)) {
26802                 return;
26803             }
26804             var element = _this._container.element;
26805             var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
26806             var groundX = canvasX - offset[0];
26807             var groundY = canvasY - offset[1];
26808             var _d = _this._viewportCoords
26809                 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
26810             var direction = new THREE.Vector3(viewportX, viewportY, 1)
26811                 .unproject(render.perspective)
26812                 .sub(render.perspective.position)
26813                 .normalize();
26814             var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
26815             if (distance < 0) {
26816                 return;
26817             }
26818             var intersection = direction
26819                 .clone()
26820                 .multiplyScalar(distance)
26821                 .add(render.perspective.position);
26822             intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
26823             var _e = _this._geoCoords
26824                 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
26825             _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
26826             _this._markerSet.update(marker);
26827             var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
26828             _this.fire(MarkerComponent.changed, markerEvent);
26829         });
26830     };
26831     MarkerComponent.prototype._deactivate = function () {
26832         this._adjustHeightSubscription.unsubscribe();
26833         this._dragEventSubscription.unsubscribe();
26834         this._markersUpdatedSubscription.unsubscribe();
26835         this._mouseClaimSubscription.unsubscribe();
26836         this._referenceSubscription.unsubscribe();
26837         this._renderSubscription.unsubscribe();
26838         this._setChangedSubscription.unsubscribe();
26839         this._updateMarkerSubscription.unsubscribe();
26840         this._markerScene.clear();
26841     };
26842     MarkerComponent.prototype._getDefaultConfiguration = function () {
26843         return { visibleBBoxSize: 100 };
26844     };
26845     MarkerComponent.componentName = "marker";
26846     /**
26847      * Fired when the position of a marker is changed.
26848      * @event
26849      * @type {IMarkerEvent} markerEvent - Marker event data.
26850      * @example
26851      * ```
26852      * markerComponent.on("changed", function(e) {
26853      *     console.log(e.marker.id, e.marker.latLon);
26854      * });
26855      * ```
26856      */
26857     MarkerComponent.changed = "changed";
26858     /**
26859      * Fired when a marker drag interaction starts.
26860      * @event
26861      * @type {IMarkerEvent} markerEvent - Marker event data.
26862      * @example
26863      * ```
26864      * markerComponent.on("dragstart", function(e) {
26865      *     console.log(e.marker.id, e.marker.latLon);
26866      * });
26867      * ```
26868      */
26869     MarkerComponent.dragstart = "dragstart";
26870     /**
26871      * Fired when a marker drag interaction ends.
26872      * @event
26873      * @type {IMarkerEvent} markerEvent - Marker event data.
26874      * @example
26875      * ```
26876      * markerComponent.on("dragend", function(e) {
26877      *     console.log(e.marker.id, e.marker.latLon);
26878      * });
26879      * ```
26880      */
26881     MarkerComponent.dragend = "dragend";
26882     return MarkerComponent;
26883 }(Component_1.Component));
26884 exports.MarkerComponent = MarkerComponent;
26885 Component_1.ComponentService.register(MarkerComponent);
26886 exports.default = MarkerComponent;
26887
26888
26889 },{"../../Component":275,"../../Geo":278,"../../Graph":279,"../../Render":281,"rxjs":27,"rxjs/operators":225,"three":226,"when":272}],317:[function(require,module,exports){
26890 "use strict";
26891 Object.defineProperty(exports, "__esModule", { value: true });
26892 var THREE = require("three");
26893 var MarkerScene = /** @class */ (function () {
26894     function MarkerScene(scene, raycaster) {
26895         this._needsRender = false;
26896         this._interactiveObjects = [];
26897         this._markers = {};
26898         this._objectMarkers = {};
26899         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
26900         this._scene = !!scene ? scene : new THREE.Scene();
26901     }
26902     Object.defineProperty(MarkerScene.prototype, "markers", {
26903         get: function () {
26904             return this._markers;
26905         },
26906         enumerable: true,
26907         configurable: true
26908     });
26909     Object.defineProperty(MarkerScene.prototype, "needsRender", {
26910         get: function () {
26911             return this._needsRender;
26912         },
26913         enumerable: true,
26914         configurable: true
26915     });
26916     MarkerScene.prototype.add = function (marker, position) {
26917         if (marker.id in this._markers) {
26918             this._dispose(marker.id);
26919         }
26920         marker.createGeometry(position);
26921         this._scene.add(marker.geometry);
26922         this._markers[marker.id] = marker;
26923         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
26924             var interactiveObject = _a[_i];
26925             this._interactiveObjects.push(interactiveObject);
26926             this._objectMarkers[interactiveObject.uuid] = marker.id;
26927         }
26928         this._needsRender = true;
26929     };
26930     MarkerScene.prototype.clear = function () {
26931         for (var id in this._markers) {
26932             if (!this._markers.hasOwnProperty) {
26933                 continue;
26934             }
26935             this._dispose(id);
26936         }
26937         this._needsRender = true;
26938     };
26939     MarkerScene.prototype.get = function (id) {
26940         return this._markers[id];
26941     };
26942     MarkerScene.prototype.getAll = function () {
26943         var _this = this;
26944         return Object
26945             .keys(this._markers)
26946             .map(function (id) { return _this._markers[id]; });
26947     };
26948     MarkerScene.prototype.has = function (id) {
26949         return id in this._markers;
26950     };
26951     MarkerScene.prototype.intersectObjects = function (_a, camera) {
26952         var viewportX = _a[0], viewportY = _a[1];
26953         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
26954         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
26955         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
26956             var intersect = intersects_1[_i];
26957             if (intersect.object.uuid in this._objectMarkers) {
26958                 return this._objectMarkers[intersect.object.uuid];
26959             }
26960         }
26961         return null;
26962     };
26963     MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
26964         if (!(id in this._markers)) {
26965             return;
26966         }
26967         this._markers[id].lerpAltitude(alt, alpha);
26968         this._needsRender = true;
26969     };
26970     MarkerScene.prototype.remove = function (id) {
26971         if (!(id in this._markers)) {
26972             return;
26973         }
26974         this._dispose(id);
26975         this._needsRender = true;
26976     };
26977     MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
26978         renderer.render(this._scene, perspectiveCamera);
26979         this._needsRender = false;
26980     };
26981     MarkerScene.prototype.update = function (id, position, latLon) {
26982         if (!(id in this._markers)) {
26983             return;
26984         }
26985         var marker = this._markers[id];
26986         marker.updatePosition(position, latLon);
26987         this._needsRender = true;
26988     };
26989     MarkerScene.prototype._dispose = function (id) {
26990         var marker = this._markers[id];
26991         this._scene.remove(marker.geometry);
26992         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
26993             var interactiveObject = _a[_i];
26994             var index = this._interactiveObjects.indexOf(interactiveObject);
26995             if (index !== -1) {
26996                 this._interactiveObjects.splice(index, 1);
26997             }
26998             else {
26999                 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
27000             }
27001             delete this._objectMarkers[interactiveObject.uuid];
27002         }
27003         marker.disposeGeometry();
27004         delete this._markers[id];
27005     };
27006     return MarkerScene;
27007 }());
27008 exports.MarkerScene = MarkerScene;
27009 exports.default = MarkerScene;
27010
27011 },{"three":226}],318:[function(require,module,exports){
27012 "use strict";
27013 Object.defineProperty(exports, "__esModule", { value: true });
27014 var rbush = require("rbush");
27015 var rxjs_1 = require("rxjs");
27016 var MarkerSet = /** @class */ (function () {
27017     function MarkerSet() {
27018         this._hash = {};
27019         this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
27020         this._indexChanged$ = new rxjs_1.Subject();
27021         this._updated$ = new rxjs_1.Subject();
27022     }
27023     Object.defineProperty(MarkerSet.prototype, "changed$", {
27024         get: function () {
27025             return this._indexChanged$;
27026         },
27027         enumerable: true,
27028         configurable: true
27029     });
27030     Object.defineProperty(MarkerSet.prototype, "updated$", {
27031         get: function () {
27032             return this._updated$;
27033         },
27034         enumerable: true,
27035         configurable: true
27036     });
27037     MarkerSet.prototype.add = function (markers) {
27038         var updated = [];
27039         var hash = this._hash;
27040         var index = this._index;
27041         for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
27042             var marker = markers_1[_i];
27043             var id = marker.id;
27044             if (id in hash) {
27045                 index.remove(hash[id]);
27046                 updated.push(marker);
27047             }
27048             var item = {
27049                 lat: marker.latLon.lat,
27050                 lon: marker.latLon.lon,
27051                 marker: marker,
27052             };
27053             hash[id] = item;
27054             index.insert(item);
27055         }
27056         if (updated.length > 0) {
27057             this._updated$.next(updated);
27058         }
27059         if (markers.length > updated.length) {
27060             this._indexChanged$.next(this);
27061         }
27062     };
27063     MarkerSet.prototype.has = function (id) {
27064         return id in this._hash;
27065     };
27066     MarkerSet.prototype.get = function (id) {
27067         return this.has(id) ? this._hash[id].marker : undefined;
27068     };
27069     MarkerSet.prototype.getAll = function () {
27070         return this._index
27071             .all()
27072             .map(function (indexItem) {
27073             return indexItem.marker;
27074         });
27075     };
27076     MarkerSet.prototype.remove = function (ids) {
27077         var hash = this._hash;
27078         var index = this._index;
27079         var changed = false;
27080         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
27081             var id = ids_1[_i];
27082             if (!(id in hash)) {
27083                 continue;
27084             }
27085             var item = hash[id];
27086             index.remove(item);
27087             delete hash[id];
27088             changed = true;
27089         }
27090         if (changed) {
27091             this._indexChanged$.next(this);
27092         }
27093     };
27094     MarkerSet.prototype.removeAll = function () {
27095         this._hash = {};
27096         this._index.clear();
27097         this._indexChanged$.next(this);
27098     };
27099     MarkerSet.prototype.search = function (_a) {
27100         var sw = _a[0], ne = _a[1];
27101         return this._index
27102             .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
27103             .map(function (indexItem) {
27104             return indexItem.marker;
27105         });
27106     };
27107     MarkerSet.prototype.update = function (marker) {
27108         var hash = this._hash;
27109         var index = this._index;
27110         var id = marker.id;
27111         if (!(id in hash)) {
27112             return;
27113         }
27114         index.remove(hash[id]);
27115         var item = {
27116             lat: marker.latLon.lat,
27117             lon: marker.latLon.lon,
27118             marker: marker,
27119         };
27120         hash[id] = item;
27121         index.insert(item);
27122     };
27123     return MarkerSet;
27124 }());
27125 exports.MarkerSet = MarkerSet;
27126 exports.default = MarkerSet;
27127
27128 },{"rbush":26,"rxjs":27}],319:[function(require,module,exports){
27129 "use strict";
27130 var __extends = (this && this.__extends) || (function () {
27131     var extendStatics = function (d, b) {
27132         extendStatics = Object.setPrototypeOf ||
27133             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27134             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27135         return extendStatics(d, b);
27136     }
27137     return function (d, b) {
27138         extendStatics(d, b);
27139         function __() { this.constructor = d; }
27140         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27141     };
27142 })();
27143 Object.defineProperty(exports, "__esModule", { value: true });
27144 var THREE = require("three");
27145 var Component_1 = require("../../../Component");
27146 /**
27147  * @class CircleMarker
27148  *
27149  * @classdesc Non-interactive marker with a flat circle shape. The circle
27150  * marker can not be configured to be interactive.
27151  *
27152  * Circle marker properties can not be updated after creation.
27153  *
27154  * To create and add one `CircleMarker` with default configuration
27155  * and one with configuration use
27156  *
27157  * @example
27158  * ```
27159  * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
27160  *     "id-1",
27161  *     { lat: 0, lon: 0, });
27162  *
27163  * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
27164  *     "id-2",
27165  *     { lat: 0, lon: 0, },
27166  *     {
27167  *         color: "#0Ff",
27168  *         opacity: 0.3,
27169  *         radius: 0.7,
27170  *     });
27171  *
27172  * markerComponent.add([defaultMarker, configuredMarker]);
27173  * ```
27174  */
27175 var CircleMarker = /** @class */ (function (_super) {
27176     __extends(CircleMarker, _super);
27177     function CircleMarker(id, latLon, options) {
27178         var _this = _super.call(this, id, latLon) || this;
27179         options = !!options ? options : {};
27180         _this._color = options.color != null ? options.color : 0xffffff;
27181         _this._opacity = options.opacity != null ? options.opacity : 0.4;
27182         _this._radius = options.radius != null ? options.radius : 1;
27183         return _this;
27184     }
27185     CircleMarker.prototype._createGeometry = function (position) {
27186         var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
27187             color: this._color,
27188             opacity: this._opacity,
27189             transparent: true,
27190         }));
27191         circle.up.fromArray([0, 0, 1]);
27192         circle.renderOrder = -1;
27193         var group = new THREE.Object3D();
27194         group.add(circle);
27195         group.position.fromArray(position);
27196         this._geometry = group;
27197     };
27198     CircleMarker.prototype._disposeGeometry = function () {
27199         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
27200             var mesh = _a[_i];
27201             mesh.geometry.dispose();
27202             mesh.material.dispose();
27203         }
27204     };
27205     CircleMarker.prototype._getInteractiveObjects = function () {
27206         return [];
27207     };
27208     return CircleMarker;
27209 }(Component_1.Marker));
27210 exports.CircleMarker = CircleMarker;
27211 exports.default = CircleMarker;
27212
27213 },{"../../../Component":275,"three":226}],320:[function(require,module,exports){
27214 "use strict";
27215 Object.defineProperty(exports, "__esModule", { value: true });
27216 /**
27217  * @class Marker
27218  *
27219  * @classdesc Represents an abstract marker class that should be extended
27220  * by marker implementations used in the marker component.
27221  */
27222 var Marker = /** @class */ (function () {
27223     function Marker(id, latLon) {
27224         this._id = id;
27225         this._latLon = latLon;
27226     }
27227     Object.defineProperty(Marker.prototype, "id", {
27228         /**
27229          * Get id.
27230          * @returns {string} The id of the marker.
27231          */
27232         get: function () {
27233             return this._id;
27234         },
27235         enumerable: true,
27236         configurable: true
27237     });
27238     Object.defineProperty(Marker.prototype, "geometry", {
27239         /**
27240          * Get geometry.
27241          *
27242          * @ignore
27243          */
27244         get: function () {
27245             return this._geometry;
27246         },
27247         enumerable: true,
27248         configurable: true
27249     });
27250     Object.defineProperty(Marker.prototype, "latLon", {
27251         /**
27252          * Get lat lon.
27253          * @returns {ILatLon} The geographic coordinates of the marker.
27254          */
27255         get: function () {
27256             return this._latLon;
27257         },
27258         enumerable: true,
27259         configurable: true
27260     });
27261     /** @ignore */
27262     Marker.prototype.createGeometry = function (position) {
27263         if (!!this._geometry) {
27264             return;
27265         }
27266         this._createGeometry(position);
27267         // update matrix world if raycasting occurs before first render
27268         this._geometry.updateMatrixWorld(true);
27269     };
27270     /** @ignore */
27271     Marker.prototype.disposeGeometry = function () {
27272         if (!this._geometry) {
27273             return;
27274         }
27275         this._disposeGeometry();
27276         this._geometry = undefined;
27277     };
27278     /** @ignore */
27279     Marker.prototype.getInteractiveObjects = function () {
27280         if (!this._geometry) {
27281             return [];
27282         }
27283         return this._getInteractiveObjects();
27284     };
27285     /** @ignore */
27286     Marker.prototype.lerpAltitude = function (alt, alpha) {
27287         if (!this._geometry) {
27288             return;
27289         }
27290         this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
27291     };
27292     /** @ignore */
27293     Marker.prototype.updatePosition = function (position, latLon) {
27294         if (!!latLon) {
27295             this._latLon.lat = latLon.lat;
27296             this._latLon.lon = latLon.lon;
27297         }
27298         if (!this._geometry) {
27299             return;
27300         }
27301         this._geometry.position.fromArray(position);
27302         this._geometry.updateMatrixWorld(true);
27303     };
27304     return Marker;
27305 }());
27306 exports.Marker = Marker;
27307 exports.default = Marker;
27308
27309 },{}],321:[function(require,module,exports){
27310 "use strict";
27311 var __extends = (this && this.__extends) || (function () {
27312     var extendStatics = function (d, b) {
27313         extendStatics = Object.setPrototypeOf ||
27314             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27315             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27316         return extendStatics(d, b);
27317     }
27318     return function (d, b) {
27319         extendStatics(d, b);
27320         function __() { this.constructor = d; }
27321         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27322     };
27323 })();
27324 Object.defineProperty(exports, "__esModule", { value: true });
27325 var THREE = require("three");
27326 var Component_1 = require("../../../Component");
27327 /**
27328  * @class SimpleMarker
27329  *
27330  * @classdesc Interactive marker with ice cream shape. The sphere
27331  * inside the ice cream can be configured to be interactive.
27332  *
27333  * Simple marker properties can not be updated after creation.
27334  *
27335  * To create and add one `SimpleMarker` with default configuration
27336  * (non-interactive) and one interactive with configuration use
27337  *
27338  * @example
27339  * ```
27340  * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
27341  *     "id-1",
27342  *     { lat: 0, lon: 0, });
27343  *
27344  * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
27345  *     "id-2",
27346  *     { lat: 0, lon: 0, },
27347  *     {
27348  *         ballColor: "#00f",
27349  *         ballOpacity: 0.5,
27350  *         color: "#00f",
27351  *         interactive: true,
27352  *         opacity: 0.3,
27353  *         radius: 0.7,
27354  *     });
27355  *
27356  * markerComponent.add([defaultMarker, interactiveMarker]);
27357  * ```
27358  */
27359 var SimpleMarker = /** @class */ (function (_super) {
27360     __extends(SimpleMarker, _super);
27361     function SimpleMarker(id, latLon, options) {
27362         var _this = _super.call(this, id, latLon) || this;
27363         options = !!options ? options : {};
27364         _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
27365         _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
27366         _this._circleToRayAngle = 2;
27367         _this._color = options.color != null ? options.color : 0xff0000;
27368         _this._interactive = !!options.interactive;
27369         _this._opacity = options.opacity != null ? options.opacity : 0.4;
27370         _this._radius = options.radius != null ? options.radius : 1;
27371         return _this;
27372     }
27373     SimpleMarker.prototype._createGeometry = function (position) {
27374         var radius = this._radius;
27375         var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
27376             color: this._color,
27377             opacity: this._opacity,
27378             transparent: true,
27379         }));
27380         cone.renderOrder = 1;
27381         var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
27382             color: this._ballColor,
27383             opacity: this._ballOpacity,
27384             transparent: true,
27385         }));
27386         ball.position.z = this._markerHeight(radius);
27387         var group = new THREE.Object3D();
27388         group.add(ball);
27389         group.add(cone);
27390         group.position.fromArray(position);
27391         this._geometry = group;
27392     };
27393     SimpleMarker.prototype._disposeGeometry = function () {
27394         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
27395             var mesh = _a[_i];
27396             mesh.geometry.dispose();
27397             mesh.material.dispose();
27398         }
27399     };
27400     SimpleMarker.prototype._getInteractiveObjects = function () {
27401         return this._interactive ? [this._geometry.children[0]] : [];
27402     };
27403     SimpleMarker.prototype._markerHeight = function (radius) {
27404         var t = Math.tan(Math.PI - this._circleToRayAngle);
27405         return radius * Math.sqrt(1 + t * t);
27406     };
27407     SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
27408         var geometry = new THREE.Geometry();
27409         widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
27410         heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
27411         var height = this._markerHeight(radius);
27412         var vertices = [];
27413         for (var y = 0; y <= heightSegments; ++y) {
27414             var verticesRow = [];
27415             for (var x = 0; x <= widthSegments; ++x) {
27416                 var u = x / widthSegments * Math.PI * 2;
27417                 var v = y / heightSegments * Math.PI;
27418                 var r = void 0;
27419                 if (v < this._circleToRayAngle) {
27420                     r = radius;
27421                 }
27422                 else {
27423                     var t = Math.tan(v - this._circleToRayAngle);
27424                     r = radius * Math.sqrt(1 + t * t);
27425                 }
27426                 var vertex = new THREE.Vector3();
27427                 vertex.x = r * Math.cos(u) * Math.sin(v);
27428                 vertex.y = r * Math.sin(u) * Math.sin(v);
27429                 vertex.z = r * Math.cos(v) + height;
27430                 geometry.vertices.push(vertex);
27431                 verticesRow.push(geometry.vertices.length - 1);
27432             }
27433             vertices.push(verticesRow);
27434         }
27435         for (var y = 0; y < heightSegments; ++y) {
27436             for (var x = 0; x < widthSegments; ++x) {
27437                 var v1 = vertices[y][x + 1];
27438                 var v2 = vertices[y][x];
27439                 var v3 = vertices[y + 1][x];
27440                 var v4 = vertices[y + 1][x + 1];
27441                 var n1 = geometry.vertices[v1].clone().normalize();
27442                 var n2 = geometry.vertices[v2].clone().normalize();
27443                 var n3 = geometry.vertices[v3].clone().normalize();
27444                 var n4 = geometry.vertices[v4].clone().normalize();
27445                 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
27446                 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
27447             }
27448         }
27449         geometry.computeFaceNormals();
27450         geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
27451         return geometry;
27452     };
27453     return SimpleMarker;
27454 }(Component_1.Marker));
27455 exports.SimpleMarker = SimpleMarker;
27456 exports.default = SimpleMarker;
27457
27458 },{"../../../Component":275,"three":226}],322:[function(require,module,exports){
27459 "use strict";
27460 var __extends = (this && this.__extends) || (function () {
27461     var extendStatics = function (d, b) {
27462         extendStatics = Object.setPrototypeOf ||
27463             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27464             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27465         return extendStatics(d, b);
27466     }
27467     return function (d, b) {
27468         extendStatics(d, b);
27469         function __() { this.constructor = d; }
27470         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27471     };
27472 })();
27473 Object.defineProperty(exports, "__esModule", { value: true });
27474 var rxjs_1 = require("rxjs");
27475 var operators_1 = require("rxjs/operators");
27476 var Component_1 = require("../../Component");
27477 /**
27478  * The `BounceHandler` ensures that the viewer bounces back to the image
27479  * when drag panning outside of the image edge.
27480  */
27481 var BounceHandler = /** @class */ (function (_super) {
27482     __extends(BounceHandler, _super);
27483     function BounceHandler(component, container, navigator, viewportCoords, spatial) {
27484         var _this = _super.call(this, component, container, navigator) || this;
27485         _this._spatial = spatial;
27486         _this._viewportCoords = viewportCoords;
27487         return _this;
27488     }
27489     BounceHandler.prototype._enable = function () {
27490         var _this = this;
27491         var inTransition$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
27492             return frame.state.alpha < 1;
27493         }), operators_1.distinctUntilChanged());
27494         this._bounceSubscription = rxjs_1.combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$).pipe(operators_1.map(function (noForce) {
27495             return noForce[0] || noForce[1] || noForce[2] || noForce[3];
27496         }), operators_1.distinctUntilChanged(), operators_1.switchMap(function (noForce) {
27497             return noForce ?
27498                 rxjs_1.empty() :
27499                 rxjs_1.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.pipe(operators_1.first()));
27500         }), operators_1.withLatestFrom(this._navigator.panService.panNodes$))
27501             .subscribe(function (_a) {
27502             var _b = _a[0], render = _b[0], transform = _b[1], nts = _a[1];
27503             if (!transform.hasValidScale && render.camera.focal < 0.1) {
27504                 return;
27505             }
27506             if (render.perspective.aspect === 0 || render.perspective.aspect === Number.POSITIVE_INFINITY) {
27507                 return;
27508             }
27509             var distances = Component_1.ImageBoundary.viewportDistances(transform, render.perspective, _this._viewportCoords);
27510             var basic = _this._viewportCoords.viewportToBasic(0, 0, transform, render.perspective);
27511             if ((basic[0] < 0 || basic[0] > 1) && nts.length > 0) {
27512                 distances[0] = distances[2] = 0;
27513             }
27514             for (var _i = 0, nts_1 = nts; _i < nts_1.length; _i++) {
27515                 var _c = nts_1[_i], t = _c[1];
27516                 var d = Component_1.ImageBoundary.viewportDistances(t, render.perspective, _this._viewportCoords);
27517                 for (var i = 1; i < distances.length; i += 2) {
27518                     if (d[i] < distances[i]) {
27519                         distances[i] = d[i];
27520                     }
27521                 }
27522             }
27523             if (Math.max.apply(Math, distances) < 0.01) {
27524                 return;
27525             }
27526             var horizontalDistance = distances[1] - distances[3];
27527             var verticalDistance = distances[0] - distances[2];
27528             var currentDirection = _this._viewportCoords
27529                 .unprojectFromViewport(0, 0, render.perspective)
27530                 .sub(render.perspective.position);
27531             var directionPhi = _this._viewportCoords
27532                 .unprojectFromViewport(horizontalDistance, 0, render.perspective)
27533                 .sub(render.perspective.position);
27534             var directionTheta = _this._viewportCoords
27535                 .unprojectFromViewport(0, verticalDistance, render.perspective)
27536                 .sub(render.perspective.position);
27537             var phi = (horizontalDistance > 0 ? 1 : -1) * directionPhi.angleTo(currentDirection);
27538             var theta = (verticalDistance > 0 ? 1 : -1) * directionTheta.angleTo(currentDirection);
27539             var threshold = Math.PI / 60;
27540             var coeff = 1e-1;
27541             phi = _this._spatial.clamp(coeff * phi, -threshold, threshold);
27542             theta = _this._spatial.clamp(coeff * theta, -threshold, threshold);
27543             _this._navigator.stateService.rotateUnbounded({ phi: phi, theta: theta });
27544         });
27545     };
27546     BounceHandler.prototype._disable = function () {
27547         this._bounceSubscription.unsubscribe();
27548     };
27549     BounceHandler.prototype._getConfiguration = function () {
27550         return {};
27551     };
27552     return BounceHandler;
27553 }(Component_1.HandlerBase));
27554 exports.BounceHandler = BounceHandler;
27555 exports.default = BounceHandler;
27556
27557 },{"../../Component":275,"rxjs":27,"rxjs/operators":225}],323:[function(require,module,exports){
27558 "use strict";
27559 var __extends = (this && this.__extends) || (function () {
27560     var extendStatics = function (d, b) {
27561         extendStatics = Object.setPrototypeOf ||
27562             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27563             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27564         return extendStatics(d, b);
27565     }
27566     return function (d, b) {
27567         extendStatics(d, b);
27568         function __() { this.constructor = d; }
27569         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27570     };
27571 })();
27572 Object.defineProperty(exports, "__esModule", { value: true });
27573 var rxjs_1 = require("rxjs");
27574 var operators_1 = require("rxjs/operators");
27575 var Component_1 = require("../../Component");
27576 /**
27577  * The `DoubleClickZoomHandler` allows the user to zoom the viewer image at a point by double clicking.
27578  *
27579  * @example
27580  * ```
27581  * var mouseComponent = viewer.getComponent("mouse");
27582  *
27583  * mouseComponent.doubleClickZoom.disable();
27584  * mouseComponent.doubleClickZoom.enable();
27585  *
27586  * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
27587  * ```
27588  */
27589 var DoubleClickZoomHandler = /** @class */ (function (_super) {
27590     __extends(DoubleClickZoomHandler, _super);
27591     /** @ignore */
27592     function DoubleClickZoomHandler(component, container, navigator, viewportCoords) {
27593         var _this = _super.call(this, component, container, navigator) || this;
27594         _this._viewportCoords = viewportCoords;
27595         return _this;
27596     }
27597     DoubleClickZoomHandler.prototype._enable = function () {
27598         var _this = this;
27599         this._zoomSubscription = rxjs_1.merge(this._container.mouseService
27600             .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$.pipe(operators_1.map(function (e) {
27601             var touch = e.touches[0];
27602             return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
27603         }))).pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
27604             .subscribe(function (_a) {
27605             var event = _a[0], render = _a[1], transform = _a[2];
27606             var element = _this._container.element;
27607             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
27608             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
27609             var reference = transform.projectBasic(unprojected.toArray());
27610             var delta = !!event.shiftKey ? -1 : 1;
27611             _this._navigator.stateService.zoomIn(delta, reference);
27612         });
27613     };
27614     DoubleClickZoomHandler.prototype._disable = function () {
27615         this._zoomSubscription.unsubscribe();
27616     };
27617     DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
27618         return { doubleClickZoom: enable };
27619     };
27620     return DoubleClickZoomHandler;
27621 }(Component_1.HandlerBase));
27622 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
27623 exports.default = DoubleClickZoomHandler;
27624
27625 },{"../../Component":275,"rxjs":27,"rxjs/operators":225}],324:[function(require,module,exports){
27626 "use strict";
27627 var __extends = (this && this.__extends) || (function () {
27628     var extendStatics = function (d, b) {
27629         extendStatics = Object.setPrototypeOf ||
27630             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27631             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27632         return extendStatics(d, b);
27633     }
27634     return function (d, b) {
27635         extendStatics(d, b);
27636         function __() { this.constructor = d; }
27637         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27638     };
27639 })();
27640 Object.defineProperty(exports, "__esModule", { value: true });
27641 var rxjs_1 = require("rxjs");
27642 var operators_1 = require("rxjs/operators");
27643 var Component_1 = require("../../Component");
27644 /**
27645  * The `DragPanHandler` allows the user to pan the viewer image by clicking and dragging the cursor.
27646  *
27647  * @example
27648  * ```
27649  * var mouseComponent = viewer.getComponent("mouse");
27650  *
27651  * mouseComponent.dragPan.disable();
27652  * mouseComponent.dragPan.enable();
27653  *
27654  * var isEnabled = mouseComponent.dragPan.isEnabled;
27655  * ```
27656  */
27657 var DragPanHandler = /** @class */ (function (_super) {
27658     __extends(DragPanHandler, _super);
27659     /** @ignore */
27660     function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
27661         var _this = _super.call(this, component, container, navigator) || this;
27662         _this._spatial = spatial;
27663         _this._viewportCoords = viewportCoords;
27664         return _this;
27665     }
27666     DragPanHandler.prototype._enable = function () {
27667         var _this = this;
27668         var draggingStarted$ = this._container.mouseService
27669             .filtered$(this._component.name, this._container.mouseService.mouseDragStart$).pipe(operators_1.map(function () {
27670             return true;
27671         }), operators_1.share());
27672         var draggingStopped$ = this._container.mouseService
27673             .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$).pipe(operators_1.map(function () {
27674             return false;
27675         }), operators_1.share());
27676         this._activeMouseSubscription = rxjs_1.merge(draggingStarted$, draggingStopped$)
27677             .subscribe(this._container.mouseService.activate$);
27678         var documentMouseMove$ = rxjs_1.merge(draggingStarted$, draggingStopped$).pipe(operators_1.switchMap(function (dragging) {
27679             return dragging ?
27680                 _this._container.mouseService.documentMouseMove$ :
27681                 rxjs_1.empty();
27682         }));
27683         this._preventDefaultSubscription = rxjs_1.merge(documentMouseMove$, this._container.touchService.touchMove$)
27684             .subscribe(function (event) {
27685             event.preventDefault(); // prevent selection of content outside the viewer
27686         });
27687         var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$.pipe(operators_1.map(function () {
27688             return true;
27689         }));
27690         var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$.pipe(operators_1.map(function () {
27691             return false;
27692         }));
27693         this._activeTouchSubscription = rxjs_1.merge(touchMovingStarted$, touchMovingStopped$)
27694             .subscribe(this._container.touchService.activate$);
27695         var rotation$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
27696             return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
27697         }), operators_1.distinctUntilChanged(), operators_1.switchMap(function (enable) {
27698             if (!enable) {
27699                 return rxjs_1.empty();
27700             }
27701             var mouseDrag$ = Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService);
27702             var singleTouchDrag$ = rxjs_1.merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.pipe(operators_1.map(function () { return null; }))).pipe(operators_1.map(function (event) {
27703                 return event != null && event.touches.length > 0 ?
27704                     event.touches[0] : null;
27705             }), operators_1.pairwise(), operators_1.filter(function (pair) {
27706                 return pair[0] != null && pair[1] != null;
27707             }));
27708             return rxjs_1.merge(mouseDrag$, singleTouchDrag$);
27709         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.panService.panNodes$), operators_1.map(function (_a) {
27710             var events = _a[0], render = _a[1], transform = _a[2], nts = _a[3];
27711             var previousEvent = events[0];
27712             var event = events[1];
27713             var movementX = event.clientX - previousEvent.clientX;
27714             var movementY = event.clientY - previousEvent.clientY;
27715             var element = _this._container.element;
27716             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
27717             var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
27718                 .sub(render.perspective.position);
27719             var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
27720                 .sub(render.perspective.position);
27721             var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
27722                 .sub(render.perspective.position);
27723             var phi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
27724             var theta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
27725             var distances = Component_1.ImageBoundary.viewportDistances(transform, render.perspective, _this._viewportCoords);
27726             for (var _i = 0, nts_1 = nts; _i < nts_1.length; _i++) {
27727                 var _c = nts_1[_i], t = _c[1];
27728                 var d = Component_1.ImageBoundary.viewportDistances(t, render.perspective, _this._viewportCoords);
27729                 for (var i = 0; i < distances.length; i++) {
27730                     if (d[i] < distances[i]) {
27731                         distances[i] = d[i];
27732                     }
27733                 }
27734             }
27735             if (distances[0] > 0 && theta < 0) {
27736                 theta /= Math.max(1, 2e2 * distances[0]);
27737             }
27738             if (distances[2] > 0 && theta > 0) {
27739                 theta /= Math.max(1, 2e2 * distances[2]);
27740             }
27741             if (distances[1] > 0 && phi < 0) {
27742                 phi /= Math.max(1, 2e2 * distances[1]);
27743             }
27744             if (distances[3] > 0 && phi > 0) {
27745                 phi /= Math.max(1, 2e2 * distances[3]);
27746             }
27747             return { phi: phi, theta: theta };
27748         }), operators_1.share());
27749         this._rotateWithoutInertiaSubscription = rotation$
27750             .subscribe(function (rotation) {
27751             _this._navigator.stateService.rotateWithoutInertia(rotation);
27752         });
27753         this._rotateSubscription = rotation$.pipe(operators_1.scan(function (rotationBuffer, rotation) {
27754             _this._drainBuffer(rotationBuffer);
27755             rotationBuffer.push([Date.now(), rotation]);
27756             return rotationBuffer;
27757         }, []), operators_1.sample(rxjs_1.merge(this._container.mouseService.filtered$(this._component.name, this._container.mouseService.mouseDragEnd$), this._container.touchService.singleTouchDragEnd$)), operators_1.map(function (rotationBuffer) {
27758             var drainedBuffer = _this._drainBuffer(rotationBuffer.slice());
27759             var rotation = { phi: 0, theta: 0 };
27760             for (var _i = 0, drainedBuffer_1 = drainedBuffer; _i < drainedBuffer_1.length; _i++) {
27761                 var bufferedRotation = drainedBuffer_1[_i];
27762                 rotation.phi += bufferedRotation[1].phi;
27763                 rotation.theta += bufferedRotation[1].theta;
27764             }
27765             var count = drainedBuffer.length;
27766             if (count > 0) {
27767                 rotation.phi /= count;
27768                 rotation.theta /= count;
27769             }
27770             var threshold = Math.PI / 18;
27771             rotation.phi = _this._spatial.clamp(rotation.phi, -threshold, threshold);
27772             rotation.theta = _this._spatial.clamp(rotation.theta, -threshold, threshold);
27773             return rotation;
27774         }))
27775             .subscribe(function (rotation) {
27776             _this._navigator.stateService.rotate(rotation);
27777         });
27778     };
27779     DragPanHandler.prototype._disable = function () {
27780         this._activeMouseSubscription.unsubscribe();
27781         this._activeTouchSubscription.unsubscribe();
27782         this._preventDefaultSubscription.unsubscribe();
27783         this._rotateSubscription.unsubscribe();
27784         this._rotateWithoutInertiaSubscription.unsubscribe();
27785         this._activeMouseSubscription = null;
27786         this._activeTouchSubscription = null;
27787         this._preventDefaultSubscription = null;
27788         this._rotateSubscription = null;
27789     };
27790     DragPanHandler.prototype._getConfiguration = function (enable) {
27791         return { dragPan: enable };
27792     };
27793     DragPanHandler.prototype._drainBuffer = function (buffer) {
27794         var cutoff = 50;
27795         var now = Date.now();
27796         while (buffer.length > 0 && now - buffer[0][0] > cutoff) {
27797             buffer.shift();
27798         }
27799         return buffer;
27800     };
27801     return DragPanHandler;
27802 }(Component_1.HandlerBase));
27803 exports.DragPanHandler = DragPanHandler;
27804 exports.default = DragPanHandler;
27805
27806 },{"../../Component":275,"rxjs":27,"rxjs/operators":225}],325:[function(require,module,exports){
27807 "use strict";
27808 var __extends = (this && this.__extends) || (function () {
27809     var extendStatics = function (d, b) {
27810         extendStatics = Object.setPrototypeOf ||
27811             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27812             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27813         return extendStatics(d, b);
27814     }
27815     return function (d, b) {
27816         extendStatics(d, b);
27817         function __() { this.constructor = d; }
27818         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27819     };
27820 })();
27821 Object.defineProperty(exports, "__esModule", { value: true });
27822 var THREE = require("three");
27823 var rxjs_1 = require("rxjs");
27824 var operators_1 = require("rxjs/operators");
27825 var Component_1 = require("../../Component");
27826 var State_1 = require("../../State");
27827 var EarthControlHandler = /** @class */ (function (_super) {
27828     __extends(EarthControlHandler, _super);
27829     function EarthControlHandler(component, container, navigator, viewportCoords, spatial) {
27830         var _this = _super.call(this, component, container, navigator) || this;
27831         _this._spatial = spatial;
27832         _this._viewportCoords = viewportCoords;
27833         return _this;
27834     }
27835     EarthControlHandler.prototype._enable = function () {
27836         var _this = this;
27837         var earth$ = this._navigator.stateService.state$.pipe(operators_1.map(function (state) {
27838             return state === State_1.State.Earth;
27839         }), operators_1.share());
27840         this._preventDefaultSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
27841             return earth ?
27842                 _this._container.mouseService.mouseWheel$ :
27843                 rxjs_1.empty();
27844         }))
27845             .subscribe(function (event) {
27846             event.preventDefault();
27847         });
27848         this._truckSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
27849             if (!earth) {
27850                 return rxjs_1.empty();
27851             }
27852             return Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService).pipe(operators_1.filter(function (_a) {
27853                 var e1 = _a[0], e2 = _a[1];
27854                 return !(e1.ctrlKey && e2.ctrlKey);
27855             }));
27856         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
27857             var _b = _a[0], previous = _b[0], current = _b[1], render = _a[1], transform = _a[2];
27858             var planeNormal = [0, 0, 1];
27859             var planePoint = transform.unprojectBasic([0.5, 0.5], 0);
27860             planePoint[2] -= 2;
27861             var currentIntersection = _this._planeIntersection(current, planeNormal, planePoint, render.perspective, _this._container.element);
27862             var previousIntersection = _this._planeIntersection(previous, planeNormal, planePoint, render.perspective, _this._container.element);
27863             if (!currentIntersection || !previousIntersection) {
27864                 return null;
27865             }
27866             var direction = new THREE.Vector3()
27867                 .subVectors(currentIntersection, previousIntersection)
27868                 .multiplyScalar(-1)
27869                 .toArray();
27870             return direction;
27871         }), operators_1.filter(function (direction) {
27872             return !!direction;
27873         }))
27874             .subscribe(function (direction) {
27875             _this._navigator.stateService.truck(direction);
27876         });
27877         this._orbitSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
27878             if (!earth) {
27879                 return rxjs_1.empty();
27880             }
27881             return Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService).pipe(operators_1.filter(function (_a) {
27882                 var e1 = _a[0], e2 = _a[1];
27883                 return e1.ctrlKey && e2.ctrlKey;
27884             }));
27885         }), operators_1.map(function (_a) {
27886             var previous = _a[0], current = _a[1];
27887             var _b = _this._eventToViewport(current, _this._container.element), currentX = _b[0], currentY = _b[1];
27888             var _c = _this._eventToViewport(previous, _this._container.element), previousX = _c[0], previousY = _c[1];
27889             var phi = (previousX - currentX) * Math.PI;
27890             var theta = (currentY - previousY) * Math.PI / 2;
27891             return { phi: phi, theta: theta };
27892         }))
27893             .subscribe(function (rotation) {
27894             _this._navigator.stateService.orbit(rotation);
27895         });
27896         this._dollySubscription = earth$.pipe(operators_1.switchMap(function (earth) {
27897             if (!earth) {
27898                 return rxjs_1.empty();
27899             }
27900             return _this._container.mouseService
27901                 .filteredWheel$(_this._component.name, _this._container.mouseService.mouseWheel$);
27902         }), operators_1.map(function (event) {
27903             var delta = event.deltaY;
27904             if (event.deltaMode === 1) {
27905                 delta = 40 * delta;
27906             }
27907             else if (event.deltaMode === 2) {
27908                 delta = 800 * delta;
27909             }
27910             var canvasSize = _this._viewportCoords.containerToCanvas(_this._container.element);
27911             return -delta / canvasSize[1];
27912         }))
27913             .subscribe(function (delta) {
27914             _this._navigator.stateService.dolly(delta);
27915         });
27916     };
27917     EarthControlHandler.prototype._disable = function () {
27918         this._dollySubscription.unsubscribe();
27919         this._orbitSubscription.unsubscribe();
27920         this._preventDefaultSubscription.unsubscribe();
27921         this._truckSubscription.unsubscribe();
27922     };
27923     EarthControlHandler.prototype._getConfiguration = function () {
27924         return {};
27925     };
27926     EarthControlHandler.prototype._eventToViewport = function (event, element) {
27927         var previousCanvas = this._viewportCoords.canvasPosition(event, element);
27928         return this._viewportCoords.canvasToViewport(previousCanvas[0], previousCanvas[1], element);
27929     };
27930     EarthControlHandler.prototype._planeIntersection = function (event, planeNormal, planePoint, camera, element) {
27931         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
27932         var direction = this._viewportCoords
27933             .unprojectFromCanvas(canvasX, canvasY, element, camera)
27934             .sub(camera.position)
27935             .normalize();
27936         if (Math.abs(this._spatial.angleToPlane(direction.toArray(), planeNormal)) < Math.PI / 90) {
27937             return null;
27938         }
27939         var l0 = camera.position.clone();
27940         var n = new THREE.Vector3().fromArray(planeNormal);
27941         var p0 = new THREE.Vector3().fromArray(planePoint);
27942         var d = new THREE.Vector3().subVectors(p0, l0).dot(n) / direction.clone().dot(n);
27943         var intersection = new THREE.Vector3().addVectors(l0, direction.multiplyScalar(d));
27944         if (this._viewportCoords.worldToCamera(intersection.toArray(), camera)[2] > 0) {
27945             return null;
27946         }
27947         return intersection;
27948     };
27949     return EarthControlHandler;
27950 }(Component_1.HandlerBase));
27951 exports.EarthControlHandler = EarthControlHandler;
27952 exports.default = EarthControlHandler;
27953
27954 },{"../../Component":275,"../../State":282,"rxjs":27,"rxjs/operators":225,"three":226}],326:[function(require,module,exports){
27955 "use strict";
27956 Object.defineProperty(exports, "__esModule", { value: true });
27957 var Geo_1 = require("../../../src/Geo");
27958 function basicBoundaryPoints(pointsPerSide) {
27959     var points = [];
27960     var os = [[0, 0], [1, 0], [1, 1], [0, 1]];
27961     var ds = [[1, 0], [0, 1], [-1, 0], [0, -1]];
27962     for (var side = 0; side < 4; ++side) {
27963         var o = os[side];
27964         var d = ds[side];
27965         for (var i = 0; i < pointsPerSide; ++i) {
27966             points.push([o[0] + d[0] * i / pointsPerSide,
27967                 o[1] + d[1] * i / pointsPerSide]);
27968         }
27969     }
27970     return points;
27971 }
27972 function insideViewport(x, y) {
27973     return x >= -1 && x <= 1 && y >= -1 && y <= 1;
27974 }
27975 function insideBasic(x, y) {
27976     return x >= 0 && x <= 1 && y >= 0 && y <= 1;
27977 }
27978 function viewportDistances(transform, perspective, viewportCoords) {
27979     var boundaryPointsBasic = basicBoundaryPoints(100);
27980     var boundaryPointsViewport = boundaryPointsBasic
27981         .map(function (basic) {
27982         return viewportCoords.basicToViewportSafe(basic[0], basic[1], transform, perspective);
27983     });
27984     var visibleBoundaryPoints = [];
27985     var viewportSides = [
27986         { x: -1, y: 1 },
27987         { x: 1, y: 1 },
27988         { x: 1, y: -1 },
27989         { x: -1, y: -1 }
27990     ];
27991     var intersections = [false, false, false, false];
27992     for (var i = 0; i < boundaryPointsViewport.length; i++) {
27993         var p1 = boundaryPointsViewport[i];
27994         var p2 = boundaryPointsViewport[(i + 1) % boundaryPointsViewport.length];
27995         if (p1 === null) {
27996             continue;
27997         }
27998         if (p2 === null) {
27999             if (insideViewport(p1[0], p1[1])) {
28000                 visibleBoundaryPoints.push(p1);
28001             }
28002             continue;
28003         }
28004         var x1 = p1[0], y1 = p1[1];
28005         var x2 = p2[0], y2 = p2[1];
28006         if (insideViewport(x1, y1)) {
28007             if (insideViewport(x2, y2)) {
28008                 visibleBoundaryPoints.push(p1);
28009             }
28010             else {
28011                 for (var side = 0; side < 4; side++) {
28012                     var s1 = { p1: { x: x1, y: y1 }, p2: { x: x2, y: y2 } };
28013                     var s2 = { p1: viewportSides[side], p2: viewportSides[(side + 1) % 4] };
28014                     var intersecting = Geo_1.Lines.segmentsIntersect(s1, s2);
28015                     if (intersecting) {
28016                         var intersection = Geo_1.Lines.segmentIntersection(s1, s2);
28017                         visibleBoundaryPoints.push(p1, [intersection.x, intersection.y]);
28018                         intersections[side] = true;
28019                     }
28020                 }
28021             }
28022         }
28023     }
28024     var _a = viewportCoords.viewportToBasic(-1, 1, transform, perspective), topLeftBasicX = _a[0], topLeftBasicY = _a[1];
28025     var _b = viewportCoords.viewportToBasic(1, 1, transform, perspective), topRightBasicX = _b[0], topRightBasicY = _b[1];
28026     var _c = viewportCoords.viewportToBasic(1, -1, transform, perspective), bottomRightBasicX = _c[0], bottomRightBasicY = _c[1];
28027     var _d = viewportCoords.viewportToBasic(-1, -1, transform, perspective), bottomLeftBasicX = _d[0], bottomLeftBasicY = _d[1];
28028     if (insideBasic(topLeftBasicX, topLeftBasicY)) {
28029         intersections[3] = intersections[0] = true;
28030     }
28031     if (insideBasic(topRightBasicX, topRightBasicY)) {
28032         intersections[0] = intersections[1] = true;
28033     }
28034     if (insideBasic(bottomRightBasicX, bottomRightBasicY)) {
28035         intersections[1] = intersections[2] = true;
28036     }
28037     if (insideBasic(bottomLeftBasicX, bottomLeftBasicY)) {
28038         intersections[2] = intersections[3] = true;
28039     }
28040     var maximums = [-1, -1, 1, 1];
28041     for (var _i = 0, visibleBoundaryPoints_1 = visibleBoundaryPoints; _i < visibleBoundaryPoints_1.length; _i++) {
28042         var visibleBoundaryPoint = visibleBoundaryPoints_1[_i];
28043         var x = visibleBoundaryPoint[0];
28044         var y = visibleBoundaryPoint[1];
28045         if (x > maximums[1]) {
28046             maximums[1] = x;
28047         }
28048         if (x < maximums[3]) {
28049             maximums[3] = x;
28050         }
28051         if (y > maximums[0]) {
28052             maximums[0] = y;
28053         }
28054         if (y < maximums[2]) {
28055             maximums[2] = y;
28056         }
28057     }
28058     var boundary = [1, 1, -1, -1];
28059     var distances = [];
28060     for (var side = 0; side < 4; side++) {
28061         if (intersections[side]) {
28062             distances.push(0);
28063             continue;
28064         }
28065         distances.push(Math.abs(boundary[side] - maximums[side]));
28066     }
28067     return distances;
28068 }
28069 exports.viewportDistances = viewportDistances;
28070
28071 },{"../../../src/Geo":278}],327:[function(require,module,exports){
28072 "use strict";
28073 var __extends = (this && this.__extends) || (function () {
28074     var extendStatics = function (d, b) {
28075         extendStatics = Object.setPrototypeOf ||
28076             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28077             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28078         return extendStatics(d, b);
28079     }
28080     return function (d, b) {
28081         extendStatics(d, b);
28082         function __() { this.constructor = d; }
28083         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28084     };
28085 })();
28086 Object.defineProperty(exports, "__esModule", { value: true });
28087 var Component_1 = require("../../Component");
28088 var Geo_1 = require("../../Geo");
28089 /**
28090  * @class MouseComponent
28091  *
28092  * @classdesc Component handling mouse and touch events for camera movement.
28093  *
28094  * To retrive and use the mouse component
28095  *
28096  * @example
28097  * ```
28098  * var viewer = new Mapillary.Viewer(
28099  *     "<element-id>",
28100  *     "<client-id>",
28101  *     "<my key>");
28102  *
28103  * var mouseComponent = viewer.getComponent("mouse");
28104  * ```
28105  */
28106 var MouseComponent = /** @class */ (function (_super) {
28107     __extends(MouseComponent, _super);
28108     /** @ignore */
28109     function MouseComponent(name, container, navigator) {
28110         var _this = _super.call(this, name, container, navigator) || this;
28111         var spatial = new Geo_1.Spatial();
28112         var viewportCoords = new Geo_1.ViewportCoords();
28113         _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
28114         _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
28115         _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
28116         _this._earthControlHandler = new Component_1.EarthControlHandler(_this, container, navigator, viewportCoords, spatial);
28117         _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
28118         _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
28119         return _this;
28120     }
28121     Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
28122         /**
28123          * Get double click zoom.
28124          *
28125          * @returns {DoubleClickZoomHandler} The double click zoom handler.
28126          */
28127         get: function () {
28128             return this._doubleClickZoomHandler;
28129         },
28130         enumerable: true,
28131         configurable: true
28132     });
28133     Object.defineProperty(MouseComponent.prototype, "dragPan", {
28134         /**
28135          * Get drag pan.
28136          *
28137          * @returns {DragPanHandler} The drag pan handler.
28138          */
28139         get: function () {
28140             return this._dragPanHandler;
28141         },
28142         enumerable: true,
28143         configurable: true
28144     });
28145     Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
28146         /**
28147          * Get scroll zoom.
28148          *
28149          * @returns {ScrollZoomHandler} The scroll zoom handler.
28150          */
28151         get: function () {
28152             return this._scrollZoomHandler;
28153         },
28154         enumerable: true,
28155         configurable: true
28156     });
28157     Object.defineProperty(MouseComponent.prototype, "touchZoom", {
28158         /**
28159          * Get touch zoom.
28160          *
28161          * @returns {TouchZoomHandler} The touch zoom handler.
28162          */
28163         get: function () {
28164             return this._touchZoomHandler;
28165         },
28166         enumerable: true,
28167         configurable: true
28168     });
28169     MouseComponent.prototype._activate = function () {
28170         var _this = this;
28171         this._bounceHandler.enable();
28172         this._earthControlHandler.enable();
28173         this._configurationSubscription = this._configuration$
28174             .subscribe(function (configuration) {
28175             if (configuration.doubleClickZoom) {
28176                 _this._doubleClickZoomHandler.enable();
28177             }
28178             else {
28179                 _this._doubleClickZoomHandler.disable();
28180             }
28181             if (configuration.dragPan) {
28182                 _this._dragPanHandler.enable();
28183             }
28184             else {
28185                 _this._dragPanHandler.disable();
28186             }
28187             if (configuration.scrollZoom) {
28188                 _this._scrollZoomHandler.enable();
28189             }
28190             else {
28191                 _this._scrollZoomHandler.disable();
28192             }
28193             if (configuration.touchZoom) {
28194                 _this._touchZoomHandler.enable();
28195             }
28196             else {
28197                 _this._touchZoomHandler.disable();
28198             }
28199         });
28200         this._container.mouseService.claimMouse(this._name, 0);
28201     };
28202     MouseComponent.prototype._deactivate = function () {
28203         this._container.mouseService.unclaimMouse(this._name);
28204         this._configurationSubscription.unsubscribe();
28205         this._bounceHandler.disable();
28206         this._doubleClickZoomHandler.disable();
28207         this._dragPanHandler.disable();
28208         this._earthControlHandler.disable();
28209         this._scrollZoomHandler.disable();
28210         this._touchZoomHandler.disable();
28211     };
28212     MouseComponent.prototype._getDefaultConfiguration = function () {
28213         return { doubleClickZoom: false, dragPan: true, scrollZoom: true, touchZoom: true };
28214     };
28215     /** @inheritdoc */
28216     MouseComponent.componentName = "mouse";
28217     return MouseComponent;
28218 }(Component_1.Component));
28219 exports.MouseComponent = MouseComponent;
28220 Component_1.ComponentService.register(MouseComponent);
28221 exports.default = MouseComponent;
28222
28223 },{"../../Component":275,"../../Geo":278}],328:[function(require,module,exports){
28224 "use strict";
28225 var __extends = (this && this.__extends) || (function () {
28226     var extendStatics = function (d, b) {
28227         extendStatics = Object.setPrototypeOf ||
28228             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28229             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28230         return extendStatics(d, b);
28231     }
28232     return function (d, b) {
28233         extendStatics(d, b);
28234         function __() { this.constructor = d; }
28235         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28236     };
28237 })();
28238 Object.defineProperty(exports, "__esModule", { value: true });
28239 var operators_1 = require("rxjs/operators");
28240 var Component_1 = require("../../Component");
28241 /**
28242  * The `ScrollZoomHandler` allows the user to zoom the viewer image by scrolling.
28243  *
28244  * @example
28245  * ```
28246  * var mouseComponent = viewer.getComponent("mouse");
28247  *
28248  * mouseComponent.scrollZoom.disable();
28249  * mouseComponent.scrollZoom.enable();
28250  *
28251  * var isEnabled = mouseComponent.scrollZoom.isEnabled;
28252  * ```
28253  */
28254 var ScrollZoomHandler = /** @class */ (function (_super) {
28255     __extends(ScrollZoomHandler, _super);
28256     /** @ignore */
28257     function ScrollZoomHandler(component, container, navigator, viewportCoords) {
28258         var _this = _super.call(this, component, container, navigator) || this;
28259         _this._viewportCoords = viewportCoords;
28260         return _this;
28261     }
28262     ScrollZoomHandler.prototype._enable = function () {
28263         var _this = this;
28264         this._container.mouseService.claimWheel(this._component.name, 0);
28265         this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
28266             .subscribe(function (event) {
28267             event.preventDefault();
28268         });
28269         this._zoomSubscription = this._container.mouseService
28270             .filteredWheel$(this._component.name, this._container.mouseService.mouseWheel$).pipe(operators_1.withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
28271             return [w, f];
28272         }), operators_1.filter(function (args) {
28273             var state = args[1].state;
28274             return state.currentNode.fullPano || state.nodesAhead < 1;
28275         }), operators_1.map(function (args) {
28276             return args[0];
28277         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
28278             return [w, r, t];
28279         }))
28280             .subscribe(function (args) {
28281             var event = args[0];
28282             var render = args[1];
28283             var transform = args[2];
28284             var element = _this._container.element;
28285             var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
28286             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
28287             var reference = transform.projectBasic(unprojected.toArray());
28288             var deltaY = event.deltaY;
28289             if (event.deltaMode === 1) {
28290                 deltaY = 40 * deltaY;
28291             }
28292             else if (event.deltaMode === 2) {
28293                 deltaY = 800 * deltaY;
28294             }
28295             var canvasSize = _this._viewportCoords.containerToCanvas(element);
28296             var zoom = -3 * deltaY / canvasSize[1];
28297             _this._navigator.stateService.zoomIn(zoom, reference);
28298         });
28299     };
28300     ScrollZoomHandler.prototype._disable = function () {
28301         this._container.mouseService.unclaimWheel(this._component.name);
28302         this._preventDefaultSubscription.unsubscribe();
28303         this._zoomSubscription.unsubscribe();
28304         this._preventDefaultSubscription = null;
28305         this._zoomSubscription = null;
28306     };
28307     ScrollZoomHandler.prototype._getConfiguration = function (enable) {
28308         return { scrollZoom: enable };
28309     };
28310     return ScrollZoomHandler;
28311 }(Component_1.HandlerBase));
28312 exports.ScrollZoomHandler = ScrollZoomHandler;
28313 exports.default = ScrollZoomHandler;
28314
28315 },{"../../Component":275,"rxjs/operators":225}],329:[function(require,module,exports){
28316 "use strict";
28317 var __extends = (this && this.__extends) || (function () {
28318     var extendStatics = function (d, b) {
28319         extendStatics = Object.setPrototypeOf ||
28320             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28321             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28322         return extendStatics(d, b);
28323     }
28324     return function (d, b) {
28325         extendStatics(d, b);
28326         function __() { this.constructor = d; }
28327         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28328     };
28329 })();
28330 Object.defineProperty(exports, "__esModule", { value: true });
28331 var rxjs_1 = require("rxjs");
28332 var operators_1 = require("rxjs/operators");
28333 var Component_1 = require("../../Component");
28334 /**
28335  * The `TouchZoomHandler` allows the user to zoom the viewer image by pinching on a touchscreen.
28336  *
28337  * @example
28338  * ```
28339  * var mouseComponent = viewer.getComponent("mouse");
28340  *
28341  * mouseComponent.touchZoom.disable();
28342  * mouseComponent.touchZoom.enable();
28343  *
28344  * var isEnabled = mouseComponent.touchZoom.isEnabled;
28345  * ```
28346  */
28347 var TouchZoomHandler = /** @class */ (function (_super) {
28348     __extends(TouchZoomHandler, _super);
28349     /** @ignore */
28350     function TouchZoomHandler(component, container, navigator, viewportCoords) {
28351         var _this = _super.call(this, component, container, navigator) || this;
28352         _this._viewportCoords = viewportCoords;
28353         return _this;
28354     }
28355     TouchZoomHandler.prototype._enable = function () {
28356         var _this = this;
28357         this._preventDefaultSubscription = this._container.touchService.pinch$
28358             .subscribe(function (pinch) {
28359             pinch.originalEvent.preventDefault();
28360         });
28361         var pinchStarted$ = this._container.touchService.pinchStart$.pipe(operators_1.map(function (event) {
28362             return true;
28363         }));
28364         var pinchStopped$ = this._container.touchService.pinchEnd$.pipe(operators_1.map(function (event) {
28365             return false;
28366         }));
28367         this._activeSubscription = rxjs_1.merge(pinchStarted$, pinchStopped$)
28368             .subscribe(this._container.touchService.activate$);
28369         this._zoomSubscription = this._container.touchService.pinch$.pipe(operators_1.withLatestFrom(this._navigator.stateService.currentState$), operators_1.filter(function (args) {
28370             var state = args[1].state;
28371             return state.currentNode.fullPano || state.nodesAhead < 1;
28372         }), operators_1.map(function (args) {
28373             return args[0];
28374         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
28375             .subscribe(function (_a) {
28376             var pinch = _a[0], render = _a[1], transform = _a[2];
28377             var element = _this._container.element;
28378             var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
28379             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
28380             var reference = transform.projectBasic(unprojected.toArray());
28381             var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
28382             var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
28383             _this._navigator.stateService.zoomIn(zoom, reference);
28384         });
28385     };
28386     TouchZoomHandler.prototype._disable = function () {
28387         this._activeSubscription.unsubscribe();
28388         this._preventDefaultSubscription.unsubscribe();
28389         this._zoomSubscription.unsubscribe();
28390         this._preventDefaultSubscription = null;
28391         this._zoomSubscription = null;
28392     };
28393     TouchZoomHandler.prototype._getConfiguration = function (enable) {
28394         return { touchZoom: enable };
28395     };
28396     return TouchZoomHandler;
28397 }(Component_1.HandlerBase));
28398 exports.TouchZoomHandler = TouchZoomHandler;
28399 exports.default = TouchZoomHandler;
28400
28401 },{"../../Component":275,"rxjs":27,"rxjs/operators":225}],330:[function(require,module,exports){
28402 "use strict";
28403 Object.defineProperty(exports, "__esModule", { value: true });
28404 var Popup_1 = require("./popup/Popup");
28405 exports.Popup = Popup_1.Popup;
28406 var PopupComponent_1 = require("./PopupComponent");
28407 exports.PopupComponent = PopupComponent_1.PopupComponent;
28408
28409 },{"./PopupComponent":331,"./popup/Popup":332}],331:[function(require,module,exports){
28410 "use strict";
28411 var __extends = (this && this.__extends) || (function () {
28412     var extendStatics = function (d, b) {
28413         extendStatics = Object.setPrototypeOf ||
28414             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28415             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28416         return extendStatics(d, b);
28417     }
28418     return function (d, b) {
28419         extendStatics(d, b);
28420         function __() { this.constructor = d; }
28421         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28422     };
28423 })();
28424 Object.defineProperty(exports, "__esModule", { value: true });
28425 var rxjs_1 = require("rxjs");
28426 var operators_1 = require("rxjs/operators");
28427 var Component_1 = require("../../Component");
28428 var Utils_1 = require("../../Utils");
28429 /**
28430  * @class PopupComponent
28431  *
28432  * @classdesc Component for showing HTML popup objects.
28433  *
28434  * The `add` method is used for adding new popups. Popups are removed by reference.
28435  *
28436  * It is not possible to update popups in the set by updating any properties
28437  * directly on the popup object. Popups need to be replaced by
28438  * removing them and creating new ones with relevant changed properties and
28439  * adding those instead.
28440  *
28441  * Popups are only relevant to a single image because they are based on
28442  * 2D basic image coordinates. Popups related to a certain image should
28443  * be removed when the viewer is moved to another node.
28444  *
28445  * To retrive and use the popup component
28446  *
28447  * @example
28448  * ```
28449  * var viewer = new Mapillary.Viewer(
28450  *     "<element-id>",
28451  *     "<client-id>",
28452  *     "<my key>",
28453  *     { component: { popup: true } });
28454  *
28455  * var popupComponent = viewer.getComponent("popup");
28456  * ```
28457  */
28458 var PopupComponent = /** @class */ (function (_super) {
28459     __extends(PopupComponent, _super);
28460     /** @ignore */
28461     function PopupComponent(name, container, navigator, dom) {
28462         var _this = _super.call(this, name, container, navigator) || this;
28463         _this._dom = !!dom ? dom : new Utils_1.DOM();
28464         _this._popups = [];
28465         _this._added$ = new rxjs_1.Subject();
28466         _this._popups$ = new rxjs_1.Subject();
28467         return _this;
28468     }
28469     /**
28470      * Add popups to the popups set.
28471      *
28472      * @description Adding a new popup never replaces an old one
28473      * because they are stored by reference. Adding an already
28474      * existing popup has no effect.
28475      *
28476      * @param {Array<Popup>} popups - Popups to add.
28477      *
28478      * @example ```popupComponent.add([popup1, popup2]);```
28479      */
28480     PopupComponent.prototype.add = function (popups) {
28481         for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
28482             var popup = popups_1[_i];
28483             if (this._popups.indexOf(popup) !== -1) {
28484                 continue;
28485             }
28486             this._popups.push(popup);
28487             if (this._activated) {
28488                 popup.setParentContainer(this._popupContainer);
28489             }
28490         }
28491         this._added$.next(popups);
28492         this._popups$.next(this._popups);
28493     };
28494     /**
28495      * Returns an array of all popups.
28496      *
28497      * @example ```var popups = popupComponent.getAll();```
28498      */
28499     PopupComponent.prototype.getAll = function () {
28500         return this._popups.slice();
28501     };
28502     /**
28503      * Remove popups based on reference from the popup set.
28504      *
28505      * @param {Array<Popup>} popups - Popups to remove.
28506      *
28507      * @example ```popupComponent.remove([popup1, popup2]);```
28508      */
28509     PopupComponent.prototype.remove = function (popups) {
28510         for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
28511             var popup = popups_2[_i];
28512             this._remove(popup);
28513         }
28514         this._popups$.next(this._popups);
28515     };
28516     /**
28517      * Remove all popups from the popup set.
28518      *
28519      * @example ```popupComponent.removeAll();```
28520      */
28521     PopupComponent.prototype.removeAll = function () {
28522         for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
28523             var popup = _a[_i];
28524             this._remove(popup);
28525         }
28526         this._popups$.next(this._popups);
28527     };
28528     PopupComponent.prototype._activate = function () {
28529         var _this = this;
28530         this._popupContainer = this._dom.createElement("div", "mapillary-js-popup-container", this._container.element);
28531         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
28532             var popup = _a[_i];
28533             popup.setParentContainer(this._popupContainer);
28534         }
28535         this._updateAllSubscription = rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
28536             .subscribe(function (_a) {
28537             var renderCamera = _a[0], size = _a[1], transform = _a[2];
28538             for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
28539                 var popup = _b[_i];
28540                 popup.update(renderCamera, size, transform);
28541             }
28542         });
28543         var changed$ = this._popups$.pipe(operators_1.startWith(this._popups), operators_1.switchMap(function (popups) {
28544             return rxjs_1.from(popups).pipe(operators_1.mergeMap(function (popup) {
28545                 return popup.changed$;
28546             }));
28547         }), operators_1.map(function (popup) {
28548             return [popup];
28549         }));
28550         this._updateAddedChangedSubscription = rxjs_1.merge(this._added$, changed$).pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$))
28551             .subscribe(function (_a) {
28552             var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
28553             for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
28554                 var popup = popups_3[_i];
28555                 popup.update(renderCamera, size, transform);
28556             }
28557         });
28558     };
28559     PopupComponent.prototype._deactivate = function () {
28560         this._updateAllSubscription.unsubscribe();
28561         this._updateAddedChangedSubscription.unsubscribe();
28562         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
28563             var popup = _a[_i];
28564             popup.remove();
28565         }
28566         this._container.element.removeChild(this._popupContainer);
28567         delete this._popupContainer;
28568     };
28569     PopupComponent.prototype._getDefaultConfiguration = function () {
28570         return {};
28571     };
28572     PopupComponent.prototype._remove = function (popup) {
28573         var index = this._popups.indexOf(popup);
28574         if (index === -1) {
28575             return;
28576         }
28577         var removed = this._popups.splice(index, 1)[0];
28578         if (this._activated) {
28579             removed.remove();
28580         }
28581     };
28582     PopupComponent.componentName = "popup";
28583     return PopupComponent;
28584 }(Component_1.Component));
28585 exports.PopupComponent = PopupComponent;
28586 Component_1.ComponentService.register(PopupComponent);
28587 exports.default = PopupComponent;
28588
28589 },{"../../Component":275,"../../Utils":285,"rxjs":27,"rxjs/operators":225}],332:[function(require,module,exports){
28590 "use strict";
28591 Object.defineProperty(exports, "__esModule", { value: true });
28592 var rxjs_1 = require("rxjs");
28593 var Geo_1 = require("../../../Geo");
28594 var Utils_1 = require("../../../Utils");
28595 var Viewer_1 = require("../../../Viewer");
28596 /**
28597  * @class Popup
28598  *
28599  * @classdesc Popup instance for rendering custom HTML content
28600  * on top of images. Popups are based on 2D basic image coordinates
28601  * (see the {@link Viewer} class documentation for more information about coordinate
28602  * systems) and a certain popup is therefore only relevant to a single image.
28603  * Popups related to a certain image should be removed when moving
28604  * to another image.
28605  *
28606  * A popup must have both its content and its point or rect set to be
28607  * rendered. Popup options can not be updated after creation but the
28608  * basic point or rect as well as its content can be changed by calling
28609  * the appropriate methods.
28610  *
28611  * To create and add one `Popup` with default configuration
28612  * (tooltip visuals and automatic float) and one with specific options
28613  * use
28614  *
28615  * @example
28616  * ```
28617  * var defaultSpan = document.createElement('span');
28618  * defaultSpan.innerHTML = 'hello default';
28619  *
28620  * var defaultPopup = new Mapillary.PopupComponent.Popup();
28621  * defaultPopup.setDOMContent(defaultSpan);
28622  * defaultPopup.setBasicPoint([0.3, 0.3]);
28623  *
28624  * var cleanSpan = document.createElement('span');
28625  * cleanSpan.innerHTML = 'hello clean';
28626  *
28627  * var cleanPopup = new Mapillary.PopupComponent.Popup({
28628  *     clean: true,
28629  *     float: Mapillary.Alignment.Top,
28630  *     offset: 10,
28631  *     opacity: 0.7,
28632  * });
28633  *
28634  * cleanPopup.setDOMContent(cleanSpan);
28635  * cleanPopup.setBasicPoint([0.6, 0.6]);
28636  *
28637  * popupComponent.add([defaultPopup, cleanPopup]);
28638  * ```
28639  *
28640  * @description Implementation of API methods and API documentation inspired
28641  * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
28642  */
28643 var Popup = /** @class */ (function () {
28644     function Popup(options, viewportCoords, dom) {
28645         this._options = {};
28646         options = !!options ? options : {};
28647         this._options.capturePointer = options.capturePointer === false ?
28648             options.capturePointer : true;
28649         this._options.clean = options.clean;
28650         this._options.float = options.float;
28651         this._options.offset = options.offset;
28652         this._options.opacity = options.opacity;
28653         this._options.position = options.position;
28654         this._dom = !!dom ? dom : new Utils_1.DOM();
28655         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
28656         this._notifyChanged$ = new rxjs_1.Subject();
28657     }
28658     Object.defineProperty(Popup.prototype, "changed$", {
28659         /**
28660          * @description Internal observable used by the component to
28661          * render the popup when its position or content has changed.
28662          * @ignore
28663          */
28664         get: function () {
28665             return this._notifyChanged$;
28666         },
28667         enumerable: true,
28668         configurable: true
28669     });
28670     /**
28671      * @description Internal method used by the component to
28672      * remove all references to the popup.
28673      * @ignore
28674      */
28675     Popup.prototype.remove = function () {
28676         if (this._content && this._content.parentNode) {
28677             this._content.parentNode.removeChild(this._content);
28678         }
28679         if (this._container) {
28680             this._container.parentNode.removeChild(this._container);
28681             delete this._container;
28682         }
28683         if (this._parentContainer) {
28684             delete this._parentContainer;
28685         }
28686     };
28687     /**
28688      * Sets a 2D basic image coordinates point to the popup's anchor, and
28689      * moves the popup to it.
28690      *
28691      * @description Overwrites any previously set point or rect.
28692      *
28693      * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
28694      *
28695      * @example
28696      * ```
28697      * var popup = new Mapillary.PopupComponent.Popup();
28698      * popup.setText('hello image');
28699      * popup.setBasicPoint([0.3, 0.3]);
28700      *
28701      * popupComponent.add([popup]);
28702      * ```
28703      */
28704     Popup.prototype.setBasicPoint = function (basicPoint) {
28705         this._point = basicPoint.slice();
28706         this._rect = null;
28707         this._notifyChanged$.next(this);
28708     };
28709     /**
28710      * Sets a 2D basic image coordinates rect to the popup's anchor, and
28711      * moves the popup to it.
28712      *
28713      * @description Overwrites any previously set point or rect.
28714      *
28715      * @param {Array<number>} basicRect - Rect in 2D basic image
28716      * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
28717      *
28718      * @example
28719      * ```
28720      * var popup = new Mapillary.PopupComponent.Popup();
28721      * popup.setText('hello image');
28722      * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
28723      *
28724      * popupComponent.add([popup]);
28725      * ```
28726      */
28727     Popup.prototype.setBasicRect = function (basicRect) {
28728         this._rect = basicRect.slice();
28729         this._point = null;
28730         this._notifyChanged$.next(this);
28731     };
28732     /**
28733      * Sets the popup's content to the element provided as a DOM node.
28734      *
28735      * @param {Node} htmlNode - A DOM node to be used as content for the popup.
28736      *
28737      * @example
28738      * ```
28739      * var div = document.createElement('div');
28740      * div.innerHTML = 'hello image';
28741      *
28742      * var popup = new Mapillary.PopupComponent.Popup();
28743      * popup.setDOMContent(div);
28744      * popup.setBasicPoint([0.3, 0.3]);
28745      *
28746      * popupComponent.add([popup]);
28747      * ```
28748      */
28749     Popup.prototype.setDOMContent = function (htmlNode) {
28750         if (this._content && this._content.parentNode) {
28751             this._content.parentNode.removeChild(this._content);
28752         }
28753         var className = "mapillaryjs-popup-content" +
28754             (this._options.clean === true ? "-clean" : "") +
28755             (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
28756         this._content = this._dom.createElement("div", className, this._container);
28757         this._content.appendChild(htmlNode);
28758         this._notifyChanged$.next(this);
28759     };
28760     /**
28761      * Sets the popup's content to the HTML provided as a string.
28762      *
28763      * @description This method does not perform HTML filtering or sanitization,
28764      * and must be used only with trusted content. Consider Popup#setText if the
28765      * content is an untrusted text string.
28766      *
28767      * @param {string} html - A string representing HTML content for the popup.
28768      *
28769      * @example
28770      * ```
28771      * var popup = new Mapillary.PopupComponent.Popup();
28772      * popup.setHTML('<div>hello image</div>');
28773      * popup.setBasicPoint([0.3, 0.3]);
28774      *
28775      * popupComponent.add([popup]);
28776      * ```
28777      */
28778     Popup.prototype.setHTML = function (html) {
28779         var frag = this._dom.document.createDocumentFragment();
28780         var temp = this._dom.createElement("body");
28781         var child;
28782         temp.innerHTML = html;
28783         while (true) {
28784             child = temp.firstChild;
28785             if (!child) {
28786                 break;
28787             }
28788             frag.appendChild(child);
28789         }
28790         this.setDOMContent(frag);
28791     };
28792     /**
28793      * Sets the popup's content to a string of text.
28794      *
28795      * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
28796      * Use this method for security against XSS if the popup content is user-provided.
28797      *
28798      * @param {string} text - Textual content for the popup.
28799      *
28800      * @example
28801      * ```
28802      * var popup = new Mapillary.PopupComponent.Popup();
28803      * popup.setText('hello image');
28804      * popup.setBasicPoint([0.3, 0.3]);
28805      *
28806      * popupComponent.add([popup]);
28807      * ```
28808      */
28809     Popup.prototype.setText = function (text) {
28810         this.setDOMContent(this._dom.document.createTextNode(text));
28811     };
28812     /**
28813      * @description Internal method for attaching the popup to
28814      * its parent container so that it is rendered in the DOM tree.
28815      * @ignore
28816      */
28817     Popup.prototype.setParentContainer = function (parentContainer) {
28818         this._parentContainer = parentContainer;
28819     };
28820     /**
28821      * @description Internal method for updating the rendered
28822      * position of the popup called by the popup component.
28823      * @ignore
28824      */
28825     Popup.prototype.update = function (renderCamera, size, transform) {
28826         var _a;
28827         if (!this._parentContainer || !this._content) {
28828             return;
28829         }
28830         if (!this._point && !this._rect) {
28831             return;
28832         }
28833         if (!this._container) {
28834             this._container = this._dom.createElement("div", "mapillaryjs-popup", this._parentContainer);
28835             var showTip = this._options.clean !== true &&
28836                 this._options.float !== Viewer_1.Alignment.Center;
28837             if (showTip) {
28838                 var tipClassName = "mapillaryjs-popup-tip" +
28839                     (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
28840                 this._tip = this._dom.createElement("div", tipClassName, this._container);
28841                 this._dom.createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
28842             }
28843             this._container.appendChild(this._content);
28844             this._parentContainer.appendChild(this._container);
28845             if (this._options.opacity != null) {
28846                 this._container.style.opacity = this._options.opacity.toString();
28847             }
28848         }
28849         var pointPixel = null;
28850         var position = this._alignmentToPopupAligment(this._options.position);
28851         var float = this._alignmentToPopupAligment(this._options.float);
28852         var classList = this._container.classList;
28853         if (this._point != null) {
28854             pointPixel =
28855                 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
28856         }
28857         else {
28858             var alignments = ["center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
28859             var appliedPosition = null;
28860             for (var _i = 0, alignments_1 = alignments; _i < alignments_1.length; _i++) {
28861                 var alignment = alignments_1[_i];
28862                 if (classList.contains("mapillaryjs-popup-float-" + alignment)) {
28863                     appliedPosition = alignment;
28864                     break;
28865                 }
28866             }
28867             _a = this._rectToPixel(this._rect, position, appliedPosition, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
28868             if (!float) {
28869                 float = position;
28870             }
28871         }
28872         if (pointPixel == null) {
28873             this._container.style.display = "none";
28874             return;
28875         }
28876         this._container.style.display = "";
28877         if (!float) {
28878             var width = this._container.offsetWidth;
28879             var height = this._container.offsetHeight;
28880             var floats = this._pixelToFloats(pointPixel, size, width, height);
28881             float = floats.length === 0 ? "top" : floats.join("-");
28882         }
28883         var offset = this._normalizeOffset(this._options.offset);
28884         pointPixel = [pointPixel[0] + offset[float][0], pointPixel[1] + offset[float][1]];
28885         pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
28886         var floatTranslate = {
28887             "bottom": "translate(-50%,0)",
28888             "bottom-left": "translate(-100%,0)",
28889             "bottom-right": "translate(0,0)",
28890             "center": "translate(-50%,-50%)",
28891             "left": "translate(-100%,-50%)",
28892             "right": "translate(0,-50%)",
28893             "top": "translate(-50%,-100%)",
28894             "top-left": "translate(-100%,-100%)",
28895             "top-right": "translate(0,-100%)",
28896         };
28897         for (var key in floatTranslate) {
28898             if (!floatTranslate.hasOwnProperty(key)) {
28899                 continue;
28900             }
28901             classList.remove("mapillaryjs-popup-float-" + key);
28902         }
28903         classList.add("mapillaryjs-popup-float-" + float);
28904         this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
28905     };
28906     Popup.prototype._rectToPixel = function (rect, position, appliedPosition, renderCamera, size, transform) {
28907         if (!position) {
28908             var width = this._container.offsetWidth;
28909             var height = this._container.offsetHeight;
28910             var floatOffsets = {
28911                 "bottom": [0, height / 2],
28912                 "bottom-left": [-width / 2, height / 2],
28913                 "bottom-right": [width / 2, height / 2],
28914                 "left": [-width / 2, 0],
28915                 "right": [width / 2, 0],
28916                 "top": [0, -height / 2],
28917                 "top-left": [-width / 2, -height / 2],
28918                 "top-right": [width / 2, -height / 2],
28919             };
28920             var automaticPositions = ["top", "bottom", "left", "right"];
28921             var largestVisibleArea = [0, null, null];
28922             for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
28923                 var automaticPosition = automaticPositions_1[_i];
28924                 var autoPointBasic = this._pointFromRectPosition(rect, automaticPosition);
28925                 var autoPointPixel = this._viewportCoords.basicToCanvasSafe(autoPointBasic[0], autoPointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
28926                 if (autoPointPixel == null) {
28927                     continue;
28928                 }
28929                 var floatOffset = floatOffsets[automaticPosition];
28930                 var offsetedPosition = [autoPointPixel[0] + floatOffset[0], autoPointPixel[1] + floatOffset[1]];
28931                 var staticCoeff = appliedPosition != null && appliedPosition === automaticPosition ? 1 : 0.7;
28932                 var floats = this._pixelToFloats(offsetedPosition, size, width / staticCoeff, height / (2 * staticCoeff));
28933                 if (floats.length === 0 &&
28934                     autoPointPixel[0] > 0 &&
28935                     autoPointPixel[0] < size.width &&
28936                     autoPointPixel[1] > 0 &&
28937                     autoPointPixel[1] < size.height) {
28938                     return [autoPointPixel, automaticPosition];
28939                 }
28940                 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
28941                 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
28942                 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
28943                 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
28944                 var visibleX = Math.max(0, maxX - minX);
28945                 var visibleY = Math.max(0, maxY - minY);
28946                 var visibleArea = staticCoeff * visibleX * visibleY;
28947                 if (visibleArea > largestVisibleArea[0]) {
28948                     largestVisibleArea[0] = visibleArea;
28949                     largestVisibleArea[1] = autoPointPixel;
28950                     largestVisibleArea[2] = automaticPosition;
28951                 }
28952             }
28953             if (largestVisibleArea[0] > 0) {
28954                 return [largestVisibleArea[1], largestVisibleArea[2]];
28955             }
28956         }
28957         var pointBasic = this._pointFromRectPosition(rect, position);
28958         var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
28959         return [pointPixel, position != null ? position : "top"];
28960     };
28961     Popup.prototype._alignmentToPopupAligment = function (float) {
28962         switch (float) {
28963             case Viewer_1.Alignment.Bottom:
28964                 return "bottom";
28965             case Viewer_1.Alignment.BottomLeft:
28966                 return "bottom-left";
28967             case Viewer_1.Alignment.BottomRight:
28968                 return "bottom-right";
28969             case Viewer_1.Alignment.Center:
28970                 return "center";
28971             case Viewer_1.Alignment.Left:
28972                 return "left";
28973             case Viewer_1.Alignment.Right:
28974                 return "right";
28975             case Viewer_1.Alignment.Top:
28976                 return "top";
28977             case Viewer_1.Alignment.TopLeft:
28978                 return "top-left";
28979             case Viewer_1.Alignment.TopRight:
28980                 return "top-right";
28981             default:
28982                 return null;
28983         }
28984     };
28985     Popup.prototype._normalizeOffset = function (offset) {
28986         if (offset == null) {
28987             return this._normalizeOffset(0);
28988         }
28989         if (typeof offset === "number") {
28990             // input specifies a radius
28991             var sideOffset = offset;
28992             var sign = sideOffset >= 0 ? 1 : -1;
28993             var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(sideOffset, 2)));
28994             return {
28995                 "bottom": [0, sideOffset],
28996                 "bottom-left": [-cornerOffset, cornerOffset],
28997                 "bottom-right": [cornerOffset, cornerOffset],
28998                 "center": [0, 0],
28999                 "left": [-sideOffset, 0],
29000                 "right": [sideOffset, 0],
29001                 "top": [0, -sideOffset],
29002                 "top-left": [-cornerOffset, -cornerOffset],
29003                 "top-right": [cornerOffset, -cornerOffset],
29004             };
29005         }
29006         else {
29007             // input specifes a value for each position
29008             return {
29009                 "bottom": offset.bottom || [0, 0],
29010                 "bottom-left": offset.bottomLeft || [0, 0],
29011                 "bottom-right": offset.bottomRight || [0, 0],
29012                 "center": offset.center || [0, 0],
29013                 "left": offset.left || [0, 0],
29014                 "right": offset.right || [0, 0],
29015                 "top": offset.top || [0, 0],
29016                 "top-left": offset.topLeft || [0, 0],
29017                 "top-right": offset.topRight || [0, 0],
29018             };
29019         }
29020     };
29021     Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
29022         var floats = [];
29023         if (pointPixel[1] < height) {
29024             floats.push("bottom");
29025         }
29026         else if (pointPixel[1] > size.height - height) {
29027             floats.push("top");
29028         }
29029         if (pointPixel[0] < width / 2) {
29030             floats.push("right");
29031         }
29032         else if (pointPixel[0] > size.width - width / 2) {
29033             floats.push("left");
29034         }
29035         return floats;
29036     };
29037     Popup.prototype._pointFromRectPosition = function (rect, position) {
29038         var x0 = rect[0];
29039         var x1 = rect[0] < rect[2] ? rect[2] : rect[2] + 1;
29040         var y0 = rect[1];
29041         var y1 = rect[3];
29042         switch (position) {
29043             case "bottom":
29044                 return [(x0 + x1) / 2, y1];
29045             case "bottom-left":
29046                 return [x0, y1];
29047             case "bottom-right":
29048                 return [x1, y1];
29049             case "center":
29050                 return [(x0 + x1) / 2, (y0 + y1) / 2];
29051             case "left":
29052                 return [x0, (y0 + y1) / 2];
29053             case "right":
29054                 return [x1, (y0 + y1) / 2];
29055             case "top":
29056                 return [(x0 + x1) / 2, y0];
29057             case "top-left":
29058                 return [x0, y0];
29059             case "top-right":
29060                 return [x1, y0];
29061             default:
29062                 return [(x0 + x1) / 2, y1];
29063         }
29064     };
29065     return Popup;
29066 }());
29067 exports.Popup = Popup;
29068 exports.default = Popup;
29069
29070
29071 },{"../../../Geo":278,"../../../Utils":285,"../../../Viewer":286,"rxjs":27}],333:[function(require,module,exports){
29072 "use strict";
29073 var __extends = (this && this.__extends) || (function () {
29074     var extendStatics = function (d, b) {
29075         extendStatics = Object.setPrototypeOf ||
29076             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29077             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29078         return extendStatics(d, b);
29079     }
29080     return function (d, b) {
29081         extendStatics(d, b);
29082         function __() { this.constructor = d; }
29083         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29084     };
29085 })();
29086 Object.defineProperty(exports, "__esModule", { value: true });
29087 var rxjs_1 = require("rxjs");
29088 var operators_1 = require("rxjs/operators");
29089 var Component_1 = require("../../Component");
29090 var Edge_1 = require("../../Edge");
29091 var Graph_1 = require("../../Graph");
29092 /**
29093  * @class SequenceComponent
29094  * @classdesc Component showing navigation arrows for sequence directions
29095  * as well as playing button. Exposes an API to start and stop play.
29096  */
29097 var SequenceComponent = /** @class */ (function (_super) {
29098     __extends(SequenceComponent, _super);
29099     function SequenceComponent(name, container, navigator, renderer, scheduler) {
29100         var _this = _super.call(this, name, container, navigator) || this;
29101         _this._sequenceDOMRenderer = !!renderer ? renderer : new Component_1.SequenceDOMRenderer(container);
29102         _this._scheduler = scheduler;
29103         _this._containerWidth$ = new rxjs_1.Subject();
29104         _this._hoveredKeySubject$ = new rxjs_1.Subject();
29105         _this._hoveredKey$ = _this._hoveredKeySubject$.pipe(operators_1.share());
29106         _this._navigator.playService.playing$.pipe(operators_1.skip(1), operators_1.withLatestFrom(_this._configuration$))
29107             .subscribe(function (_a) {
29108             var playing = _a[0], configuration = _a[1];
29109             _this.fire(SequenceComponent.playingchanged, playing);
29110             if (playing === configuration.playing) {
29111                 return;
29112             }
29113             if (playing) {
29114                 _this.play();
29115             }
29116             else {
29117                 _this.stop();
29118             }
29119         });
29120         _this._navigator.playService.direction$.pipe(operators_1.skip(1), operators_1.withLatestFrom(_this._configuration$))
29121             .subscribe(function (_a) {
29122             var direction = _a[0], configuration = _a[1];
29123             if (direction !== configuration.direction) {
29124                 _this.setDirection(direction);
29125             }
29126         });
29127         return _this;
29128     }
29129     Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
29130         /**
29131          * Get hovered key observable.
29132          *
29133          * @description An observable emitting the key of the node for the direction
29134          * arrow that is being hovered. When the mouse leaves a direction arrow null
29135          * is emitted.
29136          *
29137          * @returns {Observable<string>}
29138          */
29139         get: function () {
29140             return this._hoveredKey$;
29141         },
29142         enumerable: true,
29143         configurable: true
29144     });
29145     /**
29146      * Start playing.
29147      *
29148      * @fires PlayerComponent#playingchanged
29149      */
29150     SequenceComponent.prototype.play = function () {
29151         this.configure({ playing: true });
29152     };
29153     /**
29154      * Stop playing.
29155      *
29156      * @fires PlayerComponent#playingchanged
29157      */
29158     SequenceComponent.prototype.stop = function () {
29159         this.configure({ playing: false });
29160     };
29161     /**
29162      * Set the direction to follow when playing.
29163      *
29164      * @param {EdgeDirection} direction - The direction that will be followed when playing.
29165      */
29166     SequenceComponent.prototype.setDirection = function (direction) {
29167         this.configure({ direction: direction });
29168     };
29169     /**
29170      * Set highlight key.
29171      *
29172      * @description The arrow pointing towards the node corresponding to the
29173      * highlight key will be highlighted.
29174      *
29175      * @param {string} highlightKey Key of node to be highlighted if existing.
29176      */
29177     SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
29178         this.configure({ highlightKey: highlightKey });
29179     };
29180     /**
29181      * Set max width of container element.
29182      *
29183      * @description Set max width of the container element holding
29184      * the sequence navigation elements. If the min width is larger than the
29185      * max width the min width value will be used.
29186      *
29187      * The container element is automatically resized when the resize
29188      * method on the Viewer class is called.
29189      *
29190      * @param {number} minWidth
29191      */
29192     SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
29193         this.configure({ maxWidth: maxWidth });
29194     };
29195     /**
29196      * Set min width of container element.
29197      *
29198      * @description Set min width of the container element holding
29199      * the sequence navigation elements. If the min width is larger than the
29200      * max width the min width value will be used.
29201      *
29202      * The container element is automatically resized when the resize
29203      * method on the Viewer class is called.
29204      *
29205      * @param {number} minWidth
29206      */
29207     SequenceComponent.prototype.setMinWidth = function (minWidth) {
29208         this.configure({ minWidth: minWidth });
29209     };
29210     /**
29211      * Set the value indicating whether the sequence UI elements should be visible.
29212      *
29213      * @param {boolean} visible
29214      */
29215     SequenceComponent.prototype.setVisible = function (visible) {
29216         this.configure({ visible: visible });
29217     };
29218     SequenceComponent.prototype._activate = function () {
29219         var _this = this;
29220         this._sequenceDOMRenderer.activate();
29221         var edgeStatus$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
29222             return node.sequenceEdges$;
29223         }), operators_1.publishReplay(1), operators_1.refCount());
29224         var sequence$ = this._navigator.stateService.currentNode$.pipe(operators_1.distinctUntilChanged(undefined, function (node) {
29225             return node.sequenceKey;
29226         }), operators_1.switchMap(function (node) {
29227             return rxjs_1.concat(rxjs_1.of(null), _this._navigator.graphService.cacheSequence$(node.sequenceKey).pipe(operators_1.retry(3), operators_1.catchError(function (e) {
29228                 console.error("Failed to cache sequence", e);
29229                 return rxjs_1.of(null);
29230             })));
29231         }), operators_1.startWith(null), operators_1.publishReplay(1), operators_1.refCount());
29232         this._sequenceSubscription = sequence$.subscribe();
29233         var rendererKey$ = this._sequenceDOMRenderer.index$.pipe(operators_1.withLatestFrom(sequence$), operators_1.map(function (_a) {
29234             var index = _a[0], sequence = _a[1];
29235             return sequence != null ? sequence.keys[index] : null;
29236         }), operators_1.filter(function (key) {
29237             return !!key;
29238         }), operators_1.distinctUntilChanged(), operators_1.publish(), operators_1.refCount());
29239         this._moveSubscription = rxjs_1.merge(rendererKey$.pipe(operators_1.debounceTime(100, this._scheduler)), rendererKey$.pipe(operators_1.auditTime(400, this._scheduler))).pipe(operators_1.distinctUntilChanged(), operators_1.switchMap(function (key) {
29240             return _this._navigator.moveToKey$(key).pipe(operators_1.catchError(function (e) {
29241                 return rxjs_1.empty();
29242             }));
29243         }))
29244             .subscribe();
29245         this._setSequenceGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
29246             return changing;
29247         }))
29248             .subscribe(function () {
29249             _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Sequence);
29250         });
29251         this._setSpatialGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
29252             return !changing;
29253         }))
29254             .subscribe(function () {
29255             _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Spatial);
29256         });
29257         this._navigator.graphService.graphMode$.pipe(operators_1.switchMap(function (mode) {
29258             return mode === Graph_1.GraphMode.Spatial ?
29259                 _this._navigator.stateService.currentNode$.pipe(operators_1.take(2)) :
29260                 rxjs_1.empty();
29261         }), operators_1.filter(function (node) {
29262             return !node.spatialEdges.cached;
29263         }), operators_1.switchMap(function (node) {
29264             return _this._navigator.graphService.cacheNode$(node.key).pipe(operators_1.catchError(function (e) {
29265                 return rxjs_1.empty();
29266             }));
29267         }))
29268             .subscribe();
29269         this._stopSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
29270             return changing;
29271         }))
29272             .subscribe(function () {
29273             _this._navigator.playService.stop();
29274         });
29275         this._cacheSequenceNodesSubscription = rxjs_1.combineLatest(this._navigator.graphService.graphMode$, this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.startWith(false), operators_1.distinctUntilChanged())).pipe(operators_1.withLatestFrom(this._navigator.stateService.currentNode$), operators_1.switchMap(function (_a) {
29276             var _b = _a[0], mode = _b[0], changing = _b[1], node = _a[1];
29277             return changing && mode === Graph_1.GraphMode.Sequence ?
29278                 _this._navigator.graphService.cacheSequenceNodes$(node.sequenceKey, node.key).pipe(operators_1.retry(3), operators_1.catchError(function (error) {
29279                     console.error("Failed to cache sequence nodes.", error);
29280                     return rxjs_1.empty();
29281                 })) :
29282                 rxjs_1.empty();
29283         }))
29284             .subscribe();
29285         var position$ = sequence$.pipe(operators_1.switchMap(function (sequence) {
29286             if (!sequence) {
29287                 return rxjs_1.of({ index: null, max: null });
29288             }
29289             var firstCurrentKey = true;
29290             return _this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.startWith(false), operators_1.distinctUntilChanged(), operators_1.switchMap(function (changingPosition) {
29291                 var skipCount = !changingPosition && firstCurrentKey ? 0 : 1;
29292                 firstCurrentKey = false;
29293                 return changingPosition ?
29294                     rendererKey$ :
29295                     _this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
29296                         return node.key;
29297                     }), operators_1.distinctUntilChanged(), operators_1.skip(skipCount));
29298             }), operators_1.map(function (key) {
29299                 var index = sequence.keys.indexOf(key);
29300                 if (index === -1) {
29301                     return { index: null, max: null };
29302                 }
29303                 return { index: index, max: sequence.keys.length - 1 };
29304             }));
29305         }));
29306         this._renderSubscription = rxjs_1.combineLatest(edgeStatus$, this._configuration$, this._containerWidth$, this._sequenceDOMRenderer.changed$.pipe(operators_1.startWith(this._sequenceDOMRenderer)), this._navigator.playService.speed$, position$).pipe(operators_1.map(function (_a) {
29307             var edgeStatus = _a[0], configuration = _a[1], containerWidth = _a[2], renderer = _a[3], speed = _a[4], position = _a[5];
29308             var vNode = _this._sequenceDOMRenderer
29309                 .render(edgeStatus, configuration, containerWidth, speed, position.index, position.max, _this, _this._navigator);
29310             return { name: _this._name, vnode: vNode };
29311         }))
29312             .subscribe(this._container.domRenderer.render$);
29313         this._setSpeedSubscription = this._sequenceDOMRenderer.speed$
29314             .subscribe(function (speed) {
29315             _this._navigator.playService.setSpeed(speed);
29316         });
29317         this._setDirectionSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
29318             return configuration.direction;
29319         }), operators_1.distinctUntilChanged())
29320             .subscribe(function (direction) {
29321             _this._navigator.playService.setDirection(direction);
29322         });
29323         this._containerWidthSubscription = rxjs_1.combineLatest(this._container.renderService.size$, this._configuration$.pipe(operators_1.distinctUntilChanged(function (value1, value2) {
29324             return value1[0] === value2[0] && value1[1] === value2[1];
29325         }, function (configuration) {
29326             return [configuration.minWidth, configuration.maxWidth];
29327         }))).pipe(operators_1.map(function (_a) {
29328             var size = _a[0], configuration = _a[1];
29329             return _this._sequenceDOMRenderer.getContainerWidth(size, configuration);
29330         }))
29331             .subscribe(this._containerWidth$);
29332         this._playingSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
29333             return configuration.playing;
29334         }), operators_1.distinctUntilChanged())
29335             .subscribe(function (playing) {
29336             if (playing) {
29337                 _this._navigator.playService.play();
29338             }
29339             else {
29340                 _this._navigator.playService.stop();
29341             }
29342         });
29343         this._hoveredKeySubscription = this._sequenceDOMRenderer.mouseEnterDirection$.pipe(operators_1.switchMap(function (direction) {
29344             var edgeTo$ = edgeStatus$.pipe(operators_1.map(function (edgeStatus) {
29345                 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
29346                     var edge = _a[_i];
29347                     if (edge.data.direction === direction) {
29348                         return edge.to;
29349                     }
29350                 }
29351                 return null;
29352             }), operators_1.takeUntil(_this._sequenceDOMRenderer.mouseLeaveDirection$));
29353             return rxjs_1.concat(edgeTo$, rxjs_1.of(null));
29354         }), operators_1.distinctUntilChanged())
29355             .subscribe(this._hoveredKeySubject$);
29356         this._emitHoveredKeySubscription = this._hoveredKey$
29357             .subscribe(function (key) {
29358             _this.fire(SequenceComponent.hoveredkeychanged, key);
29359         });
29360     };
29361     SequenceComponent.prototype._deactivate = function () {
29362         this._emitHoveredKeySubscription.unsubscribe();
29363         this._renderSubscription.unsubscribe();
29364         this._playingSubscription.unsubscribe();
29365         this._containerWidthSubscription.unsubscribe();
29366         this._hoveredKeySubscription.unsubscribe();
29367         this._setSpeedSubscription.unsubscribe();
29368         this._setDirectionSubscription.unsubscribe();
29369         this._setSequenceGraphModeSubscription.unsubscribe();
29370         this._setSpatialGraphModeSubscription.unsubscribe();
29371         this._sequenceSubscription.unsubscribe();
29372         this._moveSubscription.unsubscribe();
29373         this._cacheSequenceNodesSubscription.unsubscribe();
29374         this._stopSubscription.unsubscribe();
29375         this._sequenceDOMRenderer.deactivate();
29376     };
29377     SequenceComponent.prototype._getDefaultConfiguration = function () {
29378         return {
29379             direction: Edge_1.EdgeDirection.Next,
29380             maxWidth: 108,
29381             minWidth: 70,
29382             playing: false,
29383             visible: true,
29384         };
29385     };
29386     /** @inheritdoc */
29387     SequenceComponent.componentName = "sequence";
29388     /**
29389      * Event fired when playing starts or stops.
29390      *
29391      * @event SequenceComponent#playingchanged
29392      * @type {boolean} Indicates whether the player is playing.
29393      */
29394     SequenceComponent.playingchanged = "playingchanged";
29395     /**
29396      * Event fired when the hovered key changes.
29397      *
29398      * @description Emits the key of the node for the direction
29399      * arrow that is being hovered. When the mouse leaves a
29400      * direction arrow null is emitted.
29401      *
29402      * @event SequenceComponent#hoveredkeychanged
29403      * @type {string} The hovered key, null if no key is hovered.
29404      */
29405     SequenceComponent.hoveredkeychanged = "hoveredkeychanged";
29406     return SequenceComponent;
29407 }(Component_1.Component));
29408 exports.SequenceComponent = SequenceComponent;
29409 Component_1.ComponentService.register(SequenceComponent);
29410 exports.default = SequenceComponent;
29411
29412 },{"../../Component":275,"../../Edge":276,"../../Graph":279,"rxjs":27,"rxjs/operators":225}],334:[function(require,module,exports){
29413 "use strict";
29414 Object.defineProperty(exports, "__esModule", { value: true });
29415 var rxjs_1 = require("rxjs");
29416 var operators_1 = require("rxjs/operators");
29417 var vd = require("virtual-dom");
29418 var Component_1 = require("../../Component");
29419 var Edge_1 = require("../../Edge");
29420 var Error_1 = require("../../Error");
29421 var SequenceDOMRenderer = /** @class */ (function () {
29422     function SequenceDOMRenderer(container) {
29423         this._container = container;
29424         this._minThresholdWidth = 320;
29425         this._maxThresholdWidth = 1480;
29426         this._minThresholdHeight = 240;
29427         this._maxThresholdHeight = 820;
29428         this._stepperDefaultWidth = 108;
29429         this._controlsDefaultWidth = 88;
29430         this._defaultHeight = 30;
29431         this._expandControls = false;
29432         this._mode = Component_1.SequenceMode.Default;
29433         this._speed = 0.5;
29434         this._changingSpeed = false;
29435         this._index = null;
29436         this._changingPosition = false;
29437         this._mouseEnterDirection$ = new rxjs_1.Subject();
29438         this._mouseLeaveDirection$ = new rxjs_1.Subject();
29439         this._notifyChanged$ = new rxjs_1.Subject();
29440         this._notifyChangingPositionChanged$ = new rxjs_1.Subject();
29441         this._notifySpeedChanged$ = new rxjs_1.Subject();
29442         this._notifyIndexChanged$ = new rxjs_1.Subject();
29443     }
29444     Object.defineProperty(SequenceDOMRenderer.prototype, "changed$", {
29445         get: function () {
29446             return this._notifyChanged$;
29447         },
29448         enumerable: true,
29449         configurable: true
29450     });
29451     Object.defineProperty(SequenceDOMRenderer.prototype, "changingPositionChanged$", {
29452         get: function () {
29453             return this._notifyChangingPositionChanged$;
29454         },
29455         enumerable: true,
29456         configurable: true
29457     });
29458     Object.defineProperty(SequenceDOMRenderer.prototype, "speed$", {
29459         get: function () {
29460             return this._notifySpeedChanged$;
29461         },
29462         enumerable: true,
29463         configurable: true
29464     });
29465     Object.defineProperty(SequenceDOMRenderer.prototype, "index$", {
29466         get: function () {
29467             return this._notifyIndexChanged$;
29468         },
29469         enumerable: true,
29470         configurable: true
29471     });
29472     Object.defineProperty(SequenceDOMRenderer.prototype, "mouseEnterDirection$", {
29473         get: function () {
29474             return this._mouseEnterDirection$;
29475         },
29476         enumerable: true,
29477         configurable: true
29478     });
29479     Object.defineProperty(SequenceDOMRenderer.prototype, "mouseLeaveDirection$", {
29480         get: function () {
29481             return this._mouseLeaveDirection$;
29482         },
29483         enumerable: true,
29484         configurable: true
29485     });
29486     SequenceDOMRenderer.prototype.activate = function () {
29487         var _this = this;
29488         if (!!this._changingSubscription) {
29489             return;
29490         }
29491         this._changingSubscription = rxjs_1.merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$.pipe(operators_1.filter(function (touchEvent) {
29492             return touchEvent.touches.length === 0;
29493         })))
29494             .subscribe(function (event) {
29495             if (_this._changingSpeed) {
29496                 _this._changingSpeed = false;
29497             }
29498             if (_this._changingPosition) {
29499                 _this._setChangingPosition(false);
29500             }
29501         });
29502     };
29503     SequenceDOMRenderer.prototype.deactivate = function () {
29504         if (!this._changingSubscription) {
29505             return;
29506         }
29507         this._changingSpeed = false;
29508         this._changingPosition = false;
29509         this._expandControls = false;
29510         this._mode = Component_1.SequenceMode.Default;
29511         this._changingSubscription.unsubscribe();
29512         this._changingSubscription = null;
29513     };
29514     SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, speed, index, max, component, navigator) {
29515         if (configuration.visible === false) {
29516             return vd.h("div.SequenceContainer", {}, []);
29517         }
29518         var stepper = this._createStepper(edgeStatus, configuration, containerWidth, component, navigator);
29519         var controls = this._createSequenceControls(containerWidth);
29520         var playback = this._createPlaybackControls(containerWidth, speed, component, configuration);
29521         var timeline = this._createTimelineControls(containerWidth, index, max);
29522         return vd.h("div.SequenceContainer", [stepper, controls, playback, timeline]);
29523     };
29524     SequenceDOMRenderer.prototype.getContainerWidth = function (size, configuration) {
29525         var minWidth = configuration.minWidth;
29526         var maxWidth = configuration.maxWidth;
29527         if (maxWidth < minWidth) {
29528             maxWidth = minWidth;
29529         }
29530         var relativeWidth = (size.width - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
29531         var relativeHeight = (size.height - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
29532         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
29533         return minWidth + coeff * (maxWidth - minWidth);
29534     };
29535     SequenceDOMRenderer.prototype._createPositionInput = function (index, max) {
29536         var _this = this;
29537         this._index = index;
29538         var onPosition = function (e) {
29539             _this._index = Number(e.target.value);
29540             _this._notifyIndexChanged$.next(_this._index);
29541         };
29542         var boundingRect = this._container.domContainer.getBoundingClientRect();
29543         var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 65;
29544         var onStart = function (e) {
29545             e.stopPropagation();
29546             _this._setChangingPosition(true);
29547         };
29548         var onMove = function (e) {
29549             if (_this._changingPosition === true) {
29550                 e.stopPropagation();
29551             }
29552         };
29553         var onKeyDown = function (e) {
29554             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
29555                 e.key === "ArrowRight" || e.key === "ArrowUp") {
29556                 e.preventDefault();
29557             }
29558         };
29559         var positionInputProperties = {
29560             max: max != null ? max : 1,
29561             min: 0,
29562             onchange: onPosition,
29563             oninput: onPosition,
29564             onkeydown: onKeyDown,
29565             onmousedown: onStart,
29566             onmousemove: onMove,
29567             ontouchmove: onMove,
29568             ontouchstart: onStart,
29569             style: {
29570                 width: width + "px",
29571             },
29572             type: "range",
29573             value: index != null ? index : 0,
29574         };
29575         var disabled = index == null || max == null || max <= 1;
29576         if (disabled) {
29577             positionInputProperties.disabled = "true";
29578         }
29579         var positionInput = vd.h("input.SequencePosition", positionInputProperties, []);
29580         var positionContainerClass = disabled ? ".SequencePositionContainerDisabled" : ".SequencePositionContainer";
29581         return vd.h("div" + positionContainerClass, [positionInput]);
29582     };
29583     SequenceDOMRenderer.prototype._createSpeedInput = function (speed) {
29584         var _this = this;
29585         this._speed = speed;
29586         var onSpeed = function (e) {
29587             _this._speed = Number(e.target.value) / 1000;
29588             _this._notifySpeedChanged$.next(_this._speed);
29589         };
29590         var boundingRect = this._container.domContainer.getBoundingClientRect();
29591         var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 160;
29592         var onStart = function (e) {
29593             _this._changingSpeed = true;
29594             e.stopPropagation();
29595         };
29596         var onMove = function (e) {
29597             if (_this._changingSpeed === true) {
29598                 e.stopPropagation();
29599             }
29600         };
29601         var onKeyDown = function (e) {
29602             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
29603                 e.key === "ArrowRight" || e.key === "ArrowUp") {
29604                 e.preventDefault();
29605             }
29606         };
29607         var speedInput = vd.h("input.SequenceSpeed", {
29608             max: 1000,
29609             min: 0,
29610             onchange: onSpeed,
29611             oninput: onSpeed,
29612             onkeydown: onKeyDown,
29613             onmousedown: onStart,
29614             onmousemove: onMove,
29615             ontouchmove: onMove,
29616             ontouchstart: onStart,
29617             style: {
29618                 width: width + "px",
29619             },
29620             type: "range",
29621             value: 1000 * speed,
29622         }, []);
29623         return vd.h("div.SequenceSpeedContainer", [speedInput]);
29624     };
29625     SequenceDOMRenderer.prototype._createPlaybackControls = function (containerWidth, speed, component, configuration) {
29626         var _this = this;
29627         if (this._mode !== Component_1.SequenceMode.Playback) {
29628             return vd.h("div.SequencePlayback", []);
29629         }
29630         var switchIcon = vd.h("div.SequenceSwitchIcon.SequenceIconVisible", []);
29631         var direction = configuration.direction === Edge_1.EdgeDirection.Next ?
29632             Edge_1.EdgeDirection.Prev : Edge_1.EdgeDirection.Next;
29633         var playing = configuration.playing;
29634         var switchButtonProperties = {
29635             onclick: function () {
29636                 if (!playing) {
29637                     component.setDirection(direction);
29638                 }
29639             },
29640         };
29641         var switchButtonClassName = configuration.playing ? ".SequenceSwitchButtonDisabled" : ".SequenceSwitchButton";
29642         var switchButton = vd.h("div" + switchButtonClassName, switchButtonProperties, [switchIcon]);
29643         var slowIcon = vd.h("div.SequenceSlowIcon.SequenceIconVisible", []);
29644         var slowContainer = vd.h("div.SequenceSlowContainer", [slowIcon]);
29645         var fastIcon = vd.h("div.SequenceFastIcon.SequenceIconVisible", []);
29646         var fastContainer = vd.h("div.SequenceFastContainer", [fastIcon]);
29647         var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
29648         var closeButtonProperties = {
29649             onclick: function () {
29650                 _this._mode = Component_1.SequenceMode.Default;
29651                 _this._notifyChanged$.next(_this);
29652             },
29653         };
29654         var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
29655         var speedInput = this._createSpeedInput(speed);
29656         var playbackChildren = [switchButton, slowContainer, speedInput, fastContainer, closeButton];
29657         var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
29658         var playbackProperties = { style: { top: top + "px" } };
29659         return vd.h("div.SequencePlayback", playbackProperties, playbackChildren);
29660     };
29661     SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
29662         var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
29663             configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
29664         var onclick = configuration.playing ?
29665             function (e) { component.stop(); } :
29666             canPlay ? function (e) { component.play(); } : null;
29667         var buttonProperties = { onclick: onclick };
29668         var iconClass = configuration.playing ?
29669             "Stop" :
29670             canPlay ? "Play" : "PlayDisabled";
29671         var iconProperties = { className: iconClass };
29672         if (configuration.direction === Edge_1.EdgeDirection.Prev) {
29673             iconProperties.style = {
29674                 transform: "rotate(180deg) translate(50%, 50%)",
29675             };
29676         }
29677         var icon = vd.h("div.SequenceComponentIcon", iconProperties, []);
29678         var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
29679         return vd.h("div." + buttonClass, buttonProperties, [icon]);
29680     };
29681     SequenceDOMRenderer.prototype._createSequenceControls = function (containerWidth) {
29682         var _this = this;
29683         var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
29684         var expanderProperties = {
29685             onclick: function () {
29686                 _this._expandControls = !_this._expandControls;
29687                 _this._mode = Component_1.SequenceMode.Default;
29688                 _this._notifyChanged$.next(_this);
29689             },
29690             style: {
29691                 "border-bottom-right-radius": borderRadius + "px",
29692                 "border-top-right-radius": borderRadius + "px",
29693             },
29694         };
29695         var expanderBar = vd.h("div.SequenceExpanderBar", []);
29696         var expander = vd.h("div.SequenceExpanderButton", expanderProperties, [expanderBar]);
29697         var fastIconClassName = this._mode === Component_1.SequenceMode.Playback ?
29698             ".SequenceFastIconGrey.SequenceIconVisible" : ".SequenceFastIcon";
29699         var fastIcon = vd.h("div" + fastIconClassName, []);
29700         var playbackProperties = {
29701             onclick: function () {
29702                 _this._mode = _this._mode === Component_1.SequenceMode.Playback ?
29703                     Component_1.SequenceMode.Default :
29704                     Component_1.SequenceMode.Playback;
29705                 _this._notifyChanged$.next(_this);
29706             },
29707         };
29708         var playback = vd.h("div.SequencePlaybackButton", playbackProperties, [fastIcon]);
29709         var timelineIconClassName = this._mode === Component_1.SequenceMode.Timeline ?
29710             ".SequenceTimelineIconGrey.SequenceIconVisible" : ".SequenceTimelineIcon";
29711         var timelineIcon = vd.h("div" + timelineIconClassName, []);
29712         var timelineProperties = {
29713             onclick: function () {
29714                 _this._mode = _this._mode === Component_1.SequenceMode.Timeline ?
29715                     Component_1.SequenceMode.Default :
29716                     Component_1.SequenceMode.Timeline;
29717                 _this._notifyChanged$.next(_this);
29718             },
29719         };
29720         var timeline = vd.h("div.SequenceTimelineButton", timelineProperties, [timelineIcon]);
29721         var properties = {
29722             style: {
29723                 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
29724                 transform: "translate(" + (containerWidth / 2 + 2) + "px, 0)",
29725                 width: (this._controlsDefaultWidth / this._stepperDefaultWidth * containerWidth) + "px",
29726             },
29727         };
29728         var className = ".SequenceControls" +
29729             (this._expandControls ? ".SequenceControlsExpanded" : "");
29730         return vd.h("div" + className, properties, [playback, timeline, expander]);
29731     };
29732     SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, containerWidth, configuration, navigator) {
29733         var _this = this;
29734         var nextProperties = {
29735             onclick: nextKey != null ?
29736                 function (e) {
29737                     navigator.moveDir$(Edge_1.EdgeDirection.Next)
29738                         .subscribe(undefined, function (error) {
29739                         if (!(error instanceof Error_1.AbortMapillaryError)) {
29740                             console.error(error);
29741                         }
29742                     });
29743                 } :
29744                 null,
29745             onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
29746             onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
29747         };
29748         var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
29749         var prevProperties = {
29750             onclick: prevKey != null ?
29751                 function (e) {
29752                     navigator.moveDir$(Edge_1.EdgeDirection.Prev)
29753                         .subscribe(undefined, function (error) {
29754                         if (!(error instanceof Error_1.AbortMapillaryError)) {
29755                             console.error(error);
29756                         }
29757                     });
29758                 } :
29759                 null,
29760             onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
29761             onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
29762             style: {
29763                 "border-bottom-left-radius": borderRadius + "px",
29764                 "border-top-left-radius": borderRadius + "px",
29765             },
29766         };
29767         var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
29768         var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
29769         var nextIcon = vd.h("div.SequenceComponentIcon", []);
29770         var prevIcon = vd.h("div.SequenceComponentIcon", []);
29771         return [
29772             vd.h("div." + prevClass, prevProperties, [prevIcon]),
29773             vd.h("div." + nextClass, nextProperties, [nextIcon]),
29774         ];
29775     };
29776     SequenceDOMRenderer.prototype._createStepper = function (edgeStatus, configuration, containerWidth, component, navigator) {
29777         var nextKey = null;
29778         var prevKey = null;
29779         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
29780             var edge = _a[_i];
29781             if (edge.data.direction === Edge_1.EdgeDirection.Next) {
29782                 nextKey = edge.to;
29783             }
29784             if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
29785                 prevKey = edge.to;
29786             }
29787         }
29788         var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
29789         var buttons = this._createSequenceArrows(nextKey, prevKey, containerWidth, configuration, navigator);
29790         buttons.splice(1, 0, playingButton);
29791         var containerProperties = {
29792             oncontextmenu: function (event) { event.preventDefault(); },
29793             style: {
29794                 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
29795                 width: containerWidth + "px",
29796             },
29797         };
29798         return vd.h("div.SequenceStepper", containerProperties, buttons);
29799     };
29800     SequenceDOMRenderer.prototype._createTimelineControls = function (containerWidth, index, max) {
29801         var _this = this;
29802         if (this._mode !== Component_1.SequenceMode.Timeline) {
29803             return vd.h("div.SequenceTimeline", []);
29804         }
29805         var positionInput = this._createPositionInput(index, max);
29806         var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
29807         var closeButtonProperties = {
29808             onclick: function () {
29809                 _this._mode = Component_1.SequenceMode.Default;
29810                 _this._notifyChanged$.next(_this);
29811             },
29812         };
29813         var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
29814         var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
29815         var playbackProperties = { style: { top: top + "px" } };
29816         return vd.h("div.SequenceTimeline", playbackProperties, [positionInput, closeButton]);
29817     };
29818     SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
29819         var className = direction === Edge_1.EdgeDirection.Next ?
29820             "SequenceStepNext" :
29821             "SequenceStepPrev";
29822         if (key == null) {
29823             className += "Disabled";
29824         }
29825         else {
29826             if (highlightKey === key) {
29827                 className += "Highlight";
29828             }
29829         }
29830         return className;
29831     };
29832     SequenceDOMRenderer.prototype._setChangingPosition = function (value) {
29833         this._changingPosition = value;
29834         this._notifyChangingPositionChanged$.next(value);
29835     };
29836     return SequenceDOMRenderer;
29837 }());
29838 exports.SequenceDOMRenderer = SequenceDOMRenderer;
29839 exports.default = SequenceDOMRenderer;
29840
29841 },{"../../Component":275,"../../Edge":276,"../../Error":277,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],335:[function(require,module,exports){
29842 "use strict";
29843 Object.defineProperty(exports, "__esModule", { value: true });
29844 var SequenceMode;
29845 (function (SequenceMode) {
29846     SequenceMode[SequenceMode["Default"] = 0] = "Default";
29847     SequenceMode[SequenceMode["Playback"] = 1] = "Playback";
29848     SequenceMode[SequenceMode["Timeline"] = 2] = "Timeline";
29849 })(SequenceMode = exports.SequenceMode || (exports.SequenceMode = {}));
29850 exports.default = SequenceMode;
29851
29852 },{}],336:[function(require,module,exports){
29853 "use strict";
29854 Object.defineProperty(exports, "__esModule", { value: true });
29855
29856 var path = require("path");
29857 var Shaders = /** @class */ (function () {
29858     function Shaders() {
29859     }
29860     Shaders.equirectangular = {
29861         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump 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}",
29862         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}",
29863     };
29864     Shaders.equirectangularCurtain = {
29865         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float curtain;\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\n    bool inverted = curtain < 0.5;\n\n    float curtainMin = inverted ? curtain + 0.5 : curtain - 0.5;\n    float curtainMax = curtain;\n\n    bool insideCurtain = inverted ?\n        x > curtainMin || x < curtainMax :\n        x > curtainMin && x < curtainMax;\n\n    vec4 baseColor;\n    if (insideCurtain) {\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}",
29866         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}",
29867     };
29868     Shaders.perspective = {
29869         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float focal;\nuniform float k1;\nuniform float k2;\nuniform float scale_x;\nuniform float scale_y;\nuniform float radial_peak;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float x = vRstq.x / vRstq.z;\n    float y = vRstq.y / vRstq.z;\n    float r2 = x * x + y * y;\n\n    if (radial_peak > 0. && r2 > radial_peak * sqrt(r2)) {\n        r2 = radial_peak * radial_peak;\n    }\n\n    float d = 1.0 + k1 * r2 + k2 * r2 * r2;\n    float u = scale_x * focal * d * x + 0.5;\n    float v = - scale_y * focal * d * y + 0.5;\n\n    vec4 baseColor;\n    if (u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}",
29870         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}",
29871     };
29872     Shaders.perspectiveCurtain = {
29873         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float focal;\nuniform float k1;\nuniform float k2;\nuniform float scale_x;\nuniform float scale_y;\nuniform float radial_peak;\nuniform float curtain;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float x = vRstq.x / vRstq.z;\n    float y = vRstq.y / vRstq.z;\n    float r2 = x * x + y * y;\n\n    if (radial_peak > 0. && r2 > radial_peak * sqrt(r2)) {\n        r2 = radial_peak * radial_peak;\n    }\n\n    float d = 1.0 + k1 * r2 + k2 * r2 * r2;\n    float u = scale_x * focal * d * x + 0.5;\n    float v = - scale_y * focal * d * y + 0.5;\n\n    vec4 baseColor;\n    if ((u < curtain || curtain >= 1.0) && u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}\n",
29874         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}",
29875     };
29876     Shaders.fisheye = {
29877         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float focal;\nuniform float k1;\nuniform float k2;\nuniform float scale_x;\nuniform float scale_y;\nuniform float radial_peak;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float x = vRstq.x;\n    float y = vRstq.y;\n    float z = vRstq.z;\n\n    float r = sqrt(x * x + y * y);\n    float theta = atan(r, z);\n\n    if (radial_peak > 0. && theta > radial_peak) {\n        theta = radial_peak;\n    }\n\n    float theta2 = theta * theta;\n    float theta_d = theta * (1.0 + theta2 * (k1 + theta2 * k2));\n    float s = focal * theta_d / r;\n\n    float u = scale_x * s * x + 0.5;\n    float v = -scale_y * s * y + 0.5;\n\n    vec4 baseColor;\n    if (u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}\n",
29878         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}",
29879     };
29880     Shaders.fisheyeCurtain = {
29881         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float focal;\nuniform float k1;\nuniform float k2;\nuniform float scale_x;\nuniform float scale_y;\nuniform float radial_peak;\nuniform float curtain;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float x = vRstq.x;\n    float y = vRstq.y;\n    float z = vRstq.z;\n\n    float r2 = sqrt(x * x + y * y);\n    float theta = atan(r2, z);\n\n    if (radial_peak > 0. && theta > radial_peak) {\n        theta = radial_peak;\n    }\n\n    float theta2 = theta * theta;\n    float theta_d = theta * (1.0 + theta2 * (k1 + theta2 * k2));\n    float s = focal * theta_d / r2;\n\n    float u = scale_x * s * x + 0.5;\n    float v = -scale_y * s * y + 0.5;\n\n    vec4 baseColor;\n    if ((u < curtain || curtain >= 1.0) && u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}\n",
29882         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}",
29883     };
29884     Shaders.perspectiveDistorted = {
29885         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float u = vRstq.x / vRstq.w;\n    float v = vRstq.y / vRstq.w;\n\n    vec4 baseColor;\n    if (u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}\n",
29886         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}\n",
29887     };
29888     Shaders.perspectiveDistortedCurtain = {
29889         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float curtain;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float u = vRstq.x / vRstq.w;\n    float v = vRstq.y / vRstq.w;\n\n    vec4 baseColor;\n    if ((u < curtain || curtain >= 1.0) && u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}\n",
29890         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}\n",
29891     };
29892     return Shaders;
29893 }());
29894 exports.Shaders = Shaders;
29895
29896
29897 },{"path":23}],337:[function(require,module,exports){
29898 "use strict";
29899 var __extends = (this && this.__extends) || (function () {
29900     var extendStatics = function (d, b) {
29901         extendStatics = Object.setPrototypeOf ||
29902             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29903             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29904         return extendStatics(d, b);
29905     }
29906     return function (d, b) {
29907         extendStatics(d, b);
29908         function __() { this.constructor = d; }
29909         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29910     };
29911 })();
29912 Object.defineProperty(exports, "__esModule", { value: true });
29913 var rxjs_1 = require("rxjs");
29914 var operators_1 = require("rxjs/operators");
29915 var Component_1 = require("../../Component");
29916 var Geo_1 = require("../../Geo");
29917 var State_1 = require("../../State");
29918 var Render_1 = require("../../Render");
29919 var Tiles_1 = require("../../Tiles");
29920 var Utils_1 = require("../../Utils");
29921 /**
29922  * @class SliderComponent
29923  *
29924  * @classdesc Component for comparing pairs of images. Renders
29925  * a slider for adjusting the curtain of the first image.
29926  *
29927  * Deactivate the sequence, direction and image plane
29928  * components when activating the slider component to avoid
29929  * interfering UI elements.
29930  *
29931  * To retrive and use the slider component
29932  *
29933  * @example
29934  * ```
29935  * var viewer = new Mapillary.Viewer(
29936  *     "<element-id>",
29937  *     "<client-id>",
29938  *     "<my key>");
29939  *
29940  * viewer.deactivateComponent("imagePlane");
29941  * viewer.deactivateComponent("direction");
29942  * viewer.deactivateComponent("sequence");
29943  *
29944  * viewer.activateComponent("slider");
29945  *
29946  * var sliderComponent = viewer.getComponent("slider");
29947  * ```
29948  */
29949 var SliderComponent = /** @class */ (function (_super) {
29950     __extends(SliderComponent, _super);
29951     /** @ignore */
29952     function SliderComponent(name, container, navigator, viewportCoords) {
29953         var _this = _super.call(this, name, container, navigator) || this;
29954         _this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
29955         _this._domRenderer = new Component_1.SliderDOMRenderer(container);
29956         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
29957         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
29958         _this._spatial = new Geo_1.Spatial();
29959         _this._glRendererOperation$ = new rxjs_1.Subject();
29960         _this._glRendererCreator$ = new rxjs_1.Subject();
29961         _this._glRendererDisposer$ = new rxjs_1.Subject();
29962         _this._glRenderer$ = _this._glRendererOperation$.pipe(operators_1.scan(function (glRenderer, operation) {
29963             return operation(glRenderer);
29964         }, null), operators_1.filter(function (glRenderer) {
29965             return glRenderer != null;
29966         }), operators_1.distinctUntilChanged(undefined, function (glRenderer) {
29967             return glRenderer.frameId;
29968         }));
29969         _this._glRendererCreator$.pipe(operators_1.map(function () {
29970             return function (glRenderer) {
29971                 if (glRenderer != null) {
29972                     throw new Error("Multiple slider states can not be created at the same time");
29973                 }
29974                 return new Component_1.SliderGLRenderer();
29975             };
29976         }))
29977             .subscribe(_this._glRendererOperation$);
29978         _this._glRendererDisposer$.pipe(operators_1.map(function () {
29979             return function (glRenderer) {
29980                 glRenderer.dispose();
29981                 return null;
29982             };
29983         }))
29984             .subscribe(_this._glRendererOperation$);
29985         return _this;
29986     }
29987     /**
29988      * Set the initial position.
29989      *
29990      * @description Configures the intial position of the slider.
29991      * The inital position value will be used when the component
29992      * is activated.
29993      *
29994      * @param {number} initialPosition - Initial slider position.
29995      */
29996     SliderComponent.prototype.setInitialPosition = function (initialPosition) {
29997         this.configure({ initialPosition: initialPosition });
29998     };
29999     /**
30000      * Set the image keys.
30001      *
30002      * @description Configures the component to show the image
30003      * planes for the supplied image keys.
30004      *
30005      * @param {ISliderKeys} keys - Slider keys object specifying
30006      * the images to be shown in the foreground and the background.
30007      */
30008     SliderComponent.prototype.setKeys = function (keys) {
30009         this.configure({ keys: keys });
30010     };
30011     /**
30012      * Set the slider mode.
30013      *
30014      * @description Configures the mode for transitions between
30015      * image pairs.
30016      *
30017      * @param {SliderMode} mode - Slider mode to be set.
30018      */
30019     SliderComponent.prototype.setSliderMode = function (mode) {
30020         this.configure({ mode: mode });
30021     };
30022     /**
30023      * Set the value controlling if the slider is visible.
30024      *
30025      * @param {boolean} sliderVisible - Value indicating if
30026      * the slider should be visible or not.
30027      */
30028     SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
30029         this.configure({ sliderVisible: sliderVisible });
30030     };
30031     SliderComponent.prototype._activate = function () {
30032         var _this = this;
30033         this._modeSubcription = this._domRenderer.mode$
30034             .subscribe(function (mode) {
30035             _this.setSliderMode(mode);
30036         });
30037         this._glRenderSubscription = this._glRenderer$.pipe(operators_1.map(function (glRenderer) {
30038             var renderHash = {
30039                 name: _this._name,
30040                 render: {
30041                     frameId: glRenderer.frameId,
30042                     needsRender: glRenderer.needsRender,
30043                     render: glRenderer.render.bind(glRenderer),
30044                     stage: Render_1.GLRenderStage.Background,
30045                 },
30046             };
30047             return renderHash;
30048         }))
30049             .subscribe(this._container.glRenderer.render$);
30050         var position$ = rxjs_1.concat(this.configuration$.pipe(operators_1.map(function (configuration) {
30051             return configuration.initialPosition != null ?
30052                 configuration.initialPosition : 1;
30053         }), operators_1.first()), this._domRenderer.position$);
30054         var mode$ = this.configuration$.pipe(operators_1.map(function (configuration) {
30055             return configuration.mode;
30056         }), operators_1.distinctUntilChanged());
30057         var motionless$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
30058             return frame.state.motionless;
30059         }), operators_1.distinctUntilChanged());
30060         var fullPano$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
30061             return frame.state.currentNode.fullPano;
30062         }), operators_1.distinctUntilChanged());
30063         var sliderVisible$ = rxjs_1.combineLatest(this._configuration$.pipe(operators_1.map(function (configuration) {
30064             return configuration.sliderVisible;
30065         })), this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
30066             return !(frame.state.currentNode == null ||
30067                 frame.state.previousNode == null ||
30068                 (frame.state.currentNode.pano && !frame.state.currentNode.fullPano) ||
30069                 (frame.state.previousNode.pano && !frame.state.previousNode.fullPano) ||
30070                 (frame.state.currentNode.fullPano && !frame.state.previousNode.fullPano));
30071         }), operators_1.distinctUntilChanged())).pipe(operators_1.map(function (_a) {
30072             var sliderVisible = _a[0], enabledState = _a[1];
30073             return sliderVisible && enabledState;
30074         }), operators_1.distinctUntilChanged());
30075         this._waitSubscription = rxjs_1.combineLatest(mode$, motionless$, fullPano$, sliderVisible$).pipe(operators_1.withLatestFrom(this._navigator.stateService.state$))
30076             .subscribe(function (_a) {
30077             var _b = _a[0], mode = _b[0], motionless = _b[1], fullPano = _b[2], sliderVisible = _b[3], state = _a[1];
30078             var interactive = sliderVisible &&
30079                 (motionless || mode === Component_1.SliderMode.Stationary || fullPano);
30080             if (interactive && state !== State_1.State.WaitingInteractively) {
30081                 _this._navigator.stateService.waitInteractively();
30082             }
30083             else if (!interactive && state !== State_1.State.Waiting) {
30084                 _this._navigator.stateService.wait();
30085             }
30086         });
30087         this._moveSubscription = rxjs_1.combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$)
30088             .subscribe(function (_a) {
30089             var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4];
30090             if (motionless || mode === Component_1.SliderMode.Stationary || fullPano) {
30091                 _this._navigator.stateService.moveTo(1);
30092             }
30093             else {
30094                 _this._navigator.stateService.moveTo(position);
30095             }
30096         });
30097         this._domRenderSubscription = rxjs_1.combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
30098             var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4], size = _a[5];
30099             return {
30100                 name: _this._name,
30101                 vnode: _this._domRenderer.render(position, mode, motionless, fullPano, sliderVisible),
30102             };
30103         }))
30104             .subscribe(this._container.domRenderer.render$);
30105         this._glRendererCreator$.next(null);
30106         this._updateCurtainSubscription = rxjs_1.combineLatest(position$, fullPano$, sliderVisible$, this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.map(function (_a) {
30107             var position = _a[0], fullPano = _a[1], visible = _a[2], render = _a[3], transform = _a[4];
30108             if (!fullPano) {
30109                 return visible ? position : 1;
30110             }
30111             var basicMin = _this._viewportCoords.viewportToBasic(-1.15, 0, transform, render.perspective);
30112             var basicMax = _this._viewportCoords.viewportToBasic(1.15, 0, transform, render.perspective);
30113             var shiftedMax = basicMax[0] < basicMin[0] ? basicMax[0] + 1 : basicMax[0];
30114             var basicPosition = basicMin[0] + position * (shiftedMax - basicMin[0]);
30115             return basicPosition > 1 ? basicPosition - 1 : basicPosition;
30116         }), operators_1.map(function (position) {
30117             return function (glRenderer) {
30118                 glRenderer.updateCurtain(position);
30119                 return glRenderer;
30120             };
30121         }))
30122             .subscribe(this._glRendererOperation$);
30123         this._stateSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentState$, mode$).pipe(operators_1.map(function (_a) {
30124             var frame = _a[0], mode = _a[1];
30125             return function (glRenderer) {
30126                 glRenderer.update(frame, mode);
30127                 return glRenderer;
30128             };
30129         }))
30130             .subscribe(this._glRendererOperation$);
30131         this._setKeysSubscription = this._configuration$.pipe(operators_1.filter(function (configuration) {
30132             return configuration.keys != null;
30133         }), operators_1.switchMap(function (configuration) {
30134             return rxjs_1.zip(rxjs_1.zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground)).pipe(operators_1.map(function (nodes) {
30135                 return { background: nodes[0], foreground: nodes[1] };
30136             })), _this._navigator.stateService.currentState$.pipe(operators_1.first())).pipe(operators_1.map(function (nf) {
30137                 return { nodes: nf[0], state: nf[1].state };
30138             }));
30139         }))
30140             .subscribe(function (co) {
30141             if (co.state.currentNode != null &&
30142                 co.state.previousNode != null &&
30143                 co.state.currentNode.key === co.nodes.foreground.key &&
30144                 co.state.previousNode.key === co.nodes.background.key) {
30145                 return;
30146             }
30147             if (co.state.currentNode.key === co.nodes.background.key) {
30148                 _this._navigator.stateService.setNodes([co.nodes.foreground]);
30149                 return;
30150             }
30151             if (co.state.currentNode.key === co.nodes.foreground.key &&
30152                 co.state.trajectory.length === 1) {
30153                 _this._navigator.stateService.prependNodes([co.nodes.background]);
30154                 return;
30155             }
30156             _this._navigator.stateService.setNodes([co.nodes.background]);
30157             _this._navigator.stateService.setNodes([co.nodes.foreground]);
30158         }, function (e) {
30159             console.error(e);
30160         });
30161         var previousNode$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
30162             return frame.state.previousNode;
30163         }), operators_1.filter(function (node) {
30164             return node != null;
30165         }), operators_1.distinctUntilChanged(undefined, function (node) {
30166             return node.key;
30167         }));
30168         var textureProvider$ = this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
30169             return frame.state.currentNode.key;
30170         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
30171             var frame = _a[0], renderer = _a[1], size = _a[2];
30172             var state = frame.state;
30173             var viewportSize = Math.max(size.width, size.height);
30174             var currentNode = state.currentNode;
30175             var currentTransform = state.currentTransform;
30176             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
30177             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
30178         }), operators_1.publishReplay(1), operators_1.refCount());
30179         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
30180         this._setTextureProviderSubscription = textureProvider$.pipe(operators_1.map(function (provider) {
30181             return function (renderer) {
30182                 renderer.setTextureProvider(provider.key, provider);
30183                 return renderer;
30184             };
30185         }))
30186             .subscribe(this._glRendererOperation$);
30187         this._setTileSizeSubscription = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
30188             return rxjs_1.combineLatest(textureProvider$, rxjs_1.of(size)).pipe(operators_1.first());
30189         }))
30190             .subscribe(function (_a) {
30191             var provider = _a[0], size = _a[1];
30192             var viewportSize = Math.max(size.width, size.height);
30193             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
30194             provider.setTileSize(tileSize);
30195         });
30196         this._abortTextureProviderSubscription = textureProvider$.pipe(operators_1.pairwise())
30197             .subscribe(function (pair) {
30198             var previous = pair[0];
30199             previous.abort();
30200         });
30201         var roiTrigger$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
30202             var camera = _a[0], size = _a[1];
30203             return [
30204                 camera.camera.position.clone(),
30205                 camera.camera.lookat.clone(),
30206                 camera.zoom.valueOf(),
30207                 size.height.valueOf(),
30208                 size.width.valueOf()
30209             ];
30210         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
30211             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
30212         }), operators_1.map(function (pls) {
30213             var samePosition = pls[0][0].equals(pls[1][0]);
30214             var sameLookat = pls[0][1].equals(pls[1][1]);
30215             var sameZoom = pls[0][2] === pls[1][2];
30216             var sameHeight = pls[0][3] === pls[1][3];
30217             var sameWidth = pls[0][4] === pls[1][4];
30218             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
30219         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
30220             return stalled;
30221         }), operators_1.switchMap(function (stalled) {
30222             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
30223         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
30224         this._setRegionOfInterestSubscription = textureProvider$.pipe(operators_1.switchMap(function (provider) {
30225             return roiTrigger$.pipe(operators_1.map(function (_a) {
30226                 var camera = _a[0], size = _a[1], transform = _a[2];
30227                 return [
30228                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
30229                     provider,
30230                 ];
30231             }));
30232         }), operators_1.filter(function (args) {
30233             return !args[1].disposed;
30234         }))
30235             .subscribe(function (args) {
30236             var roi = args[0];
30237             var provider = args[1];
30238             provider.setRegionOfInterest(roi);
30239         });
30240         var hasTexture$ = textureProvider$.pipe(operators_1.switchMap(function (provider) {
30241             return provider.hasTexture$;
30242         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
30243         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
30244         var nodeImage$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
30245             return frame.state.nodesAhead === 0;
30246         }), operators_1.map(function (frame) {
30247             return frame.state.currentNode;
30248         }), operators_1.distinctUntilChanged(undefined, function (node) {
30249             return node.key;
30250         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexture$), operators_1.filter(function (args) {
30251             return !args[1];
30252         }), operators_1.map(function (args) {
30253             return args[0];
30254         }), operators_1.filter(function (node) {
30255             return node.pano ?
30256                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
30257                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
30258         }), operators_1.switchMap(function (node) {
30259             var baseImageSize = node.pano ?
30260                 Utils_1.Settings.basePanoramaSize :
30261                 Utils_1.Settings.baseImageSize;
30262             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
30263                 return rxjs_1.empty();
30264             }
30265             var image$ = node
30266                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
30267                 return [n.image, n];
30268             }));
30269             return image$.pipe(operators_1.takeUntil(hasTexture$.pipe(operators_1.filter(function (hasTexture) {
30270                 return hasTexture;
30271             }))), operators_1.catchError(function (error, caught) {
30272                 console.error("Failed to fetch high res image (" + node.key + ")", error);
30273                 return rxjs_1.empty();
30274             }));
30275         })).pipe(operators_1.publish(), operators_1.refCount());
30276         this._updateBackgroundSubscription = nodeImage$.pipe(operators_1.withLatestFrom(textureProvider$))
30277             .subscribe(function (args) {
30278             if (args[0][1].key !== args[1].key ||
30279                 args[1].disposed) {
30280                 return;
30281             }
30282             args[1].updateBackground(args[0][0]);
30283         });
30284         this._updateTextureImageSubscription = nodeImage$.pipe(operators_1.map(function (imn) {
30285             return function (renderer) {
30286                 renderer.updateTextureImage(imn[0], imn[1]);
30287                 return renderer;
30288             };
30289         }))
30290             .subscribe(this._glRendererOperation$);
30291         var textureProviderPrev$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
30292             return !!frame.state.previousNode;
30293         }), operators_1.distinctUntilChanged(undefined, function (frame) {
30294             return frame.state.previousNode.key;
30295         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
30296             var frame = _a[0], renderer = _a[1], size = _a[2];
30297             var state = frame.state;
30298             var viewportSize = Math.max(size.width, size.height);
30299             var previousNode = state.previousNode;
30300             var previousTransform = state.previousTransform;
30301             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
30302             return new Tiles_1.TextureProvider(previousNode.key, previousTransform.basicWidth, previousTransform.basicHeight, tileSize, previousNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
30303         }), operators_1.publishReplay(1), operators_1.refCount());
30304         this._textureProviderSubscriptionPrev = textureProviderPrev$.subscribe(function () { });
30305         this._setTextureProviderSubscriptionPrev = textureProviderPrev$.pipe(operators_1.map(function (provider) {
30306             return function (renderer) {
30307                 renderer.setTextureProviderPrev(provider.key, provider);
30308                 return renderer;
30309             };
30310         }))
30311             .subscribe(this._glRendererOperation$);
30312         this._setTileSizeSubscriptionPrev = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
30313             return rxjs_1.combineLatest(textureProviderPrev$, rxjs_1.of(size)).pipe(operators_1.first());
30314         }))
30315             .subscribe(function (_a) {
30316             var provider = _a[0], size = _a[1];
30317             var viewportSize = Math.max(size.width, size.height);
30318             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
30319             provider.setTileSize(tileSize);
30320         });
30321         this._abortTextureProviderSubscriptionPrev = textureProviderPrev$.pipe(operators_1.pairwise())
30322             .subscribe(function (pair) {
30323             var previous = pair[0];
30324             previous.abort();
30325         });
30326         var roiTriggerPrev$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
30327             var camera = _a[0], size = _a[1];
30328             return [
30329                 camera.camera.position.clone(),
30330                 camera.camera.lookat.clone(),
30331                 camera.zoom.valueOf(),
30332                 size.height.valueOf(),
30333                 size.width.valueOf()
30334             ];
30335         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
30336             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
30337         }), operators_1.map(function (pls) {
30338             var samePosition = pls[0][0].equals(pls[1][0]);
30339             var sameLookat = pls[0][1].equals(pls[1][1]);
30340             var sameZoom = pls[0][2] === pls[1][2];
30341             var sameHeight = pls[0][3] === pls[1][3];
30342             var sameWidth = pls[0][4] === pls[1][4];
30343             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
30344         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
30345             return stalled;
30346         }), operators_1.switchMap(function (stalled) {
30347             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
30348         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
30349         this._setRegionOfInterestSubscriptionPrev = textureProviderPrev$.pipe(operators_1.switchMap(function (provider) {
30350             return roiTriggerPrev$.pipe(operators_1.map(function (_a) {
30351                 var camera = _a[0], size = _a[1], transform = _a[2];
30352                 return [
30353                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
30354                     provider,
30355                 ];
30356             }));
30357         }), operators_1.filter(function (args) {
30358             return !args[1].disposed;
30359         }), operators_1.withLatestFrom(this._navigator.stateService.currentState$))
30360             .subscribe(function (_a) {
30361             var _b = _a[0], roi = _b[0], provider = _b[1], frame = _a[1];
30362             var shiftedRoi = null;
30363             if (frame.state.previousNode.fullPano) {
30364                 if (frame.state.currentNode.fullPano) {
30365                     var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation);
30366                     var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation);
30367                     var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y);
30368                     var shift = directionDiff / (2 * Math.PI);
30369                     var bbox = {
30370                         maxX: _this._spatial.wrap(roi.bbox.maxX + shift, 0, 1),
30371                         maxY: roi.bbox.maxY,
30372                         minX: _this._spatial.wrap(roi.bbox.minX + shift, 0, 1),
30373                         minY: roi.bbox.minY,
30374                     };
30375                     shiftedRoi = {
30376                         bbox: bbox,
30377                         pixelHeight: roi.pixelHeight,
30378                         pixelWidth: roi.pixelWidth,
30379                     };
30380                 }
30381                 else {
30382                     var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation);
30383                     var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation);
30384                     var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y);
30385                     var shiftX = directionDiff / (2 * Math.PI);
30386                     var a1 = _this._spatial.angleToPlane(currentViewingDirection.toArray(), [0, 0, 1]);
30387                     var a2 = _this._spatial.angleToPlane(previousViewingDirection.toArray(), [0, 0, 1]);
30388                     var shiftY = (a2 - a1) / (2 * Math.PI);
30389                     var currentTransform = frame.state.currentTransform;
30390                     var size = Math.max(currentTransform.basicWidth, currentTransform.basicHeight);
30391                     var hFov = size > 0 ?
30392                         2 * Math.atan(0.5 * currentTransform.basicWidth / (size * currentTransform.focal)) :
30393                         Math.PI / 3;
30394                     var vFov = size > 0 ?
30395                         2 * Math.atan(0.5 * currentTransform.basicHeight / (size * currentTransform.focal)) :
30396                         Math.PI / 3;
30397                     var spanningWidth = hFov / (2 * Math.PI);
30398                     var spanningHeight = vFov / Math.PI;
30399                     var basicWidth = (roi.bbox.maxX - roi.bbox.minX) * spanningWidth;
30400                     var basicHeight = (roi.bbox.maxY - roi.bbox.minY) * spanningHeight;
30401                     var pixelWidth = roi.pixelWidth * spanningWidth;
30402                     var pixelHeight = roi.pixelHeight * spanningHeight;
30403                     var zoomShiftX = (roi.bbox.minX + roi.bbox.maxX) / 2 - 0.5;
30404                     var zoomShiftY = (roi.bbox.minY + roi.bbox.maxY) / 2 - 0.5;
30405                     var minX = 0.5 + shiftX + spanningWidth * zoomShiftX - basicWidth / 2;
30406                     var maxX = 0.5 + shiftX + spanningWidth * zoomShiftX + basicWidth / 2;
30407                     var minY = 0.5 + shiftY + spanningHeight * zoomShiftY - basicHeight / 2;
30408                     var maxY = 0.5 + shiftY + spanningHeight * zoomShiftY + basicHeight / 2;
30409                     var bbox = {
30410                         maxX: _this._spatial.wrap(maxX, 0, 1),
30411                         maxY: maxY,
30412                         minX: _this._spatial.wrap(minX, 0, 1),
30413                         minY: minY,
30414                     };
30415                     shiftedRoi = {
30416                         bbox: bbox,
30417                         pixelHeight: pixelHeight,
30418                         pixelWidth: pixelWidth,
30419                     };
30420                 }
30421             }
30422             else {
30423                 var currentBasicAspect = frame.state.currentTransform.basicAspect;
30424                 var previousBasicAspect = frame.state.previousTransform.basicAspect;
30425                 var _c = _this._getBasicCorners(currentBasicAspect, previousBasicAspect), _d = _c[0], cornerMinX = _d[0], cornerMinY = _d[1], _e = _c[1], cornerMaxX = _e[0], cornerMaxY = _e[1];
30426                 var basicWidth = cornerMaxX - cornerMinX;
30427                 var basicHeight = cornerMaxY - cornerMinY;
30428                 var pixelWidth = roi.pixelWidth / basicWidth;
30429                 var pixelHeight = roi.pixelHeight / basicHeight;
30430                 var minX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.minX / basicWidth;
30431                 var maxX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.maxX / basicWidth;
30432                 var minY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.minY / basicHeight;
30433                 var maxY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.maxY / basicHeight;
30434                 var bbox = {
30435                     maxX: maxX,
30436                     maxY: maxY,
30437                     minX: minX,
30438                     minY: minY,
30439                 };
30440                 _this._clipBoundingBox(bbox);
30441                 shiftedRoi = {
30442                     bbox: bbox,
30443                     pixelHeight: pixelHeight,
30444                     pixelWidth: pixelWidth,
30445                 };
30446             }
30447             provider.setRegionOfInterest(shiftedRoi);
30448         });
30449         var hasTexturePrev$ = textureProviderPrev$.pipe(operators_1.switchMap(function (provider) {
30450             return provider.hasTexture$;
30451         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
30452         this._hasTextureSubscriptionPrev = hasTexturePrev$.subscribe(function () { });
30453         var nodeImagePrev$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
30454             return frame.state.nodesAhead === 0 && !!frame.state.previousNode;
30455         }), operators_1.map(function (frame) {
30456             return frame.state.previousNode;
30457         }), operators_1.distinctUntilChanged(undefined, function (node) {
30458             return node.key;
30459         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexturePrev$), operators_1.filter(function (args) {
30460             return !args[1];
30461         }), operators_1.map(function (args) {
30462             return args[0];
30463         }), operators_1.filter(function (node) {
30464             return node.pano ?
30465                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
30466                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
30467         }), operators_1.switchMap(function (node) {
30468             var baseImageSize = node.pano ?
30469                 Utils_1.Settings.basePanoramaSize :
30470                 Utils_1.Settings.baseImageSize;
30471             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
30472                 return rxjs_1.empty();
30473             }
30474             var image$ = node
30475                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
30476                 return [n.image, n];
30477             }));
30478             return image$.pipe(operators_1.takeUntil(hasTexturePrev$.pipe(operators_1.filter(function (hasTexture) {
30479                 return hasTexture;
30480             }))), operators_1.catchError(function (error, caught) {
30481                 console.error("Failed to fetch high res image (" + node.key + ")", error);
30482                 return rxjs_1.empty();
30483             }));
30484         })).pipe(operators_1.publish(), operators_1.refCount());
30485         this._updateBackgroundSubscriptionPrev = nodeImagePrev$.pipe(operators_1.withLatestFrom(textureProviderPrev$))
30486             .subscribe(function (args) {
30487             if (args[0][1].key !== args[1].key ||
30488                 args[1].disposed) {
30489                 return;
30490             }
30491             args[1].updateBackground(args[0][0]);
30492         });
30493         this._updateTextureImageSubscriptionPrev = nodeImagePrev$.pipe(operators_1.map(function (imn) {
30494             return function (renderer) {
30495                 renderer.updateTextureImage(imn[0], imn[1]);
30496                 return renderer;
30497             };
30498         }))
30499             .subscribe(this._glRendererOperation$);
30500     };
30501     SliderComponent.prototype._deactivate = function () {
30502         var _this = this;
30503         this._waitSubscription.unsubscribe();
30504         this._navigator.stateService.state$.pipe(operators_1.first())
30505             .subscribe(function (state) {
30506             if (state !== State_1.State.Traversing) {
30507                 _this._navigator.stateService.traverse();
30508             }
30509         });
30510         this._glRendererDisposer$.next(null);
30511         this._domRenderer.deactivate();
30512         this._modeSubcription.unsubscribe();
30513         this._setKeysSubscription.unsubscribe();
30514         this._stateSubscription.unsubscribe();
30515         this._glRenderSubscription.unsubscribe();
30516         this._domRenderSubscription.unsubscribe();
30517         this._moveSubscription.unsubscribe();
30518         this._updateCurtainSubscription.unsubscribe();
30519         this._textureProviderSubscription.unsubscribe();
30520         this._setTextureProviderSubscription.unsubscribe();
30521         this._setTileSizeSubscription.unsubscribe();
30522         this._abortTextureProviderSubscription.unsubscribe();
30523         this._setRegionOfInterestSubscription.unsubscribe();
30524         this._hasTextureSubscription.unsubscribe();
30525         this._updateBackgroundSubscription.unsubscribe();
30526         this._updateTextureImageSubscription.unsubscribe();
30527         this._textureProviderSubscriptionPrev.unsubscribe();
30528         this._setTextureProviderSubscriptionPrev.unsubscribe();
30529         this._setTileSizeSubscriptionPrev.unsubscribe();
30530         this._abortTextureProviderSubscriptionPrev.unsubscribe();
30531         this._setRegionOfInterestSubscriptionPrev.unsubscribe();
30532         this._hasTextureSubscriptionPrev.unsubscribe();
30533         this._updateBackgroundSubscriptionPrev.unsubscribe();
30534         this._updateTextureImageSubscriptionPrev.unsubscribe();
30535         this.configure({ keys: null });
30536     };
30537     SliderComponent.prototype._getDefaultConfiguration = function () {
30538         return {
30539             initialPosition: 1,
30540             mode: Component_1.SliderMode.Motion,
30541             sliderVisible: true,
30542         };
30543     };
30544     SliderComponent.prototype._catchCacheNode$ = function (key) {
30545         return this._navigator.graphService.cacheNode$(key).pipe(operators_1.catchError(function (error, caught) {
30546             console.error("Failed to cache slider node (" + key + ")", error);
30547             return rxjs_1.empty();
30548         }));
30549     };
30550     SliderComponent.prototype._getBasicCorners = function (currentAspect, previousAspect) {
30551         var offsetX;
30552         var offsetY;
30553         if (currentAspect > previousAspect) {
30554             offsetX = 0.5;
30555             offsetY = 0.5 * currentAspect / previousAspect;
30556         }
30557         else {
30558             offsetX = 0.5 * previousAspect / currentAspect;
30559             offsetY = 0.5;
30560         }
30561         return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]];
30562     };
30563     SliderComponent.prototype._clipBoundingBox = function (bbox) {
30564         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
30565         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
30566         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
30567         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
30568     };
30569     SliderComponent.componentName = "slider";
30570     return SliderComponent;
30571 }(Component_1.Component));
30572 exports.SliderComponent = SliderComponent;
30573 Component_1.ComponentService.register(SliderComponent);
30574 exports.default = SliderComponent;
30575
30576
30577 },{"../../Component":275,"../../Geo":278,"../../Render":281,"../../State":282,"../../Tiles":284,"../../Utils":285,"rxjs":27,"rxjs/operators":225}],338:[function(require,module,exports){
30578 "use strict";
30579 Object.defineProperty(exports, "__esModule", { value: true });
30580 var rxjs_1 = require("rxjs");
30581 var operators_1 = require("rxjs/operators");
30582 var vd = require("virtual-dom");
30583 var Component_1 = require("../../Component");
30584 var SliderDOMRenderer = /** @class */ (function () {
30585     function SliderDOMRenderer(container) {
30586         this._container = container;
30587         this._interacting = false;
30588         this._notifyModeChanged$ = new rxjs_1.Subject();
30589         this._notifyPositionChanged$ = new rxjs_1.Subject();
30590         this._stopInteractionSubscription = null;
30591     }
30592     Object.defineProperty(SliderDOMRenderer.prototype, "mode$", {
30593         get: function () {
30594             return this._notifyModeChanged$;
30595         },
30596         enumerable: true,
30597         configurable: true
30598     });
30599     Object.defineProperty(SliderDOMRenderer.prototype, "position$", {
30600         get: function () {
30601             return this._notifyPositionChanged$;
30602         },
30603         enumerable: true,
30604         configurable: true
30605     });
30606     SliderDOMRenderer.prototype.activate = function () {
30607         var _this = this;
30608         if (!!this._stopInteractionSubscription) {
30609             return;
30610         }
30611         this._stopInteractionSubscription = rxjs_1.merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$.pipe(operators_1.filter(function (touchEvent) {
30612             return touchEvent.touches.length === 0;
30613         })))
30614             .subscribe(function (event) {
30615             if (_this._interacting) {
30616                 _this._interacting = false;
30617             }
30618         });
30619     };
30620     SliderDOMRenderer.prototype.deactivate = function () {
30621         if (!this._stopInteractionSubscription) {
30622             return;
30623         }
30624         this._interacting = false;
30625         this._stopInteractionSubscription.unsubscribe();
30626         this._stopInteractionSubscription = null;
30627     };
30628     SliderDOMRenderer.prototype.render = function (position, mode, motionless, pano, visible) {
30629         var children = [];
30630         if (visible) {
30631             children.push(vd.h("div.SliderBorder", []));
30632             var modeVisible = !(motionless || pano);
30633             if (modeVisible) {
30634                 children.push(this._createModeButton(mode));
30635                 children.push(this._createModeButton2d(mode));
30636             }
30637             children.push(this._createPositionInput(position, modeVisible));
30638         }
30639         var boundingRect = this._container.domContainer.getBoundingClientRect();
30640         var width = Math.max(215, Math.min(400, boundingRect.width - 100));
30641         return vd.h("div.SliderContainer", { style: { width: width + "px" } }, children);
30642     };
30643     SliderDOMRenderer.prototype._createModeButton = function (mode) {
30644         var _this = this;
30645         var properties = {
30646             onclick: function () {
30647                 if (mode === Component_1.SliderMode.Motion) {
30648                     return;
30649                 }
30650                 _this._notifyModeChanged$.next(Component_1.SliderMode.Motion);
30651             },
30652         };
30653         var className = mode === Component_1.SliderMode.Stationary ?
30654             "SliderModeButtonDisabled" :
30655             "SliderModeButton";
30656         return vd.h("div." + className, properties, [vd.h("div.SliderModeIcon", [])]);
30657     };
30658     SliderDOMRenderer.prototype._createModeButton2d = function (mode) {
30659         var _this = this;
30660         var properties = {
30661             onclick: function () {
30662                 if (mode === Component_1.SliderMode.Stationary) {
30663                     return;
30664                 }
30665                 _this._notifyModeChanged$.next(Component_1.SliderMode.Stationary);
30666             },
30667         };
30668         var className = mode === Component_1.SliderMode.Motion ?
30669             "SliderModeButton2dDisabled" :
30670             "SliderModeButton2d";
30671         return vd.h("div." + className, properties, [vd.h("div.SliderModeIcon2d", [])]);
30672     };
30673     SliderDOMRenderer.prototype._createPositionInput = function (position, modeVisible) {
30674         var _this = this;
30675         var onChange = function (e) {
30676             _this._notifyPositionChanged$.next(Number(e.target.value) / 1000);
30677         };
30678         var onStart = function (e) {
30679             _this._interacting = true;
30680             e.stopPropagation();
30681         };
30682         var onMove = function (e) {
30683             if (_this._interacting) {
30684                 e.stopPropagation();
30685             }
30686         };
30687         var onKeyDown = function (e) {
30688             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
30689                 e.key === "ArrowRight" || e.key === "ArrowUp") {
30690                 e.preventDefault();
30691             }
30692         };
30693         var boundingRect = this._container.domContainer.getBoundingClientRect();
30694         var width = Math.max(215, Math.min(400, boundingRect.width - 105)) - 84 + (modeVisible ? 0 : 52);
30695         var positionInput = vd.h("input.SliderPosition", {
30696             max: 1000,
30697             min: 0,
30698             onchange: onChange,
30699             oninput: onChange,
30700             onkeydown: onKeyDown,
30701             onmousedown: onStart,
30702             onmousemove: onMove,
30703             ontouchmove: onMove,
30704             ontouchstart: onStart,
30705             style: {
30706                 width: width + "px",
30707             },
30708             type: "range",
30709             value: 1000 * position,
30710         }, []);
30711         return vd.h("div.SliderPositionContainer", [positionInput]);
30712     };
30713     return SliderDOMRenderer;
30714 }());
30715 exports.SliderDOMRenderer = SliderDOMRenderer;
30716 exports.default = SliderDOMRenderer;
30717
30718 },{"../../Component":275,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],339:[function(require,module,exports){
30719 "use strict";
30720 Object.defineProperty(exports, "__esModule", { value: true });
30721 var Component_1 = require("../../Component");
30722 var Geo_1 = require("../../Geo");
30723 var SliderGLRenderer = /** @class */ (function () {
30724     function SliderGLRenderer() {
30725         this._factory = new Component_1.MeshFactory();
30726         this._scene = new Component_1.MeshScene();
30727         this._spatial = new Geo_1.Spatial();
30728         this._currentKey = null;
30729         this._previousKey = null;
30730         this._disabled = false;
30731         this._curtain = 1;
30732         this._frameId = 0;
30733         this._needsRender = false;
30734         this._mode = null;
30735         this._currentProviderDisposers = {};
30736         this._previousProviderDisposers = {};
30737     }
30738     Object.defineProperty(SliderGLRenderer.prototype, "disabled", {
30739         get: function () {
30740             return this._disabled;
30741         },
30742         enumerable: true,
30743         configurable: true
30744     });
30745     Object.defineProperty(SliderGLRenderer.prototype, "frameId", {
30746         get: function () {
30747             return this._frameId;
30748         },
30749         enumerable: true,
30750         configurable: true
30751     });
30752     Object.defineProperty(SliderGLRenderer.prototype, "needsRender", {
30753         get: function () {
30754             return this._needsRender;
30755         },
30756         enumerable: true,
30757         configurable: true
30758     });
30759     SliderGLRenderer.prototype.setTextureProvider = function (key, provider) {
30760         this._setTextureProvider(key, this._currentKey, provider, this._currentProviderDisposers, this._updateTexture.bind(this));
30761     };
30762     SliderGLRenderer.prototype.setTextureProviderPrev = function (key, provider) {
30763         this._setTextureProvider(key, this._previousKey, provider, this._previousProviderDisposers, this._updateTexturePrev.bind(this));
30764     };
30765     SliderGLRenderer.prototype.update = function (frame, mode) {
30766         this._updateFrameId(frame.id);
30767         this._updateImagePlanes(frame.state, mode);
30768     };
30769     SliderGLRenderer.prototype.updateCurtain = function (curtain) {
30770         if (this._curtain === curtain) {
30771             return;
30772         }
30773         this._curtain = curtain;
30774         this._updateCurtain();
30775         this._needsRender = true;
30776     };
30777     SliderGLRenderer.prototype.updateTexture = function (image, node) {
30778         var planes = node.key === this._currentKey ?
30779             this._scene.planes :
30780             node.key === this._previousKey ?
30781                 this._scene.planesOld :
30782                 {};
30783         if (Object.keys(planes).length === 0) {
30784             return;
30785         }
30786         this._needsRender = true;
30787         for (var key in planes) {
30788             if (!planes.hasOwnProperty(key)) {
30789                 continue;
30790             }
30791             var plane = planes[key];
30792             var material = plane.material;
30793             var texture = material.uniforms.projectorTex.value;
30794             texture.image = image;
30795             texture.needsUpdate = true;
30796         }
30797     };
30798     SliderGLRenderer.prototype.updateTextureImage = function (image, node) {
30799         if (this._currentKey !== node.key) {
30800             return;
30801         }
30802         this._needsRender = true;
30803         var planes = this._scene.planes;
30804         for (var key in planes) {
30805             if (!planes.hasOwnProperty(key)) {
30806                 continue;
30807             }
30808             var plane = planes[key];
30809             var material = plane.material;
30810             var texture = material.uniforms.projectorTex.value;
30811             texture.image = image;
30812             texture.needsUpdate = true;
30813         }
30814     };
30815     SliderGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
30816         if (!this.disabled) {
30817             renderer.render(this._scene.sceneOld, perspectiveCamera);
30818         }
30819         renderer.render(this._scene.scene, perspectiveCamera);
30820         this._needsRender = false;
30821     };
30822     SliderGLRenderer.prototype.dispose = function () {
30823         this._scene.clear();
30824         for (var key in this._currentProviderDisposers) {
30825             if (!this._currentProviderDisposers.hasOwnProperty(key)) {
30826                 continue;
30827             }
30828             this._currentProviderDisposers[key]();
30829         }
30830         for (var key in this._previousProviderDisposers) {
30831             if (!this._previousProviderDisposers.hasOwnProperty(key)) {
30832                 continue;
30833             }
30834             this._previousProviderDisposers[key]();
30835         }
30836         this._currentProviderDisposers = {};
30837         this._previousProviderDisposers = {};
30838     };
30839     SliderGLRenderer.prototype._getBasicCorners = function (currentAspect, previousAspect) {
30840         var offsetX;
30841         var offsetY;
30842         if (currentAspect > previousAspect) {
30843             offsetX = 0.5;
30844             offsetY = 0.5 * currentAspect / previousAspect;
30845         }
30846         else {
30847             offsetX = 0.5 * previousAspect / currentAspect;
30848             offsetY = 0.5;
30849         }
30850         return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]];
30851     };
30852     SliderGLRenderer.prototype._setDisabled = function (state) {
30853         this._disabled = state.currentNode == null ||
30854             state.previousNode == null ||
30855             (state.currentNode.pano && !state.currentNode.fullPano) ||
30856             (state.previousNode.pano && !state.previousNode.fullPano) ||
30857             (state.currentNode.fullPano && !state.previousNode.fullPano);
30858     };
30859     SliderGLRenderer.prototype._setTextureProvider = function (key, originalKey, provider, providerDisposers, updateTexture) {
30860         var _this = this;
30861         if (key !== originalKey) {
30862             return;
30863         }
30864         var createdSubscription = provider.textureCreated$
30865             .subscribe(updateTexture);
30866         var updatedSubscription = provider.textureUpdated$
30867             .subscribe(function (updated) {
30868             _this._needsRender = true;
30869         });
30870         var dispose = function () {
30871             createdSubscription.unsubscribe();
30872             updatedSubscription.unsubscribe();
30873             provider.dispose();
30874         };
30875         if (key in providerDisposers) {
30876             var disposeProvider = providerDisposers[key];
30877             disposeProvider();
30878             delete providerDisposers[key];
30879         }
30880         providerDisposers[key] = dispose;
30881     };
30882     SliderGLRenderer.prototype._updateCurtain = function () {
30883         var planes = this._scene.planes;
30884         for (var key in planes) {
30885             if (!planes.hasOwnProperty(key)) {
30886                 continue;
30887             }
30888             var plane = planes[key];
30889             var shaderMaterial = plane.material;
30890             if (!!shaderMaterial.uniforms.curtain) {
30891                 shaderMaterial.uniforms.curtain.value = this._curtain;
30892             }
30893         }
30894     };
30895     SliderGLRenderer.prototype._updateFrameId = function (frameId) {
30896         this._frameId = frameId;
30897     };
30898     SliderGLRenderer.prototype._updateImagePlanes = function (state, mode) {
30899         var currentChanged = state.currentNode != null && this._currentKey !== state.currentNode.key;
30900         var previousChanged = state.previousNode != null && this._previousKey !== state.previousNode.key;
30901         var modeChanged = this._mode !== mode;
30902         if (!(currentChanged || previousChanged || modeChanged)) {
30903             return;
30904         }
30905         this._setDisabled(state);
30906         this._needsRender = true;
30907         this._mode = mode;
30908         var motionless = state.motionless || mode === Component_1.SliderMode.Stationary || state.currentNode.pano;
30909         if (this.disabled || previousChanged) {
30910             if (this._previousKey in this._previousProviderDisposers) {
30911                 this._previousProviderDisposers[this._previousKey]();
30912                 delete this._previousProviderDisposers[this._previousKey];
30913             }
30914         }
30915         if (this.disabled) {
30916             this._scene.setImagePlanesOld({});
30917         }
30918         else {
30919             if (previousChanged || modeChanged) {
30920                 var previousNode = state.previousNode;
30921                 this._previousKey = previousNode.key;
30922                 var elements = state.currentTransform.rt.elements;
30923                 var translation = [elements[12], elements[13], elements[14]];
30924                 var currentAspect = state.currentTransform.basicAspect;
30925                 var previousAspect = state.previousTransform.basicAspect;
30926                 var textureScale = currentAspect > previousAspect ?
30927                     [1, previousAspect / currentAspect] :
30928                     [currentAspect / previousAspect, 1];
30929                 var rotation = state.currentNode.rotation;
30930                 var width = state.currentNode.width;
30931                 var height = state.currentNode.height;
30932                 if (previousNode.fullPano) {
30933                     rotation = state.previousNode.rotation;
30934                     translation = this._spatial
30935                         .rotate(this._spatial
30936                         .opticalCenter(state.currentNode.rotation, translation)
30937                         .toArray(), rotation)
30938                         .multiplyScalar(-1)
30939                         .toArray();
30940                     width = state.previousNode.width;
30941                     height = state.previousNode.height;
30942                 }
30943                 var transform = new Geo_1.Transform(state.currentNode.orientation, width, height, state.currentNode.focal, state.currentNode.scale, previousNode.gpano, rotation, translation, previousNode.image, textureScale);
30944                 var mesh = undefined;
30945                 if (previousNode.fullPano) {
30946                     mesh = this._factory.createMesh(previousNode, motionless || state.currentNode.fullPano ? transform : state.previousTransform);
30947                 }
30948                 else {
30949                     if (motionless) {
30950                         var _a = this._getBasicCorners(currentAspect, previousAspect), _b = _a[0], basicX0 = _b[0], basicY0 = _b[1], _c = _a[1], basicX1 = _c[0], basicY1 = _c[1];
30951                         mesh = this._factory.createFlatMesh(state.previousNode, transform, basicX0, basicX1, basicY0, basicY1);
30952                     }
30953                     else {
30954                         mesh = this._factory.createMesh(state.previousNode, state.previousTransform);
30955                     }
30956                 }
30957                 var previousPlanes = {};
30958                 previousPlanes[previousNode.key] = mesh;
30959                 this._scene.setImagePlanesOld(previousPlanes);
30960             }
30961         }
30962         if (currentChanged || modeChanged) {
30963             if (this._currentKey in this._currentProviderDisposers) {
30964                 this._currentProviderDisposers[this._currentKey]();
30965                 delete this._currentProviderDisposers[this._currentKey];
30966             }
30967             this._currentKey = state.currentNode.key;
30968             var planes = {};
30969             if (state.currentNode.fullPano) {
30970                 planes[state.currentNode.key] = this._factory.createCurtainMesh(state.currentNode, state.currentTransform);
30971             }
30972             else if (state.currentNode.pano && !state.currentNode.fullPano) {
30973                 planes[state.currentNode.key] = this._factory.createMesh(state.currentNode, state.currentTransform);
30974             }
30975             else {
30976                 if (motionless) {
30977                     planes[state.currentNode.key] = this._factory.createDistortedCurtainMesh(state.currentNode, state.currentTransform);
30978                 }
30979                 else {
30980                     planes[state.currentNode.key] = this._factory.createCurtainMesh(state.currentNode, state.currentTransform);
30981                 }
30982             }
30983             this._scene.setImagePlanes(planes);
30984             this._updateCurtain();
30985         }
30986     };
30987     SliderGLRenderer.prototype._updateTexture = function (texture) {
30988         this._needsRender = true;
30989         var planes = this._scene.planes;
30990         for (var key in planes) {
30991             if (!planes.hasOwnProperty(key)) {
30992                 continue;
30993             }
30994             var plane = planes[key];
30995             var material = plane.material;
30996             var oldTexture = material.uniforms.projectorTex.value;
30997             material.uniforms.projectorTex.value = null;
30998             oldTexture.dispose();
30999             material.uniforms.projectorTex.value = texture;
31000         }
31001     };
31002     SliderGLRenderer.prototype._updateTexturePrev = function (texture) {
31003         this._needsRender = true;
31004         var planes = this._scene.planesOld;
31005         for (var key in planes) {
31006             if (!planes.hasOwnProperty(key)) {
31007                 continue;
31008             }
31009             var plane = planes[key];
31010             var material = plane.material;
31011             var oldTexture = material.uniforms.projectorTex.value;
31012             material.uniforms.projectorTex.value = null;
31013             oldTexture.dispose();
31014             material.uniforms.projectorTex.value = texture;
31015         }
31016     };
31017     return SliderGLRenderer;
31018 }());
31019 exports.SliderGLRenderer = SliderGLRenderer;
31020 exports.default = SliderGLRenderer;
31021
31022
31023 },{"../../Component":275,"../../Geo":278}],340:[function(require,module,exports){
31024 "use strict";
31025 Object.defineProperty(exports, "__esModule", { value: true });
31026 var geohash = require("latlon-geohash");
31027 var rxjs_1 = require("rxjs");
31028 var operators_1 = require("rxjs/operators");
31029 var Error_1 = require("../../Error");
31030 var Utils_1 = require("../../Utils");
31031 var SpatialDataCache = /** @class */ (function () {
31032     function SpatialDataCache(graphService) {
31033         this._graphService = graphService;
31034         this._tiles = {};
31035         this._cacheRequests = {};
31036         this._reconstructions = {};
31037         this._cachingReconstructions$ = {};
31038         this._cachingTiles$ = {};
31039     }
31040     SpatialDataCache.prototype.cacheReconstructions$ = function (hash) {
31041         var _this = this;
31042         if (!this.hasTile(hash)) {
31043             throw new Error("Cannot cache reconstructions of a non-existing tile.");
31044         }
31045         if (this.hasReconstructions(hash)) {
31046             throw new Error("Cannot cache reconstructions that already exists.");
31047         }
31048         if (this.isCachingReconstructions(hash)) {
31049             return this._cachingReconstructions$[hash];
31050         }
31051         var tile = [];
31052         if (hash in this._reconstructions) {
31053             var reconstructionKeys = this.getReconstructions(hash)
31054                 .map(function (reconstruction) {
31055                 return reconstruction.data.key;
31056             });
31057             for (var _i = 0, _a = this.getTile(hash); _i < _a.length; _i++) {
31058                 var node = _a[_i];
31059                 if (reconstructionKeys.indexOf(node.key) === -1) {
31060                     tile.push(node);
31061                 }
31062             }
31063         }
31064         else {
31065             tile.push.apply(tile, this.getTile(hash));
31066             this._reconstructions[hash] = [];
31067         }
31068         this._cacheRequests[hash] = [];
31069         this._cachingReconstructions$[hash] = rxjs_1.from(tile).pipe(operators_1.mergeMap(function (nodeData) {
31070             return !_this._cacheRequests[hash] ?
31071                 rxjs_1.empty() :
31072                 rxjs_1.zip(rxjs_1.of(nodeData), _this._getAtomicReconstruction(nodeData.key, _this._cacheRequests[hash]))
31073                     .pipe(operators_1.catchError(function (error) {
31074                     if (error instanceof Error_1.AbortMapillaryError) {
31075                         return rxjs_1.empty();
31076                     }
31077                     console.error(error);
31078                     return rxjs_1.of([nodeData, null]);
31079                 }));
31080         }, 6), operators_1.map(function (_a) {
31081             var nodeData = _a[0], reconstruction = _a[1];
31082             return { data: nodeData, reconstruction: reconstruction };
31083         }), operators_1.filter(function () {
31084             return hash in _this._reconstructions;
31085         }), operators_1.tap(function (data) {
31086             _this._reconstructions[hash].push(data);
31087         }), operators_1.filter(function (data) {
31088             return !!data.reconstruction;
31089         }), operators_1.finalize(function () {
31090             if (hash in _this._cachingReconstructions$) {
31091                 delete _this._cachingReconstructions$[hash];
31092             }
31093             if (hash in _this._cacheRequests) {
31094                 delete _this._cacheRequests[hash];
31095             }
31096         }), operators_1.publish(), operators_1.refCount());
31097         return this._cachingReconstructions$[hash];
31098     };
31099     SpatialDataCache.prototype.cacheTile$ = function (hash) {
31100         var _this = this;
31101         if (hash.length !== 8) {
31102             throw new Error("Hash needs to be level 8.");
31103         }
31104         if (this.hasTile(hash)) {
31105             throw new Error("Cannot cache tile that already exists.");
31106         }
31107         if (this.hasTile(hash)) {
31108             return this._cachingTiles$[hash];
31109         }
31110         var bounds = geohash.bounds(hash);
31111         var sw = { lat: bounds.sw.lat, lon: bounds.sw.lon };
31112         var ne = { lat: bounds.ne.lat, lon: bounds.ne.lon };
31113         this._tiles[hash] = [];
31114         this._cachingTiles$[hash] = this._graphService.cacheBoundingBox$(sw, ne).pipe(operators_1.catchError(function (error) {
31115             console.error(error);
31116             delete _this._tiles[hash];
31117             return rxjs_1.empty();
31118         }), operators_1.map(function (nodes) {
31119             return nodes
31120                 .map(function (n) {
31121                 return _this._createNodeData(n);
31122             });
31123         }), operators_1.filter(function () {
31124             return hash in _this._tiles;
31125         }), operators_1.tap(function (nodeData) {
31126             var _a;
31127             (_a = _this._tiles[hash]).push.apply(_a, nodeData);
31128             delete _this._cachingTiles$[hash];
31129         }), operators_1.finalize(function () {
31130             if (hash in _this._cachingTiles$) {
31131                 delete _this._cachingTiles$[hash];
31132             }
31133         }), operators_1.publish(), operators_1.refCount());
31134         return this._cachingTiles$[hash];
31135     };
31136     SpatialDataCache.prototype.isCachingReconstructions = function (hash) {
31137         return hash in this._cachingReconstructions$;
31138     };
31139     SpatialDataCache.prototype.isCachingTile = function (hash) {
31140         return hash in this._cachingTiles$;
31141     };
31142     SpatialDataCache.prototype.hasReconstructions = function (hash) {
31143         return !(hash in this._cachingReconstructions$) &&
31144             hash in this._reconstructions &&
31145             this._reconstructions[hash].length === this._tiles[hash].length;
31146     };
31147     SpatialDataCache.prototype.hasTile = function (hash) {
31148         return !(hash in this._cachingTiles$) && hash in this._tiles;
31149     };
31150     SpatialDataCache.prototype.getReconstructions = function (hash) {
31151         return hash in this._reconstructions ?
31152             this._reconstructions[hash]
31153                 .filter(function (data) {
31154                 return !!data.reconstruction;
31155             }) :
31156             [];
31157     };
31158     SpatialDataCache.prototype.getTile = function (hash) {
31159         return hash in this._tiles ? this._tiles[hash] : [];
31160     };
31161     SpatialDataCache.prototype.uncache = function (keepHashes) {
31162         for (var _i = 0, _a = Object.keys(this._cacheRequests); _i < _a.length; _i++) {
31163             var hash = _a[_i];
31164             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
31165                 continue;
31166             }
31167             for (var _b = 0, _c = this._cacheRequests[hash]; _b < _c.length; _b++) {
31168                 var request = _c[_b];
31169                 request.abort();
31170             }
31171             delete this._cacheRequests[hash];
31172         }
31173         for (var _d = 0, _e = Object.keys(this._reconstructions); _d < _e.length; _d++) {
31174             var hash = _e[_d];
31175             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
31176                 continue;
31177             }
31178             delete this._reconstructions[hash];
31179         }
31180         for (var _f = 0, _g = Object.keys(this._tiles); _f < _g.length; _f++) {
31181             var hash = _g[_f];
31182             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
31183                 continue;
31184             }
31185             delete this._tiles[hash];
31186         }
31187     };
31188     SpatialDataCache.prototype._createNodeData = function (node) {
31189         return {
31190             alt: node.alt,
31191             cameraProjection: node.cameraProjection,
31192             focal: node.focal,
31193             gpano: node.gpano,
31194             height: node.height,
31195             k1: node.ck1,
31196             k2: node.ck2,
31197             key: node.key,
31198             lat: node.latLon.lat,
31199             lon: node.latLon.lon,
31200             mergeCC: node.mergeCC,
31201             orientation: node.orientation,
31202             originalLat: node.originalLatLon.lat,
31203             originalLon: node.originalLatLon.lon,
31204             rotation: [node.rotation[0], node.rotation[1], node.rotation[2]],
31205             scale: node.scale,
31206             width: node.width,
31207         };
31208     };
31209     SpatialDataCache.prototype._getAtomicReconstruction = function (key, requests) {
31210         return rxjs_1.Observable.create(function (subscriber) {
31211             var xmlHTTP = new XMLHttpRequest();
31212             xmlHTTP.open("GET", Utils_1.Urls.atomicReconstruction(key), true);
31213             xmlHTTP.responseType = "json";
31214             xmlHTTP.timeout = 15000;
31215             xmlHTTP.onload = function () {
31216                 if (!xmlHTTP.response) {
31217                     subscriber.error(new Error("Atomic reconstruction does not exist (" + key + ")"));
31218                 }
31219                 else {
31220                     subscriber.next(xmlHTTP.response);
31221                     subscriber.complete();
31222                 }
31223             };
31224             xmlHTTP.onerror = function () {
31225                 subscriber.error(new Error("Failed to get atomic reconstruction (" + key + ")"));
31226             };
31227             xmlHTTP.ontimeout = function () {
31228                 subscriber.error(new Error("Atomic reconstruction request timed out (" + key + ")"));
31229             };
31230             xmlHTTP.onabort = function () {
31231                 subscriber.error(new Error_1.AbortMapillaryError("Atomic reconstruction request was aborted (" + key + ")"));
31232             };
31233             requests.push(xmlHTTP);
31234             xmlHTTP.send(null);
31235         });
31236     };
31237     return SpatialDataCache;
31238 }());
31239 exports.SpatialDataCache = SpatialDataCache;
31240 exports.default = SpatialDataCache;
31241
31242 },{"../../Error":277,"../../Utils":285,"latlon-geohash":21,"rxjs":27,"rxjs/operators":225}],341:[function(require,module,exports){
31243 "use strict";
31244 var __extends = (this && this.__extends) || (function () {
31245     var extendStatics = function (d, b) {
31246         extendStatics = Object.setPrototypeOf ||
31247             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31248             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31249         return extendStatics(d, b);
31250     }
31251     return function (d, b) {
31252         extendStatics(d, b);
31253         function __() { this.constructor = d; }
31254         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31255     };
31256 })();
31257 Object.defineProperty(exports, "__esModule", { value: true });
31258 var geohash = require("latlon-geohash");
31259 var rxjs_1 = require("rxjs");
31260 var operators_1 = require("rxjs/operators");
31261 var Component_1 = require("../../Component");
31262 var Geo_1 = require("../../Geo");
31263 var Render_1 = require("../../Render");
31264 var PlayService_1 = require("../../viewer/PlayService");
31265 var State_1 = require("../../state/State");
31266 var SpatialDataComponent = /** @class */ (function (_super) {
31267     __extends(SpatialDataComponent, _super);
31268     function SpatialDataComponent(name, container, navigator) {
31269         var _this = _super.call(this, name, container, navigator) || this;
31270         _this._cache = new Component_1.SpatialDataCache(navigator.graphService);
31271         _this._scene = new Component_1.SpatialDataScene(_this._getDefaultConfiguration());
31272         _this._viewportCoords = new Geo_1.ViewportCoords();
31273         _this._geoCoords = new Geo_1.GeoCoords();
31274         return _this;
31275     }
31276     SpatialDataComponent.prototype._activate = function () {
31277         var _this = this;
31278         this._earthControlsSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
31279             return configuration.earthControls;
31280         }), operators_1.distinctUntilChanged(), operators_1.withLatestFrom(this._navigator.stateService.state$))
31281             .subscribe(function (_a) {
31282             var earth = _a[0], state = _a[1];
31283             if (earth && state !== State_1.default.Earth) {
31284                 _this._navigator.stateService.earth();
31285             }
31286             else if (!earth && state === State_1.default.Earth) {
31287                 _this._navigator.stateService.traverse();
31288             }
31289         });
31290         var direction$ = this._container.renderService.bearing$.pipe(operators_1.map(function (bearing) {
31291             var direction = "";
31292             if (bearing > 292.5 || bearing <= 67.5) {
31293                 direction += "n";
31294             }
31295             if (bearing > 112.5 && bearing <= 247.5) {
31296                 direction += "s";
31297             }
31298             if (bearing > 22.5 && bearing <= 157.5) {
31299                 direction += "e";
31300             }
31301             if (bearing > 202.5 && bearing <= 337.5) {
31302                 direction += "w";
31303             }
31304             return direction;
31305         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
31306         var hash$ = this._navigator.stateService.reference$.pipe(operators_1.tap(function () {
31307             _this._scene.uncache();
31308         }), operators_1.switchMap(function () {
31309             return _this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
31310                 return geohash.encode(node.latLon.lat, node.latLon.lon, 8);
31311             }), operators_1.distinctUntilChanged());
31312         }), operators_1.publishReplay(1), operators_1.refCount());
31313         var sequencePlay$ = rxjs_1.combineLatest(this._navigator.playService.playing$, this._navigator.playService.speed$).pipe(operators_1.map(function (_a) {
31314             var playing = _a[0], speed = _a[1];
31315             return playing && speed > PlayService_1.default.sequenceSpeed;
31316         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
31317         this._addSubscription = rxjs_1.combineLatest(this._navigator.stateService.state$.pipe(operators_1.map(function (state) {
31318             return state === State_1.default.Earth;
31319         }), operators_1.distinctUntilChanged()), hash$, sequencePlay$, direction$).pipe(operators_1.distinctUntilChanged(function (_a, _b) {
31320             var e1 = _a[0], h1 = _a[1], s1 = _a[2], d1 = _a[3];
31321             var e2 = _b[0], h2 = _b[1], s2 = _b[2], d2 = _b[3];
31322             if (e1 !== e2) {
31323                 return false;
31324             }
31325             if (e1) {
31326                 return h1 === h2 && s1 === s2;
31327             }
31328             return h1 === h2 && s1 === s2 && d1 === d2;
31329         }), operators_1.concatMap(function (_a) {
31330             var earth = _a[0], hash = _a[1], sequencePlay = _a[2], direction = _a[3];
31331             if (earth) {
31332                 return sequencePlay ?
31333                     rxjs_1.of([hash]) :
31334                     rxjs_1.of(_this._adjacentComponent(hash, 4));
31335             }
31336             return sequencePlay ?
31337                 rxjs_1.of([hash, geohash.neighbours(hash)[direction]]) :
31338                 rxjs_1.of(_this._computeTiles(hash, direction));
31339         }), operators_1.switchMap(function (hashes) {
31340             return rxjs_1.from(hashes).pipe(operators_1.mergeMap(function (h) {
31341                 var tile$;
31342                 if (_this._cache.hasTile(h)) {
31343                     tile$ = rxjs_1.of(_this._cache.getTile(h));
31344                 }
31345                 else if (_this._cache.isCachingTile(h)) {
31346                     tile$ = _this._cache.cacheTile$(h).pipe(operators_1.last(null, {}), operators_1.switchMap(function () {
31347                         return rxjs_1.of(_this._cache.getTile(h));
31348                     }));
31349                 }
31350                 else {
31351                     tile$ = _this._cache.cacheTile$(h);
31352                 }
31353                 return rxjs_1.combineLatest(rxjs_1.of(h), tile$);
31354             }, 1), operators_1.map(function (_a) {
31355                 var hash = _a[0];
31356                 return hash;
31357             }));
31358         }), operators_1.concatMap(function (hash) {
31359             var reconstructions$;
31360             if (_this._cache.hasReconstructions(hash)) {
31361                 reconstructions$ = rxjs_1.from(_this._cache.getReconstructions(hash));
31362             }
31363             else if (_this._cache.isCachingReconstructions(hash)) {
31364                 reconstructions$ = _this._cache.cacheReconstructions$(hash).pipe(operators_1.last(null, {}), operators_1.switchMap(function () {
31365                     return rxjs_1.from(_this._cache.getReconstructions(hash));
31366                 }));
31367             }
31368             else if (_this._cache.hasTile(hash)) {
31369                 reconstructions$ = _this._cache.cacheReconstructions$(hash);
31370             }
31371             else {
31372                 reconstructions$ = rxjs_1.empty();
31373             }
31374             return rxjs_1.combineLatest(rxjs_1.of(hash), reconstructions$);
31375         }), operators_1.withLatestFrom(this._navigator.stateService.reference$), operators_1.tap(function (_a) {
31376             var hash = _a[0][0], reference = _a[1];
31377             if (_this._scene.hasTile(hash)) {
31378                 return;
31379             }
31380             _this._scene.addTile(_this._computeTileBBox(hash, reference), hash);
31381         }), operators_1.filter(function (_a) {
31382             var _b = _a[0], hash = _b[0], data = _b[1];
31383             return !_this._scene.hasReconstruction(data.reconstruction.main_shot, hash);
31384         }), operators_1.map(function (_a) {
31385             var _b = _a[0], hash = _b[0], data = _b[1], reference = _a[1];
31386             return [
31387                 data,
31388                 _this._createTransform(data.data, reference),
31389                 _this._computeOriginalPosition(data.data, reference),
31390                 hash
31391             ];
31392         }))
31393             .subscribe(function (_a) {
31394             var data = _a[0], transform = _a[1], position = _a[2], hash = _a[3];
31395             _this._scene.addReconstruction(data.reconstruction, transform, position, !!data.data.mergeCC ? data.data.mergeCC.toString() : "", hash);
31396         });
31397         this._cameraVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
31398             return configuration.camerasVisible;
31399         }), operators_1.distinctUntilChanged())
31400             .subscribe(function (visible) {
31401             _this._scene.setCameraVisibility(visible);
31402         });
31403         this._pointVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
31404             return configuration.pointsVisible;
31405         }), operators_1.distinctUntilChanged())
31406             .subscribe(function (visible) {
31407             _this._scene.setPointVisibility(visible);
31408         });
31409         this._positionVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
31410             return configuration.positionsVisible;
31411         }), operators_1.distinctUntilChanged())
31412             .subscribe(function (visible) {
31413             _this._scene.setPositionVisibility(visible);
31414         });
31415         this._tileVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
31416             return configuration.tilesVisible;
31417         }), operators_1.distinctUntilChanged())
31418             .subscribe(function (visible) {
31419             _this._scene.setTileVisibility(visible);
31420         });
31421         this._visualizeConnectedComponentSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
31422             return configuration.connectedComponents;
31423         }), operators_1.distinctUntilChanged())
31424             .subscribe(function (visualize) {
31425             _this._scene.setConnectedComponentVisualization(visualize);
31426         });
31427         this._uncacheSubscription = hash$
31428             .subscribe(function (hash) {
31429             var keepHashes = _this._adjacentComponent(hash, 4);
31430             _this._scene.uncache(keepHashes);
31431             _this._cache.uncache(keepHashes);
31432         });
31433         this._moveSubscription = this._navigator.playService.playing$.pipe(operators_1.switchMap(function (playing) {
31434             return playing ?
31435                 rxjs_1.empty() :
31436                 _this._container.mouseService.dblClick$;
31437         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$), operators_1.switchMap(function (_a) {
31438             var event = _a[0], render = _a[1];
31439             var element = _this._container.element;
31440             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
31441             var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
31442             var key = _this._scene.intersectObjects(viewport, render.perspective);
31443             return !!key ?
31444                 _this._navigator.moveToKey$(key).pipe(operators_1.catchError(function () {
31445                     return rxjs_1.empty();
31446                 })) :
31447                 rxjs_1.empty();
31448         }))
31449             .subscribe();
31450         this._renderSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
31451             var scene = _this._scene;
31452             return {
31453                 name: _this._name,
31454                 render: {
31455                     frameId: frame.id,
31456                     needsRender: scene.needsRender,
31457                     render: scene.render.bind(scene),
31458                     stage: Render_1.GLRenderStage.Foreground,
31459                 },
31460             };
31461         }))
31462             .subscribe(this._container.glRenderer.render$);
31463     };
31464     SpatialDataComponent.prototype._deactivate = function () {
31465         var _this = this;
31466         this._cache.uncache();
31467         this._scene.uncache();
31468         this._addSubscription.unsubscribe();
31469         this._cameraVisibilitySubscription.unsubscribe();
31470         this._earthControlsSubscription.unsubscribe();
31471         this._moveSubscription.unsubscribe();
31472         this._pointVisibilitySubscription.unsubscribe();
31473         this._positionVisibilitySubscription.unsubscribe();
31474         this._renderSubscription.unsubscribe();
31475         this._tileVisibilitySubscription.unsubscribe();
31476         this._uncacheSubscription.unsubscribe();
31477         this._visualizeConnectedComponentSubscription.unsubscribe();
31478         this._navigator.stateService.state$.pipe(operators_1.first())
31479             .subscribe(function (state) {
31480             if (state === State_1.default.Earth) {
31481                 _this._navigator.stateService.traverse();
31482             }
31483         });
31484     };
31485     SpatialDataComponent.prototype._getDefaultConfiguration = function () {
31486         return { camerasVisible: false, pointsVisible: true, positionsVisible: false, tilesVisible: false };
31487     };
31488     SpatialDataComponent.prototype._adjacentComponent = function (hash, depth) {
31489         var hashSet = new Set();
31490         hashSet.add(hash);
31491         this._adjacentComponentRecursive(hashSet, [hash], 0, depth);
31492         return this._setToArray(hashSet);
31493     };
31494     SpatialDataComponent.prototype._adjacentComponentRecursive = function (hashSet, currentHashes, currentDepth, maxDepth) {
31495         if (currentDepth === maxDepth) {
31496             return;
31497         }
31498         var neighbours = [];
31499         for (var _i = 0, currentHashes_1 = currentHashes; _i < currentHashes_1.length; _i++) {
31500             var hash = currentHashes_1[_i];
31501             var hashNeighbours = geohash.neighbours(hash);
31502             for (var direction in hashNeighbours) {
31503                 if (!hashNeighbours.hasOwnProperty(direction)) {
31504                     continue;
31505                 }
31506                 neighbours.push(hashNeighbours[direction]);
31507             }
31508         }
31509         var newHashes = [];
31510         for (var _a = 0, neighbours_1 = neighbours; _a < neighbours_1.length; _a++) {
31511             var neighbour = neighbours_1[_a];
31512             if (!hashSet.has(neighbour)) {
31513                 hashSet.add(neighbour);
31514                 newHashes.push(neighbour);
31515             }
31516         }
31517         this._adjacentComponentRecursive(hashSet, newHashes, currentDepth + 1, maxDepth);
31518     };
31519     SpatialDataComponent.prototype._computeOriginalPosition = function (data, reference) {
31520         return this._geoCoords.geodeticToEnu(data.originalLat, data.originalLon, data.alt, reference.lat, reference.lon, reference.alt);
31521     };
31522     SpatialDataComponent.prototype._computeTileBBox = function (hash, reference) {
31523         var bounds = geohash.bounds(hash);
31524         var sw = this._geoCoords.geodeticToEnu(bounds.sw.lat, bounds.sw.lon, 0, reference.lat, reference.lon, reference.alt);
31525         var ne = this._geoCoords.geodeticToEnu(bounds.ne.lat, bounds.ne.lon, 0, reference.lat, reference.lon, reference.alt);
31526         return [sw, ne];
31527     };
31528     SpatialDataComponent.prototype._createTransform = function (data, reference) {
31529         var translation = Geo_1.Geo.computeTranslation({ alt: data.alt, lat: data.lat, lon: data.lon }, data.rotation, reference);
31530         var transform = new Geo_1.Transform(data.orientation, data.width, data.height, data.focal, data.scale, data.gpano, data.rotation, translation, undefined, undefined, data.k1, data.k2, data.cameraProjection);
31531         return transform;
31532     };
31533     SpatialDataComponent.prototype._computeTiles = function (hash, direction) {
31534         var hashSet = new Set();
31535         var directions = ["n", "ne", "e", "se", "s", "sw", "w", "nw"];
31536         this._computeTilesRecursive(hashSet, hash, direction, directions, 0, 2);
31537         return this._setToArray(hashSet);
31538     };
31539     SpatialDataComponent.prototype._computeTilesRecursive = function (hashSet, currentHash, direction, directions, currentDepth, maxDepth) {
31540         hashSet.add(currentHash);
31541         if (currentDepth === maxDepth) {
31542             return;
31543         }
31544         var neighbours = geohash.neighbours(currentHash);
31545         var directionIndex = directions.indexOf(direction);
31546         var length = directions.length;
31547         var directionNeighbours = [
31548             neighbours[directions[this._modulo((directionIndex - 1), length)]],
31549             neighbours[direction],
31550             neighbours[directions[this._modulo((directionIndex + 1), length)]],
31551         ];
31552         for (var _i = 0, directionNeighbours_1 = directionNeighbours; _i < directionNeighbours_1.length; _i++) {
31553             var directionNeighbour = directionNeighbours_1[_i];
31554             this._computeTilesRecursive(hashSet, directionNeighbour, direction, directions, currentDepth + 1, maxDepth);
31555         }
31556     };
31557     SpatialDataComponent.prototype._modulo = function (a, n) {
31558         return ((a % n) + n) % n;
31559     };
31560     SpatialDataComponent.prototype._setToArray = function (s) {
31561         var a = [];
31562         s.forEach(function (value) {
31563             a.push(value);
31564         });
31565         return a;
31566     };
31567     SpatialDataComponent.componentName = "spatialData";
31568     return SpatialDataComponent;
31569 }(Component_1.Component));
31570 exports.SpatialDataComponent = SpatialDataComponent;
31571 Component_1.ComponentService.register(SpatialDataComponent);
31572 exports.default = SpatialDataComponent;
31573
31574 },{"../../Component":275,"../../Geo":278,"../../Render":281,"../../state/State":413,"../../viewer/PlayService":443,"latlon-geohash":21,"rxjs":27,"rxjs/operators":225}],342:[function(require,module,exports){
31575 "use strict";
31576 Object.defineProperty(exports, "__esModule", { value: true });
31577 var THREE = require("three");
31578 var SpatialDataScene = /** @class */ (function () {
31579     function SpatialDataScene(configuration, scene, raycaster) {
31580         this._scene = !!scene ? scene : new THREE.Scene();
31581         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster(undefined, undefined, 0.8);
31582         this._connectedComponentColors = {};
31583         this._needsRender = false;
31584         this._interactiveObjects = [];
31585         this._reconstructions = {};
31586         this._tiles = {};
31587         this._camerasVisible = configuration.camerasVisible;
31588         this._pointsVisible = configuration.pointsVisible;
31589         this._positionsVisible = configuration.positionsVisible;
31590         this._tilesVisible = configuration.tilesVisible;
31591         this._visualizeConnectedComponents = configuration.connectedComponents;
31592     }
31593     Object.defineProperty(SpatialDataScene.prototype, "needsRender", {
31594         get: function () {
31595             return this._needsRender;
31596         },
31597         enumerable: true,
31598         configurable: true
31599     });
31600     SpatialDataScene.prototype.addReconstruction = function (reconstruction, transform, originalPosition, connectedComponent, hash) {
31601         if (!(hash in this._reconstructions)) {
31602             this._reconstructions[hash] = {
31603                 cameraKeys: {},
31604                 cameras: new THREE.Object3D(),
31605                 connectedComponents: {},
31606                 keys: [],
31607                 points: new THREE.Object3D(),
31608                 positions: new THREE.Object3D(),
31609             };
31610             this._reconstructions[hash].cameras.visible = this._camerasVisible;
31611             this._reconstructions[hash].points.visible = this._pointsVisible;
31612             this._reconstructions[hash].positions.visible = this._positionsVisible;
31613             this._scene.add(this._reconstructions[hash].cameras, this._reconstructions[hash].points, this._reconstructions[hash].positions);
31614         }
31615         if (!(connectedComponent in this._reconstructions[hash].connectedComponents)) {
31616             this._reconstructions[hash].connectedComponents[connectedComponent] = [];
31617         }
31618         if (transform.hasValidScale) {
31619             this._reconstructions[hash].points.add(this._createPoints(reconstruction, transform));
31620         }
31621         var camera = this._createCamera(transform);
31622         this._reconstructions[hash].cameras.add(camera);
31623         for (var _i = 0, _a = camera.children; _i < _a.length; _i++) {
31624             var child = _a[_i];
31625             this._reconstructions[hash].cameraKeys[child.uuid] = reconstruction.main_shot;
31626             this._interactiveObjects.push(child);
31627         }
31628         this._reconstructions[hash].connectedComponents[connectedComponent].push(camera);
31629         var color = this._getColor(connectedComponent, this._visualizeConnectedComponents);
31630         this._setCameraColor(color, camera);
31631         this._reconstructions[hash].positions.add(this._createPosition(transform, originalPosition));
31632         this._reconstructions[hash].keys.push(reconstruction.main_shot);
31633         this._needsRender = true;
31634     };
31635     SpatialDataScene.prototype.addTile = function (tileBBox, hash) {
31636         if (this.hasTile(hash)) {
31637             return;
31638         }
31639         var sw = tileBBox[0];
31640         var ne = tileBBox[1];
31641         var geometry = new THREE.Geometry();
31642         geometry.vertices.push(new THREE.Vector3().fromArray(sw), new THREE.Vector3(sw[0], ne[1], (sw[2] + ne[2]) / 2), new THREE.Vector3().fromArray(ne), new THREE.Vector3(ne[0], sw[1], (sw[2] + ne[2]) / 2), new THREE.Vector3().fromArray(sw));
31643         var tile = new THREE.Line(geometry, new THREE.LineBasicMaterial());
31644         this._tiles[hash] = new THREE.Object3D();
31645         this._tiles[hash].visible = this._tilesVisible;
31646         this._tiles[hash].add(tile);
31647         this._scene.add(this._tiles[hash]);
31648         this._needsRender = true;
31649     };
31650     SpatialDataScene.prototype.uncache = function (keepHashes) {
31651         for (var _i = 0, _a = Object.keys(this._reconstructions); _i < _a.length; _i++) {
31652             var hash = _a[_i];
31653             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
31654                 continue;
31655             }
31656             this._disposeReconstruction(hash);
31657         }
31658         for (var _b = 0, _c = Object.keys(this._tiles); _b < _c.length; _b++) {
31659             var hash = _c[_b];
31660             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
31661                 continue;
31662             }
31663             this._disposeTile(hash);
31664         }
31665         this._needsRender = true;
31666     };
31667     SpatialDataScene.prototype.hasReconstruction = function (key, hash) {
31668         return hash in this._reconstructions && this._reconstructions[hash].keys.indexOf(key) !== -1;
31669     };
31670     SpatialDataScene.prototype.hasTile = function (hash) {
31671         return hash in this._tiles;
31672     };
31673     SpatialDataScene.prototype.intersectObjects = function (_a, camera) {
31674         var viewportX = _a[0], viewportY = _a[1];
31675         if (!this._camerasVisible) {
31676             return null;
31677         }
31678         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
31679         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
31680         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
31681             var intersect = intersects_1[_i];
31682             for (var hash in this._reconstructions) {
31683                 if (!this._reconstructions.hasOwnProperty(hash)) {
31684                     continue;
31685                 }
31686                 if (intersect.object.uuid in this._reconstructions[hash].cameraKeys) {
31687                     return this._reconstructions[hash].cameraKeys[intersect.object.uuid];
31688                 }
31689             }
31690         }
31691         return null;
31692     };
31693     SpatialDataScene.prototype.setCameraVisibility = function (visible) {
31694         if (visible === this._camerasVisible) {
31695             return;
31696         }
31697         for (var hash in this._reconstructions) {
31698             if (!this._reconstructions.hasOwnProperty(hash)) {
31699                 continue;
31700             }
31701             this._reconstructions[hash].cameras.visible = visible;
31702         }
31703         this._camerasVisible = visible;
31704         this._needsRender = true;
31705     };
31706     SpatialDataScene.prototype.setPointVisibility = function (visible) {
31707         if (visible === this._pointsVisible) {
31708             return;
31709         }
31710         for (var hash in this._reconstructions) {
31711             if (!this._reconstructions.hasOwnProperty(hash)) {
31712                 continue;
31713             }
31714             this._reconstructions[hash].points.visible = visible;
31715         }
31716         this._pointsVisible = visible;
31717         this._needsRender = true;
31718     };
31719     SpatialDataScene.prototype.setPositionVisibility = function (visible) {
31720         if (visible === this._positionsVisible) {
31721             return;
31722         }
31723         for (var hash in this._reconstructions) {
31724             if (!this._reconstructions.hasOwnProperty(hash)) {
31725                 continue;
31726             }
31727             this._reconstructions[hash].positions.visible = visible;
31728         }
31729         this._positionsVisible = visible;
31730         this._needsRender = true;
31731     };
31732     SpatialDataScene.prototype.setTileVisibility = function (visible) {
31733         if (visible === this._tilesVisible) {
31734             return;
31735         }
31736         for (var hash in this._tiles) {
31737             if (!this._tiles.hasOwnProperty(hash)) {
31738                 continue;
31739             }
31740             this._tiles[hash].visible = visible;
31741         }
31742         this._tilesVisible = visible;
31743         this._needsRender = true;
31744     };
31745     SpatialDataScene.prototype.setConnectedComponentVisualization = function (visualize) {
31746         if (visualize === this._visualizeConnectedComponents) {
31747             return;
31748         }
31749         for (var hash in this._reconstructions) {
31750             if (!this._reconstructions.hasOwnProperty(hash)) {
31751                 continue;
31752             }
31753             var connectedComponents = this._reconstructions[hash].connectedComponents;
31754             for (var connectedComponent in connectedComponents) {
31755                 if (!connectedComponents.hasOwnProperty(connectedComponent)) {
31756                     continue;
31757                 }
31758                 var color = this._getColor(connectedComponent, visualize);
31759                 for (var _i = 0, _a = connectedComponents[connectedComponent]; _i < _a.length; _i++) {
31760                     var camera = _a[_i];
31761                     this._setCameraColor(color, camera);
31762                 }
31763             }
31764         }
31765         this._visualizeConnectedComponents = visualize;
31766         this._needsRender = true;
31767     };
31768     SpatialDataScene.prototype.render = function (perspectiveCamera, renderer) {
31769         renderer.render(this._scene, perspectiveCamera);
31770         this._needsRender = false;
31771     };
31772     SpatialDataScene.prototype._arrayToFloatArray = function (a, columns) {
31773         var n = a.length;
31774         var f = new Float32Array(n * columns);
31775         for (var i = 0; i < n; i++) {
31776             var item = a[i];
31777             var index = 3 * i;
31778             f[index + 0] = item[0];
31779             f[index + 1] = item[1];
31780             f[index + 2] = item[2];
31781         }
31782         return f;
31783     };
31784     SpatialDataScene.prototype._createAxis = function (transform) {
31785         var north = transform.unprojectBasic([0.5, 0], 0.22);
31786         var south = transform.unprojectBasic([0.5, 1], 0.16);
31787         var axis = new THREE.BufferGeometry();
31788         axis.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray([north, south], 3), 3));
31789         return new THREE.Line(axis, new THREE.LineBasicMaterial());
31790     };
31791     SpatialDataScene.prototype._createCamera = function (transform) {
31792         return !!transform.gpano ?
31793             this._createPanoCamera(transform) :
31794             this._createPrespectiveCamera(transform);
31795     };
31796     SpatialDataScene.prototype._createDiagonals = function (transform, depth) {
31797         var origin = transform.unprojectBasic([0, 0], 0, true);
31798         var topLeft = transform.unprojectBasic([0, 0], depth, true);
31799         var topRight = transform.unprojectBasic([1, 0], depth, true);
31800         var bottomRight = transform.unprojectBasic([1, 1], depth, true);
31801         var bottomLeft = transform.unprojectBasic([0, 1], depth, true);
31802         var vertices = [
31803             origin, topLeft,
31804             origin, topRight,
31805             origin, bottomRight,
31806             origin, bottomLeft,
31807         ];
31808         var diagonals = new THREE.BufferGeometry();
31809         diagonals.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices, 3), 3));
31810         return new THREE.LineSegments(diagonals, new THREE.LineBasicMaterial());
31811     };
31812     SpatialDataScene.prototype._createFrame = function (transform, depth) {
31813         var vertices2d = [];
31814         vertices2d.push.apply(vertices2d, this._subsample([0, 1], [0, 0], 20));
31815         vertices2d.push.apply(vertices2d, this._subsample([0, 0], [1, 0], 20));
31816         vertices2d.push.apply(vertices2d, this._subsample([1, 0], [1, 1], 20));
31817         var vertices3d = vertices2d
31818             .map(function (basic) {
31819             return transform.unprojectBasic(basic, depth, true);
31820         });
31821         var frame = new THREE.BufferGeometry();
31822         frame.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices3d, 3), 3));
31823         return new THREE.Line(frame, new THREE.LineBasicMaterial());
31824     };
31825     SpatialDataScene.prototype._createLatitude = function (basicY, numVertices, transform) {
31826         var positions = new Float32Array((numVertices + 1) * 3);
31827         for (var i = 0; i <= numVertices; i++) {
31828             var position = transform.unprojectBasic([i / numVertices, basicY], 0.16);
31829             var index = 3 * i;
31830             positions[index + 0] = position[0];
31831             positions[index + 1] = position[1];
31832             positions[index + 2] = position[2];
31833         }
31834         var latitude = new THREE.BufferGeometry();
31835         latitude.addAttribute("position", new THREE.BufferAttribute(positions, 3));
31836         return new THREE.Line(latitude, new THREE.LineBasicMaterial());
31837     };
31838     SpatialDataScene.prototype._createLongitude = function (basicX, numVertices, transform) {
31839         var positions = new Float32Array((numVertices + 1) * 3);
31840         for (var i = 0; i <= numVertices; i++) {
31841             var position = transform.unprojectBasic([basicX, i / numVertices], 0.16);
31842             var index = 3 * i;
31843             positions[index + 0] = position[0];
31844             positions[index + 1] = position[1];
31845             positions[index + 2] = position[2];
31846         }
31847         var latitude = new THREE.BufferGeometry();
31848         latitude.addAttribute("position", new THREE.BufferAttribute(positions, 3));
31849         return new THREE.Line(latitude, new THREE.LineBasicMaterial());
31850     };
31851     SpatialDataScene.prototype._createPanoCamera = function (transform) {
31852         var camera = new THREE.Object3D();
31853         camera.children.push(this._createAxis(transform));
31854         camera.children.push(this._createLatitude(0.5, 10, transform));
31855         camera.children.push(this._createLongitude(0, 6, transform));
31856         camera.children.push(this._createLongitude(0.25, 6, transform));
31857         camera.children.push(this._createLongitude(0.5, 6, transform));
31858         camera.children.push(this._createLongitude(0.75, 6, transform));
31859         return camera;
31860     };
31861     SpatialDataScene.prototype._createPoints = function (reconstruction, transform) {
31862         var srtInverse = new THREE.Matrix4().getInverse(transform.srt);
31863         var points = Object
31864             .keys(reconstruction.points)
31865             .map(function (key) {
31866             return reconstruction.points[key];
31867         });
31868         var numPoints = points.length;
31869         var positions = new Float32Array(numPoints * 3);
31870         var colors = new Float32Array(numPoints * 3);
31871         for (var i = 0; i < numPoints; i++) {
31872             var index = 3 * i;
31873             var coords = points[i].coordinates;
31874             var point = new THREE.Vector3(coords[0], coords[1], coords[2])
31875                 .applyMatrix4(srtInverse);
31876             positions[index + 0] = point.x;
31877             positions[index + 1] = point.y;
31878             positions[index + 2] = point.z;
31879             var color = points[i].color;
31880             colors[index + 0] = color[0] / 255.0;
31881             colors[index + 1] = color[1] / 255.0;
31882             colors[index + 2] = color[2] / 255.0;
31883         }
31884         var geometry = new THREE.BufferGeometry();
31885         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
31886         geometry.addAttribute("color", new THREE.BufferAttribute(colors, 3));
31887         var material = new THREE.PointsMaterial({
31888             size: 0.1,
31889             vertexColors: THREE.VertexColors,
31890         });
31891         return new THREE.Points(geometry, material);
31892     };
31893     SpatialDataScene.prototype._createPosition = function (transform, originalPosition) {
31894         var computedPosition = transform.unprojectBasic([0, 0], 0);
31895         var vertices = [originalPosition, computedPosition];
31896         var geometry = new THREE.BufferGeometry();
31897         geometry.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices, 3), 3));
31898         return new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: new THREE.Color(1, 0, 0) }));
31899     };
31900     SpatialDataScene.prototype._createPrespectiveCamera = function (transform) {
31901         var depth = 0.2;
31902         var camera = new THREE.Object3D();
31903         camera.children.push(this._createDiagonals(transform, depth));
31904         camera.children.push(this._createFrame(transform, depth));
31905         return camera;
31906     };
31907     SpatialDataScene.prototype._disposeCameras = function (hash) {
31908         var tileCameras = this._reconstructions[hash].cameras;
31909         for (var _i = 0, _a = tileCameras.children.slice(); _i < _a.length; _i++) {
31910             var camera = _a[_i];
31911             for (var _b = 0, _c = camera.children; _b < _c.length; _b++) {
31912                 var child = _c[_b];
31913                 child.geometry.dispose();
31914                 child.material.dispose();
31915                 var index = this._interactiveObjects.indexOf(child);
31916                 if (index !== -1) {
31917                     this._interactiveObjects.splice(index, 1);
31918                 }
31919                 else {
31920                     console.warn("Object does not exist (" + child.id + ") for " + hash);
31921                 }
31922             }
31923             tileCameras.remove(camera);
31924         }
31925         this._scene.remove(tileCameras);
31926     };
31927     SpatialDataScene.prototype._disposePoints = function (hash) {
31928         var tilePoints = this._reconstructions[hash].points;
31929         for (var _i = 0, _a = tilePoints.children.slice(); _i < _a.length; _i++) {
31930             var points = _a[_i];
31931             points.geometry.dispose();
31932             points.material.dispose();
31933             tilePoints.remove(points);
31934         }
31935         this._scene.remove(tilePoints);
31936     };
31937     SpatialDataScene.prototype._disposePositions = function (hash) {
31938         var tilePositions = this._reconstructions[hash].positions;
31939         for (var _i = 0, _a = tilePositions.children.slice(); _i < _a.length; _i++) {
31940             var position = _a[_i];
31941             position.geometry.dispose();
31942             position.material.dispose();
31943             tilePositions.remove(position);
31944         }
31945         this._scene.remove(tilePositions);
31946     };
31947     SpatialDataScene.prototype._disposeReconstruction = function (hash) {
31948         this._disposeCameras(hash);
31949         this._disposePoints(hash);
31950         this._disposePositions(hash);
31951         delete this._reconstructions[hash];
31952     };
31953     SpatialDataScene.prototype._disposeTile = function (hash) {
31954         var tile = this._tiles[hash];
31955         for (var _i = 0, _a = tile.children.slice(); _i < _a.length; _i++) {
31956             var line = _a[_i];
31957             line.geometry.dispose();
31958             line.material.dispose();
31959             tile.remove(line);
31960         }
31961         this._scene.remove(tile);
31962         delete this._tiles[hash];
31963     };
31964     SpatialDataScene.prototype._getColor = function (connectedComponent, visualizeConnectedComponents) {
31965         return visualizeConnectedComponents ?
31966             this._getConnectedComponentColor(connectedComponent) :
31967             "#FFFFFF";
31968     };
31969     SpatialDataScene.prototype._getConnectedComponentColor = function (connectedComponent) {
31970         if (!(connectedComponent in this._connectedComponentColors)) {
31971             this._connectedComponentColors[connectedComponent] = this._randomColor();
31972         }
31973         return this._connectedComponentColors[connectedComponent];
31974     };
31975     SpatialDataScene.prototype._interpolate = function (a, b, alpha) {
31976         return a + alpha * (b - a);
31977     };
31978     SpatialDataScene.prototype._randomColor = function () {
31979         return "hsl(" + Math.floor(360 * Math.random()) + ", 100%, 65%)";
31980     };
31981     SpatialDataScene.prototype._setCameraColor = function (color, camera) {
31982         for (var _i = 0, _a = camera.children; _i < _a.length; _i++) {
31983             var child = _a[_i];
31984             child.material.color = new THREE.Color(color);
31985         }
31986     };
31987     SpatialDataScene.prototype._subsample = function (p1, p2, subsamples) {
31988         if (subsamples < 1) {
31989             return [p1, p2];
31990         }
31991         var samples = [];
31992         for (var i = 0; i <= subsamples + 1; i++) {
31993             var p = [];
31994             for (var j = 0; j < 3; j++) {
31995                 p.push(this._interpolate(p1[j], p2[j], i / (subsamples + 1)));
31996             }
31997             samples.push(p);
31998         }
31999         return samples;
32000     };
32001     return SpatialDataScene;
32002 }());
32003 exports.SpatialDataScene = SpatialDataScene;
32004 exports.default = SpatialDataScene;
32005
32006 },{"three":226}],343:[function(require,module,exports){
32007 "use strict";
32008 Object.defineProperty(exports, "__esModule", { value: true });
32009 var GeometryTagError_1 = require("./error/GeometryTagError");
32010 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
32011 var PointGeometry_1 = require("./geometry/PointGeometry");
32012 exports.PointGeometry = PointGeometry_1.PointGeometry;
32013 var RectGeometry_1 = require("./geometry/RectGeometry");
32014 exports.RectGeometry = RectGeometry_1.RectGeometry;
32015 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
32016 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
32017 var OutlineTag_1 = require("./tag/OutlineTag");
32018 exports.OutlineTag = OutlineTag_1.OutlineTag;
32019 var SpotTag_1 = require("./tag/SpotTag");
32020 exports.SpotTag = SpotTag_1.SpotTag;
32021 var TagDomain_1 = require("./tag/TagDomain");
32022 exports.TagDomain = TagDomain_1.TagDomain;
32023 var TagComponent_1 = require("./TagComponent");
32024 exports.TagComponent = TagComponent_1.TagComponent;
32025 var TagMode_1 = require("./TagMode");
32026 exports.TagMode = TagMode_1.TagMode;
32027
32028 },{"./TagComponent":344,"./TagMode":347,"./error/GeometryTagError":351,"./geometry/PointGeometry":353,"./geometry/PolygonGeometry":354,"./geometry/RectGeometry":355,"./tag/OutlineTag":367,"./tag/SpotTag":370,"./tag/TagDomain":372}],344:[function(require,module,exports){
32029 "use strict";
32030 var __extends = (this && this.__extends) || (function () {
32031     var extendStatics = function (d, b) {
32032         extendStatics = Object.setPrototypeOf ||
32033             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32034             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32035         return extendStatics(d, b);
32036     }
32037     return function (d, b) {
32038         extendStatics(d, b);
32039         function __() { this.constructor = d; }
32040         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32041     };
32042 })();
32043 Object.defineProperty(exports, "__esModule", { value: true });
32044 var rxjs_1 = require("rxjs");
32045 var operators_1 = require("rxjs/operators");
32046 var when = require("when");
32047 var Component_1 = require("../../Component");
32048 var Geo_1 = require("../../Geo");
32049 var Render_1 = require("../../Render");
32050 /**
32051  * @class TagComponent
32052  *
32053  * @classdesc Component for showing and editing tags with different
32054  * geometries composed from 2D basic image coordinates (see the
32055  * {@link Viewer} class documentation for more information about coordinate
32056  * systems).
32057  *
32058  * The `add` method is used for adding new tags or replacing
32059  * tags already in the set. Tags are removed by id.
32060  *
32061  * If a tag already in the set has the same
32062  * id as one of the tags added, the old tag will be removed and
32063  * the added tag will take its place.
32064  *
32065  * The tag component mode can be set to either be non interactive or
32066  * to be in creating mode of a certain geometry type.
32067  *
32068  * The tag properties can be updated at any time and the change will
32069  * be visibile immediately.
32070  *
32071  * Tags are only relevant to a single image because they are based on
32072  * 2D basic image coordinates. Tags related to a certain image should
32073  * be removed when the viewer is moved to another node.
32074  *
32075  * To retrive and use the tag component
32076  *
32077  * @example
32078  * ```
32079  * var viewer = new Mapillary.Viewer(
32080  *     "<element-id>",
32081  *     "<client-id>",
32082  *     "<my key>",
32083  *     { component: { tag: true } });
32084  *
32085  * var tagComponent = viewer.getComponent("tag");
32086  * ```
32087  */
32088 var TagComponent = /** @class */ (function (_super) {
32089     __extends(TagComponent, _super);
32090     /** @ignore */
32091     function TagComponent(name, container, navigator) {
32092         var _this = _super.call(this, name, container, navigator) || this;
32093         _this._tagDomRenderer = new Component_1.TagDOMRenderer();
32094         _this._tagScene = new Component_1.TagScene();
32095         _this._tagSet = new Component_1.TagSet();
32096         _this._tagCreator = new Component_1.TagCreator(_this, navigator);
32097         _this._viewportCoords = new Geo_1.ViewportCoords();
32098         _this._createHandlers = {
32099             "CreatePoint": new Component_1.CreatePointHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
32100             "CreatePolygon": new Component_1.CreatePolygonHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
32101             "CreateRect": new Component_1.CreateRectHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
32102             "CreateRectDrag": new Component_1.CreateRectDragHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
32103             "Default": undefined,
32104         };
32105         _this._editVertexHandler = new Component_1.EditVertexHandler(_this, container, navigator, _this._viewportCoords, _this._tagSet);
32106         _this._renderTags$ = _this._tagSet.changed$.pipe(operators_1.map(function (tagSet) {
32107             var tags = tagSet.getAll();
32108             // ensure that tags are always rendered in the same order
32109             // to avoid hover tracking problems on first resize.
32110             tags.sort(function (t1, t2) {
32111                 var id1 = t1.tag.id;
32112                 var id2 = t2.tag.id;
32113                 if (id1 < id2) {
32114                     return -1;
32115                 }
32116                 if (id1 > id2) {
32117                     return 1;
32118                 }
32119                 return 0;
32120             });
32121             return tags;
32122         }), operators_1.share());
32123         _this._tagChanged$ = _this._renderTags$.pipe(operators_1.switchMap(function (tags) {
32124             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
32125                 return rxjs_1.merge(tag.tag.changed$, tag.tag.geometryChanged$);
32126             }));
32127         }), operators_1.share());
32128         _this._renderTagGLChanged$ = _this._renderTags$.pipe(operators_1.switchMap(function (tags) {
32129             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
32130                 return tag.glObjectsChanged$;
32131             }));
32132         }), operators_1.share());
32133         _this._createGeometryChanged$ = _this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32134             return tag != null ?
32135                 tag.geometryChanged$ :
32136                 rxjs_1.empty();
32137         }), operators_1.share());
32138         _this._createGLObjectsChanged$ = _this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32139             return tag != null ?
32140                 tag.glObjectsChanged$ :
32141                 rxjs_1.empty();
32142         }), operators_1.share());
32143         _this._creatingConfiguration$ = _this._configuration$.pipe(operators_1.distinctUntilChanged(function (c1, c2) {
32144             return c1.mode === c2.mode;
32145         }, function (configuration) {
32146             return {
32147                 createColor: configuration.createColor,
32148                 mode: configuration.mode,
32149             };
32150         }), operators_1.publishReplay(1), operators_1.refCount());
32151         _this._creatingConfiguration$
32152             .subscribe(function (configuration) {
32153             _this.fire(TagComponent.modechanged, configuration.mode);
32154         });
32155         return _this;
32156     }
32157     /**
32158      * Add tags to the tag set or replace tags in the tag set.
32159      *
32160      * @description If a tag already in the set has the same
32161      * id as one of the tags added, the old tag will be removed
32162      * the added tag will take its place.
32163      *
32164      * @param {Array<Tag>} tags - Tags to add.
32165      *
32166      * @example ```tagComponent.add([tag1, tag2]);```
32167      */
32168     TagComponent.prototype.add = function (tags) {
32169         var _this = this;
32170         if (this._activated) {
32171             this._navigator.stateService.currentTransform$.pipe(operators_1.first())
32172                 .subscribe(function (transform) {
32173                 _this._tagSet.add(tags, transform);
32174                 var renderTags = tags
32175                     .map(function (tag) {
32176                     return _this._tagSet.get(tag.id);
32177                 });
32178                 _this._tagScene.add(renderTags);
32179             });
32180         }
32181         else {
32182             this._tagSet.addDeactivated(tags);
32183         }
32184     };
32185     /**
32186      * Change the current tag mode.
32187      *
32188      * @description Change the tag mode to one of the create modes for creating new geometries.
32189      *
32190      * @param {TagMode} mode - New tag mode.
32191      *
32192      * @fires TagComponent#modechanged
32193      *
32194      * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
32195      */
32196     TagComponent.prototype.changeMode = function (mode) {
32197         this.configure({ mode: mode });
32198     };
32199     /**
32200      * Returns the tag in the tag set with the specified id, or
32201      * undefined if the id matches no tag.
32202      *
32203      * @param {string} tagId - Id of the tag.
32204      *
32205      * @example ```var tag = tagComponent.get("tagId");```
32206      */
32207     TagComponent.prototype.get = function (tagId) {
32208         if (this._activated) {
32209             var renderTag = this._tagSet.get(tagId);
32210             return renderTag !== undefined ? renderTag.tag : undefined;
32211         }
32212         else {
32213             return this._tagSet.getDeactivated(tagId);
32214         }
32215     };
32216     /**
32217      * Returns an array of all tags.
32218      *
32219      * @example ```var tags = tagComponent.getAll();```
32220      */
32221     TagComponent.prototype.getAll = function () {
32222         if (this.activated) {
32223             return this._tagSet
32224                 .getAll()
32225                 .map(function (renderTag) {
32226                 return renderTag.tag;
32227             });
32228         }
32229         else {
32230             return this._tagSet.getAllDeactivated();
32231         }
32232     };
32233     /**
32234      * Returns an array of tag ids for tags that contain the specified point.
32235      *
32236      * @description The pixel point must lie inside the polygon or rectangle
32237      * of an added tag for the tag id to be returned. Tag ids for
32238      * tags that do not have a fill will also be returned if the point is inside
32239      * the geometry of the tag. Tags with point geometries can not be retrieved.
32240      *
32241      * No tag ids will be returned for polygons rendered in cropped panoramas or
32242      * rectangles rendered in panoramas.
32243      *
32244      * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
32245      *
32246      * With this function, you can use the coordinates provided by mouse
32247      * events to get information out of the tag component.
32248      *
32249      * If no tag at exist the pixel point, an empty array will be returned.
32250      *
32251      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
32252      * @returns {Array<string>} Ids of the tags that contain the specified pixel point.
32253      *
32254      * @example
32255      * ```
32256      * tagComponent.getTagIdsAt([100, 100])
32257      *     .then((tagIds) => { console.log(tagIds); });
32258      * ```
32259      */
32260     TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
32261         var _this = this;
32262         return when.promise(function (resolve, reject) {
32263             _this._container.renderService.renderCamera$.pipe(operators_1.first(), operators_1.map(function (render) {
32264                 var viewport = _this._viewportCoords
32265                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
32266                 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
32267                 return ids;
32268             }))
32269                 .subscribe(function (ids) {
32270                 resolve(ids);
32271             }, function (error) {
32272                 reject(error);
32273             });
32274         });
32275     };
32276     /**
32277      * Check if a tag exist in the tag set.
32278      *
32279      * @param {string} tagId - Id of the tag.
32280      *
32281      * @example ```var tagExists = tagComponent.has("tagId");```
32282      */
32283     TagComponent.prototype.has = function (tagId) {
32284         return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
32285     };
32286     /**
32287      * Remove tags with the specified ids from the tag set.
32288      *
32289      * @param {Array<string>} tagIds - Ids for tags to remove.
32290      *
32291      * @example ```tagComponent.remove(["id-1", "id-2"]);```
32292      */
32293     TagComponent.prototype.remove = function (tagIds) {
32294         if (this._activated) {
32295             this._tagSet.remove(tagIds);
32296             this._tagScene.remove(tagIds);
32297         }
32298         else {
32299             this._tagSet.removeDeactivated(tagIds);
32300         }
32301     };
32302     /**
32303      * Remove all tags from the tag set.
32304      *
32305      * @example ```tagComponent.removeAll();```
32306      */
32307     TagComponent.prototype.removeAll = function () {
32308         if (this._activated) {
32309             this._tagSet.removeAll();
32310             this._tagScene.removeAll();
32311         }
32312         else {
32313             this._tagSet.removeAllDeactivated();
32314         }
32315     };
32316     TagComponent.prototype._activate = function () {
32317         var _this = this;
32318         this._editVertexHandler.enable();
32319         var handlerGeometryCreated$ = rxjs_1.from(Object.keys(this._createHandlers)).pipe(operators_1.map(function (key) {
32320             return _this._createHandlers[key];
32321         }), operators_1.filter(function (handler) {
32322             return !!handler;
32323         }), operators_1.mergeMap(function (handler) {
32324             return handler.geometryCreated$;
32325         }), operators_1.share());
32326         this._fireGeometryCreatedSubscription = handlerGeometryCreated$
32327             .subscribe(function (geometry) {
32328             _this.fire(TagComponent.geometrycreated, geometry);
32329         });
32330         this._fireCreateGeometryEventSubscription = this._tagCreator.tag$.pipe(operators_1.skipWhile(function (tag) {
32331             return tag == null;
32332         }), operators_1.distinctUntilChanged())
32333             .subscribe(function (tag) {
32334             var eventType = tag != null ?
32335                 TagComponent.creategeometrystart :
32336                 TagComponent.creategeometryend;
32337             _this.fire(eventType, _this);
32338         });
32339         this._handlerStopCreateSubscription = handlerGeometryCreated$
32340             .subscribe(function () {
32341             _this.changeMode(Component_1.TagMode.Default);
32342         });
32343         this._handlerEnablerSubscription = this._creatingConfiguration$
32344             .subscribe(function (configuration) {
32345             _this._disableCreateHandlers();
32346             var mode = Component_1.TagMode[configuration.mode];
32347             var handler = _this._createHandlers[mode];
32348             if (!!handler) {
32349                 handler.enable();
32350             }
32351         });
32352         this._fireTagsChangedSubscription = this._renderTags$
32353             .subscribe(function (tags) {
32354             _this.fire(TagComponent.tagschanged, _this);
32355         });
32356         this._stopCreateSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32357             return tag != null ?
32358                 tag.aborted$.pipe(operators_1.map(function (t) { return null; })) :
32359                 rxjs_1.empty();
32360         }))
32361             .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
32362         this._setGLCreateTagSubscription = this._tagCreator.tag$
32363             .subscribe(function (tag) {
32364             if (_this._tagScene.hasCreateTag()) {
32365                 _this._tagScene.removeCreateTag();
32366             }
32367             if (tag != null) {
32368                 _this._tagScene.addCreateTag(tag);
32369             }
32370         });
32371         this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
32372             .subscribe(function (tag) {
32373             _this._tagScene.updateCreateTagObjects(tag);
32374         });
32375         this._updateGLObjectsSubscription = this._renderTagGLChanged$
32376             .subscribe(function (tag) {
32377             _this._tagScene.updateObjects(tag);
32378         });
32379         this._updateTagSceneSubscription = this._tagChanged$
32380             .subscribe(function (tag) {
32381             _this._tagScene.update();
32382         });
32383         this._domSubscription = rxjs_1.combineLatest(this._renderTags$.pipe(operators_1.startWith([]), operators_1.tap(function (tags) {
32384             _this._container.domRenderer.render$.next({
32385                 name: _this._name,
32386                 vnode: _this._tagDomRenderer.clear(),
32387             });
32388         })), this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._container.renderService.size$, this._tagChanged$.pipe(operators_1.startWith(null)), rxjs_1.merge(this._tagCreator.tag$, this._createGeometryChanged$).pipe(operators_1.startWith(null))).pipe(operators_1.map(function (_a) {
32389             var renderTags = _a[0], rc = _a[1], atlas = _a[2], size = _a[3], tag = _a[4], ct = _a[5];
32390             return {
32391                 name: _this._name,
32392                 vnode: _this._tagDomRenderer.render(renderTags, ct, atlas, rc.perspective, size),
32393             };
32394         }))
32395             .subscribe(this._container.domRenderer.render$);
32396         this._glSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
32397             var tagScene = _this._tagScene;
32398             return {
32399                 name: _this._name,
32400                 render: {
32401                     frameId: frame.id,
32402                     needsRender: tagScene.needsRender,
32403                     render: tagScene.render.bind(tagScene),
32404                     stage: Render_1.GLRenderStage.Foreground,
32405                 },
32406             };
32407         }))
32408             .subscribe(this._container.glRenderer.render$);
32409         this._navigator.stateService.currentTransform$.pipe(operators_1.first())
32410             .subscribe(function (transform) {
32411             _this._tagSet.activate(transform);
32412             _this._tagScene.add(_this._tagSet.getAll());
32413         });
32414     };
32415     TagComponent.prototype._deactivate = function () {
32416         this._editVertexHandler.disable();
32417         this._disableCreateHandlers();
32418         this._tagScene.clear();
32419         this._tagSet.deactivate();
32420         this._tagCreator.delete$.next(null);
32421         this._updateGLObjectsSubscription.unsubscribe();
32422         this._updateTagSceneSubscription.unsubscribe();
32423         this._stopCreateSubscription.unsubscribe();
32424         this._setGLCreateTagSubscription.unsubscribe();
32425         this._createGLObjectsChangedSubscription.unsubscribe();
32426         this._domSubscription.unsubscribe();
32427         this._glSubscription.unsubscribe();
32428         this._fireCreateGeometryEventSubscription.unsubscribe();
32429         this._fireGeometryCreatedSubscription.unsubscribe();
32430         this._fireTagsChangedSubscription.unsubscribe();
32431         this._handlerStopCreateSubscription.unsubscribe();
32432         this._handlerEnablerSubscription.unsubscribe();
32433         this._container.element.classList.remove("component-tag-create");
32434     };
32435     TagComponent.prototype._getDefaultConfiguration = function () {
32436         return {
32437             createColor: 0xFFFFFF,
32438             mode: Component_1.TagMode.Default,
32439         };
32440     };
32441     TagComponent.prototype._disableCreateHandlers = function () {
32442         var createHandlers = this._createHandlers;
32443         for (var key in createHandlers) {
32444             if (!createHandlers.hasOwnProperty(key)) {
32445                 continue;
32446             }
32447             var handler = createHandlers[key];
32448             if (!!handler) {
32449                 handler.disable();
32450             }
32451         }
32452     };
32453     /** @inheritdoc */
32454     TagComponent.componentName = "tag";
32455     /**
32456      * Event fired when an interaction to create a geometry ends.
32457      *
32458      * @description A create interaction can by a geometry being created
32459      * or by the creation being aborted.
32460      *
32461      * @event TagComponent#creategeometryend
32462      * @type {TagComponent} Tag component.
32463      * @example
32464      * ```
32465      * tagComponent.on("creategeometryend", function(component) {
32466      *     console.log(component);
32467      * });
32468      * ```
32469      */
32470     TagComponent.creategeometryend = "creategeometryend";
32471     /**
32472      * Event fired when an interaction to create a geometry starts.
32473      *
32474      * @description A create interaction starts when the first vertex
32475      * is created in the geometry.
32476      *
32477      * @event TagComponent#creategeometrystart
32478      * @type {TagComponent} Tag component.
32479      * @example
32480      * ```
32481      * tagComponent.on("creategeometrystart", function(component) {
32482      *     console.log(component);
32483      * });
32484      * ```
32485      */
32486     TagComponent.creategeometrystart = "creategeometrystart";
32487     /**
32488      * Event fired when the create mode is changed.
32489      *
32490      * @event TagComponent#modechanged
32491      * @type {TagMode} Tag mode
32492      * @example
32493      * ```
32494      * tagComponent.on("modechanged", function(mode) {
32495      *     console.log(mode);
32496      * });
32497      * ```
32498      */
32499     TagComponent.modechanged = "modechanged";
32500     /**
32501      * Event fired when a geometry has been created.
32502      *
32503      * @event TagComponent#geometrycreated
32504      * @type {Geometry} Created geometry.
32505      * @example
32506      * ```
32507      * tagComponent.on("geometrycreated", function(geometry) {
32508      *     console.log(geometry);
32509      * });
32510      * ```
32511      */
32512     TagComponent.geometrycreated = "geometrycreated";
32513     /**
32514      * Event fired when the tags collection has changed.
32515      *
32516      * @event TagComponent#tagschanged
32517      * @type {TagComponent} Tag component.
32518      * @example
32519      * ```
32520      * tagComponent.on("tagschanged", function(component) {
32521      *     console.log(component.getAll());
32522      * });
32523      * ```
32524      */
32525     TagComponent.tagschanged = "tagschanged";
32526     return TagComponent;
32527 }(Component_1.Component));
32528 exports.TagComponent = TagComponent;
32529 Component_1.ComponentService.register(TagComponent);
32530 exports.default = TagComponent;
32531
32532 },{"../../Component":275,"../../Geo":278,"../../Render":281,"rxjs":27,"rxjs/operators":225,"when":272}],345:[function(require,module,exports){
32533 "use strict";
32534 Object.defineProperty(exports, "__esModule", { value: true });
32535 var operators_1 = require("rxjs/operators");
32536 var rxjs_1 = require("rxjs");
32537 var Component_1 = require("../../Component");
32538 var TagCreator = /** @class */ (function () {
32539     function TagCreator(component, navigator) {
32540         this._component = component;
32541         this._navigator = navigator;
32542         this._tagOperation$ = new rxjs_1.Subject();
32543         this._createPolygon$ = new rxjs_1.Subject();
32544         this._createRect$ = new rxjs_1.Subject();
32545         this._delete$ = new rxjs_1.Subject();
32546         this._tag$ = this._tagOperation$.pipe(operators_1.scan(function (tag, operation) {
32547             return operation(tag);
32548         }, null), operators_1.share());
32549         this._createRect$.pipe(operators_1.withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
32550             var coord = _a[0], conf = _a[1], transform = _a[2];
32551             return function (tag) {
32552                 var geometry = new Component_1.RectGeometry([
32553                     coord[0],
32554                     coord[1],
32555                     coord[0],
32556                     coord[1],
32557                 ]);
32558                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
32559             };
32560         }))
32561             .subscribe(this._tagOperation$);
32562         this._createPolygon$.pipe(operators_1.withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
32563             var coord = _a[0], conf = _a[1], transform = _a[2];
32564             return function (tag) {
32565                 var geometry = new Component_1.PolygonGeometry([
32566                     [coord[0], coord[1]],
32567                     [coord[0], coord[1]],
32568                     [coord[0], coord[1]],
32569                 ]);
32570                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
32571             };
32572         }))
32573             .subscribe(this._tagOperation$);
32574         this._delete$.pipe(operators_1.map(function () {
32575             return function (tag) {
32576                 return null;
32577             };
32578         }))
32579             .subscribe(this._tagOperation$);
32580     }
32581     Object.defineProperty(TagCreator.prototype, "createRect$", {
32582         get: function () {
32583             return this._createRect$;
32584         },
32585         enumerable: true,
32586         configurable: true
32587     });
32588     Object.defineProperty(TagCreator.prototype, "createPolygon$", {
32589         get: function () {
32590             return this._createPolygon$;
32591         },
32592         enumerable: true,
32593         configurable: true
32594     });
32595     Object.defineProperty(TagCreator.prototype, "delete$", {
32596         get: function () {
32597             return this._delete$;
32598         },
32599         enumerable: true,
32600         configurable: true
32601     });
32602     Object.defineProperty(TagCreator.prototype, "tag$", {
32603         get: function () {
32604             return this._tag$;
32605         },
32606         enumerable: true,
32607         configurable: true
32608     });
32609     return TagCreator;
32610 }());
32611 exports.TagCreator = TagCreator;
32612 exports.default = TagCreator;
32613
32614 },{"../../Component":275,"rxjs":27,"rxjs/operators":225}],346:[function(require,module,exports){
32615 "use strict";
32616 Object.defineProperty(exports, "__esModule", { value: true });
32617 var vd = require("virtual-dom");
32618 var TagDOMRenderer = /** @class */ (function () {
32619     function TagDOMRenderer() {
32620     }
32621     TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
32622         var vNodes = [];
32623         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
32624             var tag = tags_1[_i];
32625             vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
32626         }
32627         if (createTag != null) {
32628             vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
32629         }
32630         return vd.h("div.TagContainer", {}, vNodes);
32631     };
32632     TagDOMRenderer.prototype.clear = function () {
32633         return vd.h("div", {}, []);
32634     };
32635     return TagDOMRenderer;
32636 }());
32637 exports.TagDOMRenderer = TagDOMRenderer;
32638
32639 },{"virtual-dom":231}],347:[function(require,module,exports){
32640 "use strict";
32641 Object.defineProperty(exports, "__esModule", { value: true });
32642 /**
32643  * Enumeration for tag modes
32644  * @enum {number}
32645  * @readonly
32646  * @description Modes for the interaction in the tag component.
32647  */
32648 var TagMode;
32649 (function (TagMode) {
32650     /**
32651      * Disables creating tags.
32652      */
32653     TagMode[TagMode["Default"] = 0] = "Default";
32654     /**
32655      * Create a point geometry through a click.
32656      */
32657     TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
32658     /**
32659      * Create a polygon geometry through clicks.
32660      */
32661     TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
32662     /**
32663      * Create a rect geometry through clicks.
32664      */
32665     TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
32666     /**
32667      * Create a rect geometry through drag.
32668      *
32669      * @description Claims the mouse which results in mouse handlers like
32670      * drag pan and scroll zoom becoming inactive.
32671      */
32672     TagMode[TagMode["CreateRectDrag"] = 4] = "CreateRectDrag";
32673 })(TagMode = exports.TagMode || (exports.TagMode = {}));
32674 exports.default = TagMode;
32675
32676 },{}],348:[function(require,module,exports){
32677 "use strict";
32678 Object.defineProperty(exports, "__esModule", { value: true });
32679 var TagOperation;
32680 (function (TagOperation) {
32681     TagOperation[TagOperation["None"] = 0] = "None";
32682     TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
32683     TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
32684 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
32685 exports.default = TagOperation;
32686
32687 },{}],349:[function(require,module,exports){
32688 "use strict";
32689 Object.defineProperty(exports, "__esModule", { value: true });
32690 var THREE = require("three");
32691 var TagScene = /** @class */ (function () {
32692     function TagScene(scene, raycaster) {
32693         this._createTag = null;
32694         this._needsRender = false;
32695         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
32696         this._scene = !!scene ? scene : new THREE.Scene();
32697         this._objectTags = {};
32698         this._retrievableObjects = [];
32699         this._tags = {};
32700     }
32701     Object.defineProperty(TagScene.prototype, "needsRender", {
32702         get: function () {
32703             return this._needsRender;
32704         },
32705         enumerable: true,
32706         configurable: true
32707     });
32708     TagScene.prototype.add = function (tags) {
32709         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
32710             var tag = tags_1[_i];
32711             if (tag.tag.id in this._tags) {
32712                 this._remove(tag.tag.id);
32713             }
32714             this._add(tag);
32715         }
32716         this._needsRender = true;
32717     };
32718     TagScene.prototype.addCreateTag = function (tag) {
32719         for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
32720             var object = _a[_i];
32721             this._scene.add(object);
32722         }
32723         this._createTag = { tag: tag, objects: tag.glObjects };
32724         this._needsRender = true;
32725     };
32726     TagScene.prototype.clear = function () {
32727         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
32728             var id = _a[_i];
32729             this._remove(id);
32730         }
32731         this._needsRender = false;
32732     };
32733     TagScene.prototype.get = function (id) {
32734         return this.has(id) ? this._tags[id].tag : undefined;
32735     };
32736     TagScene.prototype.has = function (id) {
32737         return id in this._tags;
32738     };
32739     TagScene.prototype.hasCreateTag = function () {
32740         return this._createTag != null;
32741     };
32742     TagScene.prototype.intersectObjects = function (_a, camera) {
32743         var viewportX = _a[0], viewportY = _a[1];
32744         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
32745         var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
32746         var intersectedIds = [];
32747         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
32748             var intersect = intersects_1[_i];
32749             if (intersect.object.uuid in this._objectTags) {
32750                 intersectedIds.push(this._objectTags[intersect.object.uuid]);
32751             }
32752         }
32753         return intersectedIds;
32754     };
32755     TagScene.prototype.remove = function (ids) {
32756         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
32757             var id = ids_1[_i];
32758             this._remove(id);
32759         }
32760         this._needsRender = true;
32761     };
32762     TagScene.prototype.removeAll = function () {
32763         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
32764             var id = _a[_i];
32765             this._remove(id);
32766         }
32767         this._needsRender = true;
32768     };
32769     TagScene.prototype.removeCreateTag = function () {
32770         if (this._createTag == null) {
32771             return;
32772         }
32773         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
32774             var object = _a[_i];
32775             this._scene.remove(object);
32776         }
32777         this._createTag.tag.dispose();
32778         this._createTag = null;
32779         this._needsRender = true;
32780     };
32781     TagScene.prototype.render = function (perspectiveCamera, renderer) {
32782         renderer.render(this._scene, perspectiveCamera);
32783         this._needsRender = false;
32784     };
32785     TagScene.prototype.update = function () {
32786         this._needsRender = true;
32787     };
32788     TagScene.prototype.updateCreateTagObjects = function (tag) {
32789         if (this._createTag.tag !== tag) {
32790             throw new Error("Create tags do not have the same reference.");
32791         }
32792         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
32793             var object = _a[_i];
32794             this._scene.remove(object);
32795         }
32796         for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
32797             var object = _c[_b];
32798             this._scene.add(object);
32799         }
32800         this._createTag.objects = tag.glObjects;
32801         this._needsRender = true;
32802     };
32803     TagScene.prototype.updateObjects = function (tag) {
32804         var id = tag.tag.id;
32805         if (this._tags[id].tag !== tag) {
32806             throw new Error("Tags do not have the same reference.");
32807         }
32808         var tagObjects = this._tags[id];
32809         this._removeObjects(tagObjects);
32810         delete this._tags[id];
32811         this._add(tag);
32812         this._needsRender = true;
32813     };
32814     TagScene.prototype._add = function (tag) {
32815         var id = tag.tag.id;
32816         var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
32817         this._tags[id] = tagObjects;
32818         for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
32819             var object = _a[_i];
32820             tagObjects.objects.push(object);
32821             this._scene.add(object);
32822         }
32823         for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
32824             var retrievableObject = _c[_b];
32825             tagObjects.retrievableObjects.push(retrievableObject);
32826             this._retrievableObjects.push(retrievableObject);
32827             this._objectTags[retrievableObject.uuid] = tag.tag.id;
32828         }
32829     };
32830     TagScene.prototype._remove = function (id) {
32831         var tagObjects = this._tags[id];
32832         this._removeObjects(tagObjects);
32833         tagObjects.tag.dispose();
32834         delete this._tags[id];
32835     };
32836     TagScene.prototype._removeObjects = function (tagObjects) {
32837         for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
32838             var object = _a[_i];
32839             this._scene.remove(object);
32840         }
32841         for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
32842             var retrievableObject = _c[_b];
32843             var index = this._retrievableObjects.indexOf(retrievableObject);
32844             if (index !== -1) {
32845                 this._retrievableObjects.splice(index, 1);
32846             }
32847         }
32848     };
32849     return TagScene;
32850 }());
32851 exports.TagScene = TagScene;
32852 exports.default = TagScene;
32853
32854 },{"three":226}],350:[function(require,module,exports){
32855 "use strict";
32856 Object.defineProperty(exports, "__esModule", { value: true });
32857 var rxjs_1 = require("rxjs");
32858 var Component_1 = require("../../Component");
32859 var TagSet = /** @class */ (function () {
32860     function TagSet() {
32861         this._active = false;
32862         this._hash = {};
32863         this._hashDeactivated = {};
32864         this._notifyChanged$ = new rxjs_1.Subject();
32865     }
32866     Object.defineProperty(TagSet.prototype, "active", {
32867         get: function () {
32868             return this._active;
32869         },
32870         enumerable: true,
32871         configurable: true
32872     });
32873     Object.defineProperty(TagSet.prototype, "changed$", {
32874         get: function () {
32875             return this._notifyChanged$;
32876         },
32877         enumerable: true,
32878         configurable: true
32879     });
32880     TagSet.prototype.activate = function (transform) {
32881         if (this._active) {
32882             return;
32883         }
32884         for (var id in this._hashDeactivated) {
32885             if (!this._hashDeactivated.hasOwnProperty(id)) {
32886                 continue;
32887             }
32888             var tag = this._hashDeactivated[id];
32889             this._add(tag, transform);
32890         }
32891         this._hashDeactivated = {};
32892         this._active = true;
32893         this._notifyChanged$.next(this);
32894     };
32895     TagSet.prototype.deactivate = function () {
32896         if (!this._active) {
32897             return;
32898         }
32899         for (var id in this._hash) {
32900             if (!this._hash.hasOwnProperty(id)) {
32901                 continue;
32902             }
32903             this._hashDeactivated[id] = this._hash[id].tag;
32904         }
32905         this._hash = {};
32906         this._active = false;
32907     };
32908     TagSet.prototype.add = function (tags, transform) {
32909         this._assertActivationState(true);
32910         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
32911             var tag = tags_1[_i];
32912             this._add(tag, transform);
32913         }
32914         this._notifyChanged$.next(this);
32915     };
32916     TagSet.prototype.addDeactivated = function (tags) {
32917         this._assertActivationState(false);
32918         for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
32919             var tag = tags_2[_i];
32920             if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) {
32921                 throw new Error("Tag type not supported");
32922             }
32923             this._hashDeactivated[tag.id] = tag;
32924         }
32925     };
32926     TagSet.prototype.get = function (id) {
32927         return this.has(id) ? this._hash[id] : undefined;
32928     };
32929     TagSet.prototype.getAll = function () {
32930         var hash = this._hash;
32931         return Object.keys(hash)
32932             .map(function (id) {
32933             return hash[id];
32934         });
32935     };
32936     TagSet.prototype.getAllDeactivated = function () {
32937         var hashDeactivated = this._hashDeactivated;
32938         return Object.keys(hashDeactivated)
32939             .map(function (id) {
32940             return hashDeactivated[id];
32941         });
32942     };
32943     TagSet.prototype.getDeactivated = function (id) {
32944         return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
32945     };
32946     TagSet.prototype.has = function (id) {
32947         return id in this._hash;
32948     };
32949     TagSet.prototype.hasDeactivated = function (id) {
32950         return id in this._hashDeactivated;
32951     };
32952     TagSet.prototype.remove = function (ids) {
32953         this._assertActivationState(true);
32954         var hash = this._hash;
32955         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
32956             var id = ids_1[_i];
32957             if (!(id in hash)) {
32958                 continue;
32959             }
32960             delete hash[id];
32961         }
32962         this._notifyChanged$.next(this);
32963     };
32964     TagSet.prototype.removeAll = function () {
32965         this._assertActivationState(true);
32966         this._hash = {};
32967         this._notifyChanged$.next(this);
32968     };
32969     TagSet.prototype.removeAllDeactivated = function () {
32970         this._assertActivationState(false);
32971         this._hashDeactivated = {};
32972     };
32973     TagSet.prototype.removeDeactivated = function (ids) {
32974         this._assertActivationState(false);
32975         var hashDeactivated = this._hashDeactivated;
32976         for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
32977             var id = ids_2[_i];
32978             if (!(id in hashDeactivated)) {
32979                 continue;
32980             }
32981             delete hashDeactivated[id];
32982         }
32983     };
32984     TagSet.prototype._add = function (tag, transform) {
32985         if (tag instanceof Component_1.OutlineTag) {
32986             this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
32987         }
32988         else if (tag instanceof Component_1.SpotTag) {
32989             this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
32990         }
32991         else {
32992             throw new Error("Tag type not supported");
32993         }
32994     };
32995     TagSet.prototype._assertActivationState = function (should) {
32996         if (should !== this._active) {
32997             throw new Error("Tag set not in correct state for operation.");
32998         }
32999     };
33000     return TagSet;
33001 }());
33002 exports.TagSet = TagSet;
33003 exports.default = TagSet;
33004
33005 },{"../../Component":275,"rxjs":27}],351:[function(require,module,exports){
33006 "use strict";
33007 var __extends = (this && this.__extends) || (function () {
33008     var extendStatics = function (d, b) {
33009         extendStatics = Object.setPrototypeOf ||
33010             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33011             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33012         return extendStatics(d, b);
33013     }
33014     return function (d, b) {
33015         extendStatics(d, b);
33016         function __() { this.constructor = d; }
33017         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33018     };
33019 })();
33020 Object.defineProperty(exports, "__esModule", { value: true });
33021 var Error_1 = require("../../../Error");
33022 var GeometryTagError = /** @class */ (function (_super) {
33023     __extends(GeometryTagError, _super);
33024     function GeometryTagError(message) {
33025         var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
33026         _this.name = "GeometryTagError";
33027         return _this;
33028     }
33029     return GeometryTagError;
33030 }(Error_1.MapillaryError));
33031 exports.GeometryTagError = GeometryTagError;
33032 exports.default = Error_1.MapillaryError;
33033
33034 },{"../../../Error":277}],352:[function(require,module,exports){
33035 "use strict";
33036 Object.defineProperty(exports, "__esModule", { value: true });
33037 var rxjs_1 = require("rxjs");
33038 /**
33039  * @class Geometry
33040  * @abstract
33041  * @classdesc Represents a geometry.
33042  */
33043 var Geometry = /** @class */ (function () {
33044     /**
33045      * Create a geometry.
33046      *
33047      * @constructor
33048      * @ignore
33049      */
33050     function Geometry() {
33051         this._notifyChanged$ = new rxjs_1.Subject();
33052     }
33053     Object.defineProperty(Geometry.prototype, "changed$", {
33054         /**
33055          * Get changed observable.
33056          *
33057          * @description Emits the geometry itself every time the geometry
33058          * has changed.
33059          *
33060          * @returns {Observable<Geometry>} Observable emitting the geometry instance.
33061          * @ignore
33062          */
33063         get: function () {
33064             return this._notifyChanged$;
33065         },
33066         enumerable: true,
33067         configurable: true
33068     });
33069     return Geometry;
33070 }());
33071 exports.Geometry = Geometry;
33072 exports.default = Geometry;
33073
33074 },{"rxjs":27}],353:[function(require,module,exports){
33075 "use strict";
33076 var __extends = (this && this.__extends) || (function () {
33077     var extendStatics = function (d, b) {
33078         extendStatics = Object.setPrototypeOf ||
33079             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33080             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33081         return extendStatics(d, b);
33082     }
33083     return function (d, b) {
33084         extendStatics(d, b);
33085         function __() { this.constructor = d; }
33086         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33087     };
33088 })();
33089 Object.defineProperty(exports, "__esModule", { value: true });
33090 var Component_1 = require("../../../Component");
33091 /**
33092  * @class PointGeometry
33093  *
33094  * @classdesc Represents a point geometry in the 2D basic image coordinate system.
33095  *
33096  * @example
33097  * ```
33098  * var basicPoint = [0.5, 0.7];
33099  * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
33100  * ```
33101  */
33102 var PointGeometry = /** @class */ (function (_super) {
33103     __extends(PointGeometry, _super);
33104     /**
33105      * Create a point geometry.
33106      *
33107      * @constructor
33108      * @param {Array<number>} point - An array representing the basic coordinates of
33109      * the point.
33110      *
33111      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
33112      */
33113     function PointGeometry(point) {
33114         var _this = _super.call(this) || this;
33115         var x = point[0];
33116         var y = point[1];
33117         if (x < 0 || x > 1 || y < 0 || y > 1) {
33118             throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
33119         }
33120         _this._point = point.slice();
33121         return _this;
33122     }
33123     Object.defineProperty(PointGeometry.prototype, "point", {
33124         /**
33125          * Get point property.
33126          * @returns {Array<number>} Array representing the basic coordinates of the point.
33127          */
33128         get: function () {
33129             return this._point;
33130         },
33131         enumerable: true,
33132         configurable: true
33133     });
33134     /**
33135      * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
33136      * basic coordinates of the point itself.
33137      *
33138      * @returns {Array<number>} 2D basic coordinates representing the centroid.
33139      * @ignore
33140      */
33141     PointGeometry.prototype.getCentroid2d = function () {
33142         return this._point.slice();
33143     };
33144     /**
33145      * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
33146      * world coordinates of the point itself.
33147      *
33148      * @param {Transform} transform - The transform of the node related to the point.
33149      * @returns {Array<number>} 3D world coordinates representing the centroid.
33150      * @ignore
33151      */
33152     PointGeometry.prototype.getCentroid3d = function (transform) {
33153         return transform.unprojectBasic(this._point, 200);
33154     };
33155     /**
33156      * Set the centroid of the point, i.e. the point coordinates.
33157      *
33158      * @param {Array<number>} value - The new value of the centroid.
33159      * @param {Transform} transform - The transform of the node related to the point.
33160      * @ignore
33161      */
33162     PointGeometry.prototype.setCentroid2d = function (value, transform) {
33163         var changed = [
33164             Math.max(0, Math.min(1, value[0])),
33165             Math.max(0, Math.min(1, value[1])),
33166         ];
33167         this._point[0] = changed[0];
33168         this._point[1] = changed[1];
33169         this._notifyChanged$.next(this);
33170     };
33171     return PointGeometry;
33172 }(Component_1.Geometry));
33173 exports.PointGeometry = PointGeometry;
33174
33175 },{"../../../Component":275}],354:[function(require,module,exports){
33176 "use strict";
33177 var __extends = (this && this.__extends) || (function () {
33178     var extendStatics = function (d, b) {
33179         extendStatics = Object.setPrototypeOf ||
33180             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33181             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33182         return extendStatics(d, b);
33183     }
33184     return function (d, b) {
33185         extendStatics(d, b);
33186         function __() { this.constructor = d; }
33187         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33188     };
33189 })();
33190 Object.defineProperty(exports, "__esModule", { value: true });
33191 var Component_1 = require("../../../Component");
33192 /**
33193  * @class PolygonGeometry
33194  *
33195  * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
33196  * All polygons and holes provided to the constructor needs to be closed.
33197  *
33198  * @example
33199  * ```
33200  * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
33201  * var polygonGeometry = new Mapillary.TagComponent.PolygonGeometry(basicPolygon);
33202  * ```
33203  */
33204 var PolygonGeometry = /** @class */ (function (_super) {
33205     __extends(PolygonGeometry, _super);
33206     /**
33207      * Create a polygon geometry.
33208      *
33209      * @constructor
33210      * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
33211      * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
33212      * Each array of holes vertices must be closed.
33213      *
33214      * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
33215      */
33216     function PolygonGeometry(polygon, holes) {
33217         var _this = _super.call(this) || this;
33218         var polygonLength = polygon.length;
33219         if (polygonLength < 3) {
33220             throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
33221         }
33222         if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
33223             polygon[0][1] !== polygon[polygonLength - 1][1]) {
33224             throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
33225         }
33226         _this._polygon = [];
33227         for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
33228             var vertex = polygon_1[_i];
33229             if (vertex[0] < 0 || vertex[0] > 1 ||
33230                 vertex[1] < 0 || vertex[1] > 1) {
33231                 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
33232             }
33233             _this._polygon.push(vertex.slice());
33234         }
33235         _this._holes = [];
33236         if (holes == null) {
33237             return _this;
33238         }
33239         for (var i = 0; i < holes.length; i++) {
33240             var hole = holes[i];
33241             var holeLength = hole.length;
33242             if (holeLength < 3) {
33243                 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
33244             }
33245             if (hole[0][0] !== hole[holeLength - 1][0] ||
33246                 hole[0][1] !== hole[holeLength - 1][1]) {
33247                 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
33248             }
33249             _this._holes.push([]);
33250             for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
33251                 var vertex = hole_1[_a];
33252                 if (vertex[0] < 0 || vertex[0] > 1 ||
33253                     vertex[1] < 0 || vertex[1] > 1) {
33254                     throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
33255                 }
33256                 _this._holes[i].push(vertex.slice());
33257             }
33258         }
33259         return _this;
33260     }
33261     Object.defineProperty(PolygonGeometry.prototype, "polygon", {
33262         /**
33263          * Get polygon property.
33264          * @returns {Array<Array<number>>} Closed 2d polygon.
33265          */
33266         get: function () {
33267             return this._polygon;
33268         },
33269         enumerable: true,
33270         configurable: true
33271     });
33272     Object.defineProperty(PolygonGeometry.prototype, "holes", {
33273         /**
33274          * Get holes property.
33275          * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
33276          */
33277         get: function () {
33278             return this._holes;
33279         },
33280         enumerable: true,
33281         configurable: true
33282     });
33283     /**
33284      * Add a vertex to the polygon by appending it after the last vertex.
33285      *
33286      * @param {Array<number>} vertex - Vertex to add.
33287      * @ignore
33288      */
33289     PolygonGeometry.prototype.addVertex2d = function (vertex) {
33290         var clamped = [
33291             Math.max(0, Math.min(1, vertex[0])),
33292             Math.max(0, Math.min(1, vertex[1])),
33293         ];
33294         this._polygon.splice(this._polygon.length - 1, 0, clamped);
33295         this._notifyChanged$.next(this);
33296     };
33297     /**
33298      * Get the coordinates of a vertex from the polygon representation of the geometry.
33299      *
33300      * @description The first vertex represents the bottom-left corner with the rest of
33301      * the vertices following in clockwise order.
33302      *
33303      * @param {number} index - Vertex index.
33304      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
33305      * @ignore
33306      */
33307     PolygonGeometry.prototype.getVertex2d = function (index) {
33308         return this._polygon[index].slice();
33309     };
33310     /**
33311      * Remove a vertex from the polygon.
33312      *
33313      * @param {number} index - The index of the vertex to remove.
33314      * @ignore
33315      */
33316     PolygonGeometry.prototype.removeVertex2d = function (index) {
33317         if (index < 0 ||
33318             index >= this._polygon.length ||
33319             this._polygon.length < 4) {
33320             throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
33321         }
33322         if (index > 0 && index < this._polygon.length - 1) {
33323             this._polygon.splice(index, 1);
33324         }
33325         else {
33326             this._polygon.splice(0, 1);
33327             this._polygon.pop();
33328             var closing = this._polygon[0].slice();
33329             this._polygon.push(closing);
33330         }
33331         this._notifyChanged$.next(this);
33332     };
33333     /** @ignore */
33334     PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
33335         var changed = [
33336             Math.max(0, Math.min(1, value[0])),
33337             Math.max(0, Math.min(1, value[1])),
33338         ];
33339         if (index === 0 || index === this._polygon.length - 1) {
33340             this._polygon[0] = changed.slice();
33341             this._polygon[this._polygon.length - 1] = changed.slice();
33342         }
33343         else {
33344             this._polygon[index] = changed.slice();
33345         }
33346         this._notifyChanged$.next(this);
33347     };
33348     /** @ignore */
33349     PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
33350         var xs = this._polygon.map(function (point) { return point[0]; });
33351         var ys = this._polygon.map(function (point) { return point[1]; });
33352         var minX = Math.min.apply(Math, xs);
33353         var maxX = Math.max.apply(Math, xs);
33354         var minY = Math.min.apply(Math, ys);
33355         var maxY = Math.max.apply(Math, ys);
33356         var centroid = this.getCentroid2d();
33357         var minTranslationX = -minX;
33358         var maxTranslationX = 1 - maxX;
33359         var minTranslationY = -minY;
33360         var maxTranslationY = 1 - maxY;
33361         var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
33362         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
33363         for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
33364             var point = _a[_i];
33365             point[0] += translationX;
33366             point[1] += translationY;
33367         }
33368         this._notifyChanged$.next(this);
33369     };
33370     /** @ignore */
33371     PolygonGeometry.prototype.getPoints3d = function (transform) {
33372         return this._getPoints3d(this._subsample(this._polygon), transform);
33373     };
33374     /** @ignore */
33375     PolygonGeometry.prototype.getVertex3d = function (index, transform) {
33376         return transform.unprojectBasic(this._polygon[index], 200);
33377     };
33378     /** @ignore */
33379     PolygonGeometry.prototype.getVertices2d = function () {
33380         return this._polygon.slice();
33381     };
33382     /** @ignore */
33383     PolygonGeometry.prototype.getVertices3d = function (transform) {
33384         return this._getPoints3d(this._polygon, transform);
33385     };
33386     /**
33387      * Get a polygon representation of the 3D coordinates for the vertices of each hole
33388      * of the geometry. Line segments between vertices will possibly be subsampled
33389      * resulting in a larger number of points than the total number of vertices.
33390      *
33391      * @param {Transform} transform - The transform of the node related to the geometry.
33392      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
33393      * representing the vertices of each hole of the geometry.
33394      * @ignore
33395      */
33396     PolygonGeometry.prototype.getHolePoints3d = function (transform) {
33397         var _this = this;
33398         return this._holes
33399             .map(function (hole2d) {
33400             return _this._getPoints3d(_this._subsample(hole2d), transform);
33401         });
33402     };
33403     /**
33404      * Get a polygon representation of the 3D coordinates for the vertices of each hole
33405      * of the geometry.
33406      *
33407      * @param {Transform} transform - The transform of the node related to the geometry.
33408      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
33409      * representing the vertices of each hole of the geometry.
33410      * @ignore
33411      */
33412     PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
33413         var _this = this;
33414         return this._holes
33415             .map(function (hole2d) {
33416             return _this._getPoints3d(hole2d, transform);
33417         });
33418     };
33419     /** @ignore */
33420     PolygonGeometry.prototype.getCentroid2d = function () {
33421         var polygon = this._polygon;
33422         var area = 0;
33423         var centroidX = 0;
33424         var centroidY = 0;
33425         for (var i = 0; i < polygon.length - 1; i++) {
33426             var xi = polygon[i][0];
33427             var yi = polygon[i][1];
33428             var xi1 = polygon[i + 1][0];
33429             var yi1 = polygon[i + 1][1];
33430             var a = xi * yi1 - xi1 * yi;
33431             area += a;
33432             centroidX += (xi + xi1) * a;
33433             centroidY += (yi + yi1) * a;
33434         }
33435         area /= 2;
33436         centroidX /= 6 * area;
33437         centroidY /= 6 * area;
33438         return [centroidX, centroidY];
33439     };
33440     /** @ignore */
33441     PolygonGeometry.prototype.getCentroid3d = function (transform) {
33442         var centroid2d = this.getCentroid2d();
33443         return transform.unprojectBasic(centroid2d, 200);
33444     };
33445     /** @ignore */
33446     PolygonGeometry.prototype.get3dDomainTriangles3d = function (transform) {
33447         var _this = this;
33448         return this._triangulate(this._project(this._polygon, transform), this.getVertices3d(transform), this._holes
33449             .map(function (hole2d) {
33450             return _this._project(hole2d, transform);
33451         }), this.getHoleVertices3d(transform));
33452     };
33453     /** @ignore */
33454     PolygonGeometry.prototype.getTriangles3d = function (transform) {
33455         var _this = this;
33456         if (transform.fullPano) {
33457             return this._triangulatePano(this._polygon.slice(), this.holes.slice(), transform);
33458         }
33459         var points2d = this._project(this._subsample(this._polygon), transform);
33460         var points3d = this.getPoints3d(transform);
33461         var holes2d = this._holes
33462             .map(function (hole) {
33463             return _this._project(_this._subsample(hole), transform);
33464         });
33465         var holes3d = this.getHolePoints3d(transform);
33466         return this._triangulate(points2d, points3d, holes2d, holes3d);
33467     };
33468     /** @ignore */
33469     PolygonGeometry.prototype.getPoleOfInaccessibility2d = function () {
33470         return this._getPoleOfInaccessibility2d(this._polygon.slice());
33471     };
33472     /** @ignore */
33473     PolygonGeometry.prototype.getPoleOfInaccessibility3d = function (transform) {
33474         var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
33475         return transform.unprojectBasic(pole2d, 200);
33476     };
33477     PolygonGeometry.prototype._getPoints3d = function (points2d, transform) {
33478         return points2d
33479             .map(function (point) {
33480             return transform.unprojectBasic(point, 200);
33481         });
33482     };
33483     return PolygonGeometry;
33484 }(Component_1.VertexGeometry));
33485 exports.PolygonGeometry = PolygonGeometry;
33486 exports.default = PolygonGeometry;
33487
33488 },{"../../../Component":275}],355:[function(require,module,exports){
33489 "use strict";
33490 var __extends = (this && this.__extends) || (function () {
33491     var extendStatics = function (d, b) {
33492         extendStatics = Object.setPrototypeOf ||
33493             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33494             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33495         return extendStatics(d, b);
33496     }
33497     return function (d, b) {
33498         extendStatics(d, b);
33499         function __() { this.constructor = d; }
33500         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33501     };
33502 })();
33503 Object.defineProperty(exports, "__esModule", { value: true });
33504 var Component_1 = require("../../../Component");
33505 /**
33506  * @class RectGeometry
33507  *
33508  * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
33509  *
33510  * @example
33511  * ```
33512  * var basicRect = [0.5, 0.3, 0.7, 0.4];
33513  * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
33514  * ```
33515  */
33516 var RectGeometry = /** @class */ (function (_super) {
33517     __extends(RectGeometry, _super);
33518     /**
33519      * Create a rectangle geometry.
33520      *
33521      * @constructor
33522      * @param {Array<number>} rect - An array representing the top-left and bottom-right
33523      * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
33524      *
33525      * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
33526      */
33527     function RectGeometry(rect) {
33528         var _this = _super.call(this) || this;
33529         if (rect[1] > rect[3]) {
33530             throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
33531         }
33532         for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
33533             var coord = rect_1[_i];
33534             if (coord < 0 || coord > 1) {
33535                 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
33536             }
33537         }
33538         _this._anchorIndex = undefined;
33539         _this._rect = rect.slice(0, 4);
33540         _this._inverted = _this._rect[0] > _this._rect[2];
33541         return _this;
33542     }
33543     Object.defineProperty(RectGeometry.prototype, "anchorIndex", {
33544         /**
33545          * Get anchor index property.
33546          *
33547          * @returns {number} Index representing the current anchor property if
33548          * achoring indexing has been initialized. If anchor indexing has not been
33549          * initialized or has been terminated undefined will be returned.
33550          * @ignore
33551          */
33552         get: function () {
33553             return this._anchorIndex;
33554         },
33555         enumerable: true,
33556         configurable: true
33557     });
33558     Object.defineProperty(RectGeometry.prototype, "inverted", {
33559         /**
33560          * Get inverted property.
33561          *
33562          * @returns {boolean} Boolean determining whether the rect geometry is
33563          * inverted. For panoramas the rect geometrye may be inverted.
33564          * @ignore
33565          */
33566         get: function () {
33567             return this._inverted;
33568         },
33569         enumerable: true,
33570         configurable: true
33571     });
33572     Object.defineProperty(RectGeometry.prototype, "rect", {
33573         /**
33574          * Get rect property.
33575          *
33576          * @returns {Array<number>} Array representing the top-left and bottom-right
33577          * corners of the rectangle in basic coordinates.
33578          */
33579         get: function () {
33580             return this._rect;
33581         },
33582         enumerable: true,
33583         configurable: true
33584     });
33585     /**
33586      * Initialize anchor indexing to enable setting opposite vertex.
33587      *
33588      * @param {number} [index] - The index of the vertex to use as anchor.
33589      *
33590      * @throws {Error} If anchor indexing has already been initialized.
33591      * @throws {Error} If index is not valid (0 to 3).
33592      * @ignore
33593      */
33594     RectGeometry.prototype.initializeAnchorIndexing = function (index) {
33595         if (this._anchorIndex !== undefined) {
33596             throw new Error("Anchor indexing is already initialized.");
33597         }
33598         if (index < 0 || index > 3) {
33599             throw new Error("Invalid anchor index: " + index + ".");
33600         }
33601         this._anchorIndex = index === undefined ? 0 : index;
33602     };
33603     /**
33604      * Terminate anchor indexing to disable setting pposite vertex.
33605      * @ignore
33606      */
33607     RectGeometry.prototype.terminateAnchorIndexing = function () {
33608         this._anchorIndex = undefined;
33609     };
33610     /**
33611      * Set the value of the vertex opposite to the anchor in the polygon
33612      * representation of the rectangle.
33613      *
33614      * @description Setting the opposite vertex may change the anchor index.
33615      *
33616      * @param {Array<number>} opposite - The new value of the vertex opposite to the anchor.
33617      * @param {Transform} transform - The transform of the node related to the rectangle.
33618      *
33619      * @throws {Error} When anchor indexing has not been initialized.
33620      * @ignore
33621      */
33622     RectGeometry.prototype.setOppositeVertex2d = function (opposite, transform) {
33623         if (this._anchorIndex === undefined) {
33624             throw new Error("Anchor indexing needs to be initialized.");
33625         }
33626         var changed = [
33627             Math.max(0, Math.min(1, opposite[0])),
33628             Math.max(0, Math.min(1, opposite[1])),
33629         ];
33630         var original = this._rect.slice();
33631         var anchor = this._anchorIndex === 0 ? [original[0], original[3]] :
33632             this._anchorIndex === 1 ? [original[0], original[1]] :
33633                 this._anchorIndex === 2 ? [original[2], original[1]] :
33634                     [original[2], original[3]];
33635         if (transform.fullPano) {
33636             var deltaX = this._anchorIndex < 2 ?
33637                 changed[0] - original[2] :
33638                 changed[0] - original[0];
33639             if (!this._inverted && this._anchorIndex < 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
33640                 // right side passes boundary rightward
33641                 this._inverted = true;
33642                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
33643             }
33644             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
33645                 // left side passes right side and boundary rightward
33646                 this._inverted = true;
33647                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
33648             }
33649             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[0] > 0.75 && deltaX < -0.5) {
33650                 this._inverted = false;
33651                 if (anchor[0] > changed[0]) {
33652                     // left side passes boundary rightward
33653                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
33654                 }
33655                 else {
33656                     // left side passes right side and boundary rightward
33657                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
33658                 }
33659             }
33660             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
33661                 // left side passes boundary leftward
33662                 this._inverted = true;
33663                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
33664             }
33665             else if (!this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
33666                 // right side passes left side and boundary leftward
33667                 this._inverted = true;
33668                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
33669             }
33670             else if (this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[2] < 0.25 && deltaX > 0.5) {
33671                 this._inverted = false;
33672                 if (anchor[0] > changed[0]) {
33673                     // right side passes boundary leftward
33674                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
33675                 }
33676                 else {
33677                     // right side passes left side and boundary leftward
33678                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
33679                 }
33680             }
33681             else if (this._inverted && this._anchorIndex < 2 && changed[0] > original[0]) {
33682                 // inverted and right side passes left side completing a loop
33683                 this._inverted = false;
33684                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
33685             }
33686             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < original[2]) {
33687                 // inverted and left side passes right side completing a loop
33688                 this._inverted = false;
33689                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
33690             }
33691             else if (this._inverted) {
33692                 // if still inverted only top and bottom can switch
33693                 if (this._anchorIndex < 2) {
33694                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
33695                 }
33696                 else {
33697                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
33698                 }
33699             }
33700             else {
33701                 // if still not inverted treat as non full pano
33702                 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
33703                     this._anchorIndex = 0;
33704                 }
33705                 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
33706                     this._anchorIndex = 1;
33707                 }
33708                 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
33709                     this._anchorIndex = 2;
33710                 }
33711                 else {
33712                     this._anchorIndex = 3;
33713                 }
33714             }
33715             var rect = [];
33716             if (this._anchorIndex === 0) {
33717                 rect[0] = anchor[0];
33718                 rect[1] = changed[1];
33719                 rect[2] = changed[0];
33720                 rect[3] = anchor[1];
33721             }
33722             else if (this._anchorIndex === 1) {
33723                 rect[0] = anchor[0];
33724                 rect[1] = anchor[1];
33725                 rect[2] = changed[0];
33726                 rect[3] = changed[1];
33727             }
33728             else if (this._anchorIndex === 2) {
33729                 rect[0] = changed[0];
33730                 rect[1] = anchor[1];
33731                 rect[2] = anchor[0];
33732                 rect[3] = changed[1];
33733             }
33734             else {
33735                 rect[0] = changed[0];
33736                 rect[1] = changed[1];
33737                 rect[2] = anchor[0];
33738                 rect[3] = anchor[1];
33739             }
33740             if (!this._inverted && rect[0] > rect[2] ||
33741                 this._inverted && rect[0] < rect[2]) {
33742                 rect[0] = original[0];
33743                 rect[2] = original[2];
33744             }
33745             if (rect[1] > rect[3]) {
33746                 rect[1] = original[1];
33747                 rect[3] = original[3];
33748             }
33749             this._rect[0] = rect[0];
33750             this._rect[1] = rect[1];
33751             this._rect[2] = rect[2];
33752             this._rect[3] = rect[3];
33753         }
33754         else {
33755             if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
33756                 this._anchorIndex = 0;
33757             }
33758             else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
33759                 this._anchorIndex = 1;
33760             }
33761             else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
33762                 this._anchorIndex = 2;
33763             }
33764             else {
33765                 this._anchorIndex = 3;
33766             }
33767             var rect = [];
33768             if (this._anchorIndex === 0) {
33769                 rect[0] = anchor[0];
33770                 rect[1] = changed[1];
33771                 rect[2] = changed[0];
33772                 rect[3] = anchor[1];
33773             }
33774             else if (this._anchorIndex === 1) {
33775                 rect[0] = anchor[0];
33776                 rect[1] = anchor[1];
33777                 rect[2] = changed[0];
33778                 rect[3] = changed[1];
33779             }
33780             else if (this._anchorIndex === 2) {
33781                 rect[0] = changed[0];
33782                 rect[1] = anchor[1];
33783                 rect[2] = anchor[0];
33784                 rect[3] = changed[1];
33785             }
33786             else {
33787                 rect[0] = changed[0];
33788                 rect[1] = changed[1];
33789                 rect[2] = anchor[0];
33790                 rect[3] = anchor[1];
33791             }
33792             if (rect[0] > rect[2]) {
33793                 rect[0] = original[0];
33794                 rect[2] = original[2];
33795             }
33796             if (rect[1] > rect[3]) {
33797                 rect[1] = original[1];
33798                 rect[3] = original[3];
33799             }
33800             this._rect[0] = rect[0];
33801             this._rect[1] = rect[1];
33802             this._rect[2] = rect[2];
33803             this._rect[3] = rect[3];
33804         }
33805         this._notifyChanged$.next(this);
33806     };
33807     /**
33808      * Set the value of a vertex in the polygon representation of the rectangle.
33809      *
33810      * @description The polygon is defined to have the first vertex at the
33811      * bottom-left corner with the rest of the vertices following in clockwise order.
33812      *
33813      * @param {number} index - The index of the vertex to be set.
33814      * @param {Array<number>} value - The new value of the vertex.
33815      * @param {Transform} transform - The transform of the node related to the rectangle.
33816      * @ignore
33817      */
33818     RectGeometry.prototype.setVertex2d = function (index, value, transform) {
33819         var original = this._rect.slice();
33820         var changed = [
33821             Math.max(0, Math.min(1, value[0])),
33822             Math.max(0, Math.min(1, value[1])),
33823         ];
33824         var rect = [];
33825         if (index === 0) {
33826             rect[0] = changed[0];
33827             rect[1] = original[1];
33828             rect[2] = original[2];
33829             rect[3] = changed[1];
33830         }
33831         else if (index === 1) {
33832             rect[0] = changed[0];
33833             rect[1] = changed[1];
33834             rect[2] = original[2];
33835             rect[3] = original[3];
33836         }
33837         else if (index === 2) {
33838             rect[0] = original[0];
33839             rect[1] = changed[1];
33840             rect[2] = changed[0];
33841             rect[3] = original[3];
33842         }
33843         else if (index === 3) {
33844             rect[0] = original[0];
33845             rect[1] = original[1];
33846             rect[2] = changed[0];
33847             rect[3] = changed[1];
33848         }
33849         if (transform.fullPano) {
33850             var passingBoundaryLeftward = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
33851                 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
33852             var passingBoundaryRightward = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
33853                 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
33854             if (passingBoundaryLeftward || passingBoundaryRightward) {
33855                 this._inverted = !this._inverted;
33856             }
33857             else {
33858                 if (rect[0] - original[0] < -0.25) {
33859                     rect[0] = original[0];
33860                 }
33861                 if (rect[2] - original[2] > 0.25) {
33862                     rect[2] = original[2];
33863                 }
33864             }
33865             if (!this._inverted && rect[0] > rect[2] ||
33866                 this._inverted && rect[0] < rect[2]) {
33867                 rect[0] = original[0];
33868                 rect[2] = original[2];
33869             }
33870         }
33871         else {
33872             if (rect[0] > rect[2]) {
33873                 rect[0] = original[0];
33874                 rect[2] = original[2];
33875             }
33876         }
33877         if (rect[1] > rect[3]) {
33878             rect[1] = original[1];
33879             rect[3] = original[3];
33880         }
33881         this._rect[0] = rect[0];
33882         this._rect[1] = rect[1];
33883         this._rect[2] = rect[2];
33884         this._rect[3] = rect[3];
33885         this._notifyChanged$.next(this);
33886     };
33887     /** @ignore */
33888     RectGeometry.prototype.setCentroid2d = function (value, transform) {
33889         var original = this._rect.slice();
33890         var x0 = original[0];
33891         var x1 = this._inverted ? original[2] + 1 : original[2];
33892         var y0 = original[1];
33893         var y1 = original[3];
33894         var centerX = x0 + (x1 - x0) / 2;
33895         var centerY = y0 + (y1 - y0) / 2;
33896         var translationX = 0;
33897         if (transform.gpano != null &&
33898             transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
33899             translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
33900         }
33901         else {
33902             var minTranslationX = -x0;
33903             var maxTranslationX = 1 - x1;
33904             translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
33905         }
33906         var minTranslationY = -y0;
33907         var maxTranslationY = 1 - y1;
33908         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
33909         this._rect[0] = original[0] + translationX;
33910         this._rect[1] = original[1] + translationY;
33911         this._rect[2] = original[2] + translationX;
33912         this._rect[3] = original[3] + translationY;
33913         if (this._rect[0] < 0) {
33914             this._rect[0] += 1;
33915             this._inverted = !this._inverted;
33916         }
33917         else if (this._rect[0] > 1) {
33918             this._rect[0] -= 1;
33919             this._inverted = !this._inverted;
33920         }
33921         if (this._rect[2] < 0) {
33922             this._rect[2] += 1;
33923             this._inverted = !this._inverted;
33924         }
33925         else if (this._rect[2] > 1) {
33926             this._rect[2] -= 1;
33927             this._inverted = !this._inverted;
33928         }
33929         this._notifyChanged$.next(this);
33930     };
33931     /**
33932      * Get the 3D coordinates for the vertices of the rectangle with
33933      * interpolated points along the lines.
33934      *
33935      * @param {Transform} transform - The transform of the node related to
33936      * the rectangle.
33937      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
33938      * representing the rectangle.
33939      * @ignore
33940      */
33941     RectGeometry.prototype.getPoints3d = function (transform) {
33942         return this._getPoints2d()
33943             .map(function (point) {
33944             return transform.unprojectBasic(point, 200);
33945         });
33946     };
33947     /**
33948      * Get the coordinates of a vertex from the polygon representation of the geometry.
33949      *
33950      * @description The first vertex represents the bottom-left corner with the rest of
33951      * the vertices following in clockwise order. The method shifts the right side
33952      * coordinates of the rectangle by one unit to ensure that the vertices are ordered
33953      * clockwise.
33954      *
33955      * @param {number} index - Vertex index.
33956      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
33957      * @ignore
33958      */
33959     RectGeometry.prototype.getVertex2d = function (index) {
33960         return this._rectToVertices2d(this._rect)[index];
33961     };
33962     /**
33963      * Get the coordinates of a vertex from the polygon representation of the geometry.
33964      *
33965      * @description The first vertex represents the bottom-left corner with the rest of
33966      * the vertices following in clockwise order. The coordinates will not be shifted
33967      * so they may not appear in clockwise order when layed out on the plane.
33968      *
33969      * @param {number} index - Vertex index.
33970      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
33971      * @ignore
33972      */
33973     RectGeometry.prototype.getNonAdjustedVertex2d = function (index) {
33974         return this._rectToNonAdjustedVertices2d(this._rect)[index];
33975     };
33976     /**
33977      * Get a vertex from the polygon representation of the 3D coordinates for the
33978      * vertices of the geometry.
33979      *
33980      * @description The first vertex represents the bottom-left corner with the rest of
33981      * the vertices following in clockwise order.
33982      *
33983      * @param {number} index - Vertex index.
33984      * @param {Transform} transform - The transform of the node related to the geometry.
33985      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
33986      * the vertices of the geometry.
33987      * @ignore
33988      */
33989     RectGeometry.prototype.getVertex3d = function (index, transform) {
33990         return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
33991     };
33992     /**
33993      * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
33994      *
33995      * @description The first vertex represents the bottom-left corner with the rest of
33996      * the vertices following in clockwise order.
33997      *
33998      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
33999      * the rectangle vertices.
34000      * @ignore
34001      */
34002     RectGeometry.prototype.getVertices2d = function () {
34003         return this._rectToVertices2d(this._rect);
34004     };
34005     /**
34006      * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
34007      *
34008      * @description The first vertex represents the bottom-left corner with the rest of
34009      * the vertices following in clockwise order.
34010      *
34011      * @param {Transform} transform - The transform of the node related to the rectangle.
34012      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
34013      * the rectangle vertices.
34014      * @ignore
34015      */
34016     RectGeometry.prototype.getVertices3d = function (transform) {
34017         return this._rectToVertices2d(this._rect)
34018             .map(function (vertex) {
34019             return transform.unprojectBasic(vertex, 200);
34020         });
34021     };
34022     /** @ignore */
34023     RectGeometry.prototype.getCentroid2d = function () {
34024         var rect = this._rect;
34025         var x0 = rect[0];
34026         var x1 = this._inverted ? rect[2] + 1 : rect[2];
34027         var y0 = rect[1];
34028         var y1 = rect[3];
34029         var centroidX = (x0 + x1) / 2;
34030         var centroidY = (y0 + y1) / 2;
34031         return [centroidX, centroidY];
34032     };
34033     /** @ignore */
34034     RectGeometry.prototype.getCentroid3d = function (transform) {
34035         var centroid2d = this.getCentroid2d();
34036         return transform.unprojectBasic(centroid2d, 200);
34037     };
34038     /**
34039      * @ignore
34040      */
34041     RectGeometry.prototype.getPoleOfInaccessibility2d = function () {
34042         return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
34043     };
34044     /** @ignore */
34045     RectGeometry.prototype.getPoleOfInaccessibility3d = function (transform) {
34046         var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
34047         return transform.unprojectBasic(pole2d, 200);
34048     };
34049     /** @ignore */
34050     RectGeometry.prototype.getTriangles3d = function (transform) {
34051         return transform.fullPano ?
34052             [] :
34053             this._triangulate(this._project(this._getPoints2d(), transform), this.getPoints3d(transform));
34054     };
34055     /**
34056      * Check if a particular bottom-right value is valid according to the current
34057      * rectangle coordinates.
34058      *
34059      * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
34060      * @returns {boolean} Value indicating whether the provided bottom-right coordinates
34061      * are valid.
34062      * @ignore
34063      */
34064     RectGeometry.prototype.validate = function (bottomRight) {
34065         var rect = this._rect;
34066         if (!this._inverted && bottomRight[0] < rect[0] ||
34067             bottomRight[0] - rect[2] > 0.25 ||
34068             bottomRight[1] < rect[1]) {
34069             return false;
34070         }
34071         return true;
34072     };
34073     /**
34074      * Get the 2D coordinates for the vertices of the rectangle with
34075      * interpolated points along the lines.
34076      *
34077      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
34078      * representing the rectangle.
34079      */
34080     RectGeometry.prototype._getPoints2d = function () {
34081         var vertices2d = this._rectToVertices2d(this._rect);
34082         var sides = vertices2d.length - 1;
34083         var sections = 10;
34084         var points2d = [];
34085         for (var i = 0; i < sides; ++i) {
34086             var startX = vertices2d[i][0];
34087             var startY = vertices2d[i][1];
34088             var endX = vertices2d[i + 1][0];
34089             var endY = vertices2d[i + 1][1];
34090             var intervalX = (endX - startX) / (sections - 1);
34091             var intervalY = (endY - startY) / (sections - 1);
34092             for (var j = 0; j < sections; ++j) {
34093                 var point = [
34094                     startX + j * intervalX,
34095                     startY + j * intervalY,
34096                 ];
34097                 points2d.push(point);
34098             }
34099         }
34100         return points2d;
34101     };
34102     /**
34103      * Convert the top-left, bottom-right representation of a rectangle to a polygon
34104      * representation of the vertices starting at the bottom-left corner going
34105      * clockwise.
34106      *
34107      * @description The method shifts the right side coordinates of the rectangle
34108      * by one unit to ensure that the vertices are ordered clockwise.
34109      *
34110      * @param {Array<number>} rect - Top-left, bottom-right representation of a
34111      * rectangle.
34112      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
34113      * rectangle.
34114      */
34115     RectGeometry.prototype._rectToVertices2d = function (rect) {
34116         return [
34117             [rect[0], rect[3]],
34118             [rect[0], rect[1]],
34119             [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
34120             [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
34121             [rect[0], rect[3]],
34122         ];
34123     };
34124     /**
34125      * Convert the top-left, bottom-right representation of a rectangle to a polygon
34126      * representation of the vertices starting at the bottom-left corner going
34127      * clockwise.
34128      *
34129      * @description The first vertex represents the bottom-left corner with the rest of
34130      * the vertices following in clockwise order. The coordinates will not be shifted
34131      * to ensure that the vertices are ordered clockwise when layed out on the plane.
34132      *
34133      * @param {Array<number>} rect - Top-left, bottom-right representation of a
34134      * rectangle.
34135      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
34136      * rectangle.
34137      */
34138     RectGeometry.prototype._rectToNonAdjustedVertices2d = function (rect) {
34139         return [
34140             [rect[0], rect[3]],
34141             [rect[0], rect[1]],
34142             [rect[2], rect[1]],
34143             [rect[2], rect[3]],
34144             [rect[0], rect[3]],
34145         ];
34146     };
34147     return RectGeometry;
34148 }(Component_1.VertexGeometry));
34149 exports.RectGeometry = RectGeometry;
34150 exports.default = RectGeometry;
34151
34152 },{"../../../Component":275}],356:[function(require,module,exports){
34153 "use strict";
34154 var __extends = (this && this.__extends) || (function () {
34155     var extendStatics = function (d, b) {
34156         extendStatics = Object.setPrototypeOf ||
34157             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34158             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34159         return extendStatics(d, b);
34160     }
34161     return function (d, b) {
34162         extendStatics(d, b);
34163         function __() { this.constructor = d; }
34164         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34165     };
34166 })();
34167 Object.defineProperty(exports, "__esModule", { value: true });
34168 var earcut_1 = require("earcut");
34169 var martinez = require("martinez-polygon-clipping");
34170 var polylabel = require("@mapbox/polylabel");
34171 var THREE = require("three");
34172 var Component_1 = require("../../../Component");
34173 /**
34174  * @class VertexGeometry
34175  * @abstract
34176  * @classdesc Represents a vertex geometry.
34177  */
34178 var VertexGeometry = /** @class */ (function (_super) {
34179     __extends(VertexGeometry, _super);
34180     /**
34181      * Create a vertex geometry.
34182      *
34183      * @constructor
34184      * @ignore
34185      */
34186     function VertexGeometry() {
34187         var _this = _super.call(this) || this;
34188         _this._subsampleThreshold = 0.005;
34189         return _this;
34190     }
34191     /**
34192      * Finds the polygon pole of inaccessibility, the most distant internal
34193      * point from the polygon outline.
34194      *
34195      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
34196      * @returns {Array<number>} Point of inaccessibility.
34197      * @ignore
34198      */
34199     VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
34200         var pole2d = polylabel([points2d], 3e-2);
34201         return pole2d;
34202     };
34203     VertexGeometry.prototype._project = function (points2d, transform) {
34204         var camera = this._createCamera(transform.upVector().toArray(), transform.unprojectSfM([0, 0], 0), transform.unprojectSfM([0, 0], 10));
34205         return this._deunproject(points2d, transform, camera);
34206     };
34207     VertexGeometry.prototype._subsample = function (points2d, threshold) {
34208         if (threshold === void 0) { threshold = this._subsampleThreshold; }
34209         var subsampled = [];
34210         var length = points2d.length;
34211         for (var index = 0; index < length; index++) {
34212             var p1 = points2d[index];
34213             var p2 = points2d[(index + 1) % length];
34214             subsampled.push(p1);
34215             var dist = Math.sqrt(Math.pow((p2[0] - p1[0]), 2) + Math.pow((p2[1] - p1[1]), 2));
34216             var subsamples = Math.floor(dist / threshold);
34217             var coeff = 1 / (subsamples + 1);
34218             for (var i = 1; i <= subsamples; i++) {
34219                 var alpha = i * coeff;
34220                 var subsample = [
34221                     (1 - alpha) * p1[0] + alpha * p2[0],
34222                     (1 - alpha) * p1[1] + alpha * p2[1],
34223                 ];
34224                 subsampled.push(subsample);
34225             }
34226         }
34227         return subsampled;
34228     };
34229     /**
34230      * Triangulates a 2d polygon and returns the triangle
34231      * representation as a flattened array of 3d points.
34232      *
34233      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
34234      * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
34235      * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
34236      * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
34237      * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
34238      * @ignore
34239      */
34240     VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
34241         var data = [points2d.slice(0, -1)];
34242         for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
34243             var hole2d = _a[_i];
34244             data.push(hole2d.slice(0, -1));
34245         }
34246         var points = points3d.slice(0, -1);
34247         for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
34248             var hole3d = _c[_b];
34249             points = points.concat(hole3d.slice(0, -1));
34250         }
34251         var flattened = earcut_1.default.flatten(data);
34252         var indices = earcut_1.default(flattened.vertices, flattened.holes, flattened.dimensions);
34253         var triangles = [];
34254         for (var i = 0; i < indices.length; ++i) {
34255             var point = points[indices[i]];
34256             triangles.push(point[0]);
34257             triangles.push(point[1]);
34258             triangles.push(point[2]);
34259         }
34260         return triangles;
34261     };
34262     VertexGeometry.prototype._triangulatePano = function (points2d, holes2d, transform) {
34263         var triangles = [];
34264         var epsilon = 1e-9;
34265         var subareasX = 3;
34266         var subareasY = 3;
34267         for (var x = 0; x < subareasX; x++) {
34268             for (var y = 0; y < subareasY; y++) {
34269                 var epsilonX0 = x === 0 ? -epsilon : epsilon;
34270                 var epsilonY0 = y === 0 ? -epsilon : epsilon;
34271                 var x0 = x / subareasX + epsilonX0;
34272                 var y0 = y / subareasY + epsilonY0;
34273                 var x1 = (x + 1) / subareasX + epsilon;
34274                 var y1 = (y + 1) / subareasY + epsilon;
34275                 var bbox2d = [
34276                     [x0, y0],
34277                     [x0, y1],
34278                     [x1, y1],
34279                     [x1, y0],
34280                     [x0, y0],
34281                 ];
34282                 var lookat2d = [
34283                     (2 * x + 1) / (2 * subareasX),
34284                     (2 * y + 1) / (2 * subareasY),
34285                 ];
34286                 triangles.push.apply(triangles, this._triangulateSubarea(points2d, holes2d, bbox2d, lookat2d, transform));
34287             }
34288         }
34289         return triangles;
34290     };
34291     VertexGeometry.prototype._unproject = function (points2d, transform, distance) {
34292         if (distance === void 0) { distance = 200; }
34293         return points2d
34294             .map(function (point) {
34295             return transform.unprojectBasic(point, distance);
34296         });
34297     };
34298     VertexGeometry.prototype._createCamera = function (upVector, position, lookAt) {
34299         var camera = new THREE.Camera();
34300         camera.up.copy(new THREE.Vector3().fromArray(upVector));
34301         camera.position.copy(new THREE.Vector3().fromArray(position));
34302         camera.lookAt(new THREE.Vector3().fromArray(lookAt));
34303         camera.updateMatrix();
34304         camera.updateMatrixWorld(true);
34305         return camera;
34306     };
34307     VertexGeometry.prototype._deunproject = function (points2d, transform, camera) {
34308         return points2d
34309             .map(function (point2d) {
34310             var pointWorld = transform.unprojectBasic(point2d, 10000);
34311             var pointCamera = new THREE.Vector3(pointWorld[0], pointWorld[1], pointWorld[2])
34312                 .applyMatrix4(camera.matrixWorldInverse);
34313             return [pointCamera.x / pointCamera.z, pointCamera.y / pointCamera.z];
34314         });
34315     };
34316     VertexGeometry.prototype._triangulateSubarea = function (points2d, holes2d, bbox2d, lookat2d, transform) {
34317         var intersections = martinez.intersection([points2d].concat(holes2d), [bbox2d]);
34318         if (!intersections) {
34319             return [];
34320         }
34321         var triangles = [];
34322         var threshold = this._subsampleThreshold;
34323         var camera = this._createCamera(transform.upVector().toArray(), transform.unprojectSfM([0, 0], 0), transform.unprojectBasic(lookat2d, 10));
34324         for (var _i = 0, intersections_1 = intersections; _i < intersections_1.length; _i++) {
34325             var intersection = intersections_1[_i];
34326             var subsampledPolygon2d = this._subsample(intersection[0], threshold);
34327             var polygon2d = this._deunproject(subsampledPolygon2d, transform, camera);
34328             var polygon3d = this._unproject(subsampledPolygon2d, transform);
34329             var polygonHoles2d = [];
34330             var polygonHoles3d = [];
34331             for (var i = 1; i < intersection.length; i++) {
34332                 var subsampledHole2d = this._subsample(intersection[i], threshold);
34333                 var hole2d = this._deunproject(subsampledHole2d, transform, camera);
34334                 var hole3d = this._unproject(subsampledHole2d, transform);
34335                 polygonHoles2d.push(hole2d);
34336                 polygonHoles3d.push(hole3d);
34337             }
34338             triangles.push.apply(triangles, this._triangulate(polygon2d, polygon3d, polygonHoles2d, polygonHoles3d));
34339         }
34340         return triangles;
34341     };
34342     return VertexGeometry;
34343 }(Component_1.Geometry));
34344 exports.VertexGeometry = VertexGeometry;
34345 exports.default = VertexGeometry;
34346
34347 },{"../../../Component":275,"@mapbox/polylabel":1,"earcut":8,"martinez-polygon-clipping":22,"three":226}],357:[function(require,module,exports){
34348 "use strict";
34349 var __extends = (this && this.__extends) || (function () {
34350     var extendStatics = function (d, b) {
34351         extendStatics = Object.setPrototypeOf ||
34352             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34353             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34354         return extendStatics(d, b);
34355     }
34356     return function (d, b) {
34357         extendStatics(d, b);
34358         function __() { this.constructor = d; }
34359         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34360     };
34361 })();
34362 Object.defineProperty(exports, "__esModule", { value: true });
34363 var operators_1 = require("rxjs/operators");
34364 var rxjs_1 = require("rxjs");
34365 var Component_1 = require("../../../Component");
34366 var CreateHandlerBase = /** @class */ (function (_super) {
34367     __extends(CreateHandlerBase, _super);
34368     function CreateHandlerBase(component, container, navigator, viewportCoords, tagCreator) {
34369         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
34370         _this._tagCreator = tagCreator;
34371         _this._geometryCreated$ = new rxjs_1.Subject();
34372         return _this;
34373     }
34374     Object.defineProperty(CreateHandlerBase.prototype, "geometryCreated$", {
34375         get: function () {
34376             return this._geometryCreated$;
34377         },
34378         enumerable: true,
34379         configurable: true
34380     });
34381     CreateHandlerBase.prototype._enable = function () {
34382         this._enableCreate();
34383         this._container.element.classList.add("component-tag-create");
34384     };
34385     CreateHandlerBase.prototype._disable = function () {
34386         this._container.element.classList.remove("component-tag-create");
34387         this._disableCreate();
34388     };
34389     CreateHandlerBase.prototype._validateBasic = function (basic) {
34390         var x = basic[0];
34391         var y = basic[1];
34392         return 0 <= x && x <= 1 && 0 <= y && y <= 1;
34393     };
34394     CreateHandlerBase.prototype._mouseEventToBasic$ = function (mouseEvent$) {
34395         var _this = this;
34396         return mouseEvent$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
34397             var event = _a[0], camera = _a[1], transform = _a[2];
34398             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
34399         }));
34400     };
34401     return CreateHandlerBase;
34402 }(Component_1.TagHandlerBase));
34403 exports.CreateHandlerBase = CreateHandlerBase;
34404 exports.default = CreateHandlerBase;
34405
34406 },{"../../../Component":275,"rxjs":27,"rxjs/operators":225}],358:[function(require,module,exports){
34407 "use strict";
34408 var __extends = (this && this.__extends) || (function () {
34409     var extendStatics = function (d, b) {
34410         extendStatics = Object.setPrototypeOf ||
34411             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34412             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34413         return extendStatics(d, b);
34414     }
34415     return function (d, b) {
34416         extendStatics(d, b);
34417         function __() { this.constructor = d; }
34418         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34419     };
34420 })();
34421 Object.defineProperty(exports, "__esModule", { value: true });
34422 var operators_1 = require("rxjs/operators");
34423 var Component_1 = require("../../../Component");
34424 var CreatePointHandler = /** @class */ (function (_super) {
34425     __extends(CreatePointHandler, _super);
34426     function CreatePointHandler() {
34427         return _super !== null && _super.apply(this, arguments) || this;
34428     }
34429     CreatePointHandler.prototype._enableCreate = function () {
34430         this._container.mouseService.deferPixels(this._name, 4);
34431         this._geometryCreatedSubscription = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).pipe(operators_1.filter(this._validateBasic), operators_1.map(function (basic) {
34432             return new Component_1.PointGeometry(basic);
34433         }))
34434             .subscribe(this._geometryCreated$);
34435     };
34436     CreatePointHandler.prototype._disableCreate = function () {
34437         this._container.mouseService.undeferPixels(this._name);
34438         this._geometryCreatedSubscription.unsubscribe();
34439     };
34440     CreatePointHandler.prototype._getNameExtension = function () {
34441         return "create-point";
34442     };
34443     return CreatePointHandler;
34444 }(Component_1.CreateHandlerBase));
34445 exports.CreatePointHandler = CreatePointHandler;
34446 exports.default = CreatePointHandler;
34447
34448 },{"../../../Component":275,"rxjs/operators":225}],359:[function(require,module,exports){
34449 "use strict";
34450 var __extends = (this && this.__extends) || (function () {
34451     var extendStatics = function (d, b) {
34452         extendStatics = Object.setPrototypeOf ||
34453             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34454             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34455         return extendStatics(d, b);
34456     }
34457     return function (d, b) {
34458         extendStatics(d, b);
34459         function __() { this.constructor = d; }
34460         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34461     };
34462 })();
34463 Object.defineProperty(exports, "__esModule", { value: true });
34464 var Component_1 = require("../../../Component");
34465 var CreatePolygonHandler = /** @class */ (function (_super) {
34466     __extends(CreatePolygonHandler, _super);
34467     function CreatePolygonHandler() {
34468         return _super !== null && _super.apply(this, arguments) || this;
34469     }
34470     CreatePolygonHandler.prototype._addPoint = function (tag, basicPoint) {
34471         tag.addPoint(basicPoint);
34472     };
34473     Object.defineProperty(CreatePolygonHandler.prototype, "_create$", {
34474         get: function () {
34475             return this._tagCreator.createPolygon$;
34476         },
34477         enumerable: true,
34478         configurable: true
34479     });
34480     CreatePolygonHandler.prototype._getNameExtension = function () {
34481         return "create-polygon";
34482     };
34483     CreatePolygonHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
34484         tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basicPoint, transform);
34485     };
34486     return CreatePolygonHandler;
34487 }(Component_1.CreateVertexHandler));
34488 exports.CreatePolygonHandler = CreatePolygonHandler;
34489 exports.default = CreatePolygonHandler;
34490
34491 },{"../../../Component":275}],360:[function(require,module,exports){
34492 "use strict";
34493 var __extends = (this && this.__extends) || (function () {
34494     var extendStatics = function (d, b) {
34495         extendStatics = Object.setPrototypeOf ||
34496             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34497             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34498         return extendStatics(d, b);
34499     }
34500     return function (d, b) {
34501         extendStatics(d, b);
34502         function __() { this.constructor = d; }
34503         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34504     };
34505 })();
34506 Object.defineProperty(exports, "__esModule", { value: true });
34507 var rxjs_1 = require("rxjs");
34508 var operators_1 = require("rxjs/operators");
34509 var Component_1 = require("../../../Component");
34510 var CreateRectDragHandler = /** @class */ (function (_super) {
34511     __extends(CreateRectDragHandler, _super);
34512     function CreateRectDragHandler() {
34513         return _super !== null && _super.apply(this, arguments) || this;
34514     }
34515     CreateRectDragHandler.prototype._enableCreate = function () {
34516         var _this = this;
34517         this._container.mouseService.claimMouse(this._name, 2);
34518         this._deleteSubscription = this._navigator.stateService.currentTransform$.pipe(operators_1.map(function (transform) { return null; }), operators_1.skip(1))
34519             .subscribe(this._tagCreator.delete$);
34520         this._createSubscription = this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDragStart$)).pipe(operators_1.filter(this._validateBasic))
34521             .subscribe(this._tagCreator.createRect$);
34522         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$.pipe(operators_1.filter(function (tag) {
34523             return !!tag;
34524         }))
34525             .subscribe(function (tag) {
34526             tag.geometry.initializeAnchorIndexing();
34527         });
34528         var basicMouse$ = rxjs_1.combineLatest(rxjs_1.merge(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseMove$), this._container.mouseService.filtered$(this._name, this._container.mouseService.domMouseMove$)), this._container.renderService.renderCamera$).pipe(operators_1.withLatestFrom(this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
34529             var _b = _a[0], event = _b[0], camera = _b[1], transform = _a[1];
34530             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
34531         }));
34532         this._setVertexSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
34533             return !!tag ?
34534                 rxjs_1.combineLatest(rxjs_1.of(tag), basicMouse$, _this._navigator.stateService.currentTransform$) :
34535                 rxjs_1.empty();
34536         }))
34537             .subscribe(function (_a) {
34538             var tag = _a[0], basicPoint = _a[1], transform = _a[2];
34539             tag.geometry.setOppositeVertex2d(basicPoint, transform);
34540         });
34541         var basicMouseDragEnd$ = this._container.mouseService.mouseDragEnd$.pipe(operators_1.withLatestFrom(this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDrag$)).pipe(operators_1.filter(this._validateBasic)), function (event, basicPoint) {
34542             return basicPoint;
34543         }), operators_1.share());
34544         this._addPointSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
34545             return !!tag ?
34546                 rxjs_1.combineLatest(rxjs_1.of(tag), basicMouseDragEnd$) :
34547                 rxjs_1.empty();
34548         }))
34549             .subscribe(function (_a) {
34550             var tag = _a[0], basicPoint = _a[1];
34551             var rectGeometry = tag.geometry;
34552             if (!rectGeometry.validate(basicPoint)) {
34553                 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
34554             }
34555             tag.addPoint(basicPoint);
34556         });
34557         this._geometryCreatedSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
34558             return !!tag ?
34559                 tag.created$.pipe(operators_1.map(function (t) {
34560                     return t.geometry;
34561                 })) :
34562                 rxjs_1.empty();
34563         }))
34564             .subscribe(this._geometryCreated$);
34565     };
34566     CreateRectDragHandler.prototype._disableCreate = function () {
34567         this._container.mouseService.unclaimMouse(this._name);
34568         this._tagCreator.delete$.next(null);
34569         this._addPointSubscription.unsubscribe();
34570         this._createSubscription.unsubscribe();
34571         this._deleteSubscription.unsubscribe();
34572         this._geometryCreatedSubscription.unsubscribe();
34573         this._initializeAnchorIndexingSubscription.unsubscribe();
34574         this._setVertexSubscription.unsubscribe();
34575     };
34576     CreateRectDragHandler.prototype._getNameExtension = function () {
34577         return "create-rect-drag";
34578     };
34579     return CreateRectDragHandler;
34580 }(Component_1.CreateHandlerBase));
34581 exports.CreateRectDragHandler = CreateRectDragHandler;
34582 exports.default = CreateRectDragHandler;
34583
34584 },{"../../../Component":275,"rxjs":27,"rxjs/operators":225}],361:[function(require,module,exports){
34585 "use strict";
34586 var __extends = (this && this.__extends) || (function () {
34587     var extendStatics = function (d, b) {
34588         extendStatics = Object.setPrototypeOf ||
34589             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34590             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34591         return extendStatics(d, b);
34592     }
34593     return function (d, b) {
34594         extendStatics(d, b);
34595         function __() { this.constructor = d; }
34596         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34597     };
34598 })();
34599 Object.defineProperty(exports, "__esModule", { value: true });
34600 var operators_1 = require("rxjs/operators");
34601 var Component_1 = require("../../../Component");
34602 var CreateRectHandler = /** @class */ (function (_super) {
34603     __extends(CreateRectHandler, _super);
34604     function CreateRectHandler() {
34605         return _super !== null && _super.apply(this, arguments) || this;
34606     }
34607     Object.defineProperty(CreateRectHandler.prototype, "_create$", {
34608         get: function () {
34609             return this._tagCreator.createRect$;
34610         },
34611         enumerable: true,
34612         configurable: true
34613     });
34614     CreateRectHandler.prototype._addPoint = function (tag, basicPoint) {
34615         var rectGeometry = tag.geometry;
34616         if (!rectGeometry.validate(basicPoint)) {
34617             basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
34618         }
34619         tag.addPoint(basicPoint);
34620     };
34621     CreateRectHandler.prototype._enable = function () {
34622         _super.prototype._enable.call(this);
34623         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$.pipe(operators_1.filter(function (tag) {
34624             return !!tag;
34625         }))
34626             .subscribe(function (tag) {
34627             tag.geometry.initializeAnchorIndexing();
34628         });
34629     };
34630     CreateRectHandler.prototype._disable = function () {
34631         _super.prototype._disable.call(this);
34632         this._initializeAnchorIndexingSubscription.unsubscribe();
34633     };
34634     CreateRectHandler.prototype._getNameExtension = function () {
34635         return "create-rect";
34636     };
34637     CreateRectHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
34638         tag.geometry.setOppositeVertex2d(basicPoint, transform);
34639     };
34640     return CreateRectHandler;
34641 }(Component_1.CreateVertexHandler));
34642 exports.CreateRectHandler = CreateRectHandler;
34643 exports.default = CreateRectHandler;
34644
34645 },{"../../../Component":275,"rxjs/operators":225}],362:[function(require,module,exports){
34646 "use strict";
34647 var __extends = (this && this.__extends) || (function () {
34648     var extendStatics = function (d, b) {
34649         extendStatics = Object.setPrototypeOf ||
34650             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34651             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34652         return extendStatics(d, b);
34653     }
34654     return function (d, b) {
34655         extendStatics(d, b);
34656         function __() { this.constructor = d; }
34657         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34658     };
34659 })();
34660 Object.defineProperty(exports, "__esModule", { value: true });
34661 var rxjs_1 = require("rxjs");
34662 var operators_1 = require("rxjs/operators");
34663 var Component_1 = require("../../../Component");
34664 var CreateVertexHandler = /** @class */ (function (_super) {
34665     __extends(CreateVertexHandler, _super);
34666     function CreateVertexHandler() {
34667         return _super !== null && _super.apply(this, arguments) || this;
34668     }
34669     CreateVertexHandler.prototype._enableCreate = function () {
34670         var _this = this;
34671         this._container.mouseService.deferPixels(this._name, 4);
34672         var transformChanged$ = this._navigator.stateService.currentTransform$.pipe(operators_1.map(function (transform) { }), operators_1.publishReplay(1), operators_1.refCount());
34673         this._deleteSubscription = transformChanged$.pipe(operators_1.skip(1))
34674             .subscribe(this._tagCreator.delete$);
34675         var basicClick$ = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).pipe(operators_1.share());
34676         this._createSubscription = transformChanged$.pipe(operators_1.switchMap(function () {
34677             return basicClick$.pipe(operators_1.filter(_this._validateBasic), operators_1.take(1));
34678         }))
34679             .subscribe(this._create$);
34680         this._setVertexSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
34681             return !!tag ?
34682                 rxjs_1.combineLatest(rxjs_1.of(tag), rxjs_1.merge(_this._container.mouseService.mouseMove$, _this._container.mouseService.domMouseMove$), _this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$) :
34683                 rxjs_1.empty();
34684         }))
34685             .subscribe(function (_a) {
34686             var tag = _a[0], event = _a[1], camera = _a[2], transform = _a[3];
34687             var basicPoint = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
34688             _this._setVertex2d(tag, basicPoint, transform);
34689         });
34690         this._addPointSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
34691             return !!tag ?
34692                 rxjs_1.combineLatest(rxjs_1.of(tag), basicClick$) :
34693                 rxjs_1.empty();
34694         }))
34695             .subscribe(function (_a) {
34696             var tag = _a[0], basicPoint = _a[1];
34697             _this._addPoint(tag, basicPoint);
34698         });
34699         this._geometryCreateSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
34700             return !!tag ?
34701                 tag.created$.pipe(operators_1.map(function (t) {
34702                     return t.geometry;
34703                 })) :
34704                 rxjs_1.empty();
34705         }))
34706             .subscribe(this._geometryCreated$);
34707     };
34708     CreateVertexHandler.prototype._disableCreate = function () {
34709         this._container.mouseService.undeferPixels(this._name);
34710         this._tagCreator.delete$.next(null);
34711         this._addPointSubscription.unsubscribe();
34712         this._createSubscription.unsubscribe();
34713         this._deleteSubscription.unsubscribe();
34714         this._geometryCreateSubscription.unsubscribe();
34715         this._setVertexSubscription.unsubscribe();
34716     };
34717     return CreateVertexHandler;
34718 }(Component_1.CreateHandlerBase));
34719 exports.CreateVertexHandler = CreateVertexHandler;
34720 exports.default = CreateVertexHandler;
34721
34722 },{"../../../Component":275,"rxjs":27,"rxjs/operators":225}],363:[function(require,module,exports){
34723 "use strict";
34724 var __extends = (this && this.__extends) || (function () {
34725     var extendStatics = function (d, b) {
34726         extendStatics = Object.setPrototypeOf ||
34727             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34728             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34729         return extendStatics(d, b);
34730     }
34731     return function (d, b) {
34732         extendStatics(d, b);
34733         function __() { this.constructor = d; }
34734         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34735     };
34736 })();
34737 Object.defineProperty(exports, "__esModule", { value: true });
34738 var rxjs_1 = require("rxjs");
34739 var operators_1 = require("rxjs/operators");
34740 var Component_1 = require("../../../Component");
34741 var EditVertexHandler = /** @class */ (function (_super) {
34742     __extends(EditVertexHandler, _super);
34743     function EditVertexHandler(component, container, navigator, viewportCoords, tagSet) {
34744         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
34745         _this._tagSet = tagSet;
34746         return _this;
34747     }
34748     EditVertexHandler.prototype._enable = function () {
34749         var _this = this;
34750         var interaction$ = this._tagSet.changed$.pipe(operators_1.map(function (tagSet) {
34751             return tagSet.getAll();
34752         }), operators_1.switchMap(function (tags) {
34753             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
34754                 return tag.interact$;
34755             }));
34756         }), operators_1.switchMap(function (interaction) {
34757             return rxjs_1.concat(rxjs_1.of(interaction), _this._container.mouseService.documentMouseUp$.pipe(operators_1.map(function () {
34758                 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
34759             }), operators_1.first()));
34760         }), operators_1.share());
34761         var mouseMove$ = rxjs_1.merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$).pipe(operators_1.share());
34762         this._claimMouseSubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
34763             return !!interaction.tag ? _this._container.mouseService.domMouseDragStart$ : rxjs_1.empty();
34764         }))
34765             .subscribe(function () {
34766             _this._container.mouseService.claimMouse(_this._name, 3);
34767         });
34768         this._cursorSubscription = interaction$.pipe(operators_1.map(function (interaction) {
34769             return interaction.cursor;
34770         }), operators_1.distinctUntilChanged())
34771             .subscribe(function (cursor) {
34772             var interactionCursors = ["crosshair", "move", "nesw-resize", "nwse-resize"];
34773             for (var _i = 0, interactionCursors_1 = interactionCursors; _i < interactionCursors_1.length; _i++) {
34774                 var interactionCursor = interactionCursors_1[_i];
34775                 _this._container.element.classList.remove("component-tag-edit-" + interactionCursor);
34776             }
34777             if (!!cursor) {
34778                 _this._container.element.classList.add("component-tag-edit-" + cursor);
34779             }
34780         });
34781         this._unclaimMouseSubscription = this._container.mouseService
34782             .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
34783             .subscribe(function (e) {
34784             _this._container.mouseService.unclaimMouse(_this._name);
34785         });
34786         this._preventDefaultSubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
34787             return !!interaction.tag ?
34788                 _this._container.mouseService.documentMouseMove$ :
34789                 rxjs_1.empty();
34790         }))
34791             .subscribe(function (event) {
34792             event.preventDefault(); // prevent selection of content outside the viewer
34793         });
34794         this._updateGeometrySubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
34795             if (interaction.operation === Component_1.TagOperation.None || !interaction.tag) {
34796                 return rxjs_1.empty();
34797             }
34798             var mouseDrag$ = _this._container.mouseService
34799                 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$).pipe(operators_1.filter(function (event) {
34800                 return _this._viewportCoords.insideElement(event, _this._container.element);
34801             }));
34802             return rxjs_1.combineLatest(mouseDrag$, _this._container.renderService.renderCamera$).pipe(operators_1.withLatestFrom(rxjs_1.of(interaction), _this._navigator.stateService.currentTransform$, function (_a, i, transform) {
34803                 var event = _a[0], render = _a[1];
34804                 return [event, render, i, transform];
34805             }));
34806         }))
34807             .subscribe(function (_a) {
34808             var mouseEvent = _a[0], renderCamera = _a[1], interaction = _a[2], transform = _a[3];
34809             var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, interaction.offsetX, interaction.offsetY);
34810             var geometry = interaction.tag.geometry;
34811             if (interaction.operation === Component_1.TagOperation.Centroid) {
34812                 geometry.setCentroid2d(basic, transform);
34813             }
34814             else if (interaction.operation === Component_1.TagOperation.Vertex) {
34815                 geometry.setVertex2d(interaction.vertexIndex, basic, transform);
34816             }
34817         });
34818     };
34819     EditVertexHandler.prototype._disable = function () {
34820         this._claimMouseSubscription.unsubscribe();
34821         this._cursorSubscription.unsubscribe();
34822         this._preventDefaultSubscription.unsubscribe();
34823         this._unclaimMouseSubscription.unsubscribe();
34824         this._updateGeometrySubscription.unsubscribe();
34825     };
34826     EditVertexHandler.prototype._getNameExtension = function () {
34827         return "edit-vertex";
34828     };
34829     return EditVertexHandler;
34830 }(Component_1.TagHandlerBase));
34831 exports.EditVertexHandler = EditVertexHandler;
34832 exports.default = EditVertexHandler;
34833
34834
34835 },{"../../../Component":275,"rxjs":27,"rxjs/operators":225}],364:[function(require,module,exports){
34836 "use strict";
34837 var __extends = (this && this.__extends) || (function () {
34838     var extendStatics = function (d, b) {
34839         extendStatics = Object.setPrototypeOf ||
34840             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34841             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34842         return extendStatics(d, b);
34843     }
34844     return function (d, b) {
34845         extendStatics(d, b);
34846         function __() { this.constructor = d; }
34847         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34848     };
34849 })();
34850 Object.defineProperty(exports, "__esModule", { value: true });
34851 var Component_1 = require("../../../Component");
34852 var TagHandlerBase = /** @class */ (function (_super) {
34853     __extends(TagHandlerBase, _super);
34854     function TagHandlerBase(component, container, navigator, viewportCoords) {
34855         var _this = _super.call(this, component, container, navigator) || this;
34856         _this._name = _this._component.name + "-" + _this._getNameExtension();
34857         _this._viewportCoords = viewportCoords;
34858         return _this;
34859     }
34860     TagHandlerBase.prototype._getConfiguration = function (enable) {
34861         return {};
34862     };
34863     TagHandlerBase.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
34864         offsetX = offsetX != null ? offsetX : 0;
34865         offsetY = offsetY != null ? offsetY : 0;
34866         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
34867         var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
34868         return basic;
34869     };
34870     return TagHandlerBase;
34871 }(Component_1.HandlerBase));
34872 exports.TagHandlerBase = TagHandlerBase;
34873 exports.default = TagHandlerBase;
34874
34875
34876 },{"../../../Component":275}],365:[function(require,module,exports){
34877 "use strict";
34878 Object.defineProperty(exports, "__esModule", { value: true });
34879 var operators_1 = require("rxjs/operators");
34880 var THREE = require("three");
34881 var vd = require("virtual-dom");
34882 var rxjs_1 = require("rxjs");
34883 var Component_1 = require("../../../Component");
34884 var Geo_1 = require("../../../Geo");
34885 var OutlineCreateTag = /** @class */ (function () {
34886     function OutlineCreateTag(geometry, options, transform, viewportCoords) {
34887         var _this = this;
34888         this._geometry = geometry;
34889         this._options = { color: options.color == null ? 0xFFFFFF : options.color };
34890         this._transform = transform;
34891         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
34892         this._outline = this._createOutine();
34893         this._glObjects = [this._outline];
34894         this._aborted$ = new rxjs_1.Subject();
34895         this._created$ = new rxjs_1.Subject();
34896         this._glObjectsChanged$ = new rxjs_1.Subject();
34897         this._geometryChangedSubscription = this._geometry.changed$
34898             .subscribe(function (vertexGeometry) {
34899             _this._disposeOutline();
34900             _this._outline = _this._createOutine();
34901             _this._glObjects = [_this._outline];
34902             _this._glObjectsChanged$.next(_this);
34903         });
34904     }
34905     Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
34906         get: function () {
34907             return this._geometry;
34908         },
34909         enumerable: true,
34910         configurable: true
34911     });
34912     Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
34913         get: function () {
34914             return this._glObjects;
34915         },
34916         enumerable: true,
34917         configurable: true
34918     });
34919     Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
34920         get: function () {
34921             return this._aborted$;
34922         },
34923         enumerable: true,
34924         configurable: true
34925     });
34926     Object.defineProperty(OutlineCreateTag.prototype, "created$", {
34927         get: function () {
34928             return this._created$;
34929         },
34930         enumerable: true,
34931         configurable: true
34932     });
34933     Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
34934         get: function () {
34935             return this._glObjectsChanged$;
34936         },
34937         enumerable: true,
34938         configurable: true
34939     });
34940     Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
34941         get: function () {
34942             var _this = this;
34943             return this._geometry.changed$.pipe(operators_1.map(function (geometry) {
34944                 return _this;
34945             }));
34946         },
34947         enumerable: true,
34948         configurable: true
34949     });
34950     OutlineCreateTag.prototype.dispose = function () {
34951         this._disposeOutline();
34952         this._geometryChangedSubscription.unsubscribe();
34953     };
34954     OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
34955         var _this = this;
34956         var vNodes = [];
34957         var container = {
34958             offsetHeight: size.height, offsetWidth: size.width,
34959         };
34960         var abort = function (e) {
34961             e.stopPropagation();
34962             _this._aborted$.next(_this);
34963         };
34964         if (this._geometry instanceof Component_1.RectGeometry) {
34965             var anchorIndex = this._geometry.anchorIndex;
34966             var vertexIndex = anchorIndex === undefined ? 1 : anchorIndex;
34967             var _a = this._geometry.getVertex2d(vertexIndex), basicX = _a[0], basicY = _a[1];
34968             var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
34969             if (canvasPoint != null) {
34970                 var background = this._colorToBackground(this._options.color);
34971                 var transform = this._canvasToTransform(canvasPoint);
34972                 var pointProperties = {
34973                     style: { background: background, transform: transform },
34974                 };
34975                 var completerProperties = {
34976                     onclick: abort,
34977                     style: { transform: transform },
34978                 };
34979                 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
34980                 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
34981             }
34982         }
34983         else if (this._geometry instanceof Component_1.PolygonGeometry) {
34984             var polygonGeometry_1 = this._geometry;
34985             var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
34986             var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
34987             if (firstVertexCanvas != null) {
34988                 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
34989                     function (e) {
34990                         e.stopPropagation();
34991                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
34992                         _this._created$.next(_this);
34993                     } :
34994                     abort;
34995                 var transform = this._canvasToTransform(firstVertexCanvas);
34996                 var completerProperties = {
34997                     onclick: firstOnclick,
34998                     style: { transform: transform },
34999                 };
35000                 var firstClass = polygonGeometry_1.polygon.length > 4 ?
35001                     "TagCompleter" :
35002                     "TagInteractor";
35003                 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
35004             }
35005             if (polygonGeometry_1.polygon.length > 3) {
35006                 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
35007                 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
35008                 if (lastVertexCanvas != null) {
35009                     var remove = function (e) {
35010                         e.stopPropagation();
35011                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
35012                     };
35013                     var transform = this._canvasToTransform(lastVertexCanvas);
35014                     var completerProperties = {
35015                         onclick: remove,
35016                         style: { transform: transform },
35017                     };
35018                     vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
35019                 }
35020             }
35021             var verticesBasic = polygonGeometry_1.polygon.slice();
35022             verticesBasic.splice(-2, 2);
35023             for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
35024                 var vertexBasic = verticesBasic_1[_i];
35025                 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
35026                 if (vertexCanvas != null) {
35027                     var background = this._colorToBackground(this._options.color);
35028                     var transform = this._canvasToTransform(vertexCanvas);
35029                     var pointProperties = {
35030                         style: {
35031                             background: background,
35032                             transform: transform,
35033                         },
35034                     };
35035                     vNodes.push(vd.h("div.TagVertex", pointProperties, []));
35036                 }
35037             }
35038         }
35039         return vNodes;
35040     };
35041     OutlineCreateTag.prototype.addPoint = function (point) {
35042         if (this._geometry instanceof Component_1.RectGeometry) {
35043             var rectGeometry = this._geometry;
35044             if (!rectGeometry.validate(point)) {
35045                 return;
35046             }
35047             this._created$.next(this);
35048         }
35049         else if (this._geometry instanceof Component_1.PolygonGeometry) {
35050             var polygonGeometry = this._geometry;
35051             polygonGeometry.addVertex2d(point);
35052         }
35053     };
35054     OutlineCreateTag.prototype._canvasToTransform = function (canvas) {
35055         var canvasX = Math.round(canvas[0]);
35056         var canvasY = Math.round(canvas[1]);
35057         var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
35058         return transform;
35059     };
35060     OutlineCreateTag.prototype._colorToBackground = function (color) {
35061         return "#" + ("000000" + color.toString(16)).substr(-6);
35062     };
35063     OutlineCreateTag.prototype._createOutine = function () {
35064         var polygon3d = this._geometry instanceof Component_1.RectGeometry ?
35065             this._geometry.getPoints3d(this._transform) :
35066             this._geometry.getVertices3d(this._transform);
35067         var positions = this._getLinePositions(polygon3d);
35068         var geometry = new THREE.BufferGeometry();
35069         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
35070         var material = new THREE.LineBasicMaterial({
35071             color: this._options.color,
35072             linewidth: 1,
35073         });
35074         return new THREE.Line(geometry, material);
35075     };
35076     OutlineCreateTag.prototype._disposeOutline = function () {
35077         if (this._outline == null) {
35078             return;
35079         }
35080         var line = this._outline;
35081         line.geometry.dispose();
35082         line.material.dispose();
35083         this._outline = null;
35084         this._glObjects = [];
35085     };
35086     OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
35087         var length = polygon3d.length;
35088         var positions = new Float32Array(length * 3);
35089         for (var i = 0; i < length; ++i) {
35090             var index = 3 * i;
35091             var position = polygon3d[i];
35092             positions[index] = position[0];
35093             positions[index + 1] = position[1];
35094             positions[index + 2] = position[2];
35095         }
35096         return positions;
35097     };
35098     return OutlineCreateTag;
35099 }());
35100 exports.OutlineCreateTag = OutlineCreateTag;
35101 exports.default = OutlineCreateTag;
35102
35103
35104 },{"../../../Component":275,"../../../Geo":278,"rxjs":27,"rxjs/operators":225,"three":226,"virtual-dom":231}],366:[function(require,module,exports){
35105 "use strict";
35106 var __extends = (this && this.__extends) || (function () {
35107     var extendStatics = function (d, b) {
35108         extendStatics = Object.setPrototypeOf ||
35109             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35110             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35111         return extendStatics(d, b);
35112     }
35113     return function (d, b) {
35114         extendStatics(d, b);
35115         function __() { this.constructor = d; }
35116         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35117     };
35118 })();
35119 Object.defineProperty(exports, "__esModule", { value: true });
35120 var THREE = require("three");
35121 var vd = require("virtual-dom");
35122 var Component_1 = require("../../../Component");
35123 /**
35124  * @class OutlineRenderTag
35125  * @classdesc Tag visualizing the properties of an OutlineTag.
35126  */
35127 var OutlineRenderTag = /** @class */ (function (_super) {
35128     __extends(OutlineRenderTag, _super);
35129     function OutlineRenderTag(tag, transform) {
35130         var _this = _super.call(this, tag, transform) || this;
35131         _this._fill = !transform.gpano ?
35132             _this._createFill() :
35133             transform.fullPano &&
35134                 tag.domain === Component_1.TagDomain.TwoDimensional &&
35135                 tag.geometry instanceof Component_1.PolygonGeometry ?
35136                 _this._createFill() :
35137                 null;
35138         _this._holes = _this._tag.lineWidth >= 1 ?
35139             _this._createHoles() :
35140             [];
35141         _this._outline = _this._tag.lineWidth >= 1 ?
35142             _this._createOutline() :
35143             null;
35144         _this._geometryChangedSubscription = _this._tag.geometry.changed$
35145             .subscribe(function () {
35146             if (_this._fill != null) {
35147                 _this._updateFillGeometry();
35148             }
35149             if (_this._holes.length > 0) {
35150                 _this._updateHoleGeometries();
35151             }
35152             if (_this._outline != null) {
35153                 _this._updateOulineGeometry();
35154             }
35155         });
35156         _this._changedSubscription = _this._tag.changed$
35157             .subscribe(function () {
35158             var glObjectsChanged = false;
35159             if (_this._fill != null) {
35160                 _this._updateFillMaterial(_this._fill.material);
35161             }
35162             if (_this._outline == null) {
35163                 if (_this._tag.lineWidth >= 1) {
35164                     _this._holes = _this._createHoles();
35165                     _this._outline = _this._createOutline();
35166                     glObjectsChanged = true;
35167                 }
35168             }
35169             else {
35170                 _this._updateHoleMaterials();
35171                 _this._updateOutlineMaterial();
35172             }
35173             if (glObjectsChanged) {
35174                 _this._glObjectsChanged$.next(_this);
35175             }
35176         });
35177         return _this;
35178     }
35179     OutlineRenderTag.prototype.dispose = function () {
35180         this._disposeFill();
35181         this._disposeHoles();
35182         this._disposeOutline();
35183         this._changedSubscription.unsubscribe();
35184         this._geometryChangedSubscription.unsubscribe();
35185     };
35186     OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
35187         var _this = this;
35188         var vNodes = [];
35189         var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
35190         var isPerspective = !this._transform.gpano;
35191         var container = {
35192             offsetHeight: size.height, offsetWidth: size.width,
35193         };
35194         if (this._tag.icon != null && (isRect || isPerspective)) {
35195             var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
35196                 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
35197                 this._tag.geometry.getPoleOfInaccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
35198             var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
35199             if (iconCanvas != null) {
35200                 var interact = function (e) {
35201                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
35202                 };
35203                 if (atlas.loaded) {
35204                     var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
35205                     var iconCanvasX = Math.round(iconCanvas[0]);
35206                     var iconCanvasY = Math.round(iconCanvas[1]);
35207                     var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
35208                     var click = function (e) {
35209                         e.stopPropagation();
35210                         _this._tag.click$.next(_this._tag);
35211                     };
35212                     var properties = {
35213                         onclick: click,
35214                         onmousedown: interact,
35215                         style: { transform: transform },
35216                     };
35217                     vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
35218                 }
35219             }
35220         }
35221         else if (this._tag.text != null && (isRect || isPerspective)) {
35222             var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
35223                 this._tag.geometry.getVertex2d(3) :
35224                 this._tag.geometry.getPoleOfInaccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
35225             var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
35226             if (textCanvas != null) {
35227                 var textCanvasX = Math.round(textCanvas[0]);
35228                 var textCanvasY = Math.round(textCanvas[1]);
35229                 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
35230                     "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
35231                     "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
35232                 var interact = function (e) {
35233                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
35234                 };
35235                 var properties = {
35236                     onmousedown: interact,
35237                     style: {
35238                         color: this._colorToCss(this._tag.textColor),
35239                         transform: transform,
35240                     },
35241                     textContent: this._tag.text,
35242                 };
35243                 vNodes.push(vd.h("span.TagSymbol", properties, []));
35244             }
35245         }
35246         if (!this._tag.editable) {
35247             return vNodes;
35248         }
35249         var lineColor = this._colorToCss(this._tag.lineColor);
35250         if (this._tag.geometry instanceof Component_1.RectGeometry) {
35251             var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
35252             var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
35253             if (centroidCanvas != null) {
35254                 var interact = this._interact(Component_1.TagOperation.Centroid, "move");
35255                 var centroidCanvasX = Math.round(centroidCanvas[0]);
35256                 var centroidCanvasY = Math.round(centroidCanvas[1]);
35257                 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
35258                 var properties = {
35259                     onmousedown: interact,
35260                     style: { background: lineColor, transform: transform },
35261                 };
35262                 vNodes.push(vd.h("div.TagMover", properties, []));
35263             }
35264         }
35265         var vertices2d = this._tag.geometry.getVertices2d();
35266         for (var i = 0; i < vertices2d.length - 1; i++) {
35267             if (isRect &&
35268                 ((this._tag.icon != null && i === this._tag.iconIndex) ||
35269                     (this._tag.icon == null && this._tag.text != null && i === 3))) {
35270                 continue;
35271             }
35272             var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
35273             var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
35274             if (vertexCanvas == null) {
35275                 continue;
35276             }
35277             var cursor = isRect ?
35278                 i % 2 === 0 ? "nesw-resize" : "nwse-resize" :
35279                 "crosshair";
35280             var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i);
35281             var vertexCanvasX = Math.round(vertexCanvas[0]);
35282             var vertexCanvasY = Math.round(vertexCanvas[1]);
35283             var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
35284             var properties = {
35285                 onmousedown: interact,
35286                 style: { background: lineColor, transform: transform, cursor: cursor },
35287             };
35288             vNodes.push(vd.h("div.TagResizer", properties, []));
35289             if (!this._tag.indicateVertices) {
35290                 continue;
35291             }
35292             var pointProperties = {
35293                 style: { background: lineColor, transform: transform },
35294             };
35295             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
35296         }
35297         return vNodes;
35298     };
35299     OutlineRenderTag.prototype.getGLObjects = function () {
35300         var glObjects = [];
35301         if (this._fill != null) {
35302             glObjects.push(this._fill);
35303         }
35304         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
35305             var hole = _a[_i];
35306             glObjects.push(hole);
35307         }
35308         if (this._outline != null) {
35309             glObjects.push(this._outline);
35310         }
35311         return glObjects;
35312     };
35313     OutlineRenderTag.prototype.getRetrievableObjects = function () {
35314         return this._fill != null ? [this._fill] : [];
35315     };
35316     OutlineRenderTag.prototype._colorToCss = function (color) {
35317         return "#" + ("000000" + color.toString(16)).substr(-6);
35318     };
35319     OutlineRenderTag.prototype._createFill = function () {
35320         var triangles = this._getTriangles();
35321         var positions = new Float32Array(triangles);
35322         var geometry = new THREE.BufferGeometry();
35323         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
35324         geometry.computeBoundingSphere();
35325         var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
35326         this._updateFillMaterial(material);
35327         return new THREE.Mesh(geometry, material);
35328     };
35329     OutlineRenderTag.prototype._createHoles = function () {
35330         var holes = [];
35331         if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
35332             var holes3d = this._getHoles3d();
35333             for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
35334                 var holePoints3d = holes3d_1[_i];
35335                 var hole = this._createLine(holePoints3d);
35336                 holes.push(hole);
35337             }
35338         }
35339         return holes;
35340     };
35341     OutlineRenderTag.prototype._createLine = function (points3d) {
35342         var positions = this._getLinePositions(points3d);
35343         var geometry = new THREE.BufferGeometry();
35344         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
35345         geometry.computeBoundingSphere();
35346         var material = new THREE.LineBasicMaterial();
35347         this._updateLineBasicMaterial(material);
35348         var line = new THREE.Line(geometry, material);
35349         line.renderOrder = 1;
35350         return line;
35351     };
35352     OutlineRenderTag.prototype._createOutline = function () {
35353         return this._createLine(this._getPoints3d());
35354     };
35355     OutlineRenderTag.prototype._disposeFill = function () {
35356         if (this._fill == null) {
35357             return;
35358         }
35359         this._fill.geometry.dispose();
35360         this._fill.material.dispose();
35361         this._fill = null;
35362     };
35363     OutlineRenderTag.prototype._disposeHoles = function () {
35364         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
35365             var hole = _a[_i];
35366             hole.geometry.dispose();
35367             hole.material.dispose();
35368         }
35369         this._holes = [];
35370     };
35371     OutlineRenderTag.prototype._disposeOutline = function () {
35372         if (this._outline == null) {
35373             return;
35374         }
35375         this._outline.geometry.dispose();
35376         this._outline.material.dispose();
35377         this._outline = null;
35378     };
35379     OutlineRenderTag.prototype._getLinePositions = function (points3d) {
35380         var length = points3d.length;
35381         var positions = new Float32Array(length * 3);
35382         for (var i = 0; i < length; ++i) {
35383             var index = 3 * i;
35384             var position = points3d[i];
35385             positions[index + 0] = position[0];
35386             positions[index + 1] = position[1];
35387             positions[index + 2] = position[2];
35388         }
35389         return positions;
35390     };
35391     OutlineRenderTag.prototype._getHoles3d = function () {
35392         var polygonGeometry = this._tag.geometry;
35393         return this._in3dDomain() ?
35394             polygonGeometry.getHoleVertices3d(this._transform) :
35395             polygonGeometry.getHolePoints3d(this._transform);
35396     };
35397     OutlineRenderTag.prototype._getPoints3d = function () {
35398         return this._in3dDomain() ?
35399             this._tag.geometry.getVertices3d(this._transform) :
35400             this._tag.geometry.getPoints3d(this._transform);
35401     };
35402     OutlineRenderTag.prototype._getTriangles = function () {
35403         return this._in3dDomain() ?
35404             this._tag.geometry.get3dDomainTriangles3d(this._transform) :
35405             this._tag.geometry.getTriangles3d(this._transform);
35406     };
35407     OutlineRenderTag.prototype._in3dDomain = function () {
35408         return this._tag.geometry instanceof Component_1.PolygonGeometry && this._tag.domain === Component_1.TagDomain.ThreeDimensional;
35409     };
35410     OutlineRenderTag.prototype._interact = function (operation, cursor, vertexIndex) {
35411         var _this = this;
35412         return function (e) {
35413             var offsetX = e.offsetX - e.target.offsetWidth / 2;
35414             var offsetY = e.offsetY - e.target.offsetHeight / 2;
35415             _this._interact$.next({
35416                 cursor: cursor,
35417                 offsetX: offsetX,
35418                 offsetY: offsetY,
35419                 operation: operation,
35420                 tag: _this._tag,
35421                 vertexIndex: vertexIndex,
35422             });
35423         };
35424     };
35425     OutlineRenderTag.prototype._updateFillGeometry = function () {
35426         var triangles = this._getTriangles();
35427         var positions = new Float32Array(triangles);
35428         var geometry = this._fill.geometry;
35429         var attribute = geometry.getAttribute("position");
35430         if (attribute.array.length === positions.length) {
35431             attribute.set(positions);
35432             attribute.needsUpdate = true;
35433         }
35434         else {
35435             geometry.removeAttribute("position");
35436             geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
35437         }
35438         geometry.computeBoundingSphere();
35439     };
35440     OutlineRenderTag.prototype._updateFillMaterial = function (material) {
35441         material.color = new THREE.Color(this._tag.fillColor);
35442         material.opacity = this._tag.fillOpacity;
35443         material.needsUpdate = true;
35444     };
35445     OutlineRenderTag.prototype._updateHoleGeometries = function () {
35446         var holes3d = this._getHoles3d();
35447         if (holes3d.length !== this._holes.length) {
35448             throw new Error("Changing the number of holes is not supported.");
35449         }
35450         for (var i = 0; i < this._holes.length; i++) {
35451             var holePoints3d = holes3d[i];
35452             var hole = this._holes[i];
35453             this._updateLine(hole, holePoints3d);
35454         }
35455     };
35456     OutlineRenderTag.prototype._updateHoleMaterials = function () {
35457         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
35458             var hole = _a[_i];
35459             var material = hole.material;
35460             this._updateLineBasicMaterial(material);
35461         }
35462     };
35463     OutlineRenderTag.prototype._updateLine = function (line, points3d) {
35464         var positions = this._getLinePositions(points3d);
35465         var geometry = line.geometry;
35466         var attribute = geometry.getAttribute("position");
35467         attribute.set(positions);
35468         attribute.needsUpdate = true;
35469         geometry.computeBoundingSphere();
35470     };
35471     OutlineRenderTag.prototype._updateOulineGeometry = function () {
35472         this._updateLine(this._outline, this._getPoints3d());
35473     };
35474     OutlineRenderTag.prototype._updateOutlineMaterial = function () {
35475         var material = this._outline.material;
35476         this._updateLineBasicMaterial(material);
35477     };
35478     OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
35479         material.color = new THREE.Color(this._tag.lineColor);
35480         material.linewidth = Math.max(this._tag.lineWidth, 1);
35481         material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
35482         material.opacity = this._tag.lineOpacity;
35483         material.transparent = this._tag.lineOpacity < 1;
35484         material.needsUpdate = true;
35485     };
35486     return OutlineRenderTag;
35487 }(Component_1.RenderTag));
35488 exports.OutlineRenderTag = OutlineRenderTag;
35489
35490
35491 },{"../../../Component":275,"three":226,"virtual-dom":231}],367:[function(require,module,exports){
35492 "use strict";
35493 var __extends = (this && this.__extends) || (function () {
35494     var extendStatics = function (d, b) {
35495         extendStatics = Object.setPrototypeOf ||
35496             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35497             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35498         return extendStatics(d, b);
35499     }
35500     return function (d, b) {
35501         extendStatics(d, b);
35502         function __() { this.constructor = d; }
35503         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35504     };
35505 })();
35506 Object.defineProperty(exports, "__esModule", { value: true });
35507 var rxjs_1 = require("rxjs");
35508 var Component_1 = require("../../../Component");
35509 var Viewer_1 = require("../../../Viewer");
35510 /**
35511  * @class OutlineTag
35512  *
35513  * @classdesc Tag holding properties for visualizing a geometry outline.
35514  *
35515  * @example
35516  * ```
35517  * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
35518  * var tag = new Mapillary.TagComponent.OutlineTag(
35519  *     "id-1",
35520  *     geometry
35521  *     { editable: true, lineColor: 0xff0000 });
35522  *
35523  * tagComponent.add([tag]);
35524  * ```
35525  */
35526 var OutlineTag = /** @class */ (function (_super) {
35527     __extends(OutlineTag, _super);
35528     /**
35529      * Create an outline tag.
35530      *
35531      * @override
35532      * @constructor
35533      * @param {string} id - Unique identifier of the tag.
35534      * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
35535      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
35536      * behavior of the outline tag.
35537      */
35538     function OutlineTag(id, geometry, options) {
35539         var _this = _super.call(this, id, geometry) || this;
35540         options = !!options ? options : {};
35541         var domain = options.domain != null && geometry instanceof Component_1.PolygonGeometry ?
35542             options.domain : Component_1.TagDomain.TwoDimensional;
35543         var twoDimensionalPolygon = _this._twoDimensionalPolygon(domain, geometry);
35544         _this._domain = domain;
35545         _this._editable = options.editable == null || twoDimensionalPolygon ? false : options.editable;
35546         _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
35547         _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
35548         _this._icon = options.icon === undefined ? null : options.icon;
35549         _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
35550         _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
35551         _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
35552         _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
35553         _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
35554         _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
35555         _this._text = options.text === undefined ? null : options.text;
35556         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
35557         _this._click$ = new rxjs_1.Subject();
35558         _this._click$
35559             .subscribe(function (t) {
35560             _this.fire(OutlineTag.click, _this);
35561         });
35562         return _this;
35563     }
35564     Object.defineProperty(OutlineTag.prototype, "click$", {
35565         /**
35566          * Click observable.
35567          *
35568          * @description An observable emitting the tag when the icon of the
35569          * tag has been clicked.
35570          *
35571          * @returns {Observable<Tag>}
35572          */
35573         get: function () {
35574             return this._click$;
35575         },
35576         enumerable: true,
35577         configurable: true
35578     });
35579     Object.defineProperty(OutlineTag.prototype, "domain", {
35580         /**
35581          * Get domain property.
35582          *
35583          * @description Readonly property that can only be set in constructor.
35584          *
35585          * @returns Value indicating the domain of the tag.
35586          */
35587         get: function () {
35588             return this._domain;
35589         },
35590         enumerable: true,
35591         configurable: true
35592     });
35593     Object.defineProperty(OutlineTag.prototype, "editable", {
35594         /**
35595          * Get editable property.
35596          * @returns {boolean} Value indicating if tag is editable.
35597          */
35598         get: function () {
35599             return this._editable;
35600         },
35601         /**
35602          * Set editable property.
35603          * @param {boolean}
35604          *
35605          * @fires Tag#changed
35606          */
35607         set: function (value) {
35608             if (this._twoDimensionalPolygon(this._domain, this._geometry)) {
35609                 return;
35610             }
35611             this._editable = value;
35612             this._notifyChanged$.next(this);
35613         },
35614         enumerable: true,
35615         configurable: true
35616     });
35617     Object.defineProperty(OutlineTag.prototype, "fillColor", {
35618         /**
35619          * Get fill color property.
35620          * @returns {number}
35621          */
35622         get: function () {
35623             return this._fillColor;
35624         },
35625         /**
35626          * Set fill color property.
35627          * @param {number}
35628          *
35629          * @fires Tag#changed
35630          */
35631         set: function (value) {
35632             this._fillColor = value;
35633             this._notifyChanged$.next(this);
35634         },
35635         enumerable: true,
35636         configurable: true
35637     });
35638     Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
35639         /**
35640          * Get fill opacity property.
35641          * @returns {number}
35642          */
35643         get: function () {
35644             return this._fillOpacity;
35645         },
35646         /**
35647          * Set fill opacity property.
35648          * @param {number}
35649          *
35650          * @fires Tag#changed
35651          */
35652         set: function (value) {
35653             this._fillOpacity = value;
35654             this._notifyChanged$.next(this);
35655         },
35656         enumerable: true,
35657         configurable: true
35658     });
35659     Object.defineProperty(OutlineTag.prototype, "geometry", {
35660         /** @inheritdoc */
35661         get: function () {
35662             return this._geometry;
35663         },
35664         enumerable: true,
35665         configurable: true
35666     });
35667     Object.defineProperty(OutlineTag.prototype, "icon", {
35668         /**
35669          * Get icon property.
35670          * @returns {string}
35671          */
35672         get: function () {
35673             return this._icon;
35674         },
35675         /**
35676          * Set icon property.
35677          * @param {string}
35678          *
35679          * @fires Tag#changed
35680          */
35681         set: function (value) {
35682             this._icon = value;
35683             this._notifyChanged$.next(this);
35684         },
35685         enumerable: true,
35686         configurable: true
35687     });
35688     Object.defineProperty(OutlineTag.prototype, "iconFloat", {
35689         /**
35690          * Get icon float property.
35691          * @returns {Alignment}
35692          */
35693         get: function () {
35694             return this._iconFloat;
35695         },
35696         /**
35697          * Set icon float property.
35698          * @param {Alignment}
35699          *
35700          * @fires Tag#changed
35701          */
35702         set: function (value) {
35703             this._iconFloat = value;
35704             this._notifyChanged$.next(this);
35705         },
35706         enumerable: true,
35707         configurable: true
35708     });
35709     Object.defineProperty(OutlineTag.prototype, "iconIndex", {
35710         /**
35711          * Get icon index property.
35712          * @returns {number}
35713          */
35714         get: function () {
35715             return this._iconIndex;
35716         },
35717         /**
35718          * Set icon index property.
35719          * @param {number}
35720          *
35721          * @fires Tag#changed
35722          */
35723         set: function (value) {
35724             this._iconIndex = value;
35725             this._notifyChanged$.next(this);
35726         },
35727         enumerable: true,
35728         configurable: true
35729     });
35730     Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
35731         /**
35732          * Get indicate vertices property.
35733          * @returns {boolean} Value indicating if vertices should be indicated
35734          * when tag is editable.
35735          */
35736         get: function () {
35737             return this._indicateVertices;
35738         },
35739         /**
35740          * Set indicate vertices property.
35741          * @param {boolean}
35742          *
35743          * @fires Tag#changed
35744          */
35745         set: function (value) {
35746             this._indicateVertices = value;
35747             this._notifyChanged$.next(this);
35748         },
35749         enumerable: true,
35750         configurable: true
35751     });
35752     Object.defineProperty(OutlineTag.prototype, "lineColor", {
35753         /**
35754          * Get line color property.
35755          * @returns {number}
35756          */
35757         get: function () {
35758             return this._lineColor;
35759         },
35760         /**
35761          * Set line color property.
35762          * @param {number}
35763          *
35764          * @fires Tag#changed
35765          */
35766         set: function (value) {
35767             this._lineColor = value;
35768             this._notifyChanged$.next(this);
35769         },
35770         enumerable: true,
35771         configurable: true
35772     });
35773     Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
35774         /**
35775          * Get line opacity property.
35776          * @returns {number}
35777          */
35778         get: function () {
35779             return this._lineOpacity;
35780         },
35781         /**
35782          * Set line opacity property.
35783          * @param {number}
35784          *
35785          * @fires Tag#changed
35786          */
35787         set: function (value) {
35788             this._lineOpacity = value;
35789             this._notifyChanged$.next(this);
35790         },
35791         enumerable: true,
35792         configurable: true
35793     });
35794     Object.defineProperty(OutlineTag.prototype, "lineWidth", {
35795         /**
35796          * Get line width property.
35797          * @returns {number}
35798          */
35799         get: function () {
35800             return this._lineWidth;
35801         },
35802         /**
35803          * Set line width property.
35804          * @param {number}
35805          *
35806          * @fires Tag#changed
35807          */
35808         set: function (value) {
35809             this._lineWidth = value;
35810             this._notifyChanged$.next(this);
35811         },
35812         enumerable: true,
35813         configurable: true
35814     });
35815     Object.defineProperty(OutlineTag.prototype, "text", {
35816         /**
35817          * Get text property.
35818          * @returns {string}
35819          */
35820         get: function () {
35821             return this._text;
35822         },
35823         /**
35824          * Set text property.
35825          * @param {string}
35826          *
35827          * @fires Tag#changed
35828          */
35829         set: function (value) {
35830             this._text = value;
35831             this._notifyChanged$.next(this);
35832         },
35833         enumerable: true,
35834         configurable: true
35835     });
35836     Object.defineProperty(OutlineTag.prototype, "textColor", {
35837         /**
35838          * Get text color property.
35839          * @returns {number}
35840          */
35841         get: function () {
35842             return this._textColor;
35843         },
35844         /**
35845          * Set text color property.
35846          * @param {number}
35847          *
35848          * @fires Tag#changed
35849          */
35850         set: function (value) {
35851             this._textColor = value;
35852             this._notifyChanged$.next(this);
35853         },
35854         enumerable: true,
35855         configurable: true
35856     });
35857     /**
35858      * Set options for tag.
35859      *
35860      * @description Sets all the option properties provided and keeps
35861      * the rest of the values as is.
35862      *
35863      * @param {IOutlineTagOptions} options - Outline tag options
35864      *
35865      * @fires {Tag#changed}
35866      */
35867     OutlineTag.prototype.setOptions = function (options) {
35868         var twoDimensionalPolygon = this._twoDimensionalPolygon(this._domain, this._geometry);
35869         this._editable = twoDimensionalPolygon || options.editable == null ? this._editable : options.editable;
35870         this._icon = options.icon === undefined ? this._icon : options.icon;
35871         this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
35872         this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
35873         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
35874         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
35875         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
35876         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
35877         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
35878         this._text = options.text === undefined ? this._text : options.text;
35879         this._textColor = options.textColor == null ? this._textColor : options.textColor;
35880         this._notifyChanged$.next(this);
35881     };
35882     OutlineTag.prototype._twoDimensionalPolygon = function (domain, geometry) {
35883         return domain !== Component_1.TagDomain.ThreeDimensional && geometry instanceof Component_1.PolygonGeometry;
35884     };
35885     /**
35886      * Event fired when the icon of the outline tag is clicked.
35887      *
35888      * @event OutlineTag#click
35889      * @type {OutlineTag} The tag instance that was clicked.
35890      */
35891     OutlineTag.click = "click";
35892     return OutlineTag;
35893 }(Component_1.Tag));
35894 exports.OutlineTag = OutlineTag;
35895 exports.default = OutlineTag;
35896
35897 },{"../../../Component":275,"../../../Viewer":286,"rxjs":27}],368:[function(require,module,exports){
35898 "use strict";
35899 Object.defineProperty(exports, "__esModule", { value: true });
35900 var rxjs_1 = require("rxjs");
35901 var Geo_1 = require("../../../Geo");
35902 var RenderTag = /** @class */ (function () {
35903     function RenderTag(tag, transform, viewportCoords) {
35904         this._tag = tag;
35905         this._transform = transform;
35906         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
35907         this._glObjectsChanged$ = new rxjs_1.Subject();
35908         this._interact$ = new rxjs_1.Subject();
35909     }
35910     Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
35911         get: function () {
35912             return this._glObjectsChanged$;
35913         },
35914         enumerable: true,
35915         configurable: true
35916     });
35917     Object.defineProperty(RenderTag.prototype, "interact$", {
35918         get: function () {
35919             return this._interact$;
35920         },
35921         enumerable: true,
35922         configurable: true
35923     });
35924     Object.defineProperty(RenderTag.prototype, "tag", {
35925         get: function () {
35926             return this._tag;
35927         },
35928         enumerable: true,
35929         configurable: true
35930     });
35931     return RenderTag;
35932 }());
35933 exports.RenderTag = RenderTag;
35934 exports.default = RenderTag;
35935
35936 },{"../../../Geo":278,"rxjs":27}],369:[function(require,module,exports){
35937 "use strict";
35938 var __extends = (this && this.__extends) || (function () {
35939     var extendStatics = function (d, b) {
35940         extendStatics = Object.setPrototypeOf ||
35941             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35942             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35943         return extendStatics(d, b);
35944     }
35945     return function (d, b) {
35946         extendStatics(d, b);
35947         function __() { this.constructor = d; }
35948         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35949     };
35950 })();
35951 Object.defineProperty(exports, "__esModule", { value: true });
35952 var vd = require("virtual-dom");
35953 var Component_1 = require("../../../Component");
35954 var Viewer_1 = require("../../../Viewer");
35955 /**
35956  * @class SpotRenderTag
35957  * @classdesc Tag visualizing the properties of a SpotTag.
35958  */
35959 var SpotRenderTag = /** @class */ (function (_super) {
35960     __extends(SpotRenderTag, _super);
35961     function SpotRenderTag() {
35962         return _super !== null && _super.apply(this, arguments) || this;
35963     }
35964     SpotRenderTag.prototype.dispose = function () { };
35965     SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
35966         var _this = this;
35967         var tag = this._tag;
35968         var container = {
35969             offsetHeight: size.height, offsetWidth: size.width,
35970         };
35971         var vNodes = [];
35972         var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
35973         var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
35974         if (centroidCanvas != null) {
35975             var interactNone = function (e) {
35976                 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
35977             };
35978             var canvasX = Math.round(centroidCanvas[0]);
35979             var canvasY = Math.round(centroidCanvas[1]);
35980             if (tag.icon != null) {
35981                 if (atlas.loaded) {
35982                     var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
35983                     var iconTransform = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
35984                     var properties = {
35985                         onmousedown: interactNone,
35986                         style: {
35987                             pointerEvents: "all",
35988                             transform: iconTransform,
35989                         },
35990                     };
35991                     vNodes.push(vd.h("div", properties, [sprite]));
35992                 }
35993             }
35994             else if (tag.text != null) {
35995                 var textTransform = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
35996                 var properties = {
35997                     onmousedown: interactNone,
35998                     style: {
35999                         color: this._colorToCss(tag.textColor),
36000                         transform: textTransform,
36001                     },
36002                     textContent: tag.text,
36003                 };
36004                 vNodes.push(vd.h("span.TagSymbol", properties, []));
36005             }
36006             var interact = this._interact(Component_1.TagOperation.Centroid, tag, "move");
36007             var background = this._colorToCss(tag.color);
36008             var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
36009             if (tag.editable) {
36010                 var interactorProperties = {
36011                     onmousedown: interact,
36012                     style: {
36013                         background: background,
36014                         transform: transform,
36015                     },
36016                 };
36017                 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
36018             }
36019             var pointProperties = {
36020                 style: {
36021                     background: background,
36022                     transform: transform,
36023                 },
36024             };
36025             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
36026         }
36027         return vNodes;
36028     };
36029     SpotRenderTag.prototype.getGLObjects = function () { return []; };
36030     SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
36031     SpotRenderTag.prototype._colorToCss = function (color) {
36032         return "#" + ("000000" + color.toString(16)).substr(-6);
36033     };
36034     SpotRenderTag.prototype._interact = function (operation, tag, cursor, vertexIndex) {
36035         var _this = this;
36036         return function (e) {
36037             var offsetX = e.offsetX - e.target.offsetWidth / 2;
36038             var offsetY = e.offsetY - e.target.offsetHeight / 2;
36039             _this._interact$.next({
36040                 cursor: cursor,
36041                 offsetX: offsetX,
36042                 offsetY: offsetY,
36043                 operation: operation,
36044                 tag: tag,
36045                 vertexIndex: vertexIndex,
36046             });
36047         };
36048     };
36049     return SpotRenderTag;
36050 }(Component_1.RenderTag));
36051 exports.SpotRenderTag = SpotRenderTag;
36052
36053
36054 },{"../../../Component":275,"../../../Viewer":286,"virtual-dom":231}],370:[function(require,module,exports){
36055 "use strict";
36056 var __extends = (this && this.__extends) || (function () {
36057     var extendStatics = function (d, b) {
36058         extendStatics = Object.setPrototypeOf ||
36059             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
36060             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
36061         return extendStatics(d, b);
36062     }
36063     return function (d, b) {
36064         extendStatics(d, b);
36065         function __() { this.constructor = d; }
36066         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36067     };
36068 })();
36069 Object.defineProperty(exports, "__esModule", { value: true });
36070 var Component_1 = require("../../../Component");
36071 /**
36072  * @class SpotTag
36073  *
36074  * @classdesc Tag holding properties for visualizing the centroid of a geometry.
36075  *
36076  * @example
36077  * ```
36078  * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
36079  * var tag = new Mapillary.TagComponent.SpotTag(
36080  *     "id-1",
36081  *     geometry
36082  *     { editable: true, color: 0xff0000 });
36083  *
36084  * tagComponent.add([tag]);
36085  * ```
36086  */
36087 var SpotTag = /** @class */ (function (_super) {
36088     __extends(SpotTag, _super);
36089     /**
36090      * Create a spot tag.
36091      *
36092      * @override
36093      * @constructor
36094      * @param {string} id
36095      * @param {Geometry} geometry
36096      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
36097      * behavior of the spot tag.
36098      */
36099     function SpotTag(id, geometry, options) {
36100         var _this = _super.call(this, id, geometry) || this;
36101         options = !!options ? options : {};
36102         _this._color = options.color == null ? 0xFFFFFF : options.color;
36103         _this._editable = options.editable == null ? false : options.editable;
36104         _this._icon = options.icon === undefined ? null : options.icon;
36105         _this._text = options.text === undefined ? null : options.text;
36106         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
36107         return _this;
36108     }
36109     Object.defineProperty(SpotTag.prototype, "color", {
36110         /**
36111          * Get color property.
36112          * @returns {number} The color of the spot as a hexagonal number;
36113          */
36114         get: function () {
36115             return this._color;
36116         },
36117         /**
36118          * Set color property.
36119          * @param {number}
36120          *
36121          * @fires Tag#changed
36122          */
36123         set: function (value) {
36124             this._color = value;
36125             this._notifyChanged$.next(this);
36126         },
36127         enumerable: true,
36128         configurable: true
36129     });
36130     Object.defineProperty(SpotTag.prototype, "editable", {
36131         /**
36132          * Get editable property.
36133          * @returns {boolean} Value indicating if tag is editable.
36134          */
36135         get: function () {
36136             return this._editable;
36137         },
36138         /**
36139          * Set editable property.
36140          * @param {boolean}
36141          *
36142          * @fires Tag#changed
36143          */
36144         set: function (value) {
36145             this._editable = value;
36146             this._notifyChanged$.next(this);
36147         },
36148         enumerable: true,
36149         configurable: true
36150     });
36151     Object.defineProperty(SpotTag.prototype, "icon", {
36152         /**
36153          * Get icon property.
36154          * @returns {string}
36155          */
36156         get: function () {
36157             return this._icon;
36158         },
36159         /**
36160          * Set icon property.
36161          * @param {string}
36162          *
36163          * @fires Tag#changed
36164          */
36165         set: function (value) {
36166             this._icon = value;
36167             this._notifyChanged$.next(this);
36168         },
36169         enumerable: true,
36170         configurable: true
36171     });
36172     Object.defineProperty(SpotTag.prototype, "text", {
36173         /**
36174          * Get text property.
36175          * @returns {string}
36176          */
36177         get: function () {
36178             return this._text;
36179         },
36180         /**
36181          * Set text property.
36182          * @param {string}
36183          *
36184          * @fires Tag#changed
36185          */
36186         set: function (value) {
36187             this._text = value;
36188             this._notifyChanged$.next(this);
36189         },
36190         enumerable: true,
36191         configurable: true
36192     });
36193     Object.defineProperty(SpotTag.prototype, "textColor", {
36194         /**
36195          * Get text color property.
36196          * @returns {number}
36197          */
36198         get: function () {
36199             return this._textColor;
36200         },
36201         /**
36202          * Set text color property.
36203          * @param {number}
36204          *
36205          * @fires Tag#changed
36206          */
36207         set: function (value) {
36208             this._textColor = value;
36209             this._notifyChanged$.next(this);
36210         },
36211         enumerable: true,
36212         configurable: true
36213     });
36214     /**
36215      * Set options for tag.
36216      *
36217      * @description Sets all the option properties provided and keps
36218      * the rest of the values as is.
36219      *
36220      * @param {ISpotTagOptions} options - Spot tag options
36221      *
36222      * @fires {Tag#changed}
36223      */
36224     SpotTag.prototype.setOptions = function (options) {
36225         this._color = options.color == null ? this._color : options.color;
36226         this._editable = options.editable == null ? this._editable : options.editable;
36227         this._icon = options.icon === undefined ? this._icon : options.icon;
36228         this._text = options.text === undefined ? this._text : options.text;
36229         this._textColor = options.textColor == null ? this._textColor : options.textColor;
36230         this._notifyChanged$.next(this);
36231     };
36232     return SpotTag;
36233 }(Component_1.Tag));
36234 exports.SpotTag = SpotTag;
36235 exports.default = SpotTag;
36236
36237 },{"../../../Component":275}],371:[function(require,module,exports){
36238 "use strict";
36239 var __extends = (this && this.__extends) || (function () {
36240     var extendStatics = function (d, b) {
36241         extendStatics = Object.setPrototypeOf ||
36242             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
36243             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
36244         return extendStatics(d, b);
36245     }
36246     return function (d, b) {
36247         extendStatics(d, b);
36248         function __() { this.constructor = d; }
36249         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36250     };
36251 })();
36252 Object.defineProperty(exports, "__esModule", { value: true });
36253 var operators_1 = require("rxjs/operators");
36254 var rxjs_1 = require("rxjs");
36255 var Utils_1 = require("../../../Utils");
36256 /**
36257  * @class Tag
36258  * @abstract
36259  * @classdesc Abstract class representing the basic functionality of for a tag.
36260  */
36261 var Tag = /** @class */ (function (_super) {
36262     __extends(Tag, _super);
36263     /**
36264      * Create a tag.
36265      *
36266      * @constructor
36267      * @param {string} id
36268      * @param {Geometry} geometry
36269      */
36270     function Tag(id, geometry) {
36271         var _this = _super.call(this) || this;
36272         _this._id = id;
36273         _this._geometry = geometry;
36274         _this._notifyChanged$ = new rxjs_1.Subject();
36275         _this._notifyChanged$
36276             .subscribe(function (t) {
36277             _this.fire(Tag.changed, _this);
36278         });
36279         _this._geometry.changed$
36280             .subscribe(function (g) {
36281             _this.fire(Tag.geometrychanged, _this);
36282         });
36283         return _this;
36284     }
36285     Object.defineProperty(Tag.prototype, "id", {
36286         /**
36287          * Get id property.
36288          * @returns {string}
36289          */
36290         get: function () {
36291             return this._id;
36292         },
36293         enumerable: true,
36294         configurable: true
36295     });
36296     Object.defineProperty(Tag.prototype, "geometry", {
36297         /**
36298          * Get geometry property.
36299          * @returns {Geometry} The geometry of the tag.
36300          */
36301         get: function () {
36302             return this._geometry;
36303         },
36304         enumerable: true,
36305         configurable: true
36306     });
36307     Object.defineProperty(Tag.prototype, "changed$", {
36308         /**
36309          * Get changed observable.
36310          * @returns {Observable<Tag>}
36311          * @ignore
36312          */
36313         get: function () {
36314             return this._notifyChanged$;
36315         },
36316         enumerable: true,
36317         configurable: true
36318     });
36319     Object.defineProperty(Tag.prototype, "geometryChanged$", {
36320         /**
36321          * Get geometry changed observable.
36322          * @returns {Observable<Tag>}
36323          * @ignore
36324          */
36325         get: function () {
36326             var _this = this;
36327             return this._geometry.changed$.pipe(operators_1.map(function (geometry) {
36328                 return _this;
36329             }), operators_1.share());
36330         },
36331         enumerable: true,
36332         configurable: true
36333     });
36334     /**
36335      * Event fired when a property related to the visual appearance of the
36336      * tag has changed.
36337      *
36338      * @event Tag#changed
36339      * @type {Tag} The tag instance that has changed.
36340      */
36341     Tag.changed = "changed";
36342     /**
36343      * Event fired when the geometry of the tag has changed.
36344      *
36345      * @event Tag#geometrychanged
36346      * @type {Tag} The tag instance whose geometry has changed.
36347      */
36348     Tag.geometrychanged = "geometrychanged";
36349     return Tag;
36350 }(Utils_1.EventEmitter));
36351 exports.Tag = Tag;
36352 exports.default = Tag;
36353
36354 },{"../../../Utils":285,"rxjs":27,"rxjs/operators":225}],372:[function(require,module,exports){
36355 "use strict";
36356 Object.defineProperty(exports, "__esModule", { value: true });
36357 /**
36358  * Enumeration for tag domains.
36359  * @enum {number}
36360  * @readonly
36361  * @description Defines where lines between two vertices are treated
36362  * as straight.
36363  *
36364  * Only applicable for polygons. For rectangles lines between
36365  * vertices are always treated as straight in the distorted 2D
36366  * projection and bended in the undistorted 3D space.
36367  */
36368 var TagDomain;
36369 (function (TagDomain) {
36370     /**
36371      * Treats lines between two vertices as straight in the
36372      * distorted 2D projection, i.e. on the image. If the image
36373      * is distorted this will result in bended lines when rendered
36374      * in the undistorted 3D space.
36375      */
36376     TagDomain[TagDomain["TwoDimensional"] = 0] = "TwoDimensional";
36377     /**
36378      * Treats lines as straight in the undistorted 3D space. If the
36379      * image is distorted this will result in bended lines when rendered
36380      * on the distorted 2D projection of the image.
36381      */
36382     TagDomain[TagDomain["ThreeDimensional"] = 1] = "ThreeDimensional";
36383 })(TagDomain = exports.TagDomain || (exports.TagDomain = {}));
36384 exports.default = TagDomain;
36385
36386 },{}],373:[function(require,module,exports){
36387 "use strict";
36388 Object.defineProperty(exports, "__esModule", { value: true });
36389 /**
36390  * Enumeration for component size.
36391  * @enum {number}
36392  * @readonly
36393  * @description May be used by a component to allow for resizing
36394  * of the UI elements rendered by the component.
36395  */
36396 var ComponentSize;
36397 (function (ComponentSize) {
36398     /**
36399      * Automatic size. The size of the elements will automatically
36400      * change at a predefined threshold.
36401      */
36402     ComponentSize[ComponentSize["Automatic"] = 0] = "Automatic";
36403     /**
36404      * Large size. The size of the elements will be fixed until another
36405      * component size is configured.
36406      */
36407     ComponentSize[ComponentSize["Large"] = 1] = "Large";
36408     /**
36409      * Small size. The size of the elements will be fixed until another
36410      * component size is configured.
36411      */
36412     ComponentSize[ComponentSize["Small"] = 2] = "Small";
36413 })(ComponentSize = exports.ComponentSize || (exports.ComponentSize = {}));
36414 exports.default = ComponentSize;
36415
36416 },{}],374:[function(require,module,exports){
36417 "use strict";
36418 Object.defineProperty(exports, "__esModule", { value: true });
36419 var HandlerBase = /** @class */ (function () {
36420     /** @ignore */
36421     function HandlerBase(component, container, navigator) {
36422         this._component = component;
36423         this._container = container;
36424         this._navigator = navigator;
36425         this._enabled = false;
36426     }
36427     Object.defineProperty(HandlerBase.prototype, "isEnabled", {
36428         /**
36429          * Returns a Boolean indicating whether the interaction is enabled.
36430          *
36431          * @returns {boolean} `true` if the interaction is enabled.
36432          */
36433         get: function () {
36434             return this._enabled;
36435         },
36436         enumerable: true,
36437         configurable: true
36438     });
36439     /**
36440      * Enables the interaction.
36441      *
36442      * @example ```<component-name>.<handler-name>.enable();```
36443      */
36444     HandlerBase.prototype.enable = function () {
36445         if (this._enabled || !this._component.activated) {
36446             return;
36447         }
36448         this._enable();
36449         this._enabled = true;
36450         this._component.configure(this._getConfiguration(true));
36451     };
36452     /**
36453      * Disables the interaction.
36454      *
36455      * @example ```<component-name>.<handler-name>.disable();```
36456      */
36457     HandlerBase.prototype.disable = function () {
36458         if (!this._enabled) {
36459             return;
36460         }
36461         this._disable();
36462         this._enabled = false;
36463         if (this._component.activated) {
36464             this._component.configure(this._getConfiguration(false));
36465         }
36466     };
36467     return HandlerBase;
36468 }());
36469 exports.HandlerBase = HandlerBase;
36470 exports.default = HandlerBase;
36471
36472 },{}],375:[function(require,module,exports){
36473 "use strict";
36474 Object.defineProperty(exports, "__esModule", { value: true });
36475 var THREE = require("three");
36476 var Component_1 = require("../../Component");
36477 var MeshFactory = /** @class */ (function () {
36478     function MeshFactory(imagePlaneDepth, imageSphereRadius) {
36479         this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
36480         this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
36481     }
36482     MeshFactory.prototype.createMesh = function (node, transform) {
36483         if (node.pano) {
36484             return this._createImageSphere(node, transform);
36485         }
36486         else if (transform.cameraProjection === "fisheye") {
36487             return this._createImagePlaneFisheye(node, transform);
36488         }
36489         else {
36490             return this._createImagePlane(node, transform);
36491         }
36492     };
36493     MeshFactory.prototype.createFlatMesh = function (node, transform, basicX0, basicX1, basicY0, basicY1) {
36494         var texture = this._createTexture(node.image);
36495         var materialParameters = this._createDistortedPlaneMaterialParameters(transform, texture);
36496         var material = new THREE.ShaderMaterial(materialParameters);
36497         var geometry = this._getFlatImagePlaneGeoFromBasic(transform, basicX0, basicX1, basicY0, basicY1);
36498         return new THREE.Mesh(geometry, material);
36499     };
36500     MeshFactory.prototype.createCurtainMesh = function (node, transform) {
36501         if (node.pano && !node.fullPano) {
36502             throw new Error("Cropped panoramas cannot have curtain.");
36503         }
36504         if (node.pano) {
36505             return this._createSphereCurtainMesh(node, transform);
36506         }
36507         else if (transform.cameraProjection === "fisheye") {
36508             return this._createCurtainMeshFisheye(node, transform);
36509         }
36510         else {
36511             return this._createCurtainMesh(node, transform);
36512         }
36513     };
36514     MeshFactory.prototype.createDistortedCurtainMesh = function (node, transform) {
36515         if (node.pano) {
36516             throw new Error("Cropped panoramas cannot have curtain.");
36517         }
36518         return this._createDistortedCurtainMesh(node, transform);
36519     };
36520     MeshFactory.prototype._createCurtainMesh = function (node, transform) {
36521         var texture = this._createTexture(node.image);
36522         var materialParameters = this._createCurtainPlaneMaterialParameters(transform, texture);
36523         var material = new THREE.ShaderMaterial(materialParameters);
36524         var geometry = this._useMesh(transform, node) ?
36525             this._getImagePlaneGeo(transform, node) :
36526             this._getRegularFlatImagePlaneGeo(transform);
36527         return new THREE.Mesh(geometry, material);
36528     };
36529     MeshFactory.prototype._createCurtainMeshFisheye = function (node, transform) {
36530         var texture = this._createTexture(node.image);
36531         var materialParameters = this._createCurtainPlaneMaterialParametersFisheye(transform, texture);
36532         var material = new THREE.ShaderMaterial(materialParameters);
36533         var geometry = this._useMesh(transform, node) ?
36534             this._getImagePlaneGeoFisheye(transform, node) :
36535             this._getRegularFlatImagePlaneGeo(transform);
36536         return new THREE.Mesh(geometry, material);
36537     };
36538     MeshFactory.prototype._createDistortedCurtainMesh = function (node, transform) {
36539         var texture = this._createTexture(node.image);
36540         var materialParameters = this._createDistortedCurtainPlaneMaterialParameters(transform, texture);
36541         var material = new THREE.ShaderMaterial(materialParameters);
36542         var geometry = this._getRegularFlatImagePlaneGeo(transform);
36543         return new THREE.Mesh(geometry, material);
36544     };
36545     MeshFactory.prototype._createSphereCurtainMesh = function (node, transform) {
36546         var texture = this._createTexture(node.image);
36547         var materialParameters = this._createCurtainSphereMaterialParameters(transform, texture);
36548         var material = new THREE.ShaderMaterial(materialParameters);
36549         return this._useMesh(transform, node) ?
36550             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
36551             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
36552     };
36553     MeshFactory.prototype._createImageSphere = function (node, transform) {
36554         var texture = this._createTexture(node.image);
36555         var materialParameters = this._createSphereMaterialParameters(transform, texture);
36556         var material = new THREE.ShaderMaterial(materialParameters);
36557         var mesh = this._useMesh(transform, node) ?
36558             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
36559             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
36560         return mesh;
36561     };
36562     MeshFactory.prototype._createImagePlane = function (node, transform) {
36563         var texture = this._createTexture(node.image);
36564         var materialParameters = this._createPlaneMaterialParameters(transform, texture);
36565         var material = new THREE.ShaderMaterial(materialParameters);
36566         var geometry = this._useMesh(transform, node) ?
36567             this._getImagePlaneGeo(transform, node) :
36568             this._getRegularFlatImagePlaneGeo(transform);
36569         return new THREE.Mesh(geometry, material);
36570     };
36571     MeshFactory.prototype._createImagePlaneFisheye = function (node, transform) {
36572         var texture = this._createTexture(node.image);
36573         var materialParameters = this._createPlaneMaterialParametersFisheye(transform, texture);
36574         var material = new THREE.ShaderMaterial(materialParameters);
36575         var geometry = this._useMesh(transform, node) ?
36576             this._getImagePlaneGeoFisheye(transform, node) :
36577             this._getRegularFlatImagePlaneGeoFisheye(transform);
36578         return new THREE.Mesh(geometry, material);
36579     };
36580     MeshFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
36581         var gpano = transform.gpano;
36582         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
36583         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
36584         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
36585         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
36586         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
36587         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
36588         var materialParameters = {
36589             depthWrite: false,
36590             fragmentShader: Component_1.Shaders.equirectangular.fragment,
36591             side: THREE.DoubleSide,
36592             transparent: true,
36593             uniforms: {
36594                 opacity: {
36595                     type: "f",
36596                     value: 1,
36597                 },
36598                 phiLength: {
36599                     type: "f",
36600                     value: phiLength,
36601                 },
36602                 phiShift: {
36603                     type: "f",
36604                     value: phiShift,
36605                 },
36606                 projectorMat: {
36607                     type: "m4",
36608                     value: transform.rt,
36609                 },
36610                 projectorTex: {
36611                     type: "t",
36612                     value: texture,
36613                 },
36614                 thetaLength: {
36615                     type: "f",
36616                     value: thetaLength,
36617                 },
36618                 thetaShift: {
36619                     type: "f",
36620                     value: thetaShift,
36621                 },
36622             },
36623             vertexShader: Component_1.Shaders.equirectangular.vertex,
36624         };
36625         return materialParameters;
36626     };
36627     MeshFactory.prototype._createCurtainSphereMaterialParameters = function (transform, texture) {
36628         var gpano = transform.gpano;
36629         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
36630         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
36631         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
36632         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
36633         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
36634         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
36635         var materialParameters = {
36636             depthWrite: false,
36637             fragmentShader: Component_1.Shaders.equirectangularCurtain.fragment,
36638             side: THREE.DoubleSide,
36639             transparent: true,
36640             uniforms: {
36641                 curtain: {
36642                     type: "f",
36643                     value: 1,
36644                 },
36645                 opacity: {
36646                     type: "f",
36647                     value: 1,
36648                 },
36649                 phiLength: {
36650                     type: "f",
36651                     value: phiLength,
36652                 },
36653                 phiShift: {
36654                     type: "f",
36655                     value: phiShift,
36656                 },
36657                 projectorMat: {
36658                     type: "m4",
36659                     value: transform.rt,
36660                 },
36661                 projectorTex: {
36662                     type: "t",
36663                     value: texture,
36664                 },
36665                 thetaLength: {
36666                     type: "f",
36667                     value: thetaLength,
36668                 },
36669                 thetaShift: {
36670                     type: "f",
36671                     value: thetaShift,
36672                 },
36673             },
36674             vertexShader: Component_1.Shaders.equirectangularCurtain.vertex,
36675         };
36676         return materialParameters;
36677     };
36678     MeshFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
36679         var materialParameters = {
36680             depthWrite: false,
36681             fragmentShader: Component_1.Shaders.perspective.fragment,
36682             side: THREE.DoubleSide,
36683             transparent: true,
36684             uniforms: {
36685                 focal: {
36686                     type: "f",
36687                     value: transform.focal,
36688                 },
36689                 k1: {
36690                     type: "f",
36691                     value: transform.ck1,
36692                 },
36693                 k2: {
36694                     type: "f",
36695                     value: transform.ck2,
36696                 },
36697                 opacity: {
36698                     type: "f",
36699                     value: 1,
36700                 },
36701                 projectorMat: {
36702                     type: "m4",
36703                     value: transform.basicRt,
36704                 },
36705                 projectorTex: {
36706                     type: "t",
36707                     value: texture,
36708                 },
36709                 radial_peak: {
36710                     type: "f",
36711                     value: !!transform.radialPeak ? transform.radialPeak : 0,
36712                 },
36713                 scale_x: {
36714                     type: "f",
36715                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
36716                 },
36717                 scale_y: {
36718                     type: "f",
36719                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
36720                 },
36721             },
36722             vertexShader: Component_1.Shaders.perspective.vertex,
36723         };
36724         return materialParameters;
36725     };
36726     MeshFactory.prototype._createPlaneMaterialParametersFisheye = function (transform, texture) {
36727         var materialParameters = {
36728             depthWrite: false,
36729             fragmentShader: Component_1.Shaders.fisheye.fragment,
36730             side: THREE.DoubleSide,
36731             transparent: true,
36732             uniforms: {
36733                 focal: {
36734                     type: "f",
36735                     value: transform.focal,
36736                 },
36737                 k1: {
36738                     type: "f",
36739                     value: transform.ck1,
36740                 },
36741                 k2: {
36742                     type: "f",
36743                     value: transform.ck2,
36744                 },
36745                 opacity: {
36746                     type: "f",
36747                     value: 1,
36748                 },
36749                 projectorMat: {
36750                     type: "m4",
36751                     value: transform.basicRt,
36752                 },
36753                 projectorTex: {
36754                     type: "t",
36755                     value: texture,
36756                 },
36757                 radial_peak: {
36758                     type: "f",
36759                     value: !!transform.radialPeak ? transform.radialPeak : 0,
36760                 },
36761                 scale_x: {
36762                     type: "f",
36763                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
36764                 },
36765                 scale_y: {
36766                     type: "f",
36767                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
36768                 },
36769             },
36770             vertexShader: Component_1.Shaders.fisheye.vertex,
36771         };
36772         return materialParameters;
36773     };
36774     MeshFactory.prototype._createCurtainPlaneMaterialParametersFisheye = function (transform, texture) {
36775         var materialParameters = {
36776             depthWrite: false,
36777             fragmentShader: Component_1.Shaders.fisheyeCurtain.fragment,
36778             side: THREE.DoubleSide,
36779             transparent: true,
36780             uniforms: {
36781                 curtain: {
36782                     type: "f",
36783                     value: 1,
36784                 },
36785                 focal: {
36786                     type: "f",
36787                     value: transform.focal,
36788                 },
36789                 k1: {
36790                     type: "f",
36791                     value: transform.ck1,
36792                 },
36793                 k2: {
36794                     type: "f",
36795                     value: transform.ck2,
36796                 },
36797                 opacity: {
36798                     type: "f",
36799                     value: 1,
36800                 },
36801                 projectorMat: {
36802                     type: "m4",
36803                     value: transform.basicRt,
36804                 },
36805                 projectorTex: {
36806                     type: "t",
36807                     value: texture,
36808                 },
36809                 radial_peak: {
36810                     type: "f",
36811                     value: !!transform.radialPeak ? transform.radialPeak : 0,
36812                 },
36813                 scale_x: {
36814                     type: "f",
36815                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
36816                 },
36817                 scale_y: {
36818                     type: "f",
36819                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
36820                 },
36821             },
36822             vertexShader: Component_1.Shaders.fisheyeCurtain.vertex,
36823         };
36824         return materialParameters;
36825     };
36826     MeshFactory.prototype._createCurtainPlaneMaterialParameters = function (transform, texture) {
36827         var materialParameters = {
36828             depthWrite: false,
36829             fragmentShader: Component_1.Shaders.perspectiveCurtain.fragment,
36830             side: THREE.DoubleSide,
36831             transparent: true,
36832             uniforms: {
36833                 curtain: {
36834                     type: "f",
36835                     value: 1,
36836                 },
36837                 focal: {
36838                     type: "f",
36839                     value: transform.focal,
36840                 },
36841                 k1: {
36842                     type: "f",
36843                     value: transform.ck1,
36844                 },
36845                 k2: {
36846                     type: "f",
36847                     value: transform.ck2,
36848                 },
36849                 opacity: {
36850                     type: "f",
36851                     value: 1,
36852                 },
36853                 projectorMat: {
36854                     type: "m4",
36855                     value: transform.basicRt,
36856                 },
36857                 projectorTex: {
36858                     type: "t",
36859                     value: texture,
36860                 },
36861                 radial_peak: {
36862                     type: "f",
36863                     value: !!transform.radialPeak ? transform.radialPeak : 0,
36864                 },
36865                 scale_x: {
36866                     type: "f",
36867                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
36868                 },
36869                 scale_y: {
36870                     type: "f",
36871                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
36872                 },
36873             },
36874             vertexShader: Component_1.Shaders.perspectiveCurtain.vertex,
36875         };
36876         return materialParameters;
36877     };
36878     MeshFactory.prototype._createDistortedCurtainPlaneMaterialParameters = function (transform, texture) {
36879         var materialParameters = {
36880             depthWrite: false,
36881             fragmentShader: Component_1.Shaders.perspectiveDistortedCurtain.fragment,
36882             side: THREE.DoubleSide,
36883             transparent: true,
36884             uniforms: {
36885                 curtain: {
36886                     type: "f",
36887                     value: 1,
36888                 },
36889                 opacity: {
36890                     type: "f",
36891                     value: 1,
36892                 },
36893                 projectorMat: {
36894                     type: "m4",
36895                     value: transform.projectorMatrix(),
36896                 },
36897                 projectorTex: {
36898                     type: "t",
36899                     value: texture,
36900                 },
36901             },
36902             vertexShader: Component_1.Shaders.perspectiveDistortedCurtain.vertex,
36903         };
36904         return materialParameters;
36905     };
36906     MeshFactory.prototype._createDistortedPlaneMaterialParameters = function (transform, texture) {
36907         var materialParameters = {
36908             depthWrite: false,
36909             fragmentShader: Component_1.Shaders.perspectiveDistorted.fragment,
36910             side: THREE.DoubleSide,
36911             transparent: true,
36912             uniforms: {
36913                 opacity: {
36914                     type: "f",
36915                     value: 1,
36916                 },
36917                 projectorMat: {
36918                     type: "m4",
36919                     value: transform.projectorMatrix(),
36920                 },
36921                 projectorTex: {
36922                     type: "t",
36923                     value: texture,
36924                 },
36925             },
36926             vertexShader: Component_1.Shaders.perspectiveDistorted.vertex,
36927         };
36928         return materialParameters;
36929     };
36930     MeshFactory.prototype._createTexture = function (image) {
36931         var texture = new THREE.Texture(image);
36932         texture.minFilter = THREE.LinearFilter;
36933         texture.needsUpdate = true;
36934         return texture;
36935     };
36936     MeshFactory.prototype._useMesh = function (transform, node) {
36937         return node.mesh.vertices.length && transform.hasValidScale;
36938     };
36939     MeshFactory.prototype._getImageSphereGeo = function (transform, node) {
36940         var t = new THREE.Matrix4().getInverse(transform.srt);
36941         // push everything at least 5 meters in front of the camera
36942         var minZ = 5.0 * transform.scale;
36943         var maxZ = this._imageSphereRadius * transform.scale;
36944         var vertices = node.mesh.vertices;
36945         var numVertices = vertices.length / 3;
36946         var positions = new Float32Array(vertices.length);
36947         for (var i = 0; i < numVertices; ++i) {
36948             var index = 3 * i;
36949             var x = vertices[index + 0];
36950             var y = vertices[index + 1];
36951             var z = vertices[index + 2];
36952             var l = Math.sqrt(x * x + y * y + z * z);
36953             var boundedL = Math.max(minZ, Math.min(l, maxZ));
36954             var factor = boundedL / l;
36955             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
36956             p.applyMatrix4(t);
36957             positions[index + 0] = p.x;
36958             positions[index + 1] = p.y;
36959             positions[index + 2] = p.z;
36960         }
36961         var faces = node.mesh.faces;
36962         var indices = new Uint16Array(faces.length);
36963         for (var i = 0; i < faces.length; ++i) {
36964             indices[i] = faces[i];
36965         }
36966         var geometry = new THREE.BufferGeometry();
36967         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
36968         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
36969         return geometry;
36970     };
36971     MeshFactory.prototype._getImagePlaneGeo = function (transform, node) {
36972         var undistortionMarginFactor = 3;
36973         var t = new THREE.Matrix4().getInverse(transform.srt);
36974         // push everything at least 5 meters in front of the camera
36975         var minZ = 5.0 * transform.scale;
36976         var maxZ = this._imagePlaneDepth * transform.scale;
36977         var vertices = node.mesh.vertices;
36978         var numVertices = vertices.length / 3;
36979         var positions = new Float32Array(vertices.length);
36980         for (var i = 0; i < numVertices; ++i) {
36981             var index = 3 * i;
36982             var x = vertices[index + 0];
36983             var y = vertices[index + 1];
36984             var z = vertices[index + 2];
36985             if (i < 4) {
36986                 x *= undistortionMarginFactor;
36987                 y *= undistortionMarginFactor;
36988             }
36989             var boundedZ = Math.max(minZ, Math.min(z, maxZ));
36990             var factor = boundedZ / z;
36991             var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
36992             p.applyMatrix4(t);
36993             positions[index + 0] = p.x;
36994             positions[index + 1] = p.y;
36995             positions[index + 2] = p.z;
36996         }
36997         var faces = node.mesh.faces;
36998         var indices = new Uint16Array(faces.length);
36999         for (var i = 0; i < faces.length; ++i) {
37000             indices[i] = faces[i];
37001         }
37002         var geometry = new THREE.BufferGeometry();
37003         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
37004         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
37005         return geometry;
37006     };
37007     MeshFactory.prototype._getImagePlaneGeoFisheye = function (transform, node) {
37008         var t = new THREE.Matrix4().getInverse(transform.srt);
37009         // push everything at least 5 meters in front of the camera
37010         var minZ = 5.0 * transform.scale;
37011         var maxZ = this._imagePlaneDepth * transform.scale;
37012         var vertices = node.mesh.vertices;
37013         var numVertices = vertices.length / 3;
37014         var positions = new Float32Array(vertices.length);
37015         for (var i = 0; i < numVertices; ++i) {
37016             var index = 3 * i;
37017             var x = vertices[index + 0];
37018             var y = vertices[index + 1];
37019             var z = vertices[index + 2];
37020             var l = Math.sqrt(x * x + y * y + z * z);
37021             var boundedL = Math.max(minZ, Math.min(l, maxZ));
37022             var factor = boundedL / l;
37023             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
37024             p.applyMatrix4(t);
37025             positions[index + 0] = p.x;
37026             positions[index + 1] = p.y;
37027             positions[index + 2] = p.z;
37028         }
37029         var faces = node.mesh.faces;
37030         var indices = new Uint16Array(faces.length);
37031         for (var i = 0; i < faces.length; ++i) {
37032             indices[i] = faces[i];
37033         }
37034         var geometry = new THREE.BufferGeometry();
37035         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
37036         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
37037         return geometry;
37038     };
37039     MeshFactory.prototype._getFlatImageSphereGeo = function (transform) {
37040         var gpano = transform.gpano;
37041         var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
37042         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
37043         var thetaStart = Math.PI *
37044             (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
37045             gpano.FullPanoHeightPixels;
37046         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
37047         var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
37048         geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
37049         return geometry;
37050     };
37051     MeshFactory.prototype._getRegularFlatImagePlaneGeo = function (transform) {
37052         var width = transform.width;
37053         var height = transform.height;
37054         var size = Math.max(width, height);
37055         var dx = width / 2.0 / size;
37056         var dy = height / 2.0 / size;
37057         return this._getFlatImagePlaneGeo(transform, dx, dy);
37058     };
37059     MeshFactory.prototype._getFlatImagePlaneGeo = function (transform, dx, dy) {
37060         var vertices = [];
37061         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
37062         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
37063         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
37064         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
37065         return this._createFlatGeometry(vertices);
37066     };
37067     MeshFactory.prototype._getRegularFlatImagePlaneGeoFisheye = function (transform) {
37068         var width = transform.width;
37069         var height = transform.height;
37070         var size = Math.max(width, height);
37071         var dx = width / 2.0 / size;
37072         var dy = height / 2.0 / size;
37073         return this._getFlatImagePlaneGeoFisheye(transform, dx, dy);
37074     };
37075     MeshFactory.prototype._getFlatImagePlaneGeoFisheye = function (transform, dx, dy) {
37076         var vertices = [];
37077         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
37078         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
37079         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
37080         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
37081         return this._createFlatGeometry(vertices);
37082     };
37083     MeshFactory.prototype._getFlatImagePlaneGeoFromBasic = function (transform, basicX0, basicX1, basicY0, basicY1) {
37084         var vertices = [];
37085         vertices.push(transform.unprojectBasic([basicX0, basicY0], this._imagePlaneDepth));
37086         vertices.push(transform.unprojectBasic([basicX1, basicY0], this._imagePlaneDepth));
37087         vertices.push(transform.unprojectBasic([basicX1, basicY1], this._imagePlaneDepth));
37088         vertices.push(transform.unprojectBasic([basicX0, basicY1], this._imagePlaneDepth));
37089         return this._createFlatGeometry(vertices);
37090     };
37091     MeshFactory.prototype._createFlatGeometry = function (vertices) {
37092         var positions = new Float32Array(12);
37093         for (var i = 0; i < vertices.length; i++) {
37094             var index = 3 * i;
37095             positions[index + 0] = vertices[i][0];
37096             positions[index + 1] = vertices[i][1];
37097             positions[index + 2] = vertices[i][2];
37098         }
37099         var indices = new Uint16Array(6);
37100         indices[0] = 0;
37101         indices[1] = 1;
37102         indices[2] = 3;
37103         indices[3] = 1;
37104         indices[4] = 2;
37105         indices[5] = 3;
37106         var geometry = new THREE.BufferGeometry();
37107         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
37108         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
37109         return geometry;
37110     };
37111     return MeshFactory;
37112 }());
37113 exports.MeshFactory = MeshFactory;
37114 exports.default = MeshFactory;
37115
37116 },{"../../Component":275,"three":226}],376:[function(require,module,exports){
37117 "use strict";
37118 Object.defineProperty(exports, "__esModule", { value: true });
37119 var THREE = require("three");
37120 var MeshScene = /** @class */ (function () {
37121     function MeshScene() {
37122         this._planes = {};
37123         this._planesOld = {};
37124         this._planesPeriphery = {};
37125         this._scene = new THREE.Scene();
37126         this._sceneOld = new THREE.Scene();
37127         this._scenePeriphery = new THREE.Scene();
37128     }
37129     Object.defineProperty(MeshScene.prototype, "planes", {
37130         get: function () {
37131             return this._planes;
37132         },
37133         enumerable: true,
37134         configurable: true
37135     });
37136     Object.defineProperty(MeshScene.prototype, "planesOld", {
37137         get: function () {
37138             return this._planesOld;
37139         },
37140         enumerable: true,
37141         configurable: true
37142     });
37143     Object.defineProperty(MeshScene.prototype, "planesPeriphery", {
37144         get: function () {
37145             return this._planesPeriphery;
37146         },
37147         enumerable: true,
37148         configurable: true
37149     });
37150     Object.defineProperty(MeshScene.prototype, "scene", {
37151         get: function () {
37152             return this._scene;
37153         },
37154         enumerable: true,
37155         configurable: true
37156     });
37157     Object.defineProperty(MeshScene.prototype, "sceneOld", {
37158         get: function () {
37159             return this._sceneOld;
37160         },
37161         enumerable: true,
37162         configurable: true
37163     });
37164     Object.defineProperty(MeshScene.prototype, "scenePeriphery", {
37165         get: function () {
37166             return this._scenePeriphery;
37167         },
37168         enumerable: true,
37169         configurable: true
37170     });
37171     MeshScene.prototype.updateImagePlanes = function (planes) {
37172         this._dispose(this._planesOld, this.sceneOld);
37173         for (var key in this._planes) {
37174             if (!this._planes.hasOwnProperty(key)) {
37175                 continue;
37176             }
37177             var plane = this._planes[key];
37178             this._scene.remove(plane);
37179             this._sceneOld.add(plane);
37180         }
37181         for (var key in planes) {
37182             if (!planes.hasOwnProperty(key)) {
37183                 continue;
37184             }
37185             this._scene.add(planes[key]);
37186         }
37187         this._planesOld = this._planes;
37188         this._planes = planes;
37189     };
37190     MeshScene.prototype.addImagePlanes = function (planes) {
37191         for (var key in planes) {
37192             if (!planes.hasOwnProperty(key)) {
37193                 continue;
37194             }
37195             var plane = planes[key];
37196             this._scene.add(plane);
37197             this._planes[key] = plane;
37198         }
37199     };
37200     MeshScene.prototype.addImagePlanesOld = function (planes) {
37201         for (var key in planes) {
37202             if (!planes.hasOwnProperty(key)) {
37203                 continue;
37204             }
37205             var plane = planes[key];
37206             this._sceneOld.add(plane);
37207             this._planesOld[key] = plane;
37208         }
37209     };
37210     MeshScene.prototype.setImagePlanes = function (planes) {
37211         this._clear();
37212         this.addImagePlanes(planes);
37213     };
37214     MeshScene.prototype.addPeripheryPlanes = function (planes) {
37215         for (var key in planes) {
37216             if (!planes.hasOwnProperty(key)) {
37217                 continue;
37218             }
37219             var plane = planes[key];
37220             this._scenePeriphery.add(plane);
37221             this._planesPeriphery[key] = plane;
37222         }
37223     };
37224     MeshScene.prototype.setPeripheryPlanes = function (planes) {
37225         this._clearPeriphery();
37226         this.addPeripheryPlanes(planes);
37227     };
37228     MeshScene.prototype.setImagePlanesOld = function (planes) {
37229         this._clearOld();
37230         this.addImagePlanesOld(planes);
37231     };
37232     MeshScene.prototype.clear = function () {
37233         this._clear();
37234         this._clearOld();
37235     };
37236     MeshScene.prototype._clear = function () {
37237         this._dispose(this._planes, this._scene);
37238         this._planes = {};
37239     };
37240     MeshScene.prototype._clearOld = function () {
37241         this._dispose(this._planesOld, this._sceneOld);
37242         this._planesOld = {};
37243     };
37244     MeshScene.prototype._clearPeriphery = function () {
37245         this._dispose(this._planesPeriphery, this._scenePeriphery);
37246         this._planesPeriphery = {};
37247     };
37248     MeshScene.prototype._dispose = function (planes, scene) {
37249         for (var key in planes) {
37250             if (!planes.hasOwnProperty(key)) {
37251                 continue;
37252             }
37253             var plane = planes[key];
37254             scene.remove(plane);
37255             plane.geometry.dispose();
37256             plane.material.dispose();
37257             var texture = plane.material.uniforms.projectorTex.value;
37258             if (texture != null) {
37259                 texture.dispose();
37260             }
37261         }
37262     };
37263     return MeshScene;
37264 }());
37265 exports.MeshScene = MeshScene;
37266 exports.default = MeshScene;
37267
37268 },{"three":226}],377:[function(require,module,exports){
37269 "use strict";
37270 Object.defineProperty(exports, "__esModule", { value: true });
37271 var rxjs_1 = require("rxjs");
37272 var operators_1 = require("rxjs/operators");
37273 var MouseOperator = /** @class */ (function () {
37274     function MouseOperator() {
37275     }
37276     MouseOperator.filteredPairwiseMouseDrag$ = function (name, mouseService) {
37277         return mouseService
37278             .filtered$(name, mouseService.mouseDragStart$).pipe(operators_1.switchMap(function (mouseDragStart) {
37279             var mouseDragging$ = rxjs_1.concat(rxjs_1.of(mouseDragStart), mouseService
37280                 .filtered$(name, mouseService.mouseDrag$));
37281             var mouseDragEnd$ = mouseService
37282                 .filtered$(name, mouseService.mouseDragEnd$).pipe(operators_1.map(function () {
37283                 return null;
37284             }));
37285             return rxjs_1.merge(mouseDragging$, mouseDragEnd$).pipe(operators_1.takeWhile(function (e) {
37286                 return !!e;
37287             }), operators_1.startWith(null));
37288         }), operators_1.pairwise(), operators_1.filter(function (pair) {
37289             return pair[0] != null && pair[1] != null;
37290         }));
37291     };
37292     return MouseOperator;
37293 }());
37294 exports.MouseOperator = MouseOperator;
37295 exports.default = MouseOperator;
37296
37297 },{"rxjs":27,"rxjs/operators":225}],378:[function(require,module,exports){
37298 "use strict";
37299 var __extends = (this && this.__extends) || (function () {
37300     var extendStatics = function (d, b) {
37301         extendStatics = Object.setPrototypeOf ||
37302             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37303             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37304         return extendStatics(d, b);
37305     }
37306     return function (d, b) {
37307         extendStatics(d, b);
37308         function __() { this.constructor = d; }
37309         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37310     };
37311 })();
37312 Object.defineProperty(exports, "__esModule", { value: true });
37313 var rxjs_1 = require("rxjs");
37314 var operators_1 = require("rxjs/operators");
37315 var vd = require("virtual-dom");
37316 var Component_1 = require("../../Component");
37317 var Geo_1 = require("../../Geo");
37318 var State_1 = require("../../State");
37319 var ComponentSize_1 = require("../utils/ComponentSize");
37320 /**
37321  * @class ZoomComponent
37322  *
37323  * @classdesc Component rendering UI elements used for zooming.
37324  *
37325  * @example
37326  * ```
37327  * var viewer = new Mapillary.Viewer(
37328  *     "<element-id>",
37329  *     "<client-id>",
37330  *     "<my key>");
37331  *
37332  * var zoomComponent = viewer.getComponent("zoom");
37333  * zoomComponent.configure({ size: Mapillary.ComponentSize.Small });
37334  * ```
37335  */
37336 var ZoomComponent = /** @class */ (function (_super) {
37337     __extends(ZoomComponent, _super);
37338     function ZoomComponent(name, container, navigator) {
37339         var _this = _super.call(this, name, container, navigator) || this;
37340         _this._viewportCoords = new Geo_1.ViewportCoords();
37341         _this._zoomDelta$ = new rxjs_1.Subject();
37342         return _this;
37343     }
37344     ZoomComponent.prototype._activate = function () {
37345         var _this = this;
37346         this._renderSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentState$, this._navigator.stateService.state$, this._configuration$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
37347             var frame = _a[0], state = _a[1], configuration = _a[2], size = _a[3];
37348             var zoom = frame.state.zoom;
37349             var zoomInIcon = vd.h("div.ZoomInIcon", []);
37350             var zoomInButton = zoom >= 3 || state === State_1.State.Waiting ?
37351                 vd.h("div.ZoomInButtonDisabled", [zoomInIcon]) :
37352                 vd.h("div.ZoomInButton", { onclick: function () { _this._zoomDelta$.next(1); } }, [zoomInIcon]);
37353             var zoomOutIcon = vd.h("div.ZoomOutIcon", []);
37354             var zoomOutButton = zoom <= 0 || state === State_1.State.Waiting ?
37355                 vd.h("div.ZoomOutButtonDisabled", [zoomOutIcon]) :
37356                 vd.h("div.ZoomOutButton", { onclick: function () { _this._zoomDelta$.next(-1); } }, [zoomOutIcon]);
37357             var compact = configuration.size === ComponentSize_1.default.Small ||
37358                 configuration.size === ComponentSize_1.default.Automatic && size.width < 640 ?
37359                 ".ZoomCompact" : "";
37360             return {
37361                 name: _this._name,
37362                 vnode: vd.h("div.ZoomContainer" + compact, { oncontextmenu: function (event) { event.preventDefault(); } }, [zoomInButton, zoomOutButton]),
37363             };
37364         }))
37365             .subscribe(this._container.domRenderer.render$);
37366         this._zoomSubscription = this._zoomDelta$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
37367             .subscribe(function (_a) {
37368             var zoomDelta = _a[0], render = _a[1], transform = _a[2];
37369             var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
37370             var reference = transform.projectBasic(unprojected.toArray());
37371             _this._navigator.stateService.zoomIn(zoomDelta, reference);
37372         });
37373     };
37374     ZoomComponent.prototype._deactivate = function () {
37375         this._renderSubscription.unsubscribe();
37376         this._zoomSubscription.unsubscribe();
37377     };
37378     ZoomComponent.prototype._getDefaultConfiguration = function () {
37379         return { size: ComponentSize_1.default.Automatic };
37380     };
37381     ZoomComponent.componentName = "zoom";
37382     return ZoomComponent;
37383 }(Component_1.Component));
37384 exports.ZoomComponent = ZoomComponent;
37385 Component_1.ComponentService.register(ZoomComponent);
37386 exports.default = ZoomComponent;
37387
37388 },{"../../Component":275,"../../Geo":278,"../../State":282,"../utils/ComponentSize":373,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],379:[function(require,module,exports){
37389 "use strict";
37390 var __extends = (this && this.__extends) || (function () {
37391     var extendStatics = function (d, b) {
37392         extendStatics = Object.setPrototypeOf ||
37393             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37394             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37395         return extendStatics(d, b);
37396     }
37397     return function (d, b) {
37398         extendStatics(d, b);
37399         function __() { this.constructor = d; }
37400         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37401     };
37402 })();
37403 Object.defineProperty(exports, "__esModule", { value: true });
37404 var MapillaryError_1 = require("./MapillaryError");
37405 /**
37406  * @class AbortMapillaryError
37407  *
37408  * @classdesc Error thrown when a move to request has been
37409  * aborted before completing because of a subsequent request.
37410  */
37411 var AbortMapillaryError = /** @class */ (function (_super) {
37412     __extends(AbortMapillaryError, _super);
37413     function AbortMapillaryError(message) {
37414         var _this = _super.call(this, message != null ? message : "The request was aborted.") || this;
37415         Object.setPrototypeOf(_this, AbortMapillaryError.prototype);
37416         _this.name = "AbortMapillaryError";
37417         return _this;
37418     }
37419     return AbortMapillaryError;
37420 }(MapillaryError_1.MapillaryError));
37421 exports.AbortMapillaryError = AbortMapillaryError;
37422 exports.default = AbortMapillaryError;
37423
37424 },{"./MapillaryError":382}],380:[function(require,module,exports){
37425 "use strict";
37426 var __extends = (this && this.__extends) || (function () {
37427     var extendStatics = function (d, b) {
37428         extendStatics = Object.setPrototypeOf ||
37429             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37430             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37431         return extendStatics(d, b);
37432     }
37433     return function (d, b) {
37434         extendStatics(d, b);
37435         function __() { this.constructor = d; }
37436         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37437     };
37438 })();
37439 Object.defineProperty(exports, "__esModule", { value: true });
37440 var MapillaryError_1 = require("./MapillaryError");
37441 var ArgumentMapillaryError = /** @class */ (function (_super) {
37442     __extends(ArgumentMapillaryError, _super);
37443     function ArgumentMapillaryError(message) {
37444         var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
37445         Object.setPrototypeOf(_this, ArgumentMapillaryError.prototype);
37446         _this.name = "ArgumentMapillaryError";
37447         return _this;
37448     }
37449     return ArgumentMapillaryError;
37450 }(MapillaryError_1.MapillaryError));
37451 exports.ArgumentMapillaryError = ArgumentMapillaryError;
37452 exports.default = ArgumentMapillaryError;
37453
37454 },{"./MapillaryError":382}],381:[function(require,module,exports){
37455 "use strict";
37456 var __extends = (this && this.__extends) || (function () {
37457     var extendStatics = function (d, b) {
37458         extendStatics = Object.setPrototypeOf ||
37459             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37460             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37461         return extendStatics(d, b);
37462     }
37463     return function (d, b) {
37464         extendStatics(d, b);
37465         function __() { this.constructor = d; }
37466         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37467     };
37468 })();
37469 Object.defineProperty(exports, "__esModule", { value: true });
37470 var MapillaryError_1 = require("./MapillaryError");
37471 var GraphMapillaryError = /** @class */ (function (_super) {
37472     __extends(GraphMapillaryError, _super);
37473     function GraphMapillaryError(message) {
37474         var _this = _super.call(this, message) || this;
37475         Object.setPrototypeOf(_this, GraphMapillaryError.prototype);
37476         _this.name = "GraphMapillaryError";
37477         return _this;
37478     }
37479     return GraphMapillaryError;
37480 }(MapillaryError_1.MapillaryError));
37481 exports.GraphMapillaryError = GraphMapillaryError;
37482 exports.default = GraphMapillaryError;
37483
37484 },{"./MapillaryError":382}],382:[function(require,module,exports){
37485 "use strict";
37486 var __extends = (this && this.__extends) || (function () {
37487     var extendStatics = function (d, b) {
37488         extendStatics = Object.setPrototypeOf ||
37489             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37490             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37491         return extendStatics(d, b);
37492     }
37493     return function (d, b) {
37494         extendStatics(d, b);
37495         function __() { this.constructor = d; }
37496         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37497     };
37498 })();
37499 Object.defineProperty(exports, "__esModule", { value: true });
37500 var MapillaryError = /** @class */ (function (_super) {
37501     __extends(MapillaryError, _super);
37502     function MapillaryError(message) {
37503         var _this = _super.call(this, message) || this;
37504         Object.setPrototypeOf(_this, MapillaryError.prototype);
37505         _this.name = "MapillaryError";
37506         return _this;
37507     }
37508     return MapillaryError;
37509 }(Error));
37510 exports.MapillaryError = MapillaryError;
37511 exports.default = MapillaryError;
37512
37513 },{}],383:[function(require,module,exports){
37514 "use strict";
37515 Object.defineProperty(exports, "__esModule", { value: true });
37516 var THREE = require("three");
37517 /**
37518  * @class Camera
37519  *
37520  * @classdesc Holds information about a camera.
37521  */
37522 var Camera = /** @class */ (function () {
37523     /**
37524      * Create a new camera instance.
37525      * @param {Transform} [transform] - Optional transform instance.
37526      */
37527     function Camera(transform) {
37528         if (transform != null) {
37529             this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
37530             this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
37531             this._up = transform.upVector();
37532             this._focal = this._getFocal(transform);
37533         }
37534         else {
37535             this._position = new THREE.Vector3(0, 0, 0);
37536             this._lookat = new THREE.Vector3(0, 0, 1);
37537             this._up = new THREE.Vector3(0, -1, 0);
37538             this._focal = 1;
37539         }
37540     }
37541     Object.defineProperty(Camera.prototype, "position", {
37542         /**
37543          * Get position.
37544          * @returns {THREE.Vector3} The position vector.
37545          */
37546         get: function () {
37547             return this._position;
37548         },
37549         enumerable: true,
37550         configurable: true
37551     });
37552     Object.defineProperty(Camera.prototype, "lookat", {
37553         /**
37554          * Get lookat.
37555          * @returns {THREE.Vector3} The lookat vector.
37556          */
37557         get: function () {
37558             return this._lookat;
37559         },
37560         enumerable: true,
37561         configurable: true
37562     });
37563     Object.defineProperty(Camera.prototype, "up", {
37564         /**
37565          * Get up.
37566          * @returns {THREE.Vector3} The up vector.
37567          */
37568         get: function () {
37569             return this._up;
37570         },
37571         enumerable: true,
37572         configurable: true
37573     });
37574     Object.defineProperty(Camera.prototype, "focal", {
37575         /**
37576          * Get focal.
37577          * @returns {number} The focal length.
37578          */
37579         get: function () {
37580             return this._focal;
37581         },
37582         /**
37583          * Set focal.
37584          */
37585         set: function (value) {
37586             this._focal = value;
37587         },
37588         enumerable: true,
37589         configurable: true
37590     });
37591     /**
37592      * Update this camera to the linearly interpolated value of two other cameras.
37593      *
37594      * @param {Camera} a - First camera.
37595      * @param {Camera} b - Second camera.
37596      * @param {number} alpha - Interpolation value on the interval [0, 1].
37597      */
37598     Camera.prototype.lerpCameras = function (a, b, alpha) {
37599         this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
37600         this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
37601         this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
37602         this._focal = (1 - alpha) * a.focal + alpha * b.focal;
37603     };
37604     /**
37605      * Copy the properties of another camera to this camera.
37606      *
37607      * @param {Camera} other - Another camera.
37608      */
37609     Camera.prototype.copy = function (other) {
37610         this._position.copy(other.position);
37611         this._lookat.copy(other.lookat);
37612         this._up.copy(other.up);
37613         this._focal = other.focal;
37614     };
37615     /**
37616      * Clone this camera.
37617      *
37618      * @returns {Camera} A camera with cloned properties equal to this camera.
37619      */
37620     Camera.prototype.clone = function () {
37621         var camera = new Camera();
37622         camera.position.copy(this._position);
37623         camera.lookat.copy(this._lookat);
37624         camera.up.copy(this._up);
37625         camera.focal = this._focal;
37626         return camera;
37627     };
37628     /**
37629      * Determine the distance between this camera and another camera.
37630      *
37631      * @param {Camera} other - Another camera.
37632      * @returns {number} The distance between the cameras.
37633      */
37634     Camera.prototype.diff = function (other) {
37635         var pd = this._position.distanceToSquared(other.position);
37636         var ld = this._lookat.distanceToSquared(other.lookat);
37637         var ud = this._up.distanceToSquared(other.up);
37638         var fd = 100 * Math.abs(this._focal - other.focal);
37639         return Math.max(pd, ld, ud, fd);
37640     };
37641     /**
37642      * Get the focal length based on the transform.
37643      *
37644      * @description Returns the focal length of the transform if gpano info is not available.
37645      * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
37646      * the gpano information if available.
37647      *
37648      * @returns {number} Focal length.
37649      */
37650     Camera.prototype._getFocal = function (transform) {
37651         if (transform.gpano == null) {
37652             return transform.focal;
37653         }
37654         var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
37655         var focal = 0.5 / Math.tan(vFov / 2);
37656         return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
37657     };
37658     return Camera;
37659 }());
37660 exports.Camera = Camera;
37661
37662 },{"three":226}],384:[function(require,module,exports){
37663 "use strict";
37664 Object.defineProperty(exports, "__esModule", { value: true });
37665 var THREE = require("three");
37666 var Geo_1 = require("../Geo");
37667 var geoCoords = new Geo_1.GeoCoords();
37668 var spatial = new Geo_1.Spatial();
37669 function computeTranslation(position, rotation, reference) {
37670     var C = geoCoords.geodeticToEnu(position.lat, position.lon, position.alt, reference.lat, reference.lon, reference.alt);
37671     var RC = spatial.rotate(C, rotation);
37672     var translation = [-RC.x, -RC.y, -RC.z];
37673     return translation;
37674 }
37675 exports.computeTranslation = computeTranslation;
37676 function computeProjectedPoints(transform, basicVertices, basicDirections, pointsPerLine, viewportCoords) {
37677     var basicPoints = [];
37678     for (var side = 0; side < basicVertices.length; ++side) {
37679         var v = basicVertices[side];
37680         var d = basicDirections[side];
37681         for (var i = 0; i <= pointsPerLine; ++i) {
37682             basicPoints.push([v[0] + d[0] * i / pointsPerLine,
37683                 v[1] + d[1] * i / pointsPerLine]);
37684         }
37685     }
37686     var camera = new THREE.Camera();
37687     camera.up.copy(transform.upVector());
37688     camera.position.copy(new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0)));
37689     camera.lookAt(new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10)));
37690     camera.updateMatrix();
37691     camera.updateMatrixWorld(true);
37692     var projectedPoints = basicPoints
37693         .map(function (basicPoint) {
37694         var worldPoint = transform.unprojectBasic(basicPoint, 10000);
37695         var cameraPoint = viewportCoords.worldToCamera(worldPoint, camera);
37696         return [
37697             Math.abs(cameraPoint[0] / cameraPoint[2]),
37698             Math.abs(cameraPoint[1] / cameraPoint[2]),
37699         ];
37700     });
37701     return projectedPoints;
37702 }
37703 exports.computeProjectedPoints = computeProjectedPoints;
37704
37705 },{"../Geo":278,"three":226}],385:[function(require,module,exports){
37706 "use strict";
37707 Object.defineProperty(exports, "__esModule", { value: true });
37708 /**
37709  * @class GeoCoords
37710  *
37711  * @classdesc Converts coordinates between the geodetic (WGS84),
37712  * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
37713  * East, North, Up (ENU) reference frames.
37714  *
37715  * The WGS84 has latitude (degrees), longitude (degrees) and
37716  * altitude (meters) values.
37717  *
37718  * The ECEF Z-axis pierces the north pole and the
37719  * XY-axis defines the equatorial plane. The X-axis extends
37720  * from the geocenter to the intersection of the Equator and
37721  * the Greenwich Meridian. All values in meters.
37722  *
37723  * The WGS84 parameters are:
37724  *
37725  * a = 6378137
37726  * b = a * (1 - f)
37727  * f = 1 / 298.257223563
37728  * e = Math.sqrt((a^2 - b^2) / a^2)
37729  * e' = Math.sqrt((a^2 - b^2) / b^2)
37730  *
37731  * The WGS84 to ECEF conversion is performed using the following:
37732  *
37733  * X = (N - h) * cos(phi) * cos(lambda)
37734  * Y = (N + h) * cos(phi) * sin(lambda)
37735  * Z = (b^2 * N / a^2 + h) * sin(phi)
37736  *
37737  * where
37738  *
37739  * phi = latitude
37740  * lambda = longitude
37741  * h = height above ellipsoid (altitude)
37742  * N = Radius of curvature (meters)
37743  *   = a / Math.sqrt(1 - e^2 * sin(phi)^2)
37744  *
37745  * The ECEF to WGS84 conversion is performed using the following:
37746  *
37747  * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
37748  * lambda = arctan(Y / X)
37749  * h = p / cos(phi) - N
37750  *
37751  * where
37752  *
37753  * p = Math.sqrt(X^2 + Y^2)
37754  * theta = arctan(Z * a / p * b)
37755  *
37756  * In the ENU reference frame the x-axis points to the
37757  * East, the y-axis to the North and the z-axis Up. All values
37758  * in meters.
37759  *
37760  * The ECEF to ENU conversion is performed using the following:
37761  *
37762  * | x |   |       -sin(lambda_r)                cos(lambda_r)             0      | | X - X_r |
37763  * | y | = | -sin(phi_r) * cos(lambda_r)  -sin(phi_r) * sin(lambda_r)  cos(phi_r) | | Y - Y_r |
37764  * | z |   |  cos(phi_r) * cos(lambda_r)   cos(phi_r) * sin(lambda_r)  sin(phi_r) | | Z - Z_r |
37765  *
37766  * where
37767  *
37768  * phi_r = latitude of reference
37769  * lambda_r = longitude of reference
37770  * X_r, Y_r, Z_r = ECEF coordinates of reference
37771  *
37772  * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
37773  *
37774  * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
37775  * the first step for both conversions.
37776  */
37777 var GeoCoords = /** @class */ (function () {
37778     function GeoCoords() {
37779         this._wgs84a = 6378137.0;
37780         this._wgs84b = 6356752.31424518;
37781     }
37782     /**
37783      * Convert coordinates from geodetic (WGS84) reference to local topocentric
37784      * (ENU) reference.
37785      *
37786      * @param {number} lat Latitude in degrees.
37787      * @param {number} lon Longitude in degrees.
37788      * @param {number} alt Altitude in meters.
37789      * @param {number} refLat Reference latitude in degrees.
37790      * @param {number} refLon Reference longitude in degrees.
37791      * @param {number} refAlt Reference altitude in meters.
37792      * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
37793      */
37794     GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
37795         var ecef = this.geodeticToEcef(lat, lon, alt);
37796         return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
37797     };
37798     /**
37799      * Convert coordinates from local topocentric (ENU) reference to
37800      * geodetic (WGS84) reference.
37801      *
37802      * @param {number} x Topocentric ENU coordinate in East direction.
37803      * @param {number} y Topocentric ENU coordinate in North direction.
37804      * @param {number} z Topocentric ENU coordinate in Up direction.
37805      * @param {number} refLat Reference latitude in degrees.
37806      * @param {number} refLon Reference longitude in degrees.
37807      * @param {number} refAlt Reference altitude in meters.
37808      * @returns {Array<number>} The latitude and longitude in degrees
37809      *                          as well as altitude in meters.
37810      */
37811     GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
37812         var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
37813         return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
37814     };
37815     /**
37816      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
37817      * to local topocentric (ENU) reference.
37818      *
37819      * @param {number} X ECEF X-value.
37820      * @param {number} Y ECEF Y-value.
37821      * @param {number} Z ECEF Z-value.
37822      * @param {number} refLat Reference latitude in degrees.
37823      * @param {number} refLon Reference longitude in degrees.
37824      * @param {number} refAlt Reference altitude in meters.
37825      * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
37826      * and Up directions respectively.
37827      */
37828     GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
37829         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
37830         var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
37831         refLat = refLat * Math.PI / 180.0;
37832         refLon = refLon * Math.PI / 180.0;
37833         var cosLat = Math.cos(refLat);
37834         var sinLat = Math.sin(refLat);
37835         var cosLon = Math.cos(refLon);
37836         var sinLon = Math.sin(refLon);
37837         var x = -sinLon * V[0] + cosLon * V[1];
37838         var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
37839         var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
37840         return [x, y, z];
37841     };
37842     /**
37843      * Convert coordinates from local topocentric (ENU) reference
37844      * to Earth-Centered, Earth-Fixed (ECEF) reference.
37845      *
37846      * @param {number} x Topocentric ENU coordinate in East direction.
37847      * @param {number} y Topocentric ENU coordinate in North direction.
37848      * @param {number} z Topocentric ENU coordinate in Up direction.
37849      * @param {number} refLat Reference latitude in degrees.
37850      * @param {number} refLon Reference longitude in degrees.
37851      * @param {number} refAlt Reference altitude in meters.
37852      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
37853      */
37854     GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
37855         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
37856         refLat = refLat * Math.PI / 180.0;
37857         refLon = refLon * Math.PI / 180.0;
37858         var cosLat = Math.cos(refLat);
37859         var sinLat = Math.sin(refLat);
37860         var cosLon = Math.cos(refLon);
37861         var sinLon = Math.sin(refLon);
37862         var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
37863         var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
37864         var Z = cosLat * y + sinLat * z + refEcef[2];
37865         return [X, Y, Z];
37866     };
37867     /**
37868      * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
37869      * Earth-Fixed (ECEF) reference.
37870      *
37871      * @param {number} lat Latitude in degrees.
37872      * @param {number} lon Longitude in degrees.
37873      * @param {number} alt Altitude in meters.
37874      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
37875      */
37876     GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
37877         var a = this._wgs84a;
37878         var b = this._wgs84b;
37879         lat = lat * Math.PI / 180.0;
37880         lon = lon * Math.PI / 180.0;
37881         var cosLat = Math.cos(lat);
37882         var sinLat = Math.sin(lat);
37883         var cosLon = Math.cos(lon);
37884         var sinLon = Math.sin(lon);
37885         var a2 = a * a;
37886         var b2 = b * b;
37887         var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
37888         var nhcl = (a2 * L + alt) * cosLat;
37889         var X = nhcl * cosLon;
37890         var Y = nhcl * sinLon;
37891         var Z = (b2 * L + alt) * sinLat;
37892         return [X, Y, Z];
37893     };
37894     /**
37895      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
37896      * to geodetic reference (WGS84).
37897      *
37898      * @param {number} X ECEF X-value.
37899      * @param {number} Y ECEF Y-value.
37900      * @param {number} Z ECEF Z-value.
37901      * @returns {Array<number>} The latitude and longitude in degrees
37902      *                          as well as altitude in meters.
37903      */
37904     GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
37905         var a = this._wgs84a;
37906         var b = this._wgs84b;
37907         var a2 = a * a;
37908         var b2 = b * b;
37909         var a2mb2 = a2 - b2;
37910         var ea = Math.sqrt(a2mb2 / a2);
37911         var eb = Math.sqrt(a2mb2 / b2);
37912         var p = Math.sqrt(X * X + Y * Y);
37913         var theta = Math.atan2(Z * a, p * b);
37914         var sinTheta = Math.sin(theta);
37915         var cosTheta = Math.cos(theta);
37916         var lon = Math.atan2(Y, X);
37917         var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
37918         var sinLat = Math.sin(lat);
37919         var cosLat = Math.cos(lat);
37920         var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
37921         var alt = p / cosLat - N;
37922         return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
37923     };
37924     return GeoCoords;
37925 }());
37926 exports.GeoCoords = GeoCoords;
37927 exports.default = GeoCoords;
37928
37929 },{}],386:[function(require,module,exports){
37930 "use strict";
37931 Object.defineProperty(exports, "__esModule", { value: true });
37932 function sign(n) {
37933     return n > 0 ? 1 : n < 0 ? -1 : 0;
37934 }
37935 function colinearPointOnSegment(p, s) {
37936     return p.x <= Math.max(s.p1.x, s.p2.x) &&
37937         p.x >= Math.min(s.p1.x, s.p2.x) &&
37938         p.y >= Math.max(s.p1.y, s.p2.y) &&
37939         p.y >= Math.min(s.p1.y, s.p2.y);
37940 }
37941 function parallel(s1, s2) {
37942     var ux = s1.p2.x - s1.p1.x;
37943     var uy = s1.p2.y - s1.p1.y;
37944     var vx = s2.p2.x - s2.p1.x;
37945     var vy = s2.p2.y - s2.p1.y;
37946     var cross = ux * vy - uy * vx;
37947     var u2 = ux * ux + uy * uy;
37948     var v2 = vx * vx + vy * vy;
37949     var epsilon2 = 1e-10;
37950     return cross * cross < epsilon2 * u2 * v2;
37951 }
37952 function tripletOrientation(p1, p2, p3) {
37953     var orientation = (p2.y - p1.y) * (p3.x - p2.x) -
37954         (p3.y - p2.y) * (p2.x - p1.x);
37955     return sign(orientation);
37956 }
37957 function segmentsIntersect(s1, s2) {
37958     if (parallel(s1, s2)) {
37959         return false;
37960     }
37961     var o1 = tripletOrientation(s1.p1, s1.p2, s2.p1);
37962     var o2 = tripletOrientation(s1.p1, s1.p2, s2.p2);
37963     var o3 = tripletOrientation(s2.p1, s2.p2, s1.p1);
37964     var o4 = tripletOrientation(s2.p1, s2.p2, s1.p2);
37965     if (o1 !== o2 && o3 !== o4) {
37966         return true;
37967     }
37968     if (o1 === 0 && colinearPointOnSegment(s2.p1, s1)) {
37969         return true;
37970     }
37971     if (o2 === 0 && colinearPointOnSegment(s2.p2, s1)) {
37972         return true;
37973     }
37974     if (o3 === 0 && colinearPointOnSegment(s1.p1, s2)) {
37975         return true;
37976     }
37977     if (o4 === 0 && colinearPointOnSegment(s1.p2, s2)) {
37978         return true;
37979     }
37980     return false;
37981 }
37982 exports.segmentsIntersect = segmentsIntersect;
37983 function segmentIntersection(s1, s2) {
37984     if (parallel(s1, s2)) {
37985         return undefined;
37986     }
37987     var x1 = s1.p1.x;
37988     var x2 = s1.p2.x;
37989     var y1 = s1.p1.y;
37990     var y2 = s1.p2.y;
37991     var x3 = s2.p1.x;
37992     var x4 = s2.p2.x;
37993     var y3 = s2.p1.y;
37994     var y4 = s2.p2.y;
37995     var den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
37996     var xNum = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4);
37997     var yNum = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4);
37998     return { x: xNum / den, y: yNum / den };
37999 }
38000 exports.segmentIntersection = segmentIntersection;
38001
38002 },{}],387:[function(require,module,exports){
38003 "use strict";
38004 Object.defineProperty(exports, "__esModule", { value: true });
38005 var THREE = require("three");
38006 /**
38007  * @class Spatial
38008  *
38009  * @classdesc Provides methods for scalar, vector and matrix calculations.
38010  */
38011 var Spatial = /** @class */ (function () {
38012     function Spatial() {
38013         this._epsilon = 1e-9;
38014     }
38015     /**
38016      * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
38017      * bearing (clockwise with origin at north or Y-axis).
38018      *
38019      * @param {number} phi - Azimuthal phi angle in radians.
38020      * @returns {number} Bearing in radians.
38021      */
38022     Spatial.prototype.azimuthalToBearing = function (phi) {
38023         return -phi + Math.PI / 2;
38024     };
38025     /**
38026      * Converts degrees to radians.
38027      *
38028      * @param {number} deg - Degrees.
38029      * @returns {number} Radians.
38030      */
38031     Spatial.prototype.degToRad = function (deg) {
38032         return Math.PI * deg / 180;
38033     };
38034     /**
38035      * Converts radians to degrees.
38036      *
38037      * @param {number} rad - Radians.
38038      * @returns {number} Degrees.
38039      */
38040     Spatial.prototype.radToDeg = function (rad) {
38041         return 180 * rad / Math.PI;
38042     };
38043     /**
38044      * Creates a rotation matrix from an angle-axis vector.
38045      *
38046      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
38047      * @returns {THREE.Matrix4} Rotation matrix.
38048      */
38049     Spatial.prototype.rotationMatrix = function (angleAxis) {
38050         var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
38051         var angle = axis.length();
38052         if (angle > 0) {
38053             axis.normalize();
38054         }
38055         return new THREE.Matrix4().makeRotationAxis(axis, angle);
38056     };
38057     /**
38058      * Rotates a vector according to a angle-axis rotation vector.
38059      *
38060      * @param {Array<number>} vector - Vector to rotate.
38061      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
38062      * @returns {THREE.Vector3} Rotated vector.
38063      */
38064     Spatial.prototype.rotate = function (vector, angleAxis) {
38065         var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
38066         var rotationMatrix = this.rotationMatrix(angleAxis);
38067         v.applyMatrix4(rotationMatrix);
38068         return v;
38069     };
38070     /**
38071      * Calculates the optical center from a rotation vector
38072      * on the angle-axis representation and a translation vector
38073      * according to C = -R^T t.
38074      *
38075      * @param {Array<number>} rotation - Angle-axis representation of a rotation.
38076      * @param {Array<number>} translation - Translation vector.
38077      * @returns {THREE.Vector3} Optical center.
38078      */
38079     Spatial.prototype.opticalCenter = function (rotation, translation) {
38080         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
38081         var vector = [-translation[0], -translation[1], -translation[2]];
38082         return this.rotate(vector, angleAxis);
38083     };
38084     /**
38085      * Calculates the viewing direction from a rotation vector
38086      * on the angle-axis representation.
38087      *
38088      * @param {number[]} rotation - Angle-axis representation of a rotation.
38089      * @returns {THREE.Vector3} Viewing direction.
38090      */
38091     Spatial.prototype.viewingDirection = function (rotation) {
38092         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
38093         return this.rotate([0, 0, 1], angleAxis);
38094     };
38095     /**
38096      * Wrap a number on the interval [min, max].
38097      *
38098      * @param {number} value - Value to wrap.
38099      * @param {number} min - Lower endpoint of interval.
38100      * @param {number} max - Upper endpoint of interval.
38101      * @returns {number} The wrapped number.
38102      */
38103     Spatial.prototype.wrap = function (value, min, max) {
38104         if (max < min) {
38105             throw new Error("Invalid arguments: max must be larger than min.");
38106         }
38107         var interval = (max - min);
38108         while (value > max || value < min) {
38109             if (value > max) {
38110                 value = value - interval;
38111             }
38112             else if (value < min) {
38113                 value = value + interval;
38114             }
38115         }
38116         return value;
38117     };
38118     /**
38119      * Wrap an angle on the interval [-Pi, Pi].
38120      *
38121      * @param {number} angle - Value to wrap.
38122      * @returns {number} Wrapped angle.
38123      */
38124     Spatial.prototype.wrapAngle = function (angle) {
38125         return this.wrap(angle, -Math.PI, Math.PI);
38126     };
38127     /**
38128      * Limit the value to the interval [min, max] by changing the value to
38129      * the nearest available one when it is outside the interval.
38130      *
38131      * @param {number} value - Value to clamp.
38132      * @param {number} min - Minimum of the interval.
38133      * @param {number} max - Maximum of the interval.
38134      * @returns {number} Clamped value.
38135      */
38136     Spatial.prototype.clamp = function (value, min, max) {
38137         if (value < min) {
38138             return min;
38139         }
38140         if (value > max) {
38141             return max;
38142         }
38143         return value;
38144     };
38145     /**
38146      * Calculates the counter-clockwise angle from the first
38147      * vector (x1, y1)^T to the second (x2, y2)^T.
38148      *
38149      * @param {number} x1 - X coordinate of first vector.
38150      * @param {number} y1 - Y coordinate of first vector.
38151      * @param {number} x2 - X coordinate of second vector.
38152      * @param {number} y2 - Y coordinate of second vector.
38153      * @returns {number} Counter clockwise angle between the vectors.
38154      */
38155     Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
38156         var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
38157         return this.wrapAngle(angle);
38158     };
38159     /**
38160      * Calculates the minimum (absolute) angle change for rotation
38161      * from one angle to another on the [-Pi, Pi] interval.
38162      *
38163      * @param {number} angle1 - Start angle.
38164      * @param {number} angle2 - Destination angle.
38165      * @returns {number} Absolute angle change between angles.
38166      */
38167     Spatial.prototype.angleDifference = function (angle1, angle2) {
38168         var angle = angle2 - angle1;
38169         return this.wrapAngle(angle);
38170     };
38171     /**
38172      * Calculates the relative rotation angle between two
38173      * angle-axis vectors.
38174      *
38175      * @param {number} rotation1 - First angle-axis vector.
38176      * @param {number} rotation2 - Second angle-axis vector.
38177      * @returns {number} Relative rotation angle.
38178      */
38179     Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
38180         var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
38181         var R2 = this.rotationMatrix(rotation2);
38182         var R = R1T.multiply(R2);
38183         var elements = R.elements;
38184         // from Tr(R) = 1 + 2 * cos(theta)
38185         var tr = elements[0] + elements[5] + elements[10];
38186         var theta = Math.acos(Math.max(Math.min((tr - 1) / 2, 1), -1));
38187         return theta;
38188     };
38189     /**
38190      * Calculates the angle from a vector to a plane.
38191      *
38192      * @param {Array<number>} vector - The vector.
38193      * @param {Array<number>} planeNormal - Normal of the plane.
38194      * @returns {number} Angle from between plane and vector.
38195      */
38196     Spatial.prototype.angleToPlane = function (vector, planeNormal) {
38197         var v = new THREE.Vector3().fromArray(vector);
38198         var norm = v.length();
38199         if (norm < this._epsilon) {
38200             return 0;
38201         }
38202         var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
38203         return Math.asin(projection / norm);
38204     };
38205     Spatial.prototype.azimuthal = function (direction, up) {
38206         var directionVector = new THREE.Vector3().fromArray(direction);
38207         var upVector = new THREE.Vector3().fromArray(up);
38208         var upProjection = directionVector.clone().dot(upVector);
38209         var planeProjection = directionVector.clone().sub(upVector.clone().multiplyScalar(upProjection));
38210         return Math.atan2(planeProjection.y, planeProjection.x);
38211     };
38212     /**
38213      * Calculates the distance between two coordinates
38214      * (latitude longitude pairs) in meters according to
38215      * the haversine formula.
38216      *
38217      * @param {number} lat1 - Latitude of the first coordinate in degrees.
38218      * @param {number} lon1 - Longitude of the first coordinate in degrees.
38219      * @param {number} lat2 - Latitude of the second coordinate in degrees.
38220      * @param {number} lon2 - Longitude of the second coordinate in degrees.
38221      * @returns {number} Distance between lat lon positions in meters.
38222      */
38223     Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
38224         var r = 6371000;
38225         var dLat = this.degToRad(lat2 - lat1);
38226         var dLon = this.degToRad(lon2 - lon1);
38227         var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
38228             Math.cos(this.degToRad(lat1)) * Math.cos(this.degToRad(lat2)) *
38229                 Math.sin(dLon / 2) * Math.sin(dLon / 2);
38230         var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
38231         return d;
38232     };
38233     return Spatial;
38234 }());
38235 exports.Spatial = Spatial;
38236 exports.default = Spatial;
38237
38238 },{"three":226}],388:[function(require,module,exports){
38239 "use strict";
38240 Object.defineProperty(exports, "__esModule", { value: true });
38241 var THREE = require("three");
38242 /**
38243  * @class Transform
38244  *
38245  * @classdesc Class used for calculating coordinate transformations
38246  * and projections.
38247  */
38248 var Transform = /** @class */ (function () {
38249     /**
38250      * Create a new transform instance.
38251      * @param {number} orientation - Image orientation.
38252      * @param {number} width - Image height.
38253      * @param {number} height - Image width.
38254      * @param {number} focal - Focal length.
38255      * @param {number} scale - Atomic scale.
38256      * @param {IGPano} gpano - Panorama properties.
38257      * @param {Array<number>} rotation - Rotation vector in three dimensions.
38258      * @param {Array<number>} translation - Translation vector in three dimensions.
38259      * @param {HTMLImageElement} image - Image for fallback size calculations.
38260      */
38261     function Transform(orientation, width, height, focal, scale, gpano, rotation, translation, image, textureScale, ck1, ck2, cameraProjection) {
38262         this._orientation = this._getValue(orientation, 1);
38263         var imageWidth = image != null ? image.width : 4;
38264         var imageHeight = image != null ? image.height : 3;
38265         var keepOrientation = this._orientation < 5;
38266         this._width = this._getValue(width, keepOrientation ? imageWidth : imageHeight);
38267         this._height = this._getValue(height, keepOrientation ? imageHeight : imageWidth);
38268         this._basicAspect = keepOrientation ?
38269             this._width / this._height :
38270             this._height / this._width;
38271         this._basicWidth = keepOrientation ? width : height;
38272         this._basicHeight = keepOrientation ? height : width;
38273         this._focal = this._getValue(focal, 1);
38274         this._scale = this._getValue(scale, 0);
38275         this._gpano = gpano != null ? gpano : null;
38276         this._rt = this._getRt(rotation, translation);
38277         this._srt = this._getSrt(this._rt, this._scale);
38278         this._basicRt = this._getBasicRt(this._rt, orientation);
38279         this._textureScale = !!textureScale ? textureScale : [1, 1];
38280         this._ck1 = !!ck1 ? ck1 : 0;
38281         this._ck2 = !!ck2 ? ck2 : 0;
38282         this._cameraProjection = !!cameraProjection ?
38283             cameraProjection :
38284             !!gpano ?
38285                 "equirectangular" :
38286                 "perspective";
38287         this._radialPeak = this._getRadialPeak(this._ck1, this._ck2);
38288     }
38289     Object.defineProperty(Transform.prototype, "ck1", {
38290         get: function () {
38291             return this._ck1;
38292         },
38293         enumerable: true,
38294         configurable: true
38295     });
38296     Object.defineProperty(Transform.prototype, "ck2", {
38297         get: function () {
38298             return this._ck2;
38299         },
38300         enumerable: true,
38301         configurable: true
38302     });
38303     Object.defineProperty(Transform.prototype, "cameraProjection", {
38304         get: function () {
38305             return this._cameraProjection;
38306         },
38307         enumerable: true,
38308         configurable: true
38309     });
38310     Object.defineProperty(Transform.prototype, "basicAspect", {
38311         /**
38312          * Get basic aspect.
38313          * @returns {number} The orientation adjusted aspect ratio.
38314          */
38315         get: function () {
38316             return this._basicAspect;
38317         },
38318         enumerable: true,
38319         configurable: true
38320     });
38321     Object.defineProperty(Transform.prototype, "basicHeight", {
38322         /**
38323          * Get basic height.
38324          *
38325          * @description Does not fall back to node image height but
38326          * uses original value from API so can be faulty.
38327          *
38328          * @returns {number} The height of the basic version image
38329          * (adjusted for orientation).
38330          */
38331         get: function () {
38332             return this._basicHeight;
38333         },
38334         enumerable: true,
38335         configurable: true
38336     });
38337     Object.defineProperty(Transform.prototype, "basicRt", {
38338         get: function () {
38339             return this._basicRt;
38340         },
38341         enumerable: true,
38342         configurable: true
38343     });
38344     Object.defineProperty(Transform.prototype, "basicWidth", {
38345         /**
38346          * Get basic width.
38347          *
38348          * @description Does not fall back to node image width but
38349          * uses original value from API so can be faulty.
38350          *
38351          * @returns {number} The width of the basic version image
38352          * (adjusted for orientation).
38353          */
38354         get: function () {
38355             return this._basicWidth;
38356         },
38357         enumerable: true,
38358         configurable: true
38359     });
38360     Object.defineProperty(Transform.prototype, "focal", {
38361         /**
38362          * Get focal.
38363          * @returns {number} The node focal length.
38364          */
38365         get: function () {
38366             return this._focal;
38367         },
38368         enumerable: true,
38369         configurable: true
38370     });
38371     Object.defineProperty(Transform.prototype, "fullPano", {
38372         /**
38373          * Get fullPano.
38374          *
38375          * @returns {boolean} Value indicating whether the node is a complete
38376          * 360 panorama.
38377          */
38378         get: function () {
38379             return this._gpano != null &&
38380                 this._gpano.CroppedAreaLeftPixels === 0 &&
38381                 this._gpano.CroppedAreaTopPixels === 0 &&
38382                 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
38383                 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
38384         },
38385         enumerable: true,
38386         configurable: true
38387     });
38388     Object.defineProperty(Transform.prototype, "gpano", {
38389         /**
38390          * Get gpano.
38391          * @returns {number} The node gpano information.
38392          */
38393         get: function () {
38394             return this._gpano;
38395         },
38396         enumerable: true,
38397         configurable: true
38398     });
38399     Object.defineProperty(Transform.prototype, "height", {
38400         /**
38401          * Get height.
38402          *
38403          * @description Falls back to the node image height if
38404          * the API data is faulty.
38405          *
38406          * @returns {number} The orientation adjusted image height.
38407          */
38408         get: function () {
38409             return this._height;
38410         },
38411         enumerable: true,
38412         configurable: true
38413     });
38414     Object.defineProperty(Transform.prototype, "orientation", {
38415         /**
38416          * Get orientation.
38417          * @returns {number} The image orientation.
38418          */
38419         get: function () {
38420             return this._orientation;
38421         },
38422         enumerable: true,
38423         configurable: true
38424     });
38425     Object.defineProperty(Transform.prototype, "rt", {
38426         /**
38427          * Get rt.
38428          * @returns {THREE.Matrix4} The extrinsic camera matrix.
38429          */
38430         get: function () {
38431             return this._rt;
38432         },
38433         enumerable: true,
38434         configurable: true
38435     });
38436     Object.defineProperty(Transform.prototype, "srt", {
38437         /**
38438          * Get srt.
38439          * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
38440          */
38441         get: function () {
38442             return this._srt;
38443         },
38444         enumerable: true,
38445         configurable: true
38446     });
38447     Object.defineProperty(Transform.prototype, "scale", {
38448         /**
38449          * Get scale.
38450          * @returns {number} The node atomic reconstruction scale.
38451          */
38452         get: function () {
38453             return this._scale;
38454         },
38455         enumerable: true,
38456         configurable: true
38457     });
38458     Object.defineProperty(Transform.prototype, "hasValidScale", {
38459         /**
38460          * Get has valid scale.
38461          * @returns {boolean} Value indicating if the scale of the transform is valid.
38462          */
38463         get: function () {
38464             return this._scale > 1e-2 && this._scale < 50;
38465         },
38466         enumerable: true,
38467         configurable: true
38468     });
38469     Object.defineProperty(Transform.prototype, "radialPeak", {
38470         /**
38471          * Get radial peak.
38472          * @returns {number} Value indicating the radius where the radial
38473          * undistortion function peaks.
38474          */
38475         get: function () {
38476             return this._radialPeak;
38477         },
38478         enumerable: true,
38479         configurable: true
38480     });
38481     Object.defineProperty(Transform.prototype, "width", {
38482         /**
38483          * Get width.
38484          *
38485          * @description Falls back to the node image width if
38486          * the API data is faulty.
38487          *
38488          * @returns {number} The orientation adjusted image width.
38489          */
38490         get: function () {
38491             return this._width;
38492         },
38493         enumerable: true,
38494         configurable: true
38495     });
38496     /**
38497      * Calculate the up vector for the node transform.
38498      *
38499      * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
38500      */
38501     Transform.prototype.upVector = function () {
38502         var rte = this._rt.elements;
38503         switch (this._orientation) {
38504             case 1:
38505                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
38506             case 3:
38507                 return new THREE.Vector3(rte[1], rte[5], rte[9]);
38508             case 6:
38509                 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
38510             case 8:
38511                 return new THREE.Vector3(rte[0], rte[4], rte[8]);
38512             default:
38513                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
38514         }
38515     };
38516     /**
38517      * Calculate projector matrix for projecting 3D points to texture map
38518      * coordinates (u and v).
38519      *
38520      * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
38521      * map coordinate calculations.
38522      */
38523     Transform.prototype.projectorMatrix = function () {
38524         var projector = this._normalizedToTextureMatrix();
38525         var f = this._focal;
38526         var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
38527         projector.multiply(projection);
38528         projector.multiply(this._rt);
38529         return projector;
38530     };
38531     /**
38532      * Project 3D world coordinates to basic coordinates.
38533      *
38534      * @param {Array<number>} point3d - 3D world coordinates.
38535      * @return {Array<number>} 2D basic coordinates.
38536      */
38537     Transform.prototype.projectBasic = function (point3d) {
38538         var sfm = this.projectSfM(point3d);
38539         return this._sfmToBasic(sfm);
38540     };
38541     /**
38542      * Unproject basic coordinates to 3D world coordinates.
38543      *
38544      * @param {Array<number>} basic - 2D basic coordinates.
38545      * @param {Array<number>} distance - Distance to unproject from camera center.
38546      * @param {boolean} [depth] - Treat the distance value as depth from camera center.
38547      *                            Only applicable for perspective images. Will be
38548      *                            ignored for panoramas.
38549      * @returns {Array<number>} Unprojected 3D world coordinates.
38550      */
38551     Transform.prototype.unprojectBasic = function (basic, distance, depth) {
38552         var sfm = this._basicToSfm(basic);
38553         return this.unprojectSfM(sfm, distance, depth);
38554     };
38555     /**
38556      * Project 3D world coordinates to SfM coordinates.
38557      *
38558      * @param {Array<number>} point3d - 3D world coordinates.
38559      * @return {Array<number>} 2D SfM coordinates.
38560      */
38561     Transform.prototype.projectSfM = function (point3d) {
38562         var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
38563         v.applyMatrix4(this._rt);
38564         return this._bearingToSfm([v.x, v.y, v.z]);
38565     };
38566     /**
38567      * Unproject SfM coordinates to a 3D world coordinates.
38568      *
38569      * @param {Array<number>} sfm - 2D SfM coordinates.
38570      * @param {Array<number>} distance - Distance to unproject from camera center.
38571      * @param {boolean} [depth] - Treat the distance value as depth from camera center.
38572      *                            Only applicable for perspective images. Will be
38573      *                            ignored for panoramas.
38574      * @returns {Array<number>} Unprojected 3D world coordinates.
38575      */
38576     Transform.prototype.unprojectSfM = function (sfm, distance, depth) {
38577         var bearing = this._sfmToBearing(sfm);
38578         var v = depth && !this.gpano ?
38579             new THREE.Vector4(distance * bearing[0] / bearing[2], distance * bearing[1] / bearing[2], distance, 1) :
38580             new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
38581         v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
38582         return [v.x / v.w, v.y / v.w, v.z / v.w];
38583     };
38584     /**
38585      * Transform SfM coordinates to bearing vector (3D cartesian
38586      * coordinates on the unit sphere).
38587      *
38588      * @param {Array<number>} sfm - 2D SfM coordinates.
38589      * @returns {Array<number>} Bearing vector (3D cartesian coordinates
38590      * on the unit sphere).
38591      */
38592     Transform.prototype._sfmToBearing = function (sfm) {
38593         if (this._fullPano()) {
38594             var lon = sfm[0] * 2 * Math.PI;
38595             var lat = -sfm[1] * 2 * Math.PI;
38596             var x = Math.cos(lat) * Math.sin(lon);
38597             var y = -Math.sin(lat);
38598             var z = Math.cos(lat) * Math.cos(lon);
38599             return [x, y, z];
38600         }
38601         else if (this._gpano) {
38602             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
38603             var fullPanoPixel = [
38604                 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
38605                 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
38606             ];
38607             var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
38608             var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
38609             var x = Math.cos(lat) * Math.sin(lon);
38610             var y = -Math.sin(lat);
38611             var z = Math.cos(lat) * Math.cos(lon);
38612             return [x, y, z];
38613         }
38614         else if (this._cameraProjection === "fisheye") {
38615             var _a = [sfm[0] / this._focal, sfm[1] / this._focal], dxn = _a[0], dyn = _a[1];
38616             var dTheta = Math.sqrt(dxn * dxn + dyn * dyn);
38617             var d = this._distortionFromDistortedRadius(dTheta, this._ck1, this._ck2, this._radialPeak);
38618             var theta = dTheta / d;
38619             var z = Math.cos(theta);
38620             var r = Math.sin(theta);
38621             var x = r * dxn / dTheta;
38622             var y = r * dyn / dTheta;
38623             return [x, y, z];
38624         }
38625         else {
38626             var _b = [sfm[0] / this._focal, sfm[1] / this._focal], dxn = _b[0], dyn = _b[1];
38627             var dr = Math.sqrt(dxn * dxn + dyn * dyn);
38628             var d = this._distortionFromDistortedRadius(dr, this._ck1, this._ck2, this._radialPeak);
38629             var xn = dxn / d;
38630             var yn = dyn / d;
38631             var v = new THREE.Vector3(xn, yn, 1);
38632             v.normalize();
38633             return [v.x, v.y, v.z];
38634         }
38635     };
38636     /** Compute distortion given the distorted radius.
38637      *
38638      *  Solves for d in the equation
38639      *    y = d(x, k1, k2) * x
38640      * given the distorted radius, y.
38641      */
38642     Transform.prototype._distortionFromDistortedRadius = function (distortedRadius, k1, k2, radialPeak) {
38643         var d = 1.0;
38644         for (var i = 0; i < 10; i++) {
38645             var radius = distortedRadius / d;
38646             if (radius > radialPeak) {
38647                 radius = radialPeak;
38648             }
38649             d = 1 + k1 * Math.pow(radius, 2) + k2 * Math.pow(radius, 4);
38650         }
38651         return d;
38652     };
38653     /**
38654      * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
38655      * SfM coordinates.
38656      *
38657      * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
38658      * unit sphere).
38659      * @returns {Array<number>} 2D SfM coordinates.
38660      */
38661     Transform.prototype._bearingToSfm = function (bearing) {
38662         if (this._fullPano()) {
38663             var x = bearing[0];
38664             var y = bearing[1];
38665             var z = bearing[2];
38666             var lon = Math.atan2(x, z);
38667             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
38668             return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
38669         }
38670         else if (this._gpano) {
38671             var x = bearing[0];
38672             var y = bearing[1];
38673             var z = bearing[2];
38674             var lon = Math.atan2(x, z);
38675             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
38676             var fullPanoPixel = [
38677                 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
38678                 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
38679             ];
38680             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
38681             return [
38682                 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
38683                 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
38684             ];
38685         }
38686         else if (this._cameraProjection === "fisheye") {
38687             if (bearing[2] > 0) {
38688                 var x = bearing[0], y = bearing[1], z = bearing[2];
38689                 var r = Math.sqrt(x * x + y * y);
38690                 var theta = Math.atan2(r, z);
38691                 if (theta > this._radialPeak) {
38692                     theta = this._radialPeak;
38693                 }
38694                 var distortion = 1.0 + Math.pow(theta, 2) * (this._ck1 + Math.pow(theta, 2) * this._ck2);
38695                 var s = this._focal * distortion * theta / r;
38696                 return [s * x, s * y];
38697             }
38698             else {
38699                 return [
38700                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
38701                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
38702                 ];
38703             }
38704         }
38705         else {
38706             if (bearing[2] > 0) {
38707                 var _a = [bearing[0] / bearing[2], bearing[1] / bearing[2]], xn = _a[0], yn = _a[1];
38708                 var r2 = xn * xn + yn * yn;
38709                 var rp2 = Math.pow(this._radialPeak, 2);
38710                 if (r2 > rp2) {
38711                     r2 = rp2;
38712                 }
38713                 var d = 1 + this._ck1 * r2 + this._ck2 * Math.pow(r2, 2);
38714                 return [
38715                     this._focal * d * xn,
38716                     this._focal * d * yn,
38717                 ];
38718             }
38719             else {
38720                 return [
38721                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
38722                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
38723                 ];
38724             }
38725         }
38726     };
38727     /**
38728      * Convert basic coordinates to SfM coordinates.
38729      *
38730      * @param {Array<number>} basic - 2D basic coordinates.
38731      * @returns {Array<number>} 2D SfM coordinates.
38732      */
38733     Transform.prototype._basicToSfm = function (basic) {
38734         var rotatedX;
38735         var rotatedY;
38736         switch (this._orientation) {
38737             case 1:
38738                 rotatedX = basic[0];
38739                 rotatedY = basic[1];
38740                 break;
38741             case 3:
38742                 rotatedX = 1 - basic[0];
38743                 rotatedY = 1 - basic[1];
38744                 break;
38745             case 6:
38746                 rotatedX = basic[1];
38747                 rotatedY = 1 - basic[0];
38748                 break;
38749             case 8:
38750                 rotatedX = 1 - basic[1];
38751                 rotatedY = basic[0];
38752                 break;
38753             default:
38754                 rotatedX = basic[0];
38755                 rotatedY = basic[1];
38756                 break;
38757         }
38758         var w = this._width;
38759         var h = this._height;
38760         var s = Math.max(w, h);
38761         var sfmX = rotatedX * w / s - w / s / 2;
38762         var sfmY = rotatedY * h / s - h / s / 2;
38763         return [sfmX, sfmY];
38764     };
38765     /**
38766      * Convert SfM coordinates to basic coordinates.
38767      *
38768      * @param {Array<number>} sfm - 2D SfM coordinates.
38769      * @returns {Array<number>} 2D basic coordinates.
38770      */
38771     Transform.prototype._sfmToBasic = function (sfm) {
38772         var w = this._width;
38773         var h = this._height;
38774         var s = Math.max(w, h);
38775         var rotatedX = (sfm[0] + w / s / 2) / w * s;
38776         var rotatedY = (sfm[1] + h / s / 2) / h * s;
38777         var basicX;
38778         var basicY;
38779         switch (this._orientation) {
38780             case 1:
38781                 basicX = rotatedX;
38782                 basicY = rotatedY;
38783                 break;
38784             case 3:
38785                 basicX = 1 - rotatedX;
38786                 basicY = 1 - rotatedY;
38787                 break;
38788             case 6:
38789                 basicX = 1 - rotatedY;
38790                 basicY = rotatedX;
38791                 break;
38792             case 8:
38793                 basicX = rotatedY;
38794                 basicY = 1 - rotatedX;
38795                 break;
38796             default:
38797                 basicX = rotatedX;
38798                 basicY = rotatedY;
38799                 break;
38800         }
38801         return [basicX, basicY];
38802     };
38803     /**
38804      * Determines if the gpano information indicates a full panorama.
38805      *
38806      * @returns {boolean} Value determining if the gpano information indicates
38807      * a full panorama.
38808      */
38809     Transform.prototype._fullPano = function () {
38810         return this.gpano != null &&
38811             this.gpano.CroppedAreaLeftPixels === 0 &&
38812             this.gpano.CroppedAreaTopPixels === 0 &&
38813             this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
38814             this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
38815     };
38816     /**
38817      * Checks a value and returns it if it exists and is larger than 0.
38818      * Fallbacks if it is null.
38819      *
38820      * @param {number} value - Value to check.
38821      * @param {number} fallback - Value to fall back to.
38822      * @returns {number} The value or its fallback value if it is not defined or negative.
38823      */
38824     Transform.prototype._getValue = function (value, fallback) {
38825         return value != null && value > 0 ? value : fallback;
38826     };
38827     /**
38828      * Creates the extrinsic camera matrix [ R | t ].
38829      *
38830      * @param {Array<number>} rotation - Rotation vector in angle axis representation.
38831      * @param {Array<number>} translation - Translation vector.
38832      * @returns {THREE.Matrix4} Extrisic camera matrix.
38833      */
38834     Transform.prototype._getRt = function (rotation, translation) {
38835         var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
38836         var angle = axis.length();
38837         if (angle > 0) {
38838             axis.normalize();
38839         }
38840         var rt = new THREE.Matrix4();
38841         rt.makeRotationAxis(axis, angle);
38842         rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
38843         return rt;
38844     };
38845     /**
38846      * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
38847      *
38848      * @param {THREE.Matrix4} rt - Extrisic camera matrix.
38849      * @param {number} scale - Scale factor.
38850      * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
38851      */
38852     Transform.prototype._getSrt = function (rt, scale) {
38853         var srt = rt.clone();
38854         var elements = srt.elements;
38855         elements[12] = scale * elements[12];
38856         elements[13] = scale * elements[13];
38857         elements[14] = scale * elements[14];
38858         srt.scale(new THREE.Vector3(scale, scale, scale));
38859         return srt;
38860     };
38861     Transform.prototype._getBasicRt = function (rt, orientation) {
38862         var axis = new THREE.Vector3(0, 0, 1);
38863         var angle = 0;
38864         switch (orientation) {
38865             case 3:
38866                 angle = Math.PI;
38867                 break;
38868             case 6:
38869                 angle = Math.PI / 2;
38870                 break;
38871             case 8:
38872                 angle = 3 * Math.PI / 2;
38873                 break;
38874             default:
38875                 break;
38876         }
38877         return new THREE.Matrix4()
38878             .makeRotationAxis(axis, angle)
38879             .multiply(rt);
38880     };
38881     Transform.prototype._getRadialPeak = function (k1, k2) {
38882         var a = 5 * k2;
38883         var b = 3 * k1;
38884         var c = 1;
38885         var d = Math.pow(b, 2) - 4 * a * c;
38886         if (d < 0) {
38887             return undefined;
38888         }
38889         var root1 = (-b - Math.sqrt(d)) / 2 / a;
38890         var root2 = (-b + Math.sqrt(d)) / 2 / a;
38891         var minRoot = Math.min(root1, root2);
38892         var maxRoot = Math.max(root1, root2);
38893         return minRoot > 0 ?
38894             Math.sqrt(minRoot) :
38895             maxRoot > 0 ?
38896                 Math.sqrt(maxRoot) :
38897                 undefined;
38898     };
38899     /**
38900      * Calculate a transformation matrix from normalized coordinates for
38901      * texture map coordinates.
38902      *
38903      * @returns {THREE.Matrix4} Normalized coordinates to texture map
38904      * coordinates transformation matrix.
38905      */
38906     Transform.prototype._normalizedToTextureMatrix = function () {
38907         var size = Math.max(this._width, this._height);
38908         var scaleX = this._orientation < 5 ? this._textureScale[0] : this._textureScale[1];
38909         var scaleY = this._orientation < 5 ? this._textureScale[1] : this._textureScale[0];
38910         var w = size / this._width * scaleX;
38911         var h = size / this._height * scaleY;
38912         switch (this._orientation) {
38913             case 1:
38914                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
38915             case 3:
38916                 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
38917             case 6:
38918                 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
38919             case 8:
38920                 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
38921             default:
38922                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
38923         }
38924     };
38925     return Transform;
38926 }());
38927 exports.Transform = Transform;
38928
38929 },{"three":226}],389:[function(require,module,exports){
38930 "use strict";
38931 Object.defineProperty(exports, "__esModule", { value: true });
38932 var THREE = require("three");
38933 /**
38934  * @class ViewportCoords
38935  *
38936  * @classdesc Provides methods for calculating 2D coordinate conversions
38937  * as well as 3D projection and unprojection.
38938  *
38939  * Basic coordinates are 2D coordinates on the [0, 1] interval and
38940  * have the origin point, (0, 0), at the top left corner and the
38941  * maximum value, (1, 1), at the bottom right corner of the original
38942  * image.
38943  *
38944  * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
38945  * have the origin point in the center. The bottom left corner point is
38946  * (-1, -1) and the top right corner point is (1, 1).
38947  *
38948  * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
38949  * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
38950  * corner and the maximum value is (canvasWidth, canvasHeight) is in the
38951  * bottom right corner.
38952  *
38953  * 3D coordinates are in the topocentric world reference frame.
38954  */
38955 var ViewportCoords = /** @class */ (function () {
38956     function ViewportCoords() {
38957         this._unprojectDepth = 200;
38958     }
38959     /**
38960      * Convert basic coordinates to canvas coordinates.
38961      *
38962      * @description Transform origin and camera position needs to be the
38963      * equal for reliable return value.
38964      *
38965      * @param {number} basicX - Basic X coordinate.
38966      * @param {number} basicY - Basic Y coordinate.
38967      * @param {HTMLElement} container - The viewer container.
38968      * @param {Transform} transform - Transform of the node to unproject from.
38969      * @param {THREE.Camera} camera - Camera used in rendering.
38970      * @returns {Array<number>} 2D canvas coordinates.
38971      */
38972     ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
38973         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
38974         var canvas = this.projectToCanvas(point3d, container, camera);
38975         return canvas;
38976     };
38977     /**
38978      * Convert basic coordinates to canvas coordinates safely. If 3D point is
38979      * behind camera null will be returned.
38980      *
38981      * @description Transform origin and camera position needs to be the
38982      * equal for reliable return value.
38983      *
38984      * @param {number} basicX - Basic X coordinate.
38985      * @param {number} basicY - Basic Y coordinate.
38986      * @param {HTMLElement} container - The viewer container.
38987      * @param {Transform} transform - Transform of the node to unproject from.
38988      * @param {THREE.Camera} camera - Camera used in rendering.
38989      * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
38990      * in front of the camera, otherwise null.
38991      */
38992     ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
38993         var viewport = this.basicToViewportSafe(basicX, basicY, transform, camera);
38994         if (viewport === null) {
38995             return null;
38996         }
38997         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
38998         return canvas;
38999     };
39000     /**
39001      * Convert basic coordinates to viewport coordinates.
39002      *
39003      * @description Transform origin and camera position needs to be the
39004      * equal for reliable return value.
39005      *
39006      * @param {number} basicX - Basic X coordinate.
39007      * @param {number} basicY - Basic Y coordinate.
39008      * @param {Transform} transform - Transform of the node to unproject from.
39009      * @param {THREE.Camera} camera - Camera used in rendering.
39010      * @returns {Array<number>} 2D viewport coordinates.
39011      */
39012     ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
39013         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
39014         var viewport = this.projectToViewport(point3d, camera);
39015         return viewport;
39016     };
39017     /**
39018      * Convert basic coordinates to viewport coordinates safely. If 3D point is
39019      * behind camera null will be returned.
39020      *
39021      * @description Transform origin and camera position needs to be the
39022      * equal for reliable return value.
39023      *
39024      * @param {number} basicX - Basic X coordinate.
39025      * @param {number} basicY - Basic Y coordinate.
39026      * @param {Transform} transform - Transform of the node to unproject from.
39027      * @param {THREE.Camera} camera - Camera used in rendering.
39028      * @returns {Array<number>} 2D viewport coordinates.
39029      */
39030     ViewportCoords.prototype.basicToViewportSafe = function (basicX, basicY, transform, camera) {
39031         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
39032         var pointCamera = this.worldToCamera(point3d, camera);
39033         if (pointCamera[2] > 0) {
39034             return null;
39035         }
39036         var viewport = this.projectToViewport(point3d, camera);
39037         return viewport;
39038     };
39039     /**
39040      * Convert camera 3D coordinates to viewport coordinates.
39041      *
39042      * @param {number} pointCamera - 3D point in camera coordinate system.
39043      * @param {THREE.Camera} camera - Camera used in rendering.
39044      * @returns {Array<number>} 2D viewport coordinates.
39045      */
39046     ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
39047         var viewport = new THREE.Vector3().fromArray(pointCamera)
39048             .applyMatrix4(camera.projectionMatrix);
39049         return [viewport.x, viewport.y];
39050     };
39051     /**
39052      * Get canvas pixel position from event.
39053      *
39054      * @param {Event} event - Event containing clientX and clientY properties.
39055      * @param {HTMLElement} element - HTML element.
39056      * @returns {Array<number>} 2D canvas coordinates.
39057      */
39058     ViewportCoords.prototype.canvasPosition = function (event, element) {
39059         var clientRect = element.getBoundingClientRect();
39060         var canvasX = event.clientX - clientRect.left - element.clientLeft;
39061         var canvasY = event.clientY - clientRect.top - element.clientTop;
39062         return [canvasX, canvasY];
39063     };
39064     /**
39065      * Convert canvas coordinates to basic coordinates.
39066      *
39067      * @description Transform origin and camera position needs to be the
39068      * equal for reliable return value.
39069      *
39070      * @param {number} canvasX - Canvas X coordinate.
39071      * @param {number} canvasY - Canvas Y coordinate.
39072      * @param {HTMLElement} container - The viewer container.
39073      * @param {Transform} transform - Transform of the node to unproject from.
39074      * @param {THREE.Camera} camera - Camera used in rendering.
39075      * @returns {Array<number>} 2D basic coordinates.
39076      */
39077     ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
39078         var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
39079             .toArray();
39080         var basic = transform.projectBasic(point3d);
39081         return basic;
39082     };
39083     /**
39084      * Convert canvas coordinates to viewport coordinates.
39085      *
39086      * @param {number} canvasX - Canvas X coordinate.
39087      * @param {number} canvasY - Canvas Y coordinate.
39088      * @param {HTMLElement} container - The viewer container.
39089      * @returns {Array<number>} 2D viewport coordinates.
39090      */
39091     ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
39092         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
39093         var viewportX = 2 * canvasX / canvasWidth - 1;
39094         var viewportY = 1 - 2 * canvasY / canvasHeight;
39095         return [viewportX, viewportY];
39096     };
39097     /**
39098      * Determines the width and height of the container in canvas coordinates.
39099      *
39100      * @param {HTMLElement} container - The viewer container.
39101      * @returns {Array<number>} 2D canvas coordinates.
39102      */
39103     ViewportCoords.prototype.containerToCanvas = function (container) {
39104         return [container.offsetWidth, container.offsetHeight];
39105     };
39106     /**
39107      * Determine basic distances from image to canvas corners.
39108      *
39109      * @description Transform origin and camera position needs to be the
39110      * equal for reliable return value.
39111      *
39112      * Determines the smallest basic distance for every side of the canvas.
39113      *
39114      * @param {Transform} transform - Transform of the node to unproject from.
39115      * @param {THREE.Camera} camera - Camera used in rendering.
39116      * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
39117      */
39118     ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
39119         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
39120         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
39121         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
39122         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
39123         var topBasicDistance = 0;
39124         var rightBasicDistance = 0;
39125         var bottomBasicDistance = 0;
39126         var leftBasicDistance = 0;
39127         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
39128             topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
39129                 -topLeftBasic[1] :
39130                 -topRightBasic[1];
39131         }
39132         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
39133             rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
39134                 topRightBasic[0] - 1 :
39135                 bottomRightBasic[0] - 1;
39136         }
39137         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
39138             bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
39139                 bottomRightBasic[1] - 1 :
39140                 bottomLeftBasic[1] - 1;
39141         }
39142         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
39143             leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
39144                 -bottomLeftBasic[0] :
39145                 -topLeftBasic[0];
39146         }
39147         return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
39148     };
39149     /**
39150      * Determine pixel distances from image to canvas corners.
39151      *
39152      * @description Transform origin and camera position needs to be the
39153      * equal for reliable return value.
39154      *
39155      * Determines the smallest pixel distance for every side of the canvas.
39156      *
39157      * @param {HTMLElement} container - The viewer container.
39158      * @param {Transform} transform - Transform of the node to unproject from.
39159      * @param {THREE.Camera} camera - Camera used in rendering.
39160      * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
39161      */
39162     ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
39163         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
39164         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
39165         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
39166         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
39167         var topPixelDistance = 0;
39168         var rightPixelDistance = 0;
39169         var bottomPixelDistance = 0;
39170         var leftPixelDistance = 0;
39171         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
39172         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
39173             var basicX = topLeftBasic[1] > topRightBasic[1] ?
39174                 topLeftBasic[0] :
39175                 topRightBasic[0];
39176             var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
39177             topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
39178         }
39179         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
39180             var basicY = topRightBasic[0] < bottomRightBasic[0] ?
39181                 topRightBasic[1] :
39182                 bottomRightBasic[1];
39183             var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
39184             rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
39185         }
39186         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
39187             var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
39188                 bottomRightBasic[0] :
39189                 bottomLeftBasic[0];
39190             var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
39191             bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
39192         }
39193         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
39194             var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
39195                 bottomLeftBasic[1] :
39196                 topLeftBasic[1];
39197             var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
39198             leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
39199         }
39200         return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
39201     };
39202     /**
39203      * Determine if an event occured inside an element.
39204      *
39205      * @param {Event} event - Event containing clientX and clientY properties.
39206      * @param {HTMLElement} element - HTML element.
39207      * @returns {boolean} Value indicating if the event occured inside the element or not.
39208      */
39209     ViewportCoords.prototype.insideElement = function (event, element) {
39210         var clientRect = element.getBoundingClientRect();
39211         var minX = clientRect.left + element.clientLeft;
39212         var maxX = minX + element.clientWidth;
39213         var minY = clientRect.top + element.clientTop;
39214         var maxY = minY + element.clientHeight;
39215         return event.clientX > minX &&
39216             event.clientX < maxX &&
39217             event.clientY > minY &&
39218             event.clientY < maxY;
39219     };
39220     /**
39221      * Project 3D world coordinates to canvas coordinates.
39222      *
39223      * @param {Array<number>} point3D - 3D world coordinates.
39224      * @param {HTMLElement} container - The viewer container.
39225      * @param {THREE.Camera} camera - Camera used in rendering.
39226      * @returns {Array<number>} 2D canvas coordinates.
39227      */
39228     ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
39229         var viewport = this.projectToViewport(point3d, camera);
39230         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
39231         return canvas;
39232     };
39233     /**
39234      * Project 3D world coordinates to viewport coordinates.
39235      *
39236      * @param {Array<number>} point3D - 3D world coordinates.
39237      * @param {THREE.Camera} camera - Camera used in rendering.
39238      * @returns {Array<number>} 2D viewport coordinates.
39239      */
39240     ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
39241         var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
39242             .project(camera);
39243         return [viewport.x, viewport.y];
39244     };
39245     /**
39246      * Uproject canvas coordinates to 3D world coordinates.
39247      *
39248      * @param {number} canvasX - Canvas X coordinate.
39249      * @param {number} canvasY - Canvas Y coordinate.
39250      * @param {HTMLElement} container - The viewer container.
39251      * @param {THREE.Camera} camera - Camera used in rendering.
39252      * @returns {Array<number>} 3D world coordinates.
39253      */
39254     ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
39255         var viewport = this.canvasToViewport(canvasX, canvasY, container);
39256         var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
39257         return point3d;
39258     };
39259     /**
39260      * Unproject viewport coordinates to 3D world coordinates.
39261      *
39262      * @param {number} viewportX - Viewport X coordinate.
39263      * @param {number} viewportY - Viewport Y coordinate.
39264      * @param {THREE.Camera} camera - Camera used in rendering.
39265      * @returns {Array<number>} 3D world coordinates.
39266      */
39267     ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
39268         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
39269             .unproject(camera);
39270         return point3d;
39271     };
39272     /**
39273      * Convert viewport coordinates to basic coordinates.
39274      *
39275      * @description Transform origin and camera position needs to be the
39276      * equal for reliable return value.
39277      *
39278      * @param {number} viewportX - Viewport X coordinate.
39279      * @param {number} viewportY - Viewport Y coordinate.
39280      * @param {Transform} transform - Transform of the node to unproject from.
39281      * @param {THREE.Camera} camera - Camera used in rendering.
39282      * @returns {Array<number>} 2D basic coordinates.
39283      */
39284     ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
39285         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
39286             .unproject(camera)
39287             .toArray();
39288         var basic = transform.projectBasic(point3d);
39289         return basic;
39290     };
39291     /**
39292      * Convert viewport coordinates to canvas coordinates.
39293      *
39294      * @param {number} viewportX - Viewport X coordinate.
39295      * @param {number} viewportY - Viewport Y coordinate.
39296      * @param {HTMLElement} container - The viewer container.
39297      * @returns {Array<number>} 2D canvas coordinates.
39298      */
39299     ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
39300         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
39301         var canvasX = canvasWidth * (viewportX + 1) / 2;
39302         var canvasY = -canvasHeight * (viewportY - 1) / 2;
39303         return [canvasX, canvasY];
39304     };
39305     /**
39306      * Convert 3D world coordinates to 3D camera coordinates.
39307      *
39308      * @param {number} point3D - 3D point in world coordinate system.
39309      * @param {THREE.Camera} camera - Camera used in rendering.
39310      * @returns {Array<number>} 3D camera coordinates.
39311      */
39312     ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
39313         var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
39314             .applyMatrix4(camera.matrixWorldInverse);
39315         return pointCamera.toArray();
39316     };
39317     return ViewportCoords;
39318 }());
39319 exports.ViewportCoords = ViewportCoords;
39320 exports.default = ViewportCoords;
39321
39322
39323 },{"three":226}],390:[function(require,module,exports){
39324 "use strict";
39325 Object.defineProperty(exports, "__esModule", { value: true });
39326 /**
39327  * @class Filter
39328  *
39329  * @classdesc Represents a class for creating node filters. Implementation and
39330  * definitions based on https://github.com/mapbox/feature-filter.
39331  */
39332 var FilterCreator = /** @class */ (function () {
39333     function FilterCreator() {
39334     }
39335     /**
39336      * Create a filter from a filter expression.
39337      *
39338      * @description The following filters are supported:
39339      *
39340      * Comparison
39341      * `==`
39342      * `!=`
39343      * `<`
39344      * `<=`
39345      * `>`
39346      * `>=`
39347      *
39348      * Set membership
39349      * `in`
39350      * `!in`
39351      *
39352      * Combining
39353      * `all`
39354      *
39355      * @param {FilterExpression} filter - Comparison, set membership or combinding filter
39356      * expression.
39357      * @returns {FilterFunction} Function taking a node and returning a boolean that
39358      * indicates whether the node passed the test or not.
39359      */
39360     FilterCreator.prototype.createFilter = function (filter) {
39361         return new Function("node", "return " + this._compile(filter) + ";");
39362     };
39363     FilterCreator.prototype._compile = function (filter) {
39364         if (filter == null || filter.length <= 1) {
39365             return "true";
39366         }
39367         var operator = filter[0];
39368         var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
39369             operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
39370                 operator === ">" ||
39371                     operator === ">=" ||
39372                     operator === "<" ||
39373                     operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
39374                     operator === "in" ?
39375                         this._compileInOp(filter[1], filter.slice(2)) :
39376                         operator === "!in" ?
39377                             this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
39378                             operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
39379                                 "true";
39380         return "(" + operation + ")";
39381     };
39382     FilterCreator.prototype._compare = function (a, b) {
39383         return a < b ? -1 : a > b ? 1 : 0;
39384     };
39385     FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
39386         var left = this._compilePropertyReference(property);
39387         var right = JSON.stringify(value);
39388         return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
39389     };
39390     FilterCreator.prototype._compileInOp = function (property, values) {
39391         var compare = this._compare;
39392         var left = JSON.stringify(values.sort(compare));
39393         var right = this._compilePropertyReference(property);
39394         return left + ".indexOf(" + right + ")!==-1";
39395     };
39396     FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
39397         var compile = this._compile.bind(this);
39398         return filters.map(compile).join(operator);
39399     };
39400     FilterCreator.prototype._compileNegation = function (expression) {
39401         return "!(" + expression + ")";
39402     };
39403     FilterCreator.prototype._compilePropertyReference = function (property) {
39404         return "node[" + JSON.stringify(property) + "]";
39405     };
39406     return FilterCreator;
39407 }());
39408 exports.FilterCreator = FilterCreator;
39409 exports.default = FilterCreator;
39410
39411 },{}],391:[function(require,module,exports){
39412 "use strict";
39413 Object.defineProperty(exports, "__esModule", { value: true });
39414 var rxjs_1 = require("rxjs");
39415 var operators_1 = require("rxjs/operators");
39416 var rbush = require("rbush");
39417 var Edge_1 = require("../Edge");
39418 var Error_1 = require("../Error");
39419 var Graph_1 = require("../Graph");
39420 /**
39421  * @class Graph
39422  *
39423  * @classdesc Represents a graph of nodes with edges.
39424  */
39425 var Graph = /** @class */ (function () {
39426     /**
39427      * Create a new graph instance.
39428      *
39429      * @param {APIv3} [apiV3] - API instance for retrieving data.
39430      * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
39431      * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
39432      * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
39433      * @param {FilterCreator} [filterCreator] - Instance for  filter creation.
39434      * @param {IGraphConfiguration} [configuration] - Configuration struct.
39435      */
39436     function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
39437         this._apiV3 = apiV3;
39438         this._cachedNodes = {};
39439         this._cachedNodeTiles = {};
39440         this._cachedSequenceNodes = {};
39441         this._cachedSpatialEdges = {};
39442         this._cachedTiles = {};
39443         this._cachingFill$ = {};
39444         this._cachingFull$ = {};
39445         this._cachingSequenceNodes$ = {};
39446         this._cachingSequences$ = {};
39447         this._cachingSpatialArea$ = {};
39448         this._cachingTiles$ = {};
39449         this._changed$ = new rxjs_1.Subject();
39450         this._defaultAlt = 2;
39451         this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
39452         this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
39453         this._filter = this._filterCreator.createFilter(undefined);
39454         this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
39455         this._configuration = configuration != null ?
39456             configuration :
39457             {
39458                 maxSequences: 50,
39459                 maxUnusedNodes: 100,
39460                 maxUnusedPreStoredNodes: 30,
39461                 maxUnusedTiles: 20,
39462             };
39463         this._nodes = {};
39464         this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
39465         this._nodeIndexTiles = {};
39466         this._nodeToTile = {};
39467         this._preStored = {};
39468         this._requiredNodeTiles = {};
39469         this._requiredSpatialArea = {};
39470         this._sequences = {};
39471         this._tilePrecision = 7;
39472         this._tileThreshold = 20;
39473     }
39474     Object.defineProperty(Graph.prototype, "changed$", {
39475         /**
39476          * Get changed$.
39477          *
39478          * @returns {Observable<Graph>} Observable emitting
39479          * the graph every time it has changed.
39480          */
39481         get: function () {
39482             return this._changed$;
39483         },
39484         enumerable: true,
39485         configurable: true
39486     });
39487     /**
39488      * Caches the full node data for all images within a bounding
39489      * box.
39490      *
39491      * @description The node assets are not cached.
39492      *
39493      * @param {ILatLon} sw - South west corner of bounding box.
39494      * @param {ILatLon} ne - North east corner of bounding box.
39495      * @returns {Observable<Graph>} Observable emitting the full
39496      * nodes in the bounding box.
39497      */
39498     Graph.prototype.cacheBoundingBox$ = function (sw, ne) {
39499         var _this = this;
39500         var cacheTiles$ = this._graphCalculator.encodeHsFromBoundingBox(sw, ne)
39501             .filter(function (h) {
39502             return !(h in _this._cachedTiles);
39503         })
39504             .map(function (h) {
39505             return h in _this._cachingTiles$ ?
39506                 _this._cachingTiles$[h] :
39507                 _this._cacheTile$(h);
39508         });
39509         if (cacheTiles$.length === 0) {
39510             cacheTiles$.push(rxjs_1.of(this));
39511         }
39512         return rxjs_1.from(cacheTiles$).pipe(operators_1.mergeAll(), operators_1.last(), operators_1.mergeMap(function (graph) {
39513             var nodes = _this._nodeIndex
39514                 .search({
39515                 maxX: ne.lat,
39516                 maxY: ne.lon,
39517                 minX: sw.lat,
39518                 minY: sw.lon,
39519             })
39520                 .map(function (item) {
39521                 return item.node;
39522             });
39523             var fullNodes = [];
39524             var coreNodes = [];
39525             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
39526                 var node = nodes_1[_i];
39527                 if (node.full) {
39528                     fullNodes.push(node);
39529                 }
39530                 else {
39531                     coreNodes.push(node.key);
39532                 }
39533             }
39534             var coreNodeBatches = [];
39535             var batchSize = 200;
39536             while (coreNodes.length > 0) {
39537                 coreNodeBatches.push(coreNodes.splice(0, batchSize));
39538             }
39539             var fullNodes$ = rxjs_1.of(fullNodes);
39540             var fillNodes$ = coreNodeBatches
39541                 .map(function (batch) {
39542                 return _this._apiV3.imageByKeyFill$(batch).pipe(operators_1.map(function (imageByKeyFill) {
39543                     var filledNodes = [];
39544                     for (var fillKey in imageByKeyFill) {
39545                         if (!imageByKeyFill.hasOwnProperty(fillKey)) {
39546                             continue;
39547                         }
39548                         if (_this.hasNode(fillKey)) {
39549                             var node = _this.getNode(fillKey);
39550                             if (!node.full) {
39551                                 _this._makeFull(node, imageByKeyFill[fillKey]);
39552                             }
39553                             filledNodes.push(node);
39554                         }
39555                     }
39556                     return filledNodes;
39557                 }));
39558             });
39559             return rxjs_1.merge(fullNodes$, rxjs_1.from(fillNodes$).pipe(operators_1.mergeAll()));
39560         }), operators_1.reduce(function (acc, value) {
39561             return acc.concat(value);
39562         }));
39563     };
39564     /**
39565      * Retrieve and cache node fill properties.
39566      *
39567      * @param {string} key - Key of node to fill.
39568      * @returns {Observable<Graph>} Observable emitting the graph
39569      * when the node has been updated.
39570      * @throws {GraphMapillaryError} When the operation is not valid on the
39571      * current graph.
39572      */
39573     Graph.prototype.cacheFill$ = function (key) {
39574         var _this = this;
39575         if (key in this._cachingFull$) {
39576             throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
39577         }
39578         if (!this.hasNode(key)) {
39579             throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
39580         }
39581         if (key in this._cachingFill$) {
39582             return this._cachingFill$[key];
39583         }
39584         var node = this.getNode(key);
39585         if (node.full) {
39586             throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
39587         }
39588         this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key]).pipe(operators_1.tap(function (imageByKeyFill) {
39589             if (!node.full) {
39590                 _this._makeFull(node, imageByKeyFill[key]);
39591             }
39592             delete _this._cachingFill$[key];
39593         }), operators_1.map(function (imageByKeyFill) {
39594             return _this;
39595         }), operators_1.finalize(function () {
39596             if (key in _this._cachingFill$) {
39597                 delete _this._cachingFill$[key];
39598             }
39599             _this._changed$.next(_this);
39600         }), operators_1.publish(), operators_1.refCount());
39601         return this._cachingFill$[key];
39602     };
39603     /**
39604      * Retrieve and cache full node properties.
39605      *
39606      * @param {string} key - Key of node to fill.
39607      * @returns {Observable<Graph>} Observable emitting the graph
39608      * when the node has been updated.
39609      * @throws {GraphMapillaryError} When the operation is not valid on the
39610      * current graph.
39611      */
39612     Graph.prototype.cacheFull$ = function (key) {
39613         var _this = this;
39614         if (key in this._cachingFull$) {
39615             return this._cachingFull$[key];
39616         }
39617         if (this.hasNode(key)) {
39618             throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
39619         }
39620         this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key]).pipe(operators_1.tap(function (imageByKeyFull) {
39621             var fn = imageByKeyFull[key];
39622             if (_this.hasNode(key)) {
39623                 var node = _this.getNode(key);
39624                 if (!node.full) {
39625                     _this._makeFull(node, fn);
39626                 }
39627             }
39628             else {
39629                 if (fn.sequence_key == null) {
39630                     throw new Error_1.GraphMapillaryError("Node has no sequence key (" + key + ").");
39631                 }
39632                 var node = new Graph_1.Node(fn);
39633                 _this._makeFull(node, fn);
39634                 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
39635                 _this._preStore(h, node);
39636                 _this._setNode(node);
39637                 delete _this._cachingFull$[key];
39638             }
39639         }), operators_1.map(function (imageByKeyFull) {
39640             return _this;
39641         }), operators_1.finalize(function () {
39642             if (key in _this._cachingFull$) {
39643                 delete _this._cachingFull$[key];
39644             }
39645             _this._changed$.next(_this);
39646         }), operators_1.publish(), operators_1.refCount());
39647         return this._cachingFull$[key];
39648     };
39649     /**
39650      * Retrieve and cache a node sequence.
39651      *
39652      * @param {string} key - Key of node for which to retrieve sequence.
39653      * @returns {Observable<Graph>} Observable emitting the graph
39654      * when the sequence has been retrieved.
39655      * @throws {GraphMapillaryError} When the operation is not valid on the
39656      * current graph.
39657      */
39658     Graph.prototype.cacheNodeSequence$ = function (key) {
39659         if (!this.hasNode(key)) {
39660             throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
39661         }
39662         var node = this.getNode(key);
39663         if (node.sequenceKey in this._sequences) {
39664             throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
39665         }
39666         return this._cacheSequence$(node.sequenceKey);
39667     };
39668     /**
39669      * Retrieve and cache a sequence.
39670      *
39671      * @param {string} sequenceKey - Key of sequence to cache.
39672      * @returns {Observable<Graph>} Observable emitting the graph
39673      * when the sequence has been retrieved.
39674      * @throws {GraphMapillaryError} When the operation is not valid on the
39675      * current graph.
39676      */
39677     Graph.prototype.cacheSequence$ = function (sequenceKey) {
39678         if (sequenceKey in this._sequences) {
39679             throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
39680         }
39681         return this._cacheSequence$(sequenceKey);
39682     };
39683     /**
39684      * Cache sequence edges for a node.
39685      *
39686      * @param {string} key - Key of node.
39687      * @throws {GraphMapillaryError} When the operation is not valid on the
39688      * current graph.
39689      */
39690     Graph.prototype.cacheSequenceEdges = function (key) {
39691         var node = this.getNode(key);
39692         if (!(node.sequenceKey in this._sequences)) {
39693             throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
39694         }
39695         var sequence = this._sequences[node.sequenceKey].sequence;
39696         var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
39697         node.cacheSequenceEdges(edges);
39698     };
39699     /**
39700      * Retrieve and cache full nodes for all keys in a sequence.
39701      *
39702      * @param {string} sequenceKey - Key of sequence.
39703      * @param {string} referenceNodeKey - Key of node to use as reference
39704      * for optimized caching.
39705      * @returns {Observable<Graph>} Observable emitting the graph
39706      * when the nodes of the sequence has been cached.
39707      */
39708     Graph.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
39709         var _this = this;
39710         if (!this.hasSequence(sequenceKey)) {
39711             throw new Error_1.GraphMapillaryError("Cannot cache sequence nodes of sequence that does not exist in graph (" + sequenceKey + ").");
39712         }
39713         if (this.hasSequenceNodes(sequenceKey)) {
39714             throw new Error_1.GraphMapillaryError("Sequence nodes already cached (" + sequenceKey + ").");
39715         }
39716         var sequence = this.getSequence(sequenceKey);
39717         if (sequence.key in this._cachingSequenceNodes$) {
39718             return this._cachingSequenceNodes$[sequence.key];
39719         }
39720         var batches = [];
39721         var keys = sequence.keys.slice();
39722         var referenceBatchSize = 50;
39723         if (!!referenceNodeKey && keys.length > referenceBatchSize) {
39724             var referenceIndex = keys.indexOf(referenceNodeKey);
39725             var startIndex = Math.max(0, Math.min(referenceIndex - referenceBatchSize / 2, keys.length - referenceBatchSize));
39726             batches.push(keys.splice(startIndex, referenceBatchSize));
39727         }
39728         var batchSize = 200;
39729         while (keys.length > 0) {
39730             batches.push(keys.splice(0, batchSize));
39731         }
39732         var batchesToCache = batches.length;
39733         var sequenceNodes$ = rxjs_1.from(batches).pipe(operators_1.mergeMap(function (batch) {
39734             return _this._apiV3.imageByKeyFull$(batch).pipe(operators_1.tap(function (imageByKeyFull) {
39735                 for (var fullKey in imageByKeyFull) {
39736                     if (!imageByKeyFull.hasOwnProperty(fullKey)) {
39737                         continue;
39738                     }
39739                     var fn = imageByKeyFull[fullKey];
39740                     if (_this.hasNode(fullKey)) {
39741                         var node = _this.getNode(fn.key);
39742                         if (!node.full) {
39743                             _this._makeFull(node, fn);
39744                         }
39745                     }
39746                     else {
39747                         if (fn.sequence_key == null) {
39748                             console.warn("Sequence missing, discarding node (" + fn.key + ")");
39749                         }
39750                         var node = new Graph_1.Node(fn);
39751                         _this._makeFull(node, fn);
39752                         var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
39753                         _this._preStore(h, node);
39754                         _this._setNode(node);
39755                     }
39756                 }
39757                 batchesToCache--;
39758             }), operators_1.map(function (imageByKeyFull) {
39759                 return _this;
39760             }));
39761         }, 6), operators_1.last(), operators_1.finalize(function () {
39762             delete _this._cachingSequenceNodes$[sequence.key];
39763             if (batchesToCache === 0) {
39764                 _this._cachedSequenceNodes[sequence.key] = true;
39765             }
39766         }), operators_1.publish(), operators_1.refCount());
39767         this._cachingSequenceNodes$[sequence.key] = sequenceNodes$;
39768         return sequenceNodes$;
39769     };
39770     /**
39771      * Retrieve and cache full nodes for a node spatial area.
39772      *
39773      * @param {string} key - Key of node for which to retrieve sequence.
39774      * @returns {Observable<Graph>} Observable emitting the graph
39775      * when the nodes in the spatial area has been made full.
39776      * @throws {GraphMapillaryError} When the operation is not valid on the
39777      * current graph.
39778      */
39779     Graph.prototype.cacheSpatialArea$ = function (key) {
39780         var _this = this;
39781         if (!this.hasNode(key)) {
39782             throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
39783         }
39784         if (key in this._cachedSpatialEdges) {
39785             throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
39786         }
39787         if (!(key in this._requiredSpatialArea)) {
39788             throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
39789         }
39790         var spatialArea = this._requiredSpatialArea[key];
39791         if (Object.keys(spatialArea.cacheNodes).length === 0) {
39792             throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
39793         }
39794         if (key in this._cachingSpatialArea$) {
39795             return this._cachingSpatialArea$[key];
39796         }
39797         var batches = [];
39798         while (spatialArea.cacheKeys.length > 0) {
39799             batches.push(spatialArea.cacheKeys.splice(0, 200));
39800         }
39801         var batchesToCache = batches.length;
39802         var spatialNodes$ = [];
39803         var _loop_1 = function (batch) {
39804             var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch).pipe(operators_1.tap(function (imageByKeyFill) {
39805                 for (var fillKey in imageByKeyFill) {
39806                     if (!imageByKeyFill.hasOwnProperty(fillKey)) {
39807                         continue;
39808                     }
39809                     var spatialNode = spatialArea.cacheNodes[fillKey];
39810                     if (spatialNode.full) {
39811                         delete spatialArea.cacheNodes[fillKey];
39812                         continue;
39813                     }
39814                     var fillNode = imageByKeyFill[fillKey];
39815                     _this._makeFull(spatialNode, fillNode);
39816                     delete spatialArea.cacheNodes[fillKey];
39817                 }
39818                 if (--batchesToCache === 0) {
39819                     delete _this._cachingSpatialArea$[key];
39820                 }
39821             }), operators_1.map(function (imageByKeyFill) {
39822                 return _this;
39823             }), operators_1.catchError(function (error) {
39824                 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
39825                     var batchKey = batch_1[_i];
39826                     if (batchKey in spatialArea.all) {
39827                         delete spatialArea.all[batchKey];
39828                     }
39829                     if (batchKey in spatialArea.cacheNodes) {
39830                         delete spatialArea.cacheNodes[batchKey];
39831                     }
39832                 }
39833                 if (--batchesToCache === 0) {
39834                     delete _this._cachingSpatialArea$[key];
39835                 }
39836                 throw error;
39837             }), operators_1.finalize(function () {
39838                 if (Object.keys(spatialArea.cacheNodes).length === 0) {
39839                     _this._changed$.next(_this);
39840                 }
39841             }), operators_1.publish(), operators_1.refCount());
39842             spatialNodes$.push(spatialNodeBatch$);
39843         };
39844         var this_1 = this;
39845         for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
39846             var batch = batches_1[_i];
39847             _loop_1(batch);
39848         }
39849         this._cachingSpatialArea$[key] = spatialNodes$;
39850         return spatialNodes$;
39851     };
39852     /**
39853      * Cache spatial edges for a node.
39854      *
39855      * @param {string} key - Key of node.
39856      * @throws {GraphMapillaryError} When the operation is not valid on the
39857      * current graph.
39858      */
39859     Graph.prototype.cacheSpatialEdges = function (key) {
39860         if (key in this._cachedSpatialEdges) {
39861             throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
39862         }
39863         var node = this.getNode(key);
39864         var sequence = this._sequences[node.sequenceKey].sequence;
39865         var fallbackKeys = [];
39866         var prevKey = sequence.findPrevKey(node.key);
39867         if (prevKey != null) {
39868             fallbackKeys.push(prevKey);
39869         }
39870         var nextKey = sequence.findNextKey(node.key);
39871         if (nextKey != null) {
39872             fallbackKeys.push(nextKey);
39873         }
39874         var allSpatialNodes = this._requiredSpatialArea[key].all;
39875         var potentialNodes = [];
39876         var filter = this._filter;
39877         for (var spatialNodeKey in allSpatialNodes) {
39878             if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
39879                 continue;
39880             }
39881             var spatialNode = allSpatialNodes[spatialNodeKey];
39882             if (filter(spatialNode)) {
39883                 potentialNodes.push(spatialNode);
39884             }
39885         }
39886         var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
39887         var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
39888         edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
39889         edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
39890         edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
39891         edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
39892         node.cacheSpatialEdges(edges);
39893         this._cachedSpatialEdges[key] = node;
39894         delete this._requiredSpatialArea[key];
39895         delete this._cachedNodeTiles[key];
39896     };
39897     /**
39898      * Retrieve and cache geohash tiles for a node.
39899      *
39900      * @param {string} key - Key of node for which to retrieve tiles.
39901      * @returns {Array<Observable<Graph>>} Array of observables emitting
39902      * the graph for each tile required for the node has been cached.
39903      * @throws {GraphMapillaryError} When the operation is not valid on the
39904      * current graph.
39905      */
39906     Graph.prototype.cacheTiles$ = function (key) {
39907         var _this = this;
39908         if (key in this._cachedNodeTiles) {
39909             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
39910         }
39911         if (key in this._cachedSpatialEdges) {
39912             throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
39913         }
39914         if (!(key in this._requiredNodeTiles)) {
39915             throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
39916         }
39917         var nodeTiles = this._requiredNodeTiles[key];
39918         if (nodeTiles.cache.length === 0 &&
39919             nodeTiles.caching.length === 0) {
39920             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
39921         }
39922         if (!this.hasNode(key)) {
39923             throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
39924         }
39925         var hs = nodeTiles.cache.slice();
39926         nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
39927         nodeTiles.cache = [];
39928         var cacheTiles$ = [];
39929         var _loop_2 = function (h) {
39930             var cacheTile$ = h in this_2._cachingTiles$ ?
39931                 this_2._cachingTiles$[h] :
39932                 this_2._cacheTile$(h);
39933             cacheTiles$.push(cacheTile$.pipe(operators_1.tap(function (graph) {
39934                 var index = nodeTiles.caching.indexOf(h);
39935                 if (index > -1) {
39936                     nodeTiles.caching.splice(index, 1);
39937                 }
39938                 if (nodeTiles.caching.length === 0 &&
39939                     nodeTiles.cache.length === 0) {
39940                     delete _this._requiredNodeTiles[key];
39941                     _this._cachedNodeTiles[key] = true;
39942                 }
39943             }), operators_1.catchError(function (error) {
39944                 var index = nodeTiles.caching.indexOf(h);
39945                 if (index > -1) {
39946                     nodeTiles.caching.splice(index, 1);
39947                 }
39948                 if (nodeTiles.caching.length === 0 &&
39949                     nodeTiles.cache.length === 0) {
39950                     delete _this._requiredNodeTiles[key];
39951                     _this._cachedNodeTiles[key] = true;
39952                 }
39953                 throw error;
39954             }), operators_1.finalize(function () {
39955                 _this._changed$.next(_this);
39956             }), operators_1.publish(), operators_1.refCount()));
39957         };
39958         var this_2 = this;
39959         for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
39960             var h = _a[_i];
39961             _loop_2(h);
39962         }
39963         return cacheTiles$;
39964     };
39965     /**
39966      * Initialize the cache for a node.
39967      *
39968      * @param {string} key - Key of node.
39969      * @throws {GraphMapillaryError} When the operation is not valid on the
39970      * current graph.
39971      */
39972     Graph.prototype.initializeCache = function (key) {
39973         if (key in this._cachedNodes) {
39974             throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
39975         }
39976         var node = this.getNode(key);
39977         node.initializeCache(new Graph_1.NodeCache());
39978         var accessed = new Date().getTime();
39979         this._cachedNodes[key] = { accessed: accessed, node: node };
39980         this._updateCachedTileAccess(key, accessed);
39981     };
39982     /**
39983      * Get a value indicating if the graph is fill caching a node.
39984      *
39985      * @param {string} key - Key of node.
39986      * @returns {boolean} Value indicating if the node is being fill cached.
39987      */
39988     Graph.prototype.isCachingFill = function (key) {
39989         return key in this._cachingFill$;
39990     };
39991     /**
39992      * Get a value indicating if the graph is fully caching a node.
39993      *
39994      * @param {string} key - Key of node.
39995      * @returns {boolean} Value indicating if the node is being fully cached.
39996      */
39997     Graph.prototype.isCachingFull = function (key) {
39998         return key in this._cachingFull$;
39999     };
40000     /**
40001      * Get a value indicating if the graph is caching a sequence of a node.
40002      *
40003      * @param {string} key - Key of node.
40004      * @returns {boolean} Value indicating if the sequence of a node is
40005      * being cached.
40006      */
40007     Graph.prototype.isCachingNodeSequence = function (key) {
40008         var node = this.getNode(key);
40009         return node.sequenceKey in this._cachingSequences$;
40010     };
40011     /**
40012      * Get a value indicating if the graph is caching a sequence.
40013      *
40014      * @param {string} sequenceKey - Key of sequence.
40015      * @returns {boolean} Value indicating if the sequence is
40016      * being cached.
40017      */
40018     Graph.prototype.isCachingSequence = function (sequenceKey) {
40019         return sequenceKey in this._cachingSequences$;
40020     };
40021     /**
40022      * Get a value indicating if the graph is caching sequence nodes.
40023      *
40024      * @param {string} sequenceKey - Key of sequence.
40025      * @returns {boolean} Value indicating if the sequence nodes are
40026      * being cached.
40027      */
40028     Graph.prototype.isCachingSequenceNodes = function (sequenceKey) {
40029         return sequenceKey in this._cachingSequenceNodes$;
40030     };
40031     /**
40032      * Get a value indicating if the graph is caching the tiles
40033      * required for calculating spatial edges of a node.
40034      *
40035      * @param {string} key - Key of node.
40036      * @returns {boolean} Value indicating if the tiles of
40037      * a node are being cached.
40038      */
40039     Graph.prototype.isCachingTiles = function (key) {
40040         return key in this._requiredNodeTiles &&
40041             this._requiredNodeTiles[key].cache.length === 0 &&
40042             this._requiredNodeTiles[key].caching.length > 0;
40043     };
40044     /**
40045      * Get a value indicating if the cache has been initialized
40046      * for a node.
40047      *
40048      * @param {string} key - Key of node.
40049      * @returns {boolean} Value indicating if the cache has been
40050      * initialized for a node.
40051      */
40052     Graph.prototype.hasInitializedCache = function (key) {
40053         return key in this._cachedNodes;
40054     };
40055     /**
40056      * Get a value indicating if a node exist in the graph.
40057      *
40058      * @param {string} key - Key of node.
40059      * @returns {boolean} Value indicating if a node exist in the graph.
40060      */
40061     Graph.prototype.hasNode = function (key) {
40062         var accessed = new Date().getTime();
40063         this._updateCachedNodeAccess(key, accessed);
40064         this._updateCachedTileAccess(key, accessed);
40065         return key in this._nodes;
40066     };
40067     /**
40068      * Get a value indicating if a node sequence exist in the graph.
40069      *
40070      * @param {string} key - Key of node.
40071      * @returns {boolean} Value indicating if a node sequence exist
40072      * in the graph.
40073      */
40074     Graph.prototype.hasNodeSequence = function (key) {
40075         var node = this.getNode(key);
40076         var sequenceKey = node.sequenceKey;
40077         var hasNodeSequence = sequenceKey in this._sequences;
40078         if (hasNodeSequence) {
40079             this._sequences[sequenceKey].accessed = new Date().getTime();
40080         }
40081         return hasNodeSequence;
40082     };
40083     /**
40084      * Get a value indicating if a sequence exist in the graph.
40085      *
40086      * @param {string} sequenceKey - Key of sequence.
40087      * @returns {boolean} Value indicating if a sequence exist
40088      * in the graph.
40089      */
40090     Graph.prototype.hasSequence = function (sequenceKey) {
40091         var hasSequence = sequenceKey in this._sequences;
40092         if (hasSequence) {
40093             this._sequences[sequenceKey].accessed = new Date().getTime();
40094         }
40095         return hasSequence;
40096     };
40097     /**
40098      * Get a value indicating if sequence nodes has been cached in the graph.
40099      *
40100      * @param {string} sequenceKey - Key of sequence.
40101      * @returns {boolean} Value indicating if a sequence nodes has been
40102      * cached in the graph.
40103      */
40104     Graph.prototype.hasSequenceNodes = function (sequenceKey) {
40105         return sequenceKey in this._cachedSequenceNodes;
40106     };
40107     /**
40108      * Get a value indicating if the graph has fully cached
40109      * all nodes in the spatial area of a node.
40110      *
40111      * @param {string} key - Key of node.
40112      * @returns {boolean} Value indicating if the spatial area
40113      * of a node has been cached.
40114      */
40115     Graph.prototype.hasSpatialArea = function (key) {
40116         if (!this.hasNode(key)) {
40117             throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
40118         }
40119         if (key in this._cachedSpatialEdges) {
40120             return true;
40121         }
40122         if (key in this._requiredSpatialArea) {
40123             return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
40124         }
40125         var node = this.getNode(key);
40126         var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
40127         var spatialItems = this._nodeIndex.search({
40128             maxX: bbox[1].lat,
40129             maxY: bbox[1].lon,
40130             minX: bbox[0].lat,
40131             minY: bbox[0].lon,
40132         });
40133         var spatialNodes = {
40134             all: {},
40135             cacheKeys: [],
40136             cacheNodes: {},
40137         };
40138         for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
40139             var spatialItem = spatialItems_1[_i];
40140             spatialNodes.all[spatialItem.node.key] = spatialItem.node;
40141             if (!spatialItem.node.full) {
40142                 spatialNodes.cacheKeys.push(spatialItem.node.key);
40143                 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
40144             }
40145         }
40146         this._requiredSpatialArea[key] = spatialNodes;
40147         return spatialNodes.cacheKeys.length === 0;
40148     };
40149     /**
40150      * Get a value indicating if the graph has a tiles required
40151      * for a node.
40152      *
40153      * @param {string} key - Key of node.
40154      * @returns {boolean} Value indicating if the the tiles required
40155      * by a node has been cached.
40156      */
40157     Graph.prototype.hasTiles = function (key) {
40158         var _this = this;
40159         if (key in this._cachedNodeTiles) {
40160             return true;
40161         }
40162         if (key in this._cachedSpatialEdges) {
40163             return true;
40164         }
40165         if (!this.hasNode(key)) {
40166             throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
40167         }
40168         var nodeTiles = { cache: [], caching: [] };
40169         if (!(key in this._requiredNodeTiles)) {
40170             var node = this.getNode(key);
40171             nodeTiles.cache = this._graphCalculator
40172                 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
40173                 .filter(function (h) {
40174                 return !(h in _this._cachedTiles);
40175             });
40176             if (nodeTiles.cache.length > 0) {
40177                 this._requiredNodeTiles[key] = nodeTiles;
40178             }
40179         }
40180         else {
40181             nodeTiles = this._requiredNodeTiles[key];
40182         }
40183         return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
40184     };
40185     /**
40186      * Get a node.
40187      *
40188      * @param {string} key - Key of node.
40189      * @returns {Node} Retrieved node.
40190      */
40191     Graph.prototype.getNode = function (key) {
40192         var accessed = new Date().getTime();
40193         this._updateCachedNodeAccess(key, accessed);
40194         this._updateCachedTileAccess(key, accessed);
40195         return this._nodes[key];
40196     };
40197     /**
40198      * Get a sequence.
40199      *
40200      * @param {string} sequenceKey - Key of sequence.
40201      * @returns {Node} Retrieved sequence.
40202      */
40203     Graph.prototype.getSequence = function (sequenceKey) {
40204         var sequenceAccess = this._sequences[sequenceKey];
40205         sequenceAccess.accessed = new Date().getTime();
40206         return sequenceAccess.sequence;
40207     };
40208     /**
40209      * Reset all spatial edges of the graph nodes.
40210      */
40211     Graph.prototype.resetSpatialEdges = function () {
40212         var cachedKeys = Object.keys(this._cachedSpatialEdges);
40213         for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
40214             var cachedKey = cachedKeys_1[_i];
40215             var node = this._cachedSpatialEdges[cachedKey];
40216             node.resetSpatialEdges();
40217             delete this._cachedSpatialEdges[cachedKey];
40218         }
40219     };
40220     /**
40221      * Reset the complete graph but keep the nodes corresponding
40222      * to the supplied keys. All other nodes will be disposed.
40223      *
40224      * @param {Array<string>} keepKeys - Keys for nodes to keep
40225      * in graph after reset.
40226      */
40227     Graph.prototype.reset = function (keepKeys) {
40228         var nodes = [];
40229         for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
40230             var key = keepKeys_1[_i];
40231             if (!this.hasNode(key)) {
40232                 throw new Error("Node does not exist " + key);
40233             }
40234             var node = this.getNode(key);
40235             node.resetSequenceEdges();
40236             node.resetSpatialEdges();
40237             nodes.push(node);
40238         }
40239         for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
40240             var cachedKey = _b[_a];
40241             if (keepKeys.indexOf(cachedKey) !== -1) {
40242                 continue;
40243             }
40244             this._cachedNodes[cachedKey].node.dispose();
40245             delete this._cachedNodes[cachedKey];
40246         }
40247         this._cachedNodeTiles = {};
40248         this._cachedSpatialEdges = {};
40249         this._cachedTiles = {};
40250         this._cachingFill$ = {};
40251         this._cachingFull$ = {};
40252         this._cachingSequences$ = {};
40253         this._cachingSpatialArea$ = {};
40254         this._cachingTiles$ = {};
40255         this._nodes = {};
40256         this._nodeToTile = {};
40257         this._preStored = {};
40258         for (var _c = 0, nodes_2 = nodes; _c < nodes_2.length; _c++) {
40259             var node = nodes_2[_c];
40260             this._nodes[node.key] = node;
40261             var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
40262             this._preStore(h, node);
40263         }
40264         this._requiredNodeTiles = {};
40265         this._requiredSpatialArea = {};
40266         this._sequences = {};
40267         this._nodeIndexTiles = {};
40268         this._nodeIndex.clear();
40269     };
40270     /**
40271      * Set the spatial node filter.
40272      *
40273      * @param {FilterExpression} filter - Filter expression to be applied
40274      * when calculating spatial edges.
40275      */
40276     Graph.prototype.setFilter = function (filter) {
40277         this._filter = this._filterCreator.createFilter(filter);
40278     };
40279     /**
40280      * Uncache the graph according to the graph configuration.
40281      *
40282      * @description Uncaches unused tiles, unused nodes and
40283      * sequences according to the numbers specified in the
40284      * graph configuration. Sequences does not have a direct
40285      * reference to either tiles or nodes and may be uncached
40286      * even if they are related to the nodes that should be kept.
40287      *
40288      * @param {Array<string>} keepKeys - Keys of nodes to keep in
40289      * graph unrelated to last access. Tiles related to those keys
40290      * will also be kept in graph.
40291      * @param {string} keepSequenceKey - Optional key of sequence
40292      * for which the belonging nodes should not be disposed or
40293      * removed from the graph. These nodes may still be uncached if
40294      * not specified in keep keys param.
40295      */
40296     Graph.prototype.uncache = function (keepKeys, keepSequenceKey) {
40297         var keysInUse = {};
40298         this._addNewKeys(keysInUse, this._cachingFull$);
40299         this._addNewKeys(keysInUse, this._cachingFill$);
40300         this._addNewKeys(keysInUse, this._cachingSpatialArea$);
40301         this._addNewKeys(keysInUse, this._requiredNodeTiles);
40302         this._addNewKeys(keysInUse, this._requiredSpatialArea);
40303         for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
40304             var key = keepKeys_2[_i];
40305             if (key in keysInUse) {
40306                 continue;
40307             }
40308             keysInUse[key] = true;
40309         }
40310         var keepHs = {};
40311         for (var key in keysInUse) {
40312             if (!keysInUse.hasOwnProperty(key)) {
40313                 continue;
40314             }
40315             var node = this._nodes[key];
40316             var nodeHs = this._graphCalculator.encodeHs(node.latLon);
40317             for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
40318                 var nodeH = nodeHs_1[_a];
40319                 if (!(nodeH in keepHs)) {
40320                     keepHs[nodeH] = true;
40321                 }
40322             }
40323         }
40324         var potentialHs = [];
40325         for (var h in this._cachedTiles) {
40326             if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
40327                 continue;
40328             }
40329             potentialHs.push([h, this._cachedTiles[h]]);
40330         }
40331         var uncacheHs = potentialHs
40332             .sort(function (h1, h2) {
40333             return h2[1].accessed - h1[1].accessed;
40334         })
40335             .slice(this._configuration.maxUnusedTiles)
40336             .map(function (h) {
40337             return h[0];
40338         });
40339         for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
40340             var uncacheH = uncacheHs_1[_b];
40341             this._uncacheTile(uncacheH, keepSequenceKey);
40342         }
40343         var potentialPreStored = [];
40344         var nonCachedPreStored = [];
40345         for (var h in this._preStored) {
40346             if (!this._preStored.hasOwnProperty(h) || h in this._cachingTiles$) {
40347                 continue;
40348             }
40349             var prestoredNodes = this._preStored[h];
40350             for (var key in prestoredNodes) {
40351                 if (!prestoredNodes.hasOwnProperty(key) || key in keysInUse) {
40352                     continue;
40353                 }
40354                 if (prestoredNodes[key].sequenceKey === keepSequenceKey) {
40355                     continue;
40356                 }
40357                 if (key in this._cachedNodes) {
40358                     potentialPreStored.push([this._cachedNodes[key], h]);
40359                 }
40360                 else {
40361                     nonCachedPreStored.push([key, h]);
40362                 }
40363             }
40364         }
40365         var uncachePreStored = potentialPreStored
40366             .sort(function (_a, _b) {
40367             var na1 = _a[0], h1 = _a[1];
40368             var na2 = _b[0], h2 = _b[1];
40369             return na2.accessed - na1.accessed;
40370         })
40371             .slice(this._configuration.maxUnusedPreStoredNodes)
40372             .map(function (_a) {
40373             var na = _a[0], h = _a[1];
40374             return [na.node.key, h];
40375         });
40376         this._uncachePreStored(nonCachedPreStored);
40377         this._uncachePreStored(uncachePreStored);
40378         var potentialNodes = [];
40379         for (var key in this._cachedNodes) {
40380             if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
40381                 continue;
40382             }
40383             potentialNodes.push(this._cachedNodes[key]);
40384         }
40385         var uncacheNodes = potentialNodes
40386             .sort(function (n1, n2) {
40387             return n2.accessed - n1.accessed;
40388         })
40389             .slice(this._configuration.maxUnusedNodes);
40390         for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
40391             var nodeAccess = uncacheNodes_1[_c];
40392             nodeAccess.node.uncache();
40393             var key = nodeAccess.node.key;
40394             delete this._cachedNodes[key];
40395             if (key in this._cachedNodeTiles) {
40396                 delete this._cachedNodeTiles[key];
40397             }
40398             if (key in this._cachedSpatialEdges) {
40399                 delete this._cachedSpatialEdges[key];
40400             }
40401         }
40402         var potentialSequences = [];
40403         for (var sequenceKey in this._sequences) {
40404             if (!this._sequences.hasOwnProperty(sequenceKey) ||
40405                 sequenceKey in this._cachingSequences$ ||
40406                 sequenceKey === keepSequenceKey) {
40407                 continue;
40408             }
40409             potentialSequences.push(this._sequences[sequenceKey]);
40410         }
40411         var uncacheSequences = potentialSequences
40412             .sort(function (s1, s2) {
40413             return s2.accessed - s1.accessed;
40414         })
40415             .slice(this._configuration.maxSequences);
40416         for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
40417             var sequenceAccess = uncacheSequences_1[_d];
40418             var sequenceKey = sequenceAccess.sequence.key;
40419             delete this._sequences[sequenceKey];
40420             if (sequenceKey in this._cachedSequenceNodes) {
40421                 delete this._cachedSequenceNodes[sequenceKey];
40422             }
40423             sequenceAccess.sequence.dispose();
40424         }
40425     };
40426     Graph.prototype._addNewKeys = function (keys, dict) {
40427         for (var key in dict) {
40428             if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
40429                 continue;
40430             }
40431             if (!(key in keys)) {
40432                 keys[key] = true;
40433             }
40434         }
40435     };
40436     Graph.prototype._cacheSequence$ = function (sequenceKey) {
40437         var _this = this;
40438         if (sequenceKey in this._cachingSequences$) {
40439             return this._cachingSequences$[sequenceKey];
40440         }
40441         this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey]).pipe(operators_1.tap(function (sequenceByKey) {
40442             if (!(sequenceKey in _this._sequences)) {
40443                 _this._sequences[sequenceKey] = {
40444                     accessed: new Date().getTime(),
40445                     sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
40446                 };
40447             }
40448             delete _this._cachingSequences$[sequenceKey];
40449         }), operators_1.map(function (sequenceByKey) {
40450             return _this;
40451         }), operators_1.finalize(function () {
40452             if (sequenceKey in _this._cachingSequences$) {
40453                 delete _this._cachingSequences$[sequenceKey];
40454             }
40455             _this._changed$.next(_this);
40456         }), operators_1.publish(), operators_1.refCount());
40457         return this._cachingSequences$[sequenceKey];
40458     };
40459     Graph.prototype._cacheTile$ = function (h) {
40460         var _this = this;
40461         this._cachingTiles$[h] = this._apiV3.imagesByH$([h]).pipe(operators_1.tap(function (imagesByH) {
40462             var coreNodes = imagesByH[h];
40463             if (h in _this._cachedTiles) {
40464                 return;
40465             }
40466             _this._nodeIndexTiles[h] = [];
40467             _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
40468             var hCache = _this._cachedTiles[h].nodes;
40469             var preStored = _this._removeFromPreStore(h);
40470             for (var index in coreNodes) {
40471                 if (!coreNodes.hasOwnProperty(index)) {
40472                     continue;
40473                 }
40474                 var coreNode = coreNodes[index];
40475                 if (coreNode == null) {
40476                     break;
40477                 }
40478                 if (coreNode.sequence_key == null) {
40479                     console.warn("Sequence missing, discarding node (" + coreNode.key + ")");
40480                     continue;
40481                 }
40482                 if (preStored != null && coreNode.key in preStored) {
40483                     var preStoredNode = preStored[coreNode.key];
40484                     delete preStored[coreNode.key];
40485                     hCache.push(preStoredNode);
40486                     var preStoredNodeIndexItem = {
40487                         lat: preStoredNode.latLon.lat,
40488                         lon: preStoredNode.latLon.lon,
40489                         node: preStoredNode,
40490                     };
40491                     _this._nodeIndex.insert(preStoredNodeIndexItem);
40492                     _this._nodeIndexTiles[h].push(preStoredNodeIndexItem);
40493                     _this._nodeToTile[preStoredNode.key] = h;
40494                     continue;
40495                 }
40496                 var node = new Graph_1.Node(coreNode);
40497                 hCache.push(node);
40498                 var nodeIndexItem = {
40499                     lat: node.latLon.lat,
40500                     lon: node.latLon.lon,
40501                     node: node,
40502                 };
40503                 _this._nodeIndex.insert(nodeIndexItem);
40504                 _this._nodeIndexTiles[h].push(nodeIndexItem);
40505                 _this._nodeToTile[node.key] = h;
40506                 _this._setNode(node);
40507             }
40508             delete _this._cachingTiles$[h];
40509         }), operators_1.map(function (imagesByH) {
40510             return _this;
40511         }), operators_1.catchError(function (error) {
40512             delete _this._cachingTiles$[h];
40513             throw error;
40514         }), operators_1.publish(), operators_1.refCount());
40515         return this._cachingTiles$[h];
40516     };
40517     Graph.prototype._makeFull = function (node, fillNode) {
40518         if (fillNode.calt == null) {
40519             fillNode.calt = this._defaultAlt;
40520         }
40521         if (fillNode.c_rotation == null) {
40522             fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
40523         }
40524         node.makeFull(fillNode);
40525     };
40526     Graph.prototype._preStore = function (h, node) {
40527         if (!(h in this._preStored)) {
40528             this._preStored[h] = {};
40529         }
40530         this._preStored[h][node.key] = node;
40531     };
40532     Graph.prototype._removeFromPreStore = function (h) {
40533         var preStored = null;
40534         if (h in this._preStored) {
40535             preStored = this._preStored[h];
40536             delete this._preStored[h];
40537         }
40538         return preStored;
40539     };
40540     Graph.prototype._setNode = function (node) {
40541         var key = node.key;
40542         if (this.hasNode(key)) {
40543             throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
40544         }
40545         this._nodes[key] = node;
40546     };
40547     Graph.prototype._uncacheTile = function (h, keepSequenceKey) {
40548         for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
40549             var node = _a[_i];
40550             var key = node.key;
40551             delete this._nodeToTile[key];
40552             if (key in this._cachedNodes) {
40553                 delete this._cachedNodes[key];
40554             }
40555             if (key in this._cachedNodeTiles) {
40556                 delete this._cachedNodeTiles[key];
40557             }
40558             if (key in this._cachedSpatialEdges) {
40559                 delete this._cachedSpatialEdges[key];
40560             }
40561             if (node.sequenceKey === keepSequenceKey) {
40562                 this._preStore(h, node);
40563                 node.uncache();
40564             }
40565             else {
40566                 delete this._nodes[key];
40567                 if (node.sequenceKey in this._cachedSequenceNodes) {
40568                     delete this._cachedSequenceNodes[node.sequenceKey];
40569                 }
40570                 node.dispose();
40571             }
40572         }
40573         for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
40574             var nodeIndexItem = _c[_b];
40575             this._nodeIndex.remove(nodeIndexItem);
40576         }
40577         delete this._nodeIndexTiles[h];
40578         delete this._cachedTiles[h];
40579     };
40580     Graph.prototype._uncachePreStored = function (preStored) {
40581         var hs = {};
40582         for (var _i = 0, preStored_1 = preStored; _i < preStored_1.length; _i++) {
40583             var _a = preStored_1[_i], key = _a[0], h = _a[1];
40584             if (key in this._nodes) {
40585                 delete this._nodes[key];
40586             }
40587             if (key in this._cachedNodes) {
40588                 delete this._cachedNodes[key];
40589             }
40590             var node = this._preStored[h][key];
40591             if (node.sequenceKey in this._cachedSequenceNodes) {
40592                 delete this._cachedSequenceNodes[node.sequenceKey];
40593             }
40594             delete this._preStored[h][key];
40595             node.dispose();
40596             hs[h] = true;
40597         }
40598         for (var h in hs) {
40599             if (!hs.hasOwnProperty(h)) {
40600                 continue;
40601             }
40602             if (Object.keys(this._preStored[h]).length === 0) {
40603                 delete this._preStored[h];
40604             }
40605         }
40606     };
40607     Graph.prototype._updateCachedTileAccess = function (key, accessed) {
40608         if (key in this._nodeToTile) {
40609             this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
40610         }
40611     };
40612     Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
40613         if (key in this._cachedNodes) {
40614             this._cachedNodes[key].accessed = accessed;
40615         }
40616     };
40617     return Graph;
40618 }());
40619 exports.Graph = Graph;
40620 exports.default = Graph;
40621
40622 },{"../Edge":276,"../Error":277,"../Graph":279,"rbush":26,"rxjs":27,"rxjs/operators":225}],392:[function(require,module,exports){
40623 "use strict";
40624 Object.defineProperty(exports, "__esModule", { value: true });
40625 var geohash = require("latlon-geohash");
40626 var THREE = require("three");
40627 var Error_1 = require("../Error");
40628 var Geo_1 = require("../Geo");
40629 /**
40630  * @class GraphCalculator
40631  *
40632  * @classdesc Represents a calculator for graph entities.
40633  */
40634 var GraphCalculator = /** @class */ (function () {
40635     /**
40636      * Create a new graph calculator instance.
40637      *
40638      * @param {GeoCoords} geoCoords - Geo coords instance.
40639      */
40640     function GraphCalculator(geoCoords) {
40641         this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
40642     }
40643     /**
40644      * Encode the geohash tile for geodetic coordinates.
40645      *
40646      * @param {ILatLon} latlon - Latitude and longitude to encode.
40647      * @param {number} precision - Precision of the encoding.
40648      *
40649      * @returns {string} The geohash tile for the lat, lon and precision.
40650      */
40651     GraphCalculator.prototype.encodeH = function (latLon, precision) {
40652         if (precision === void 0) { precision = 7; }
40653         return geohash.encode(latLon.lat, latLon.lon, precision);
40654     };
40655     /**
40656      * Encode the geohash tiles within a threshold from a position
40657      * using Manhattan distance.
40658      *
40659      * @param {ILatLon} latlon - Latitude and longitude to encode.
40660      * @param {number} precision - Precision of the encoding.
40661      * @param {number} threshold - Threshold of the encoding in meters.
40662      *
40663      * @returns {string} The geohash tiles reachable within the threshold.
40664      */
40665     GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
40666         if (precision === void 0) { precision = 7; }
40667         if (threshold === void 0) { threshold = 20; }
40668         var h = geohash.encode(latLon.lat, latLon.lon, precision);
40669         var bounds = geohash.bounds(h);
40670         var ne = bounds.ne;
40671         var sw = bounds.sw;
40672         var neighbours = geohash.neighbours(h);
40673         var bl = [0, 0, 0];
40674         var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
40675         var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
40676         var left = position[0] - bl[0];
40677         var right = tr[0] - position[0];
40678         var bottom = position[1] - bl[1];
40679         var top = tr[1] - position[1];
40680         var l = left < threshold;
40681         var r = right < threshold;
40682         var b = bottom < threshold;
40683         var t = top < threshold;
40684         var hs = [h];
40685         if (t) {
40686             hs.push(neighbours.n);
40687         }
40688         if (t && l) {
40689             hs.push(neighbours.nw);
40690         }
40691         if (l) {
40692             hs.push(neighbours.w);
40693         }
40694         if (l && b) {
40695             hs.push(neighbours.sw);
40696         }
40697         if (b) {
40698             hs.push(neighbours.s);
40699         }
40700         if (b && r) {
40701             hs.push(neighbours.se);
40702         }
40703         if (r) {
40704             hs.push(neighbours.e);
40705         }
40706         if (r && t) {
40707             hs.push(neighbours.ne);
40708         }
40709         return hs;
40710     };
40711     /**
40712      * Encode the minimum set of geohash tiles containing a bounding box.
40713      *
40714      * @description The current algorithm does expect the bounding box
40715      * to be sufficiently small to be contained in an area with the size
40716      * of maximally four tiles. Up to nine adjacent tiles may be returned.
40717      * The method currently uses the largest side as the threshold leading to
40718      * more tiles being returned than needed in edge cases.
40719      *
40720      * @param {ILatLon} sw - South west corner of bounding box.
40721      * @param {ILatLon} ne - North east corner of bounding box.
40722      * @param {number} precision - Precision of the encoding.
40723      *
40724      * @returns {string} The geohash tiles containing the bounding box.
40725      */
40726     GraphCalculator.prototype.encodeHsFromBoundingBox = function (sw, ne, precision) {
40727         if (precision === void 0) { precision = 7; }
40728         if (ne.lat <= sw.lat || ne.lon <= sw.lon) {
40729             throw new Error_1.GraphMapillaryError("North east needs to be top right of south west");
40730         }
40731         var centerLat = (sw.lat + ne.lat) / 2;
40732         var centerLon = (sw.lon + ne.lon) / 2;
40733         var enu = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, centerLat, centerLon, 0);
40734         var threshold = Math.max(enu[0], enu[1]);
40735         return this.encodeHs({ lat: centerLat, lon: centerLon }, precision, threshold);
40736     };
40737     /**
40738      * Get the bounding box corners for a circle with radius of a threshold
40739      * with center in a geodetic position.
40740      *
40741      * @param {ILatLon} latlon - Latitude and longitude to encode.
40742      * @param {number} threshold - Threshold distance from the position in meters.
40743      *
40744      * @returns {Array<ILatLon>} The south west and north east corners of the
40745      * bounding box.
40746      */
40747     GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
40748         var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
40749         var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
40750         return [
40751             { lat: bl[0], lon: bl[1] },
40752             { lat: tr[0], lon: tr[1] },
40753         ];
40754     };
40755     /**
40756      * Convert a compass angle to an angle axis rotation vector.
40757      *
40758      * @param {number} compassAngle - The compass angle in degrees.
40759      * @param {number} orientation - The orientation of the original image.
40760      *
40761      * @returns {Array<number>} Angle axis rotation vector.
40762      */
40763     GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
40764         var x = 0;
40765         var y = 0;
40766         var z = 0;
40767         switch (orientation) {
40768             case 1:
40769                 x = Math.PI / 2;
40770                 break;
40771             case 3:
40772                 x = -Math.PI / 2;
40773                 z = Math.PI;
40774                 break;
40775             case 6:
40776                 y = -Math.PI / 2;
40777                 z = -Math.PI / 2;
40778                 break;
40779             case 8:
40780                 y = Math.PI / 2;
40781                 z = Math.PI / 2;
40782                 break;
40783             default:
40784                 break;
40785         }
40786         var rz = new THREE.Matrix4().makeRotationZ(z);
40787         var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
40788         var re = new THREE.Matrix4().makeRotationFromEuler(euler);
40789         var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
40790         return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
40791     };
40792     return GraphCalculator;
40793 }());
40794 exports.GraphCalculator = GraphCalculator;
40795 exports.default = GraphCalculator;
40796
40797 },{"../Error":277,"../Geo":278,"latlon-geohash":21,"three":226}],393:[function(require,module,exports){
40798 "use strict";
40799 Object.defineProperty(exports, "__esModule", { value: true });
40800 /**
40801  * Enumeration for graph modes.
40802  * @enum {number}
40803  * @readonly
40804  * @description Modes for the retrieval and caching performed
40805  * by the graph service on the graph.
40806  */
40807 var GraphMode;
40808 (function (GraphMode) {
40809     /**
40810      * Caching is performed on sequences only and sequence edges are
40811      * calculated. Spatial tiles
40812      * are not retrieved and spatial edges are not calculated when
40813      * caching nodes. Complete sequences are being cached for requested
40814      * nodes within the graph.
40815      */
40816     GraphMode[GraphMode["Sequence"] = 0] = "Sequence";
40817     /**
40818      * Caching is performed with emphasis on spatial data. Sequence edges
40819      * as well as spatial edges are cached. Sequence data
40820      * is still requested but complete sequences are not being cached
40821      * for requested nodes.
40822      *
40823      * This is the initial mode of the graph service.
40824      */
40825     GraphMode[GraphMode["Spatial"] = 1] = "Spatial";
40826 })(GraphMode = exports.GraphMode || (exports.GraphMode = {}));
40827 exports.default = GraphMode;
40828
40829 },{}],394:[function(require,module,exports){
40830 "use strict";
40831 Object.defineProperty(exports, "__esModule", { value: true });
40832 var rxjs_1 = require("rxjs");
40833 var operators_1 = require("rxjs/operators");
40834 var Graph_1 = require("../Graph");
40835 /**
40836  * @class GraphService
40837  *
40838  * @classdesc Represents a service for graph operations.
40839  */
40840 var GraphService = /** @class */ (function () {
40841     /**
40842      * Create a new graph service instance.
40843      *
40844      * @param {Graph} graph - Graph instance to be operated on.
40845      */
40846     function GraphService(graph, imageLoadingService) {
40847         this._graph$ = rxjs_1.concat(rxjs_1.of(graph), graph.changed$).pipe(operators_1.publishReplay(1), operators_1.refCount());
40848         this._graph$.subscribe(function () { });
40849         this._graphMode = Graph_1.GraphMode.Spatial;
40850         this._graphModeSubject$ = new rxjs_1.Subject();
40851         this._graphMode$ = this._graphModeSubject$.pipe(operators_1.startWith(this._graphMode), operators_1.publishReplay(1), operators_1.refCount());
40852         this._graphMode$.subscribe(function () { });
40853         this._imageLoadingService = imageLoadingService;
40854         this._firstGraphSubjects$ = [];
40855         this._initializeCacheSubscriptions = [];
40856         this._sequenceSubscriptions = [];
40857         this._spatialSubscriptions = [];
40858     }
40859     Object.defineProperty(GraphService.prototype, "graphMode$", {
40860         /**
40861          * Get graph mode observable.
40862          *
40863          * @description Emits the current graph mode.
40864          *
40865          * @returns {Observable<GraphMode>} Observable
40866          * emitting the current graph mode when it changes.
40867          */
40868         get: function () {
40869             return this._graphMode$;
40870         },
40871         enumerable: true,
40872         configurable: true
40873     });
40874     /**
40875      * Cache full nodes in a bounding box.
40876      *
40877      * @description When called, the full properties of
40878      * the node are retrieved. The node cache is not initialized
40879      * for any new nodes retrieved and the node assets are not
40880      * retrieved, {@link cacheNode$} needs to be called for caching
40881      * assets.
40882      *
40883      * @param {ILatLon} sw - South west corner of bounding box.
40884      * @param {ILatLon} ne - North east corner of bounding box.
40885      * @return {Observable<Array<Node>>} Observable emitting a single item,
40886      * the nodes of the bounding box, when they have all been retrieved.
40887      * @throws {Error} Propagates any IO node caching errors to the caller.
40888      */
40889     GraphService.prototype.cacheBoundingBox$ = function (sw, ne) {
40890         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
40891             return graph.cacheBoundingBox$(sw, ne);
40892         }));
40893     };
40894     /**
40895      * Cache a node in the graph and retrieve it.
40896      *
40897      * @description When called, the full properties of
40898      * the node are retrieved and the node cache is initialized.
40899      * After that the node assets are cached and the node
40900      * is emitted to the observable when.
40901      * In parallel to caching the node assets, the sequence and
40902      * spatial edges of the node are cached. For this, the sequence
40903      * of the node and the required tiles and spatial nodes are
40904      * retrieved. The sequence and spatial edges may be set before
40905      * or after the node is returned.
40906      *
40907      * @param {string} key - Key of the node to cache.
40908      * @return {Observable<Node>} Observable emitting a single item,
40909      * the node, when it has been retrieved and its assets are cached.
40910      * @throws {Error} Propagates any IO node caching errors to the caller.
40911      */
40912     GraphService.prototype.cacheNode$ = function (key) {
40913         var _this = this;
40914         var firstGraphSubject$ = new rxjs_1.Subject();
40915         this._firstGraphSubjects$.push(firstGraphSubject$);
40916         var firstGraph$ = firstGraphSubject$.pipe(operators_1.publishReplay(1), operators_1.refCount());
40917         var node$ = firstGraph$.pipe(operators_1.map(function (graph) {
40918             return graph.getNode(key);
40919         }), operators_1.mergeMap(function (node) {
40920             return node.assetsCached ?
40921                 rxjs_1.of(node) :
40922                 node.cacheAssets$();
40923         }), operators_1.publishReplay(1), operators_1.refCount());
40924         node$.subscribe(function (node) {
40925             _this._imageLoadingService.loadnode$.next(node);
40926         }, function (error) {
40927             console.error("Failed to cache node (" + key + ")", error);
40928         });
40929         var initializeCacheSubscription = this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
40930             if (graph.isCachingFull(key) || !graph.hasNode(key)) {
40931                 return graph.cacheFull$(key);
40932             }
40933             if (graph.isCachingFill(key) || !graph.getNode(key).full) {
40934                 return graph.cacheFill$(key);
40935             }
40936             return rxjs_1.of(graph);
40937         }), operators_1.tap(function (graph) {
40938             if (!graph.hasInitializedCache(key)) {
40939                 graph.initializeCache(key);
40940             }
40941         }), operators_1.finalize(function () {
40942             if (initializeCacheSubscription == null) {
40943                 return;
40944             }
40945             _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
40946             _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
40947         }))
40948             .subscribe(function (graph) {
40949             firstGraphSubject$.next(graph);
40950             firstGraphSubject$.complete();
40951         }, function (error) {
40952             firstGraphSubject$.error(error);
40953         });
40954         if (!initializeCacheSubscription.closed) {
40955             this._initializeCacheSubscriptions.push(initializeCacheSubscription);
40956         }
40957         var graphSequence$ = firstGraph$.pipe(operators_1.mergeMap(function (graph) {
40958             if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
40959                 return graph.cacheNodeSequence$(key);
40960             }
40961             return rxjs_1.of(graph);
40962         }), operators_1.publishReplay(1), operators_1.refCount());
40963         var sequenceSubscription = graphSequence$.pipe(operators_1.tap(function (graph) {
40964             if (!graph.getNode(key).sequenceEdges.cached) {
40965                 graph.cacheSequenceEdges(key);
40966             }
40967         }), operators_1.finalize(function () {
40968             if (sequenceSubscription == null) {
40969                 return;
40970             }
40971             _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
40972         }))
40973             .subscribe(function (graph) { return; }, function (error) {
40974             console.error("Failed to cache sequence edges (" + key + ").", error);
40975         });
40976         if (!sequenceSubscription.closed) {
40977             this._sequenceSubscriptions.push(sequenceSubscription);
40978         }
40979         if (this._graphMode === Graph_1.GraphMode.Spatial) {
40980             var spatialSubscription_1 = firstGraph$.pipe(operators_1.expand(function (graph) {
40981                 if (graph.hasTiles(key)) {
40982                     return rxjs_1.empty();
40983                 }
40984                 return rxjs_1.from(graph.cacheTiles$(key)).pipe(operators_1.mergeMap(function (graph$) {
40985                     return graph$.pipe(operators_1.mergeMap(function (g) {
40986                         if (g.isCachingTiles(key)) {
40987                             return rxjs_1.empty();
40988                         }
40989                         return rxjs_1.of(g);
40990                     }), operators_1.catchError(function (error, caught$) {
40991                         console.error("Failed to cache tile data (" + key + ").", error);
40992                         return rxjs_1.empty();
40993                     }));
40994                 }));
40995             }), operators_1.last(), operators_1.mergeMap(function (graph) {
40996                 if (graph.hasSpatialArea(key)) {
40997                     return rxjs_1.of(graph);
40998                 }
40999                 return rxjs_1.from(graph.cacheSpatialArea$(key)).pipe(operators_1.mergeMap(function (graph$) {
41000                     return graph$.pipe(operators_1.catchError(function (error, caught$) {
41001                         console.error("Failed to cache spatial nodes (" + key + ").", error);
41002                         return rxjs_1.empty();
41003                     }));
41004                 }));
41005             }), operators_1.last(), operators_1.mergeMap(function (graph) {
41006                 return graph.hasNodeSequence(key) ?
41007                     rxjs_1.of(graph) :
41008                     graph.cacheNodeSequence$(key);
41009             }), operators_1.tap(function (graph) {
41010                 if (!graph.getNode(key).spatialEdges.cached) {
41011                     graph.cacheSpatialEdges(key);
41012                 }
41013             }), operators_1.finalize(function () {
41014                 if (spatialSubscription_1 == null) {
41015                     return;
41016                 }
41017                 _this._removeFromArray(spatialSubscription_1, _this._spatialSubscriptions);
41018             }))
41019                 .subscribe(function (graph) { return; }, function (error) {
41020                 console.error("Failed to cache spatial edges (" + key + ").", error);
41021             });
41022             if (!spatialSubscription_1.closed) {
41023                 this._spatialSubscriptions.push(spatialSubscription_1);
41024             }
41025         }
41026         return node$.pipe(operators_1.first(function (node) {
41027             return node.assetsCached;
41028         }));
41029     };
41030     /**
41031      * Cache a sequence in the graph and retrieve it.
41032      *
41033      * @param {string} sequenceKey - Sequence key.
41034      * @returns {Observable<Sequence>} Observable emitting a single item,
41035      * the sequence, when it has been retrieved and its assets are cached.
41036      * @throws {Error} Propagates any IO node caching errors to the caller.
41037      */
41038     GraphService.prototype.cacheSequence$ = function (sequenceKey) {
41039         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
41040             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
41041                 return graph.cacheSequence$(sequenceKey);
41042             }
41043             return rxjs_1.of(graph);
41044         }), operators_1.map(function (graph) {
41045             return graph.getSequence(sequenceKey);
41046         }));
41047     };
41048     /**
41049      * Cache a sequence and its nodes in the graph and retrieve the sequence.
41050      *
41051      * @description Caches a sequence and its assets are cached and
41052      * retrieves all nodes belonging to the sequence. The node assets
41053      * or edges will not be cached.
41054      *
41055      * @param {string} sequenceKey - Sequence key.
41056      * @param {string} referenceNodeKey - Key of node to use as reference
41057      * for optimized caching.
41058      * @returns {Observable<Sequence>} Observable emitting a single item,
41059      * the sequence, when it has been retrieved, its assets are cached and
41060      * all nodes belonging to the sequence has been retrieved.
41061      * @throws {Error} Propagates any IO node caching errors to the caller.
41062      */
41063     GraphService.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
41064         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
41065             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
41066                 return graph.cacheSequence$(sequenceKey);
41067             }
41068             return rxjs_1.of(graph);
41069         }), operators_1.mergeMap(function (graph) {
41070             if (graph.isCachingSequenceNodes(sequenceKey) || !graph.hasSequenceNodes(sequenceKey)) {
41071                 return graph.cacheSequenceNodes$(sequenceKey, referenceNodeKey);
41072             }
41073             return rxjs_1.of(graph);
41074         }), operators_1.map(function (graph) {
41075             return graph.getSequence(sequenceKey);
41076         }));
41077     };
41078     /**
41079      * Set a spatial edge filter on the graph.
41080      *
41081      * @description Resets the spatial edges of all cached nodes.
41082      *
41083      * @param {FilterExpression} filter - Filter expression to be applied.
41084      * @return {Observable<Graph>} Observable emitting a single item,
41085      * the graph, when the spatial edges have been reset.
41086      */
41087     GraphService.prototype.setFilter$ = function (filter) {
41088         this._resetSubscriptions(this._spatialSubscriptions);
41089         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
41090             graph.resetSpatialEdges();
41091             graph.setFilter(filter);
41092         }), operators_1.map(function (graph) {
41093             return undefined;
41094         }));
41095     };
41096     /**
41097      * Set the graph mode.
41098      *
41099      * @description If graph mode is set to spatial, caching
41100      * is performed with emphasis on spatial edges. If graph
41101      * mode is set to sequence no tile data is requested and
41102      * no spatial edges are computed.
41103      *
41104      * When setting graph mode to sequence all spatial
41105      * subscriptions are aborted.
41106      *
41107      * @param {GraphMode} mode - Graph mode to set.
41108      */
41109     GraphService.prototype.setGraphMode = function (mode) {
41110         if (this._graphMode === mode) {
41111             return;
41112         }
41113         if (mode === Graph_1.GraphMode.Sequence) {
41114             this._resetSubscriptions(this._spatialSubscriptions);
41115         }
41116         this._graphMode = mode;
41117         this._graphModeSubject$.next(this._graphMode);
41118     };
41119     /**
41120      * Reset the graph.
41121      *
41122      * @description Resets the graph but keeps the nodes of the
41123      * supplied keys.
41124      *
41125      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
41126      * @return {Observable<Node>} Observable emitting a single item,
41127      * the graph, when it has been reset.
41128      */
41129     GraphService.prototype.reset$ = function (keepKeys) {
41130         this._abortSubjects(this._firstGraphSubjects$);
41131         this._resetSubscriptions(this._initializeCacheSubscriptions);
41132         this._resetSubscriptions(this._sequenceSubscriptions);
41133         this._resetSubscriptions(this._spatialSubscriptions);
41134         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
41135             graph.reset(keepKeys);
41136         }), operators_1.map(function (graph) {
41137             return undefined;
41138         }));
41139     };
41140     /**
41141      * Uncache the graph.
41142      *
41143      * @description Uncaches the graph by removing tiles, nodes and
41144      * sequences. Keeps the nodes of the supplied keys and the tiles
41145      * related to those nodes.
41146      *
41147      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
41148      * @param {string} keepSequenceKey - Optional key of sequence
41149      * for which the belonging nodes should not be disposed or
41150      * removed from the graph. These nodes may still be uncached if
41151      * not specified in keep keys param.
41152      * @return {Observable<Graph>} Observable emitting a single item,
41153      * the graph, when the graph has been uncached.
41154      */
41155     GraphService.prototype.uncache$ = function (keepKeys, keepSequenceKey) {
41156         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
41157             graph.uncache(keepKeys, keepSequenceKey);
41158         }), operators_1.map(function (graph) {
41159             return undefined;
41160         }));
41161     };
41162     GraphService.prototype._abortSubjects = function (subjects) {
41163         for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
41164             var subject = _a[_i];
41165             this._removeFromArray(subject, subjects);
41166             subject.error(new Error("Cache node request was aborted."));
41167         }
41168     };
41169     GraphService.prototype._removeFromArray = function (object, objects) {
41170         var index = objects.indexOf(object);
41171         if (index !== -1) {
41172             objects.splice(index, 1);
41173         }
41174     };
41175     GraphService.prototype._resetSubscriptions = function (subscriptions) {
41176         for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
41177             var subscription = _a[_i];
41178             this._removeFromArray(subscription, subscriptions);
41179             if (!subscription.closed) {
41180                 subscription.unsubscribe();
41181             }
41182         }
41183     };
41184     return GraphService;
41185 }());
41186 exports.GraphService = GraphService;
41187 exports.default = GraphService;
41188
41189 },{"../Graph":279,"rxjs":27,"rxjs/operators":225}],395:[function(require,module,exports){
41190 "use strict";
41191 Object.defineProperty(exports, "__esModule", { value: true });
41192 var operators_1 = require("rxjs/operators");
41193 var rxjs_1 = require("rxjs");
41194 var ImageLoadingService = /** @class */ (function () {
41195     function ImageLoadingService() {
41196         this._loadnode$ = new rxjs_1.Subject();
41197         this._loadstatus$ = this._loadnode$.pipe(operators_1.scan(function (_a, node) {
41198             var nodes = _a[0];
41199             var changed = false;
41200             if (node.loadStatus.total === 0 || node.loadStatus.loaded === node.loadStatus.total) {
41201                 if (node.key in nodes) {
41202                     delete nodes[node.key];
41203                     changed = true;
41204                 }
41205             }
41206             else {
41207                 nodes[node.key] = node.loadStatus;
41208                 changed = true;
41209             }
41210             return [nodes, changed];
41211         }, [{}, false]), operators_1.filter(function (_a) {
41212             var nodes = _a[0], changed = _a[1];
41213             return changed;
41214         }), operators_1.map(function (_a) {
41215             var nodes = _a[0];
41216             return nodes;
41217         }), operators_1.publishReplay(1), operators_1.refCount());
41218         this._loadstatus$.subscribe(function () { });
41219     }
41220     Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
41221         get: function () {
41222             return this._loadnode$;
41223         },
41224         enumerable: true,
41225         configurable: true
41226     });
41227     Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
41228         get: function () {
41229             return this._loadstatus$;
41230         },
41231         enumerable: true,
41232         configurable: true
41233     });
41234     return ImageLoadingService;
41235 }());
41236 exports.ImageLoadingService = ImageLoadingService;
41237
41238 },{"rxjs":27,"rxjs/operators":225}],396:[function(require,module,exports){
41239 "use strict";
41240 Object.defineProperty(exports, "__esModule", { value: true });
41241 var Pbf = require("pbf");
41242 var MeshReader = /** @class */ (function () {
41243     function MeshReader() {
41244     }
41245     MeshReader.read = function (buffer) {
41246         var pbf = new Pbf(buffer);
41247         return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
41248     };
41249     MeshReader._readMeshField = function (tag, mesh, pbf) {
41250         if (tag === 1) {
41251             mesh.vertices.push(pbf.readFloat());
41252         }
41253         else if (tag === 2) {
41254             mesh.faces.push(pbf.readVarint());
41255         }
41256     };
41257     return MeshReader;
41258 }());
41259 exports.MeshReader = MeshReader;
41260
41261 },{"pbf":24}],397:[function(require,module,exports){
41262 "use strict";
41263 Object.defineProperty(exports, "__esModule", { value: true });
41264 var operators_1 = require("rxjs/operators");
41265 /**
41266  * @class Node
41267  *
41268  * @classdesc Represents a node in the navigation graph.
41269  *
41270  * Explanation of position and bearing properties:
41271  *
41272  * When images are uploaded they will have GPS information in the EXIF, this is what
41273  * is called `originalLatLon` {@link Node.originalLatLon}.
41274  *
41275  * When Structure from Motions has been run for a node a `computedLatLon` that
41276  * differs from the `originalLatLon` will be created. It is different because
41277  * GPS positions are not very exact and SfM aligns the camera positions according
41278  * to the 3D reconstruction {@link Node.computedLatLon}.
41279  *
41280  * At last there exist a `latLon` property which evaluates to
41281  * the `computedLatLon` from SfM if it exists but falls back
41282  * to the `originalLatLon` from the EXIF GPS otherwise {@link Node.latLon}.
41283  *
41284  * Everything that is done in in the Viewer is based on the SfM positions,
41285  * i.e. `computedLatLon`. That is why the smooth transitions go in the right
41286  * direction (nd not in strange directions because of bad GPS).
41287  *
41288  * E.g. when placing a marker in the Viewer it is relative to the SfM
41289  * position i.e. the `computedLatLon`.
41290  *
41291  * The same concept as above also applies to the compass angle (or bearing) properties
41292  * `originalCa`, `computedCa` and `ca`.
41293  */
41294 var Node = /** @class */ (function () {
41295     /**
41296      * Create a new node instance.
41297      *
41298      * @description Nodes are always created internally by the library.
41299      * Nodes can not be added to the library through any API method.
41300      *
41301      * @param {ICoreNode} coreNode - Raw core node data.
41302      * @ignore
41303      */
41304     function Node(core) {
41305         this._cache = null;
41306         this._core = core;
41307         this._fill = null;
41308     }
41309     Object.defineProperty(Node.prototype, "assetsCached", {
41310         /**
41311          * Get assets cached.
41312          *
41313          * @description The assets that need to be cached for this property
41314          * to report true are the following: fill properties, image and mesh.
41315          * The library ensures that the current node will always have the
41316          * assets cached.
41317          *
41318          * @returns {boolean} Value indicating whether all assets have been
41319          * cached.
41320          *
41321          * @ignore
41322          */
41323         get: function () {
41324             return this._core != null &&
41325                 this._fill != null &&
41326                 this._cache != null &&
41327                 this._cache.image != null &&
41328                 this._cache.mesh != null;
41329         },
41330         enumerable: true,
41331         configurable: true
41332     });
41333     Object.defineProperty(Node.prototype, "alt", {
41334         /**
41335          * Get alt.
41336          *
41337          * @description If SfM has not been run the computed altitude is
41338          * set to a default value of two meters.
41339          *
41340          * @returns {number} Altitude, in meters.
41341          */
41342         get: function () {
41343             return this._fill.calt;
41344         },
41345         enumerable: true,
41346         configurable: true
41347     });
41348     Object.defineProperty(Node.prototype, "ca", {
41349         /**
41350          * Get ca.
41351          *
41352          * @description If the SfM computed compass angle exists it will
41353          * be returned, otherwise the original EXIF compass angle.
41354          *
41355          * @returns {number} Compass angle, measured in degrees
41356          * clockwise with respect to north.
41357          */
41358         get: function () {
41359             return this._fill.cca != null ? this._fill.cca : this._fill.ca;
41360         },
41361         enumerable: true,
41362         configurable: true
41363     });
41364     Object.defineProperty(Node.prototype, "cameraProjection", {
41365         /**
41366          * Get cameraProjection.
41367          *
41368          * @description Will be undefined if SfM has not been run.
41369          *
41370          * @returns {number} The camera projection of the image.
41371          */
41372         get: function () {
41373             return this._fill.camera_projection_type;
41374         },
41375         enumerable: true,
41376         configurable: true
41377     });
41378     Object.defineProperty(Node.prototype, "capturedAt", {
41379         /**
41380          * Get capturedAt.
41381          *
41382          * @returns {number} Timestamp when the image was captured.
41383          */
41384         get: function () {
41385             return this._fill.captured_at;
41386         },
41387         enumerable: true,
41388         configurable: true
41389     });
41390     Object.defineProperty(Node.prototype, "cameraUuid", {
41391         /**
41392          * Get camera uuid.
41393          *
41394          * @description Will be undefined if the camera uuid was not
41395          * recorded in the image exif information.
41396          *
41397          * @returns {string} Universally unique id for camera used
41398          * when capturing image.
41399          */
41400         get: function () {
41401             return this._fill.captured_with_camera_uuid;
41402         },
41403         enumerable: true,
41404         configurable: true
41405     });
41406     Object.defineProperty(Node.prototype, "ck1", {
41407         /**
41408          * Get ck1.
41409          *
41410          * @description Will not be set if SfM has not been run.
41411          *
41412          * @returns {number} SfM computed radial distortion parameter
41413          * k1.
41414          */
41415         get: function () {
41416             return this._fill.ck1;
41417         },
41418         enumerable: true,
41419         configurable: true
41420     });
41421     Object.defineProperty(Node.prototype, "ck2", {
41422         /**
41423          * Get ck2.
41424          *
41425          * @description Will not be set if SfM has not been run.
41426          *
41427          * @returns {number} SfM computed radial distortion parameter
41428          * k2.
41429          */
41430         get: function () {
41431             return this._fill.ck2;
41432         },
41433         enumerable: true,
41434         configurable: true
41435     });
41436     Object.defineProperty(Node.prototype, "computedCA", {
41437         /**
41438          * Get computedCA.
41439          *
41440          * @description Will not be set if SfM has not been run.
41441          *
41442          * @returns {number} SfM computed compass angle, measured
41443          * in degrees clockwise with respect to north.
41444          */
41445         get: function () {
41446             return this._fill.cca;
41447         },
41448         enumerable: true,
41449         configurable: true
41450     });
41451     Object.defineProperty(Node.prototype, "computedLatLon", {
41452         /**
41453          * Get computedLatLon.
41454          *
41455          * @description Will not be set if SfM has not been run.
41456          *
41457          * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
41458          * measured in degrees.
41459          */
41460         get: function () {
41461             return this._core.cl;
41462         },
41463         enumerable: true,
41464         configurable: true
41465     });
41466     Object.defineProperty(Node.prototype, "focal", {
41467         /**
41468          * Get focal.
41469          *
41470          * @description Will not be set if SfM has not been run.
41471          *
41472          * @returns {number} SfM computed focal length.
41473          */
41474         get: function () {
41475             return this._fill.cfocal;
41476         },
41477         enumerable: true,
41478         configurable: true
41479     });
41480     Object.defineProperty(Node.prototype, "full", {
41481         /**
41482          * Get full.
41483          *
41484          * @description The library ensures that the current node will
41485          * always be full.
41486          *
41487          * @returns {boolean} Value indicating whether the node has all
41488          * properties filled.
41489          *
41490          * @ignore
41491          */
41492         get: function () {
41493             return this._fill != null;
41494         },
41495         enumerable: true,
41496         configurable: true
41497     });
41498     Object.defineProperty(Node.prototype, "fullPano", {
41499         /**
41500          * Get fullPano.
41501          *
41502          * @returns {boolean} Value indicating whether the node is a complete
41503          * 360 panorama.
41504          */
41505         get: function () {
41506             return this._fill.gpano != null &&
41507                 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
41508                 this._fill.gpano.CroppedAreaTopPixels === 0 &&
41509                 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
41510                 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
41511         },
41512         enumerable: true,
41513         configurable: true
41514     });
41515     Object.defineProperty(Node.prototype, "gpano", {
41516         /**
41517          * Get gpano.
41518          *
41519          * @description Will not be set for non panoramic images.
41520          *
41521          * @returns {IGPano} Panorama information for panorama images.
41522          */
41523         get: function () {
41524             return this._fill.gpano;
41525         },
41526         enumerable: true,
41527         configurable: true
41528     });
41529     Object.defineProperty(Node.prototype, "height", {
41530         /**
41531          * Get height.
41532          *
41533          * @returns {number} Height of original image, not adjusted
41534          * for orientation.
41535          */
41536         get: function () {
41537             return this._fill.height;
41538         },
41539         enumerable: true,
41540         configurable: true
41541     });
41542     Object.defineProperty(Node.prototype, "image", {
41543         /**
41544          * Get image.
41545          *
41546          * @description The image will always be set on the current node.
41547          *
41548          * @returns {HTMLImageElement} Cached image element of the node.
41549          */
41550         get: function () {
41551             return this._cache.image;
41552         },
41553         enumerable: true,
41554         configurable: true
41555     });
41556     Object.defineProperty(Node.prototype, "image$", {
41557         /**
41558          * Get image$.
41559          *
41560          * @returns {Observable<HTMLImageElement>} Observable emitting
41561          * the cached image when it is updated.
41562          *
41563          * @ignore
41564          */
41565         get: function () {
41566             return this._cache.image$;
41567         },
41568         enumerable: true,
41569         configurable: true
41570     });
41571     Object.defineProperty(Node.prototype, "key", {
41572         /**
41573          * Get key.
41574          *
41575          * @returns {string} Unique key of the node.
41576          */
41577         get: function () {
41578             return this._core.key;
41579         },
41580         enumerable: true,
41581         configurable: true
41582     });
41583     Object.defineProperty(Node.prototype, "latLon", {
41584         /**
41585          * Get latLon.
41586          *
41587          * @description If the SfM computed latitude longitude exist
41588          * it will be returned, otherwise the original EXIF latitude
41589          * longitude.
41590          *
41591          * @returns {ILatLon} Latitude longitude in WGS84 datum,
41592          * measured in degrees.
41593          */
41594         get: function () {
41595             return this._core.cl != null ? this._core.cl : this._core.l;
41596         },
41597         enumerable: true,
41598         configurable: true
41599     });
41600     Object.defineProperty(Node.prototype, "loadStatus", {
41601         /**
41602          * Get loadStatus.
41603          *
41604          * @returns {ILoadStatus} Value indicating the load status
41605          * of the mesh and image.
41606          *
41607          * @ignore
41608          */
41609         get: function () {
41610             return this._cache.loadStatus;
41611         },
41612         enumerable: true,
41613         configurable: true
41614     });
41615     Object.defineProperty(Node.prototype, "merged", {
41616         /**
41617          * Get merged.
41618          *
41619          * @returns {boolean} Value indicating whether SfM has been
41620          * run on the node and the node has been merged into a
41621          * connected component.
41622          */
41623         get: function () {
41624             return this._fill != null &&
41625                 this._fill.merge_version != null &&
41626                 this._fill.merge_version > 0;
41627         },
41628         enumerable: true,
41629         configurable: true
41630     });
41631     Object.defineProperty(Node.prototype, "mergeCC", {
41632         /**
41633          * Get mergeCC.
41634          *
41635          * @description Will not be set if SfM has not yet been run on
41636          * node.
41637          *
41638          * @returns {number} SfM connected component key to which
41639          * image belongs.
41640          */
41641         get: function () {
41642             return this._fill.merge_cc;
41643         },
41644         enumerable: true,
41645         configurable: true
41646     });
41647     Object.defineProperty(Node.prototype, "mergeVersion", {
41648         /**
41649          * Get mergeVersion.
41650          *
41651          * @returns {number} Version for which SfM was run and image was merged.
41652          */
41653         get: function () {
41654             return this._fill.merge_version;
41655         },
41656         enumerable: true,
41657         configurable: true
41658     });
41659     Object.defineProperty(Node.prototype, "mesh", {
41660         /**
41661          * Get mesh.
41662          *
41663          * @description The mesh will always be set on the current node.
41664          *
41665          * @returns {IMesh} SfM triangulated mesh of reconstructed
41666          * atomic 3D points.
41667          */
41668         get: function () {
41669             return this._cache.mesh;
41670         },
41671         enumerable: true,
41672         configurable: true
41673     });
41674     Object.defineProperty(Node.prototype, "organizationKey", {
41675         /**
41676          * Get organizationKey.
41677          *
41678          * @returns {string} Unique key of the organization to which
41679          * the node belongs. If the node does not belong to an
41680          * organization the organization key will be undefined.
41681          */
41682         get: function () {
41683             return this._fill.organization_key;
41684         },
41685         enumerable: true,
41686         configurable: true
41687     });
41688     Object.defineProperty(Node.prototype, "orientation", {
41689         /**
41690          * Get orientation.
41691          *
41692          * @returns {number} EXIF orientation of original image.
41693          */
41694         get: function () {
41695             return this._fill.orientation;
41696         },
41697         enumerable: true,
41698         configurable: true
41699     });
41700     Object.defineProperty(Node.prototype, "originalCA", {
41701         /**
41702          * Get originalCA.
41703          *
41704          * @returns {number} Original EXIF compass angle, measured in
41705          * degrees.
41706          */
41707         get: function () {
41708             return this._fill.ca;
41709         },
41710         enumerable: true,
41711         configurable: true
41712     });
41713     Object.defineProperty(Node.prototype, "originalLatLon", {
41714         /**
41715          * Get originalLatLon.
41716          *
41717          * @returns {ILatLon} Original EXIF latitude longitude in
41718          * WGS84 datum, measured in degrees.
41719          */
41720         get: function () {
41721             return this._core.l;
41722         },
41723         enumerable: true,
41724         configurable: true
41725     });
41726     Object.defineProperty(Node.prototype, "pano", {
41727         /**
41728          * Get pano.
41729          *
41730          * @returns {boolean} Value indicating whether the node is a panorama.
41731          * It could be a cropped or full panorama.
41732          */
41733         get: function () {
41734             return this._fill.gpano != null &&
41735                 this._fill.gpano.FullPanoWidthPixels != null;
41736         },
41737         enumerable: true,
41738         configurable: true
41739     });
41740     Object.defineProperty(Node.prototype, "private", {
41741         /**
41742          * Get private.
41743          *
41744          * @returns {boolean} Value specifying if image is accessible to
41745          * organization members only or to everyone.
41746          */
41747         get: function () {
41748             return this._fill.private;
41749         },
41750         enumerable: true,
41751         configurable: true
41752     });
41753     Object.defineProperty(Node.prototype, "projectKey", {
41754         /**
41755          * Get projectKey.
41756          *
41757          * @returns {string} Unique key of the project to which
41758          * the node belongs. If the node does not belong to a
41759          * project the project key will be undefined.
41760          *
41761          * @deprecated This property will be deprecated in favor
41762          * of the organization key and private properties.
41763          */
41764         get: function () {
41765             return this._fill.project != null ?
41766                 this._fill.project.key :
41767                 null;
41768         },
41769         enumerable: true,
41770         configurable: true
41771     });
41772     Object.defineProperty(Node.prototype, "rotation", {
41773         /**
41774          * Get rotation.
41775          *
41776          * @description Will not be set if SfM has not been run.
41777          *
41778          * @returns {Array<number>} Rotation vector in angle axis representation.
41779          */
41780         get: function () {
41781             return this._fill.c_rotation;
41782         },
41783         enumerable: true,
41784         configurable: true
41785     });
41786     Object.defineProperty(Node.prototype, "scale", {
41787         /**
41788          * Get scale.
41789          *
41790          * @description Will not be set if SfM has not been run.
41791          *
41792          * @returns {number} Scale of atomic reconstruction.
41793          */
41794         get: function () {
41795             return this._fill.atomic_scale;
41796         },
41797         enumerable: true,
41798         configurable: true
41799     });
41800     Object.defineProperty(Node.prototype, "sequenceKey", {
41801         /**
41802          * Get sequenceKey.
41803          *
41804          * @returns {string} Unique key of the sequence to which
41805          * the node belongs.
41806          */
41807         get: function () {
41808             return this._core.sequence_key;
41809         },
41810         enumerable: true,
41811         configurable: true
41812     });
41813     Object.defineProperty(Node.prototype, "sequenceEdges", {
41814         /**
41815          * Get sequenceEdges.
41816          *
41817          * @returns {IEdgeStatus} Value describing the status of the
41818          * sequence edges.
41819          *
41820          * @ignore
41821          */
41822         get: function () {
41823             return this._cache.sequenceEdges;
41824         },
41825         enumerable: true,
41826         configurable: true
41827     });
41828     Object.defineProperty(Node.prototype, "sequenceEdges$", {
41829         /**
41830          * Get sequenceEdges$.
41831          *
41832          * @description Internal observable, should not be used as an API.
41833          *
41834          * @returns {Observable<IEdgeStatus>} Observable emitting
41835          * values describing the status of the sequence edges.
41836          *
41837          * @ignore
41838          */
41839         get: function () {
41840             return this._cache.sequenceEdges$;
41841         },
41842         enumerable: true,
41843         configurable: true
41844     });
41845     Object.defineProperty(Node.prototype, "spatialEdges", {
41846         /**
41847          * Get spatialEdges.
41848          *
41849          * @returns {IEdgeStatus} Value describing the status of the
41850          * spatial edges.
41851          *
41852          * @ignore
41853          */
41854         get: function () {
41855             return this._cache.spatialEdges;
41856         },
41857         enumerable: true,
41858         configurable: true
41859     });
41860     Object.defineProperty(Node.prototype, "spatialEdges$", {
41861         /**
41862          * Get spatialEdges$.
41863          *
41864          * @description Internal observable, should not be used as an API.
41865          *
41866          * @returns {Observable<IEdgeStatus>} Observable emitting
41867          * values describing the status of the spatial edges.
41868          *
41869          * @ignore
41870          */
41871         get: function () {
41872             return this._cache.spatialEdges$;
41873         },
41874         enumerable: true,
41875         configurable: true
41876     });
41877     Object.defineProperty(Node.prototype, "userKey", {
41878         /**
41879          * Get userKey.
41880          *
41881          * @returns {string} Unique key of the user who uploaded
41882          * the image.
41883          */
41884         get: function () {
41885             return this._fill.user.key;
41886         },
41887         enumerable: true,
41888         configurable: true
41889     });
41890     Object.defineProperty(Node.prototype, "username", {
41891         /**
41892          * Get username.
41893          *
41894          * @returns {string} Username of the user who uploaded
41895          * the image.
41896          */
41897         get: function () {
41898             return this._fill.user.username;
41899         },
41900         enumerable: true,
41901         configurable: true
41902     });
41903     Object.defineProperty(Node.prototype, "width", {
41904         /**
41905          * Get width.
41906          *
41907          * @returns {number} Width of original image, not
41908          * adjusted for orientation.
41909          */
41910         get: function () {
41911             return this._fill.width;
41912         },
41913         enumerable: true,
41914         configurable: true
41915     });
41916     /**
41917      * Cache the image and mesh assets.
41918      *
41919      * @description The assets are always cached internally by the
41920      * library prior to setting a node as the current node.
41921      *
41922      * @returns {Observable<Node>} Observable emitting this node whenever the
41923      * load status has changed and when the mesh or image has been fully loaded.
41924      *
41925      * @ignore
41926      */
41927     Node.prototype.cacheAssets$ = function () {
41928         var _this = this;
41929         return this._cache.cacheAssets$(this.key, this.pano, this.merged).pipe(operators_1.map(function () {
41930             return _this;
41931         }));
41932     };
41933     /**
41934      * Cache the image asset.
41935      *
41936      * @description Use for caching a differently sized image than
41937      * the one currently held by the node.
41938      *
41939      * @returns {Observable<Node>} Observable emitting this node whenever the
41940      * load status has changed and when the mesh or image has been fully loaded.
41941      *
41942      * @ignore
41943      */
41944     Node.prototype.cacheImage$ = function (imageSize) {
41945         var _this = this;
41946         return this._cache.cacheImage$(this.key, imageSize).pipe(operators_1.map(function () {
41947             return _this;
41948         }));
41949     };
41950     /**
41951      * Cache the sequence edges.
41952      *
41953      * @description The sequence edges are cached asynchronously
41954      * internally by the library.
41955      *
41956      * @param {Array<IEdge>} edges - Sequence edges to cache.
41957      * @ignore
41958      */
41959     Node.prototype.cacheSequenceEdges = function (edges) {
41960         this._cache.cacheSequenceEdges(edges);
41961     };
41962     /**
41963      * Cache the spatial edges.
41964      *
41965      * @description The spatial edges are cached asynchronously
41966      * internally by the library.
41967      *
41968      * @param {Array<IEdge>} edges - Spatial edges to cache.
41969      * @ignore
41970      */
41971     Node.prototype.cacheSpatialEdges = function (edges) {
41972         this._cache.cacheSpatialEdges(edges);
41973     };
41974     /**
41975      * Dispose the node.
41976      *
41977      * @description Disposes all cached assets.
41978      * @ignore
41979      */
41980     Node.prototype.dispose = function () {
41981         if (this._cache != null) {
41982             this._cache.dispose();
41983             this._cache = null;
41984         }
41985         this._core = null;
41986         this._fill = null;
41987     };
41988     /**
41989      * Initialize the node cache.
41990      *
41991      * @description The node cache is initialized internally by
41992      * the library.
41993      *
41994      * @param {NodeCache} cache - The node cache to set as cache.
41995      * @ignore
41996      */
41997     Node.prototype.initializeCache = function (cache) {
41998         if (this._cache != null) {
41999             throw new Error("Node cache already initialized (" + this.key + ").");
42000         }
42001         this._cache = cache;
42002     };
42003     /**
42004      * Fill the node with all properties.
42005      *
42006      * @description The node is filled internally by
42007      * the library.
42008      *
42009      * @param {IFillNode} fill - The fill node struct.
42010      * @ignore
42011      */
42012     Node.prototype.makeFull = function (fill) {
42013         if (fill == null) {
42014             throw new Error("Fill can not be null.");
42015         }
42016         this._fill = fill;
42017     };
42018     /**
42019      * Reset the sequence edges.
42020      *
42021      * @ignore
42022      */
42023     Node.prototype.resetSequenceEdges = function () {
42024         this._cache.resetSequenceEdges();
42025     };
42026     /**
42027      * Reset the spatial edges.
42028      *
42029      * @ignore
42030      */
42031     Node.prototype.resetSpatialEdges = function () {
42032         this._cache.resetSpatialEdges();
42033     };
42034     /**
42035      * Clears the image and mesh assets, aborts
42036      * any outstanding requests and resets edges.
42037      *
42038      * @ignore
42039      */
42040     Node.prototype.uncache = function () {
42041         if (this._cache == null) {
42042             return;
42043         }
42044         this._cache.dispose();
42045         this._cache = null;
42046     };
42047     return Node;
42048 }());
42049 exports.Node = Node;
42050 exports.default = Node;
42051
42052 },{"rxjs/operators":225}],398:[function(require,module,exports){
42053 (function (Buffer){
42054 "use strict";
42055 Object.defineProperty(exports, "__esModule", { value: true });
42056 var rxjs_1 = require("rxjs");
42057 var operators_1 = require("rxjs/operators");
42058 var Graph_1 = require("../Graph");
42059 var Utils_1 = require("../Utils");
42060 /**
42061  * @class NodeCache
42062  *
42063  * @classdesc Represents the cached properties of a node.
42064  */
42065 var NodeCache = /** @class */ (function () {
42066     /**
42067      * Create a new node cache instance.
42068      */
42069     function NodeCache() {
42070         this._disposed = false;
42071         this._image = null;
42072         this._loadStatus = { loaded: 0, total: 0 };
42073         this._mesh = null;
42074         this._sequenceEdges = { cached: false, edges: [] };
42075         this._spatialEdges = { cached: false, edges: [] };
42076         this._imageChanged$ = new rxjs_1.Subject();
42077         this._image$ = this._imageChanged$.pipe(operators_1.startWith(null), operators_1.publishReplay(1), operators_1.refCount());
42078         this._iamgeSubscription = this._image$.subscribe();
42079         this._sequenceEdgesChanged$ = new rxjs_1.Subject();
42080         this._sequenceEdges$ = this._sequenceEdgesChanged$.pipe(operators_1.startWith(this._sequenceEdges), operators_1.publishReplay(1), operators_1.refCount());
42081         this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
42082         this._spatialEdgesChanged$ = new rxjs_1.Subject();
42083         this._spatialEdges$ = this._spatialEdgesChanged$.pipe(operators_1.startWith(this._spatialEdges), operators_1.publishReplay(1), operators_1.refCount());
42084         this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
42085         this._cachingAssets$ = null;
42086     }
42087     Object.defineProperty(NodeCache.prototype, "image", {
42088         /**
42089          * Get image.
42090          *
42091          * @description Will not be set when assets have not been cached
42092          * or when the object has been disposed.
42093          *
42094          * @returns {HTMLImageElement} Cached image element of the node.
42095          */
42096         get: function () {
42097             return this._image;
42098         },
42099         enumerable: true,
42100         configurable: true
42101     });
42102     Object.defineProperty(NodeCache.prototype, "image$", {
42103         /**
42104          * Get image$.
42105          *
42106          * @returns {Observable<HTMLImageElement>} Observable emitting
42107          * the cached image when it is updated.
42108          */
42109         get: function () {
42110             return this._image$;
42111         },
42112         enumerable: true,
42113         configurable: true
42114     });
42115     Object.defineProperty(NodeCache.prototype, "loadStatus", {
42116         /**
42117          * Get loadStatus.
42118          *
42119          * @returns {ILoadStatus} Value indicating the load status
42120          * of the mesh and image.
42121          */
42122         get: function () {
42123             return this._loadStatus;
42124         },
42125         enumerable: true,
42126         configurable: true
42127     });
42128     Object.defineProperty(NodeCache.prototype, "mesh", {
42129         /**
42130          * Get mesh.
42131          *
42132          * @description Will not be set when assets have not been cached
42133          * or when the object has been disposed.
42134          *
42135          * @returns {IMesh} SfM triangulated mesh of reconstructed
42136          * atomic 3D points.
42137          */
42138         get: function () {
42139             return this._mesh;
42140         },
42141         enumerable: true,
42142         configurable: true
42143     });
42144     Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
42145         /**
42146          * Get sequenceEdges.
42147          *
42148          * @returns {IEdgeStatus} Value describing the status of the
42149          * sequence edges.
42150          */
42151         get: function () {
42152             return this._sequenceEdges;
42153         },
42154         enumerable: true,
42155         configurable: true
42156     });
42157     Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
42158         /**
42159          * Get sequenceEdges$.
42160          *
42161          * @returns {Observable<IEdgeStatus>} Observable emitting
42162          * values describing the status of the sequence edges.
42163          */
42164         get: function () {
42165             return this._sequenceEdges$;
42166         },
42167         enumerable: true,
42168         configurable: true
42169     });
42170     Object.defineProperty(NodeCache.prototype, "spatialEdges", {
42171         /**
42172          * Get spatialEdges.
42173          *
42174          * @returns {IEdgeStatus} Value describing the status of the
42175          * spatial edges.
42176          */
42177         get: function () {
42178             return this._spatialEdges;
42179         },
42180         enumerable: true,
42181         configurable: true
42182     });
42183     Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
42184         /**
42185          * Get spatialEdges$.
42186          *
42187          * @returns {Observable<IEdgeStatus>} Observable emitting
42188          * values describing the status of the spatial edges.
42189          */
42190         get: function () {
42191             return this._spatialEdges$;
42192         },
42193         enumerable: true,
42194         configurable: true
42195     });
42196     /**
42197      * Cache the image and mesh assets.
42198      *
42199      * @param {string} key - Key of the node to cache.
42200      * @param {boolean} pano - Value indicating whether node is a panorama.
42201      * @param {boolean} merged - Value indicating whether node is merged.
42202      * @returns {Observable<NodeCache>} Observable emitting this node
42203      * cache whenever the load status has changed and when the mesh or image
42204      * has been fully loaded.
42205      */
42206     NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
42207         var _this = this;
42208         if (this._cachingAssets$ != null) {
42209             return this._cachingAssets$;
42210         }
42211         var imageSize = pano ?
42212             Utils_1.Settings.basePanoramaSize :
42213             Utils_1.Settings.baseImageSize;
42214         this._cachingAssets$ = rxjs_1.combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged)).pipe(operators_1.map(function (_a) {
42215             var imageStatus = _a[0], meshStatus = _a[1];
42216             _this._loadStatus.loaded = 0;
42217             _this._loadStatus.total = 0;
42218             if (meshStatus) {
42219                 _this._mesh = meshStatus.object;
42220                 _this._loadStatus.loaded += meshStatus.loaded.loaded;
42221                 _this._loadStatus.total += meshStatus.loaded.total;
42222             }
42223             if (imageStatus) {
42224                 _this._image = imageStatus.object;
42225                 _this._loadStatus.loaded += imageStatus.loaded.loaded;
42226                 _this._loadStatus.total += imageStatus.loaded.total;
42227             }
42228             return _this;
42229         }), operators_1.finalize(function () {
42230             _this._cachingAssets$ = null;
42231         }), operators_1.publishReplay(1), operators_1.refCount());
42232         this._cachingAssets$.pipe(operators_1.first(function (nodeCache) {
42233             return !!nodeCache._image;
42234         }))
42235             .subscribe(function (nodeCache) {
42236             _this._imageChanged$.next(_this._image);
42237         }, function (error) { });
42238         return this._cachingAssets$;
42239     };
42240     /**
42241      * Cache an image with a higher resolution than the current one.
42242      *
42243      * @param {string} key - Key of the node to cache.
42244      * @param {ImageSize} imageSize - The size to cache.
42245      * @returns {Observable<NodeCache>} Observable emitting a single item,
42246      * the node cache, when the image has been cached. If supplied image
42247      * size is not larger than the current image size the node cache is
42248      * returned immediately.
42249      */
42250     NodeCache.prototype.cacheImage$ = function (key, imageSize) {
42251         var _this = this;
42252         if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
42253             return rxjs_1.of(this);
42254         }
42255         var cacheImage$ = this._cacheImage$(key, imageSize).pipe(operators_1.first(function (status) {
42256             return status.object != null;
42257         }), operators_1.tap(function (status) {
42258             _this._disposeImage();
42259             _this._image = status.object;
42260         }), operators_1.map(function (imageStatus) {
42261             return _this;
42262         }), operators_1.publishReplay(1), operators_1.refCount());
42263         cacheImage$
42264             .subscribe(function (nodeCache) {
42265             _this._imageChanged$.next(_this._image);
42266         }, function (error) { });
42267         return cacheImage$;
42268     };
42269     /**
42270      * Cache the sequence edges.
42271      *
42272      * @param {Array<IEdge>} edges - Sequence edges to cache.
42273      */
42274     NodeCache.prototype.cacheSequenceEdges = function (edges) {
42275         this._sequenceEdges = { cached: true, edges: edges };
42276         this._sequenceEdgesChanged$.next(this._sequenceEdges);
42277     };
42278     /**
42279      * Cache the spatial edges.
42280      *
42281      * @param {Array<IEdge>} edges - Spatial edges to cache.
42282      */
42283     NodeCache.prototype.cacheSpatialEdges = function (edges) {
42284         this._spatialEdges = { cached: true, edges: edges };
42285         this._spatialEdgesChanged$.next(this._spatialEdges);
42286     };
42287     /**
42288      * Dispose the node cache.
42289      *
42290      * @description Disposes all cached assets and unsubscribes to
42291      * all streams.
42292      */
42293     NodeCache.prototype.dispose = function () {
42294         this._iamgeSubscription.unsubscribe();
42295         this._sequenceEdgesSubscription.unsubscribe();
42296         this._spatialEdgesSubscription.unsubscribe();
42297         this._disposeImage();
42298         this._mesh = null;
42299         this._loadStatus.loaded = 0;
42300         this._loadStatus.total = 0;
42301         this._sequenceEdges = { cached: false, edges: [] };
42302         this._spatialEdges = { cached: false, edges: [] };
42303         this._imageChanged$.next(null);
42304         this._sequenceEdgesChanged$.next(this._sequenceEdges);
42305         this._spatialEdgesChanged$.next(this._spatialEdges);
42306         this._disposed = true;
42307         if (this._imageRequest != null) {
42308             this._imageRequest.abort();
42309         }
42310         if (this._meshRequest != null) {
42311             this._meshRequest.abort();
42312         }
42313     };
42314     /**
42315      * Reset the sequence edges.
42316      */
42317     NodeCache.prototype.resetSequenceEdges = function () {
42318         this._sequenceEdges = { cached: false, edges: [] };
42319         this._sequenceEdgesChanged$.next(this._sequenceEdges);
42320     };
42321     /**
42322      * Reset the spatial edges.
42323      */
42324     NodeCache.prototype.resetSpatialEdges = function () {
42325         this._spatialEdges = { cached: false, edges: [] };
42326         this._spatialEdgesChanged$.next(this._spatialEdges);
42327     };
42328     /**
42329      * Cache the image.
42330      *
42331      * @param {string} key - Key of the node to cache.
42332      * @param {boolean} pano - Value indicating whether node is a panorama.
42333      * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
42334      * emitting a load status object every time the load status changes
42335      * and completes when the image is fully loaded.
42336      */
42337     NodeCache.prototype._cacheImage$ = function (key, imageSize) {
42338         var _this = this;
42339         return rxjs_1.Observable.create(function (subscriber) {
42340             var xmlHTTP = new XMLHttpRequest();
42341             xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize, Utils_1.Urls.origin), true);
42342             xmlHTTP.responseType = "arraybuffer";
42343             xmlHTTP.timeout = 15000;
42344             xmlHTTP.onload = function (pe) {
42345                 if (xmlHTTP.status !== 200) {
42346                     _this._imageRequest = null;
42347                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
42348                     return;
42349                 }
42350                 var image = new Image();
42351                 image.crossOrigin = "Anonymous";
42352                 image.onload = function (e) {
42353                     _this._imageRequest = null;
42354                     if (_this._disposed) {
42355                         window.URL.revokeObjectURL(image.src);
42356                         subscriber.error(new Error("Image load was aborted (" + key + ")"));
42357                         return;
42358                     }
42359                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
42360                     subscriber.complete();
42361                 };
42362                 image.onerror = function (error) {
42363                     _this._imageRequest = null;
42364                     subscriber.error(new Error("Failed to load image (" + key + ")"));
42365                 };
42366                 var blob = new Blob([xmlHTTP.response]);
42367                 image.src = window.URL.createObjectURL(blob);
42368             };
42369             xmlHTTP.onprogress = function (pe) {
42370                 if (_this._disposed) {
42371                     return;
42372                 }
42373                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
42374             };
42375             xmlHTTP.onerror = function (error) {
42376                 _this._imageRequest = null;
42377                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
42378             };
42379             xmlHTTP.ontimeout = function (e) {
42380                 _this._imageRequest = null;
42381                 subscriber.error(new Error("Image request timed out (" + key + ")"));
42382             };
42383             xmlHTTP.onabort = function (event) {
42384                 _this._imageRequest = null;
42385                 subscriber.error(new Error("Image request was aborted (" + key + ")"));
42386             };
42387             _this._imageRequest = xmlHTTP;
42388             xmlHTTP.send(null);
42389         });
42390     };
42391     /**
42392      * Cache the mesh.
42393      *
42394      * @param {string} key - Key of the node to cache.
42395      * @param {boolean} merged - Value indicating whether node is merged.
42396      * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
42397      * a load status object every time the load status changes and completes
42398      * when the mesh is fully loaded.
42399      */
42400     NodeCache.prototype._cacheMesh$ = function (key, merged) {
42401         var _this = this;
42402         return rxjs_1.Observable.create(function (subscriber) {
42403             if (!merged) {
42404                 subscriber.next(_this._createEmptyMeshLoadStatus());
42405                 subscriber.complete();
42406                 return;
42407             }
42408             var xmlHTTP = new XMLHttpRequest();
42409             xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
42410             xmlHTTP.responseType = "arraybuffer";
42411             xmlHTTP.timeout = 15000;
42412             xmlHTTP.onload = function (pe) {
42413                 _this._meshRequest = null;
42414                 if (_this._disposed) {
42415                     return;
42416                 }
42417                 var mesh = xmlHTTP.status === 200 ?
42418                     Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
42419                     { faces: [], vertices: [] };
42420                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
42421                 subscriber.complete();
42422             };
42423             xmlHTTP.onprogress = function (pe) {
42424                 if (_this._disposed) {
42425                     return;
42426                 }
42427                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
42428             };
42429             xmlHTTP.onerror = function (e) {
42430                 _this._meshRequest = null;
42431                 console.error("Failed to cache mesh (" + key + ")");
42432                 subscriber.next(_this._createEmptyMeshLoadStatus());
42433                 subscriber.complete();
42434             };
42435             xmlHTTP.ontimeout = function (e) {
42436                 _this._meshRequest = null;
42437                 console.error("Mesh request timed out (" + key + ")");
42438                 subscriber.next(_this._createEmptyMeshLoadStatus());
42439                 subscriber.complete();
42440             };
42441             xmlHTTP.onabort = function (e) {
42442                 _this._meshRequest = null;
42443                 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
42444             };
42445             _this._meshRequest = xmlHTTP;
42446             xmlHTTP.send(null);
42447         });
42448     };
42449     /**
42450      * Create a load status object with an empty mesh.
42451      *
42452      * @returns {ILoadStatusObject<IMesh>} Load status object
42453      * with empty mesh.
42454      */
42455     NodeCache.prototype._createEmptyMeshLoadStatus = function () {
42456         return {
42457             loaded: { loaded: 0, total: 0 },
42458             object: { faces: [], vertices: [] },
42459         };
42460     };
42461     NodeCache.prototype._disposeImage = function () {
42462         if (this._image != null) {
42463             window.URL.revokeObjectURL(this._image.src);
42464         }
42465         this._image = null;
42466     };
42467     return NodeCache;
42468 }());
42469 exports.NodeCache = NodeCache;
42470 exports.default = NodeCache;
42471
42472 }).call(this,require("buffer").Buffer)
42473
42474 },{"../Graph":279,"../Utils":285,"buffer":7,"rxjs":27,"rxjs/operators":225}],399:[function(require,module,exports){
42475 "use strict";
42476 Object.defineProperty(exports, "__esModule", { value: true });
42477 /**
42478  * @class Sequence
42479  *
42480  * @classdesc Represents a sequence of ordered nodes.
42481  */
42482 var Sequence = /** @class */ (function () {
42483     /**
42484      * Create a new sequene instance.
42485      *
42486      * @param {ISequence} sequence - Raw sequence data.
42487      */
42488     function Sequence(sequence) {
42489         this._key = sequence.key;
42490         this._keys = sequence.keys;
42491     }
42492     Object.defineProperty(Sequence.prototype, "key", {
42493         /**
42494          * Get key.
42495          *
42496          * @returns {string} Unique sequence key.
42497          */
42498         get: function () {
42499             return this._key;
42500         },
42501         enumerable: true,
42502         configurable: true
42503     });
42504     Object.defineProperty(Sequence.prototype, "keys", {
42505         /**
42506          * Get keys.
42507          *
42508          * @returns {Array<string>} Array of ordered node keys in the sequence.
42509          */
42510         get: function () {
42511             return this._keys;
42512         },
42513         enumerable: true,
42514         configurable: true
42515     });
42516     /**
42517      * Dispose the sequence.
42518      *
42519      * @description Disposes all cached assets.
42520      */
42521     Sequence.prototype.dispose = function () {
42522         this._key = null;
42523         this._keys = null;
42524     };
42525     /**
42526      * Find the next node key in the sequence with respect to
42527      * the provided node key.
42528      *
42529      * @param {string} key - Reference node key.
42530      * @returns {string} Next key in sequence if it exists, null otherwise.
42531      */
42532     Sequence.prototype.findNextKey = function (key) {
42533         var i = this._keys.indexOf(key);
42534         if ((i + 1) >= this._keys.length || i === -1) {
42535             return null;
42536         }
42537         else {
42538             return this._keys[i + 1];
42539         }
42540     };
42541     /**
42542      * Find the previous node key in the sequence with respect to
42543      * the provided node key.
42544      *
42545      * @param {string} key - Reference node key.
42546      * @returns {string} Previous key in sequence if it exists, null otherwise.
42547      */
42548     Sequence.prototype.findPrevKey = function (key) {
42549         var i = this._keys.indexOf(key);
42550         if (i === 0 || i === -1) {
42551             return null;
42552         }
42553         else {
42554             return this._keys[i - 1];
42555         }
42556     };
42557     return Sequence;
42558 }());
42559 exports.Sequence = Sequence;
42560 exports.default = Sequence;
42561
42562 },{}],400:[function(require,module,exports){
42563 "use strict";
42564 Object.defineProperty(exports, "__esModule", { value: true });
42565 var THREE = require("three");
42566 var Edge_1 = require("../../Edge");
42567 var Error_1 = require("../../Error");
42568 var Geo_1 = require("../../Geo");
42569 /**
42570  * @class EdgeCalculator
42571  *
42572  * @classdesc Represents a class for calculating node edges.
42573  */
42574 var EdgeCalculator = /** @class */ (function () {
42575     /**
42576      * Create a new edge calculator instance.
42577      *
42578      * @param {EdgeCalculatorSettings} settings - Settings struct.
42579      * @param {EdgeCalculatorDirections} directions - Directions struct.
42580      * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
42581      */
42582     function EdgeCalculator(settings, directions, coefficients) {
42583         this._spatial = new Geo_1.Spatial();
42584         this._geoCoords = new Geo_1.GeoCoords();
42585         this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
42586         this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
42587         this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
42588     }
42589     /**
42590      * Returns the potential edges to destination nodes for a set
42591      * of nodes with respect to a source node.
42592      *
42593      * @param {Node} node - Source node.
42594      * @param {Array<Node>} nodes - Potential destination nodes.
42595      * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
42596      * be returned even if they do not meet the criteria for a potential edge.
42597      * @throws {ArgumentMapillaryError} If node is not full.
42598      */
42599     EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
42600         if (!node.full) {
42601             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
42602         }
42603         if (!node.merged) {
42604             return [];
42605         }
42606         var currentDirection = this._spatial.viewingDirection(node.rotation);
42607         var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
42608         var potentialEdges = [];
42609         for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
42610             var potential = potentialNodes_1[_i];
42611             if (!potential.merged ||
42612                 potential.key === node.key) {
42613                 continue;
42614             }
42615             var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
42616             var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
42617             var distance = motion.length();
42618             if (distance > this._settings.maxDistance &&
42619                 fallbackKeys.indexOf(potential.key) < 0) {
42620                 continue;
42621             }
42622             var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
42623             var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
42624             var direction = this._spatial.viewingDirection(potential.rotation);
42625             var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
42626             var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
42627             var verticalDirectionChange = verticalDirection - currentVerticalDirection;
42628             var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
42629             var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
42630             var sameSequence = potential.sequenceKey != null &&
42631                 node.sequenceKey != null &&
42632                 potential.sequenceKey === node.sequenceKey;
42633             var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
42634                 potential.mergeCC === node.mergeCC;
42635             var sameUser = potential.userKey === node.userKey;
42636             var potentialEdge = {
42637                 capturedAt: potential.capturedAt,
42638                 croppedPano: potential.pano && !potential.fullPano,
42639                 directionChange: directionChange,
42640                 distance: distance,
42641                 fullPano: potential.fullPano,
42642                 key: potential.key,
42643                 motionChange: motionChange,
42644                 rotation: rotation,
42645                 sameMergeCC: sameMergeCC,
42646                 sameSequence: sameSequence,
42647                 sameUser: sameUser,
42648                 sequenceKey: potential.sequenceKey,
42649                 verticalDirectionChange: verticalDirectionChange,
42650                 verticalMotion: verticalMotion,
42651                 worldMotionAzimuth: worldMotionAzimuth,
42652             };
42653             potentialEdges.push(potentialEdge);
42654         }
42655         return potentialEdges;
42656     };
42657     /**
42658      * Computes the sequence edges for a node.
42659      *
42660      * @param {Node} node - Source node.
42661      * @throws {ArgumentMapillaryError} If node is not full.
42662      */
42663     EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
42664         if (!node.full) {
42665             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
42666         }
42667         if (node.sequenceKey !== sequence.key) {
42668             throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
42669         }
42670         var edges = [];
42671         var nextKey = sequence.findNextKey(node.key);
42672         if (nextKey != null) {
42673             edges.push({
42674                 data: {
42675                     direction: Edge_1.EdgeDirection.Next,
42676                     worldMotionAzimuth: Number.NaN,
42677                 },
42678                 from: node.key,
42679                 to: nextKey,
42680             });
42681         }
42682         var prevKey = sequence.findPrevKey(node.key);
42683         if (prevKey != null) {
42684             edges.push({
42685                 data: {
42686                     direction: Edge_1.EdgeDirection.Prev,
42687                     worldMotionAzimuth: Number.NaN,
42688                 },
42689                 from: node.key,
42690                 to: prevKey,
42691             });
42692         }
42693         return edges;
42694     };
42695     /**
42696      * Computes the similar edges for a node.
42697      *
42698      * @description Similar edges for perspective images and cropped panoramas
42699      * look roughly in the same direction and are positioned closed to the node.
42700      * Similar edges for full panoramas only target other full panoramas.
42701      *
42702      * @param {Node} node - Source node.
42703      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
42704      * @throws {ArgumentMapillaryError} If node is not full.
42705      */
42706     EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
42707         var _this = this;
42708         if (!node.full) {
42709             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
42710         }
42711         var nodeFullPano = node.fullPano;
42712         var sequenceGroups = {};
42713         for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
42714             var potentialEdge = potentialEdges_1[_i];
42715             if (potentialEdge.sequenceKey == null) {
42716                 continue;
42717             }
42718             if (potentialEdge.sameSequence) {
42719                 continue;
42720             }
42721             if (nodeFullPano) {
42722                 if (!potentialEdge.fullPano) {
42723                     continue;
42724                 }
42725             }
42726             else {
42727                 if (!potentialEdge.fullPano &&
42728                     Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
42729                     continue;
42730                 }
42731             }
42732             if (potentialEdge.distance > this._settings.similarMaxDistance) {
42733                 continue;
42734             }
42735             if (potentialEdge.sameUser &&
42736                 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
42737                     this._settings.similarMinTimeDifference) {
42738                 continue;
42739             }
42740             if (sequenceGroups[potentialEdge.sequenceKey] == null) {
42741                 sequenceGroups[potentialEdge.sequenceKey] = [];
42742             }
42743             sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
42744         }
42745         var similarEdges = [];
42746         var calculateScore = node.fullPano ?
42747             function (potentialEdge) {
42748                 return potentialEdge.distance;
42749             } :
42750             function (potentialEdge) {
42751                 return _this._coefficients.similarDistance * potentialEdge.distance +
42752                     _this._coefficients.similarRotation * potentialEdge.rotation;
42753             };
42754         for (var sequenceKey in sequenceGroups) {
42755             if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
42756                 continue;
42757             }
42758             var lowestScore = Number.MAX_VALUE;
42759             var similarEdge = null;
42760             for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
42761                 var potentialEdge = _b[_a];
42762                 var score = calculateScore(potentialEdge);
42763                 if (score < lowestScore) {
42764                     lowestScore = score;
42765                     similarEdge = potentialEdge;
42766                 }
42767             }
42768             if (similarEdge == null) {
42769                 continue;
42770             }
42771             similarEdges.push(similarEdge);
42772         }
42773         return similarEdges
42774             .map(function (potentialEdge) {
42775             return {
42776                 data: {
42777                     direction: Edge_1.EdgeDirection.Similar,
42778                     worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
42779                 },
42780                 from: node.key,
42781                 to: potentialEdge.key,
42782             };
42783         });
42784     };
42785     /**
42786      * Computes the step edges for a perspective node.
42787      *
42788      * @description Step edge targets can only be other perspective nodes.
42789      * Returns an empty array for cropped and full panoramas.
42790      *
42791      * @param {Node} node - Source node.
42792      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
42793      * @param {string} prevKey - Key of previous node in sequence.
42794      * @param {string} prevKey - Key of next node in sequence.
42795      * @throws {ArgumentMapillaryError} If node is not full.
42796      */
42797     EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
42798         if (!node.full) {
42799             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
42800         }
42801         var edges = [];
42802         if (node.pano) {
42803             return edges;
42804         }
42805         for (var k in this._directions.steps) {
42806             if (!this._directions.steps.hasOwnProperty(k)) {
42807                 continue;
42808             }
42809             var step = this._directions.steps[k];
42810             var lowestScore = Number.MAX_VALUE;
42811             var edge = null;
42812             var fallback = null;
42813             for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
42814                 var potential = potentialEdges_2[_i];
42815                 if (potential.croppedPano || potential.fullPano) {
42816                     continue;
42817                 }
42818                 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
42819                     continue;
42820                 }
42821                 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
42822                 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
42823                 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
42824                 if (Math.abs(drift) > this._settings.stepMaxDrift) {
42825                     continue;
42826                 }
42827                 var potentialKey = potential.key;
42828                 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
42829                     fallback = potential;
42830                 }
42831                 if (potential.distance > this._settings.stepMaxDistance) {
42832                     continue;
42833                 }
42834                 motionDifference = Math.sqrt(motionDifference * motionDifference +
42835                     potential.verticalMotion * potential.verticalMotion);
42836                 var score = this._coefficients.stepPreferredDistance *
42837                     Math.abs(potential.distance - this._settings.stepPreferredDistance) /
42838                     this._settings.stepMaxDistance +
42839                     this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
42840                     this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
42841                     this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
42842                     this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
42843                 if (score < lowestScore) {
42844                     lowestScore = score;
42845                     edge = potential;
42846                 }
42847             }
42848             edge = edge == null ? fallback : edge;
42849             if (edge != null) {
42850                 edges.push({
42851                     data: {
42852                         direction: step.direction,
42853                         worldMotionAzimuth: edge.worldMotionAzimuth,
42854                     },
42855                     from: node.key,
42856                     to: edge.key,
42857                 });
42858             }
42859         }
42860         return edges;
42861     };
42862     /**
42863      * Computes the turn edges for a perspective node.
42864      *
42865      * @description Turn edge targets can only be other perspective images.
42866      * Returns an empty array for cropped and full panoramas.
42867      *
42868      * @param {Node} node - Source node.
42869      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
42870      * @throws {ArgumentMapillaryError} If node is not full.
42871      */
42872     EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
42873         if (!node.full) {
42874             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
42875         }
42876         var edges = [];
42877         if (node.pano) {
42878             return edges;
42879         }
42880         for (var k in this._directions.turns) {
42881             if (!this._directions.turns.hasOwnProperty(k)) {
42882                 continue;
42883             }
42884             var turn = this._directions.turns[k];
42885             var lowestScore = Number.MAX_VALUE;
42886             var edge = null;
42887             for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
42888                 var potential = potentialEdges_3[_i];
42889                 if (potential.croppedPano || potential.fullPano) {
42890                     continue;
42891                 }
42892                 if (potential.distance > this._settings.turnMaxDistance) {
42893                     continue;
42894                 }
42895                 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
42896                     potential.distance < this._settings.turnMaxRigDistance &&
42897                     Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
42898                 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
42899                 var score = void 0;
42900                 if (rig &&
42901                     potential.directionChange * turn.directionChange > 0 &&
42902                     Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
42903                     score = -Math.PI / 2 + Math.abs(potential.directionChange);
42904                 }
42905                 else {
42906                     if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
42907                         continue;
42908                     }
42909                     var motionDifference = turn.motionChange ?
42910                         this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
42911                     motionDifference = Math.sqrt(motionDifference * motionDifference +
42912                         potential.verticalMotion * potential.verticalMotion);
42913                     score =
42914                         this._coefficients.turnDistance * potential.distance /
42915                             this._settings.turnMaxDistance +
42916                             this._coefficients.turnMotion * motionDifference / Math.PI +
42917                             this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
42918                             this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
42919                 }
42920                 if (score < lowestScore) {
42921                     lowestScore = score;
42922                     edge = potential;
42923                 }
42924             }
42925             if (edge != null) {
42926                 edges.push({
42927                     data: {
42928                         direction: turn.direction,
42929                         worldMotionAzimuth: edge.worldMotionAzimuth,
42930                     },
42931                     from: node.key,
42932                     to: edge.key,
42933                 });
42934             }
42935         }
42936         return edges;
42937     };
42938     /**
42939      * Computes the pano edges for a perspective node.
42940      *
42941      * @description Perspective to pano edge targets can only be
42942      * full pano nodes. Returns an empty array for cropped and full panoramas.
42943      *
42944      * @param {Node} node - Source node.
42945      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
42946      * @throws {ArgumentMapillaryError} If node is not full.
42947      */
42948     EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
42949         if (!node.full) {
42950             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
42951         }
42952         if (node.pano) {
42953             return [];
42954         }
42955         var lowestScore = Number.MAX_VALUE;
42956         var edge = null;
42957         for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
42958             var potential = potentialEdges_4[_i];
42959             if (!potential.fullPano) {
42960                 continue;
42961             }
42962             var score = this._coefficients.panoPreferredDistance *
42963                 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
42964                 this._settings.panoMaxDistance +
42965                 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
42966                 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
42967             if (score < lowestScore) {
42968                 lowestScore = score;
42969                 edge = potential;
42970             }
42971         }
42972         if (edge == null) {
42973             return [];
42974         }
42975         return [
42976             {
42977                 data: {
42978                     direction: Edge_1.EdgeDirection.Pano,
42979                     worldMotionAzimuth: edge.worldMotionAzimuth,
42980                 },
42981                 from: node.key,
42982                 to: edge.key,
42983             },
42984         ];
42985     };
42986     /**
42987      * Computes the full pano and step edges for a full pano node.
42988      *
42989      * @description Pano to pano edge targets can only be
42990      * full pano nodes. Pano to step edge targets can only be perspective
42991      * nodes.
42992      * Returns an empty array for cropped panoramas and perspective nodes.
42993      *
42994      * @param {Node} node - Source node.
42995      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
42996      * @throws {ArgumentMapillaryError} If node is not full.
42997      */
42998     EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
42999         if (!node.full) {
43000             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
43001         }
43002         if (!node.fullPano) {
43003             return [];
43004         }
43005         var panoEdges = [];
43006         var potentialPanos = [];
43007         var potentialSteps = [];
43008         for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
43009             var potential = potentialEdges_5[_i];
43010             if (potential.distance > this._settings.panoMaxDistance) {
43011                 continue;
43012             }
43013             if (potential.fullPano) {
43014                 if (potential.distance < this._settings.panoMinDistance) {
43015                     continue;
43016                 }
43017                 potentialPanos.push(potential);
43018             }
43019             else {
43020                 if (potential.croppedPano) {
43021                     continue;
43022                 }
43023                 for (var k in this._directions.panos) {
43024                     if (!this._directions.panos.hasOwnProperty(k)) {
43025                         continue;
43026                     }
43027                     var pano = this._directions.panos[k];
43028                     var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
43029                     var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
43030                     if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
43031                         continue;
43032                     }
43033                     potentialSteps.push([pano.direction, potential]);
43034                     // break if step direction found
43035                     break;
43036                 }
43037             }
43038         }
43039         var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
43040         var occupiedAngles = [];
43041         var stepAngles = [];
43042         for (var index = 0; index < this._settings.panoMaxItems; index++) {
43043             var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
43044             var lowestScore = Number.MAX_VALUE;
43045             var edge = null;
43046             for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
43047                 var potential = potentialPanos_1[_a];
43048                 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
43049                 if (Math.abs(motionDifference) > maxRotationDifference) {
43050                     continue;
43051                 }
43052                 var occupiedDifference = Number.MAX_VALUE;
43053                 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
43054                     var occupiedAngle = occupiedAngles_1[_b];
43055                     var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
43056                     if (difference < occupiedDifference) {
43057                         occupiedDifference = difference;
43058                     }
43059                 }
43060                 if (occupiedDifference <= maxRotationDifference) {
43061                     continue;
43062                 }
43063                 var score = this._coefficients.panoPreferredDistance *
43064                     Math.abs(potential.distance - this._settings.panoPreferredDistance) /
43065                     this._settings.panoMaxDistance +
43066                     this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
43067                     this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
43068                     this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
43069                 if (score < lowestScore) {
43070                     lowestScore = score;
43071                     edge = potential;
43072                 }
43073             }
43074             if (edge != null) {
43075                 occupiedAngles.push(edge.motionChange);
43076                 panoEdges.push({
43077                     data: {
43078                         direction: Edge_1.EdgeDirection.Pano,
43079                         worldMotionAzimuth: edge.worldMotionAzimuth,
43080                     },
43081                     from: node.key,
43082                     to: edge.key,
43083                 });
43084             }
43085             else {
43086                 stepAngles.push(rotation);
43087             }
43088         }
43089         var occupiedStepAngles = {};
43090         occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
43091         occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
43092         occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
43093         occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
43094         occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
43095         for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
43096             var stepAngle = stepAngles_1[_c];
43097             var occupations = [];
43098             for (var k in this._directions.panos) {
43099                 if (!this._directions.panos.hasOwnProperty(k)) {
43100                     continue;
43101                 }
43102                 var pano = this._directions.panos[k];
43103                 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
43104                     .concat(occupiedStepAngles[pano.direction])
43105                     .concat(occupiedStepAngles[pano.prev])
43106                     .concat(occupiedStepAngles[pano.next]);
43107                 var lowestScore = Number.MAX_VALUE;
43108                 var edge = null;
43109                 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
43110                     var potential = potentialSteps_1[_d];
43111                     if (potential[0] !== pano.direction) {
43112                         continue;
43113                     }
43114                     var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
43115                     if (Math.abs(motionChange) > maxRotationDifference) {
43116                         continue;
43117                     }
43118                     var minOccupiedDifference = Number.MAX_VALUE;
43119                     for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
43120                         var occupiedAngle = allOccupiedAngles_1[_e];
43121                         var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
43122                         if (occupiedDifference < minOccupiedDifference) {
43123                             minOccupiedDifference = occupiedDifference;
43124                         }
43125                     }
43126                     if (minOccupiedDifference <= maxRotationDifference) {
43127                         continue;
43128                     }
43129                     var score = this._coefficients.panoPreferredDistance *
43130                         Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
43131                         this._settings.panoMaxDistance +
43132                         this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
43133                         this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
43134                     if (score < lowestScore) {
43135                         lowestScore = score;
43136                         edge = potential;
43137                     }
43138                 }
43139                 if (edge != null) {
43140                     occupations.push(edge);
43141                     panoEdges.push({
43142                         data: {
43143                             direction: edge[0],
43144                             worldMotionAzimuth: edge[1].worldMotionAzimuth,
43145                         },
43146                         from: node.key,
43147                         to: edge[1].key,
43148                     });
43149                 }
43150             }
43151             for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
43152                 var occupation = occupations_1[_f];
43153                 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
43154             }
43155         }
43156         return panoEdges;
43157     };
43158     return EdgeCalculator;
43159 }());
43160 exports.EdgeCalculator = EdgeCalculator;
43161 exports.default = EdgeCalculator;
43162
43163 },{"../../Edge":276,"../../Error":277,"../../Geo":278,"three":226}],401:[function(require,module,exports){
43164 "use strict";
43165 Object.defineProperty(exports, "__esModule", { value: true });
43166 var EdgeCalculatorCoefficients = /** @class */ (function () {
43167     function EdgeCalculatorCoefficients() {
43168         this.panoPreferredDistance = 2;
43169         this.panoMotion = 2;
43170         this.panoSequencePenalty = 1;
43171         this.panoMergeCCPenalty = 4;
43172         this.stepPreferredDistance = 4;
43173         this.stepMotion = 3;
43174         this.stepRotation = 4;
43175         this.stepSequencePenalty = 2;
43176         this.stepMergeCCPenalty = 6;
43177         this.similarDistance = 2;
43178         this.similarRotation = 3;
43179         this.turnDistance = 4;
43180         this.turnMotion = 2;
43181         this.turnSequencePenalty = 1;
43182         this.turnMergeCCPenalty = 4;
43183     }
43184     return EdgeCalculatorCoefficients;
43185 }());
43186 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
43187 exports.default = EdgeCalculatorCoefficients;
43188
43189 },{}],402:[function(require,module,exports){
43190 "use strict";
43191 Object.defineProperty(exports, "__esModule", { value: true });
43192 var Edge_1 = require("../../Edge");
43193 var EdgeCalculatorDirections = /** @class */ (function () {
43194     function EdgeCalculatorDirections() {
43195         this.steps = {};
43196         this.turns = {};
43197         this.panos = {};
43198         this.steps[Edge_1.EdgeDirection.StepForward] = {
43199             direction: Edge_1.EdgeDirection.StepForward,
43200             motionChange: 0,
43201             useFallback: true,
43202         };
43203         this.steps[Edge_1.EdgeDirection.StepBackward] = {
43204             direction: Edge_1.EdgeDirection.StepBackward,
43205             motionChange: Math.PI,
43206             useFallback: true,
43207         };
43208         this.steps[Edge_1.EdgeDirection.StepLeft] = {
43209             direction: Edge_1.EdgeDirection.StepLeft,
43210             motionChange: Math.PI / 2,
43211             useFallback: false,
43212         };
43213         this.steps[Edge_1.EdgeDirection.StepRight] = {
43214             direction: Edge_1.EdgeDirection.StepRight,
43215             motionChange: -Math.PI / 2,
43216             useFallback: false,
43217         };
43218         this.turns[Edge_1.EdgeDirection.TurnLeft] = {
43219             direction: Edge_1.EdgeDirection.TurnLeft,
43220             directionChange: Math.PI / 2,
43221             motionChange: Math.PI / 4,
43222         };
43223         this.turns[Edge_1.EdgeDirection.TurnRight] = {
43224             direction: Edge_1.EdgeDirection.TurnRight,
43225             directionChange: -Math.PI / 2,
43226             motionChange: -Math.PI / 4,
43227         };
43228         this.turns[Edge_1.EdgeDirection.TurnU] = {
43229             direction: Edge_1.EdgeDirection.TurnU,
43230             directionChange: Math.PI,
43231             motionChange: null,
43232         };
43233         this.panos[Edge_1.EdgeDirection.StepForward] = {
43234             direction: Edge_1.EdgeDirection.StepForward,
43235             directionChange: 0,
43236             next: Edge_1.EdgeDirection.StepLeft,
43237             prev: Edge_1.EdgeDirection.StepRight,
43238         };
43239         this.panos[Edge_1.EdgeDirection.StepBackward] = {
43240             direction: Edge_1.EdgeDirection.StepBackward,
43241             directionChange: Math.PI,
43242             next: Edge_1.EdgeDirection.StepRight,
43243             prev: Edge_1.EdgeDirection.StepLeft,
43244         };
43245         this.panos[Edge_1.EdgeDirection.StepLeft] = {
43246             direction: Edge_1.EdgeDirection.StepLeft,
43247             directionChange: Math.PI / 2,
43248             next: Edge_1.EdgeDirection.StepBackward,
43249             prev: Edge_1.EdgeDirection.StepForward,
43250         };
43251         this.panos[Edge_1.EdgeDirection.StepRight] = {
43252             direction: Edge_1.EdgeDirection.StepRight,
43253             directionChange: -Math.PI / 2,
43254             next: Edge_1.EdgeDirection.StepForward,
43255             prev: Edge_1.EdgeDirection.StepBackward,
43256         };
43257     }
43258     return EdgeCalculatorDirections;
43259 }());
43260 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
43261
43262 },{"../../Edge":276}],403:[function(require,module,exports){
43263 "use strict";
43264 Object.defineProperty(exports, "__esModule", { value: true });
43265 var EdgeCalculatorSettings = /** @class */ (function () {
43266     function EdgeCalculatorSettings() {
43267         this.panoMinDistance = 0.1;
43268         this.panoMaxDistance = 20;
43269         this.panoPreferredDistance = 5;
43270         this.panoMaxItems = 4;
43271         this.panoMaxStepTurnChange = Math.PI / 8;
43272         this.rotationMaxDistance = this.turnMaxRigDistance;
43273         this.rotationMaxDirectionChange = Math.PI / 6;
43274         this.rotationMaxVerticalDirectionChange = Math.PI / 8;
43275         this.similarMaxDirectionChange = Math.PI / 8;
43276         this.similarMaxDistance = 12;
43277         this.similarMinTimeDifference = 12 * 3600 * 1000;
43278         this.stepMaxDistance = 20;
43279         this.stepMaxDirectionChange = Math.PI / 6;
43280         this.stepMaxDrift = Math.PI / 6;
43281         this.stepPreferredDistance = 4;
43282         this.turnMaxDistance = 15;
43283         this.turnMaxDirectionChange = 2 * Math.PI / 9;
43284         this.turnMaxRigDistance = 0.65;
43285         this.turnMinRigDirectionChange = Math.PI / 6;
43286     }
43287     Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
43288         get: function () {
43289             return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
43290         },
43291         enumerable: true,
43292         configurable: true
43293     });
43294     return EdgeCalculatorSettings;
43295 }());
43296 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
43297 exports.default = EdgeCalculatorSettings;
43298
43299 },{}],404:[function(require,module,exports){
43300 "use strict";
43301 Object.defineProperty(exports, "__esModule", { value: true });
43302 /**
43303  * Enumeration for edge directions
43304  * @enum {number}
43305  * @readonly
43306  * @description Directions for edges in node graph describing
43307  * sequence, spatial and node type relations between nodes.
43308  */
43309 var EdgeDirection;
43310 (function (EdgeDirection) {
43311     /**
43312      * Next node in the sequence.
43313      */
43314     EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
43315     /**
43316      * Previous node in the sequence.
43317      */
43318     EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
43319     /**
43320      * Step to the left keeping viewing direction.
43321      */
43322     EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
43323     /**
43324      * Step to the right keeping viewing direction.
43325      */
43326     EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
43327     /**
43328      * Step forward keeping viewing direction.
43329      */
43330     EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
43331     /**
43332      * Step backward keeping viewing direction.
43333      */
43334     EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
43335     /**
43336      * Turn 90 degrees counter clockwise.
43337      */
43338     EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
43339     /**
43340      * Turn 90 degrees clockwise.
43341      */
43342     EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
43343     /**
43344      * Turn 180 degrees.
43345      */
43346     EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
43347     /**
43348      * Panorama in general direction.
43349      */
43350     EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
43351     /**
43352      * Looking in roughly the same direction at rougly the same position.
43353      */
43354     EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
43355 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
43356
43357 },{}],405:[function(require,module,exports){
43358 "use strict";
43359 Object.defineProperty(exports, "__esModule", { value: true });
43360 var rxjs_1 = require("rxjs");
43361 var operators_1 = require("rxjs/operators");
43362 var vd = require("virtual-dom");
43363 var rxjs_2 = require("rxjs");
43364 var Render_1 = require("../Render");
43365 var DOMRenderer = /** @class */ (function () {
43366     function DOMRenderer(element, renderService, currentFrame$) {
43367         this._adaptiveOperation$ = new rxjs_2.Subject();
43368         this._render$ = new rxjs_2.Subject();
43369         this._renderAdaptive$ = new rxjs_2.Subject();
43370         this._renderService = renderService;
43371         this._currentFrame$ = currentFrame$;
43372         var rootNode = vd.create(vd.h("div.domRenderer", []));
43373         element.appendChild(rootNode);
43374         this._offset$ = this._adaptiveOperation$.pipe(operators_1.scan(function (adaptive, operation) {
43375             return operation(adaptive);
43376         }, {
43377             elementHeight: element.offsetHeight,
43378             elementWidth: element.offsetWidth,
43379             imageAspect: 0,
43380             renderMode: Render_1.RenderMode.Fill,
43381         }), operators_1.filter(function (adaptive) {
43382             return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
43383         }), operators_1.map(function (adaptive) {
43384             var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
43385             var ratio = adaptive.imageAspect / elementAspect;
43386             var verticalOffset = 0;
43387             var horizontalOffset = 0;
43388             if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
43389                 if (adaptive.imageAspect > elementAspect) {
43390                     verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
43391                 }
43392                 else {
43393                     horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
43394                 }
43395             }
43396             else {
43397                 if (adaptive.imageAspect > elementAspect) {
43398                     horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
43399                 }
43400                 else {
43401                     verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
43402                 }
43403             }
43404             return {
43405                 bottom: verticalOffset,
43406                 left: horizontalOffset,
43407                 right: horizontalOffset,
43408                 top: verticalOffset,
43409             };
43410         }));
43411         this._currentFrame$.pipe(operators_1.filter(function (frame) {
43412             return frame.state.currentNode != null;
43413         }), operators_1.distinctUntilChanged(function (k1, k2) {
43414             return k1 === k2;
43415         }, function (frame) {
43416             return frame.state.currentNode.key;
43417         }), operators_1.map(function (frame) {
43418             return frame.state.currentTransform.basicAspect;
43419         }), operators_1.map(function (aspect) {
43420             return function (adaptive) {
43421                 adaptive.imageAspect = aspect;
43422                 return adaptive;
43423             };
43424         }))
43425             .subscribe(this._adaptiveOperation$);
43426         rxjs_1.combineLatest(this._renderAdaptive$.pipe(operators_1.scan(function (vNodeHashes, vNodeHash) {
43427             if (vNodeHash.vnode == null) {
43428                 delete vNodeHashes[vNodeHash.name];
43429             }
43430             else {
43431                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
43432             }
43433             return vNodeHashes;
43434         }, {})), this._offset$).pipe(operators_1.map(function (vo) {
43435             var vNodes = [];
43436             var hashes = vo[0];
43437             for (var name_1 in hashes) {
43438                 if (!hashes.hasOwnProperty(name_1)) {
43439                     continue;
43440                 }
43441                 vNodes.push(hashes[name_1]);
43442             }
43443             var offset = vo[1];
43444             var properties = {
43445                 style: {
43446                     bottom: offset.bottom + "px",
43447                     left: offset.left + "px",
43448                     "pointer-events": "none",
43449                     position: "absolute",
43450                     right: offset.right + "px",
43451                     top: offset.top + "px",
43452                 },
43453             };
43454             return {
43455                 name: "adaptiveDomRenderer",
43456                 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
43457             };
43458         }))
43459             .subscribe(this._render$);
43460         this._vNode$ = this._render$.pipe(operators_1.scan(function (vNodeHashes, vNodeHash) {
43461             if (vNodeHash.vnode == null) {
43462                 delete vNodeHashes[vNodeHash.name];
43463             }
43464             else {
43465                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
43466             }
43467             return vNodeHashes;
43468         }, {}), operators_1.map(function (hashes) {
43469             var vNodes = [];
43470             for (var name_2 in hashes) {
43471                 if (!hashes.hasOwnProperty(name_2)) {
43472                     continue;
43473                 }
43474                 vNodes.push(hashes[name_2]);
43475             }
43476             return vd.h("div.domRenderer", vNodes);
43477         }));
43478         this._vPatch$ = this._vNode$.pipe(operators_1.scan(function (nodePatch, vNode) {
43479             nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
43480             nodePatch.vnode = vNode;
43481             return nodePatch;
43482         }, { vnode: vd.h("div.domRenderer", []), vpatch: null }), operators_1.pluck("vpatch"));
43483         this._element$ = this._vPatch$.pipe(operators_1.scan(function (oldElement, vPatch) {
43484             return vd.patch(oldElement, vPatch);
43485         }, rootNode), operators_1.publishReplay(1), operators_1.refCount());
43486         this._element$.subscribe(function () { });
43487         this._renderService.size$.pipe(operators_1.map(function (size) {
43488             return function (adaptive) {
43489                 adaptive.elementWidth = size.width;
43490                 adaptive.elementHeight = size.height;
43491                 return adaptive;
43492             };
43493         }))
43494             .subscribe(this._adaptiveOperation$);
43495         this._renderService.renderMode$.pipe(operators_1.map(function (renderMode) {
43496             return function (adaptive) {
43497                 adaptive.renderMode = renderMode;
43498                 return adaptive;
43499             };
43500         }))
43501             .subscribe(this._adaptiveOperation$);
43502     }
43503     Object.defineProperty(DOMRenderer.prototype, "element$", {
43504         get: function () {
43505             return this._element$;
43506         },
43507         enumerable: true,
43508         configurable: true
43509     });
43510     Object.defineProperty(DOMRenderer.prototype, "render$", {
43511         get: function () {
43512             return this._render$;
43513         },
43514         enumerable: true,
43515         configurable: true
43516     });
43517     Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
43518         get: function () {
43519             return this._renderAdaptive$;
43520         },
43521         enumerable: true,
43522         configurable: true
43523     });
43524     DOMRenderer.prototype.clear = function (name) {
43525         this._renderAdaptive$.next({ name: name, vnode: null });
43526         this._render$.next({ name: name, vnode: null });
43527     };
43528     return DOMRenderer;
43529 }());
43530 exports.DOMRenderer = DOMRenderer;
43531 exports.default = DOMRenderer;
43532
43533
43534 },{"../Render":281,"rxjs":27,"rxjs/operators":225,"virtual-dom":231}],406:[function(require,module,exports){
43535 "use strict";
43536 Object.defineProperty(exports, "__esModule", { value: true });
43537 var GLRenderStage;
43538 (function (GLRenderStage) {
43539     GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
43540     GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
43541 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
43542 exports.default = GLRenderStage;
43543
43544 },{}],407:[function(require,module,exports){
43545 "use strict";
43546 Object.defineProperty(exports, "__esModule", { value: true });
43547 var rxjs_1 = require("rxjs");
43548 var operators_1 = require("rxjs/operators");
43549 var THREE = require("three");
43550 var Render_1 = require("../Render");
43551 var Utils_1 = require("../Utils");
43552 var GLRenderer = /** @class */ (function () {
43553     function GLRenderer(canvasContainer, renderService, dom) {
43554         var _this = this;
43555         this._renderFrame$ = new rxjs_1.Subject();
43556         this._renderCameraOperation$ = new rxjs_1.Subject();
43557         this._render$ = new rxjs_1.Subject();
43558         this._clear$ = new rxjs_1.Subject();
43559         this._renderOperation$ = new rxjs_1.Subject();
43560         this._rendererOperation$ = new rxjs_1.Subject();
43561         this._eraserOperation$ = new rxjs_1.Subject();
43562         this._renderService = renderService;
43563         this._dom = !!dom ? dom : new Utils_1.DOM();
43564         this._renderer$ = this._rendererOperation$.pipe(operators_1.scan(function (renderer, operation) {
43565             return operation(renderer);
43566         }, { needsRender: false, renderer: null }), operators_1.filter(function (renderer) {
43567             return !!renderer.renderer;
43568         }));
43569         this._renderCollection$ = this._renderOperation$.pipe(operators_1.scan(function (hashes, operation) {
43570             return operation(hashes);
43571         }, {}), operators_1.share());
43572         this._renderCamera$ = this._renderCameraOperation$.pipe(operators_1.scan(function (rc, operation) {
43573             return operation(rc);
43574         }, { frameId: -1, needsRender: false, perspective: null }));
43575         this._eraser$ = this._eraserOperation$.pipe(operators_1.startWith(function (eraser) {
43576             return eraser;
43577         }), operators_1.scan(function (eraser, operation) {
43578             return operation(eraser);
43579         }, { needsRender: false }));
43580         rxjs_1.combineLatest(this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$).pipe(operators_1.map(function (_a) {
43581             var renderer = _a[0], hashes = _a[1], rc = _a[2], eraser = _a[3];
43582             var renders = Object.keys(hashes)
43583                 .map(function (key) {
43584                 return hashes[key];
43585             });
43586             return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
43587         }), operators_1.filter(function (co) {
43588             var needsRender = co.renderer.needsRender ||
43589                 co.camera.needsRender ||
43590                 co.eraser.needsRender;
43591             var frameId = co.camera.frameId;
43592             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
43593                 var render = _a[_i];
43594                 if (render.frameId !== frameId) {
43595                     return false;
43596                 }
43597                 needsRender = needsRender || render.needsRender;
43598             }
43599             return needsRender;
43600         }), operators_1.distinctUntilChanged(function (n1, n2) {
43601             return n1 === n2;
43602         }, function (co) {
43603             return co.eraser.needsRender ? -1 : co.camera.frameId;
43604         }))
43605             .subscribe(function (co) {
43606             co.renderer.needsRender = false;
43607             co.camera.needsRender = false;
43608             co.eraser.needsRender = false;
43609             var perspectiveCamera = co.camera.perspective;
43610             var backgroundRenders = [];
43611             var foregroundRenders = [];
43612             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
43613                 var render = _a[_i];
43614                 if (render.stage === Render_1.GLRenderStage.Background) {
43615                     backgroundRenders.push(render.render);
43616                 }
43617                 else if (render.stage === Render_1.GLRenderStage.Foreground) {
43618                     foregroundRenders.push(render.render);
43619                 }
43620             }
43621             var renderer = co.renderer.renderer;
43622             renderer.clear();
43623             for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
43624                 var render = backgroundRenders_1[_b];
43625                 render(perspectiveCamera, renderer);
43626             }
43627             renderer.clearDepth();
43628             for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
43629                 var render = foregroundRenders_1[_c];
43630                 render(perspectiveCamera, renderer);
43631             }
43632         });
43633         this._renderFrame$.pipe(operators_1.map(function (rc) {
43634             return function (irc) {
43635                 irc.frameId = rc.frameId;
43636                 irc.perspective = rc.perspective;
43637                 if (rc.changed === true) {
43638                     irc.needsRender = true;
43639                 }
43640                 return irc;
43641             };
43642         }))
43643             .subscribe(this._renderCameraOperation$);
43644         this._renderFrameSubscribe();
43645         var renderHash$ = this._render$.pipe(operators_1.map(function (hash) {
43646             return function (hashes) {
43647                 hashes[hash.name] = hash.render;
43648                 return hashes;
43649             };
43650         }));
43651         var clearHash$ = this._clear$.pipe(operators_1.map(function (name) {
43652             return function (hashes) {
43653                 delete hashes[name];
43654                 return hashes;
43655             };
43656         }));
43657         rxjs_1.merge(renderHash$, clearHash$)
43658             .subscribe(this._renderOperation$);
43659         this._webGLRenderer$ = this._render$.pipe(operators_1.first(), operators_1.map(function (hash) {
43660             var canvas = _this._dom.createElement("canvas", "mapillary-js-canvas");
43661             canvas.style.position = "absolute";
43662             canvas.setAttribute("tabindex", "0");
43663             canvasContainer.appendChild(canvas);
43664             var element = renderService.element;
43665             var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas });
43666             webGLRenderer.setPixelRatio(window.devicePixelRatio);
43667             webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
43668             webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
43669             webGLRenderer.autoClear = false;
43670             return webGLRenderer;
43671         }), operators_1.publishReplay(1), operators_1.refCount());
43672         this._webGLRenderer$.subscribe(function () { });
43673         var createRenderer$ = this._webGLRenderer$.pipe(operators_1.first(), operators_1.map(function (webGLRenderer) {
43674             return function (renderer) {
43675                 renderer.needsRender = true;
43676                 renderer.renderer = webGLRenderer;
43677                 return renderer;
43678             };
43679         }));
43680         var resizeRenderer$ = this._renderService.size$.pipe(operators_1.map(function (size) {
43681             return function (renderer) {
43682                 if (renderer.renderer == null) {
43683                     return renderer;
43684                 }
43685                 renderer.renderer.setSize(size.width, size.height);
43686                 renderer.needsRender = true;
43687                 return renderer;
43688             };
43689         }));
43690         var clearRenderer$ = this._clear$.pipe(operators_1.map(function (name) {
43691             return function (renderer) {
43692                 if (renderer.renderer == null) {
43693                     return renderer;
43694                 }
43695                 renderer.needsRender = true;
43696                 return renderer;
43697             };
43698         }));
43699         rxjs_1.merge(createRenderer$, resizeRenderer$, clearRenderer$)
43700             .subscribe(this._rendererOperation$);
43701         var renderCollectionEmpty$ = this._renderCollection$.pipe(operators_1.filter(function (hashes) {
43702             return Object.keys(hashes).length === 0;
43703         }), operators_1.share());
43704         renderCollectionEmpty$
43705             .subscribe(function (hashes) {
43706             if (_this._renderFrameSubscription == null) {
43707                 return;
43708             }
43709             _this._renderFrameSubscription.unsubscribe();
43710             _this._renderFrameSubscription = null;
43711             _this._renderFrameSubscribe();
43712         });
43713         renderCollectionEmpty$.pipe(operators_1.map(function (hashes) {
43714             return function (eraser) {
43715                 eraser.needsRender = true;
43716                 return eraser;
43717             };
43718         }))
43719             .subscribe(this._eraserOperation$);
43720     }
43721     Object.defineProperty(GLRenderer.prototype, "render$", {
43722         get: function () {
43723             return this._render$;
43724         },
43725         enumerable: true,
43726         configurable: true
43727     });
43728     Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
43729         get: function () {
43730             return this._webGLRenderer$;
43731         },
43732         enumerable: true,
43733         configurable: true
43734     });
43735     GLRenderer.prototype.clear = function (name) {
43736         this._clear$.next(name);
43737     };
43738     GLRenderer.prototype._renderFrameSubscribe = function () {
43739         var _this = this;
43740         this._render$.pipe(operators_1.first(), operators_1.map(function (renderHash) {
43741             return function (irc) {
43742                 irc.needsRender = true;
43743                 return irc;
43744             };
43745         }))
43746             .subscribe(function (operation) {
43747             _this._renderCameraOperation$.next(operation);
43748         });
43749         this._renderFrameSubscription = this._render$.pipe(operators_1.first(), operators_1.mergeMap(function (hash) {
43750             return _this._renderService.renderCameraFrame$;
43751         }))
43752             .subscribe(this._renderFrame$);
43753     };
43754     return GLRenderer;
43755 }());
43756 exports.GLRenderer = GLRenderer;
43757 exports.default = GLRenderer;
43758
43759
43760 },{"../Render":281,"../Utils":285,"rxjs":27,"rxjs/operators":225,"three":226}],408:[function(require,module,exports){
43761 "use strict";
43762 Object.defineProperty(exports, "__esModule", { value: true });
43763 var THREE = require("three");
43764 var Geo_1 = require("../Geo");
43765 var Render_1 = require("../Render");
43766 var State_1 = require("../State");
43767 var RenderCamera = /** @class */ (function () {
43768     function RenderCamera(elementWidth, elementHeight, renderMode) {
43769         this._spatial = new Geo_1.Spatial();
43770         this._viewportCoords = new Geo_1.ViewportCoords();
43771         this._initialFov = 50;
43772         this._alpha = -1;
43773         this._renderMode = renderMode;
43774         this._zoom = 0;
43775         this._frameId = -1;
43776         this._changed = false;
43777         this._changedForFrame = -1;
43778         this._currentNodeId = null;
43779         this._previousNodeId = null;
43780         this._currentPano = false;
43781         this._previousPano = false;
43782         this._state = null;
43783         this._currentProjectedPoints = [];
43784         this._previousProjectedPoints = [];
43785         this._currentFov = this._initialFov;
43786         this._previousFov = this._initialFov;
43787         this._camera = new Geo_1.Camera();
43788         this._perspective = new THREE.PerspectiveCamera(this._initialFov, this._computeAspect(elementWidth, elementHeight), 0.16, 10000);
43789         this._perspective.matrixAutoUpdate = false;
43790         this._rotation = { phi: 0, theta: 0 };
43791     }
43792     Object.defineProperty(RenderCamera.prototype, "alpha", {
43793         get: function () {
43794             return this._alpha;
43795         },
43796         enumerable: true,
43797         configurable: true
43798     });
43799     Object.defineProperty(RenderCamera.prototype, "camera", {
43800         get: function () {
43801             return this._camera;
43802         },
43803         enumerable: true,
43804         configurable: true
43805     });
43806     Object.defineProperty(RenderCamera.prototype, "changed", {
43807         get: function () {
43808             return this._frameId === this._changedForFrame;
43809         },
43810         enumerable: true,
43811         configurable: true
43812     });
43813     Object.defineProperty(RenderCamera.prototype, "frameId", {
43814         get: function () {
43815             return this._frameId;
43816         },
43817         enumerable: true,
43818         configurable: true
43819     });
43820     Object.defineProperty(RenderCamera.prototype, "perspective", {
43821         get: function () {
43822             return this._perspective;
43823         },
43824         enumerable: true,
43825         configurable: true
43826     });
43827     Object.defineProperty(RenderCamera.prototype, "renderMode", {
43828         get: function () {
43829             return this._renderMode;
43830         },
43831         enumerable: true,
43832         configurable: true
43833     });
43834     Object.defineProperty(RenderCamera.prototype, "rotation", {
43835         get: function () {
43836             return this._rotation;
43837         },
43838         enumerable: true,
43839         configurable: true
43840     });
43841     Object.defineProperty(RenderCamera.prototype, "zoom", {
43842         get: function () {
43843             return this._zoom;
43844         },
43845         enumerable: true,
43846         configurable: true
43847     });
43848     RenderCamera.prototype.setFrame = function (frame) {
43849         var state = frame.state;
43850         if (state.state !== this._state) {
43851             this._state = state.state;
43852             this._changed = true;
43853         }
43854         var currentNodeId = state.currentNode.key;
43855         var previousNodeId = !!state.previousNode ? state.previousNode.key : null;
43856         if (currentNodeId !== this._currentNodeId) {
43857             this._currentNodeId = currentNodeId;
43858             this._currentPano = !!state.currentTransform.gpano;
43859             this._currentProjectedPoints = this._computeProjectedPoints(state.currentTransform);
43860             this._changed = true;
43861         }
43862         if (previousNodeId !== this._previousNodeId) {
43863             this._previousNodeId = previousNodeId;
43864             this._previousPano = !!state.previousTransform.gpano;
43865             this._previousProjectedPoints = this._computeProjectedPoints(state.previousTransform);
43866             this._changed = true;
43867         }
43868         var zoom = state.zoom;
43869         if (zoom !== this._zoom) {
43870             this._zoom = zoom;
43871             this._changed = true;
43872         }
43873         if (this._changed) {
43874             this._currentFov = this._computeCurrentFov();
43875             this._previousFov = this._computePreviousFov();
43876         }
43877         var alpha = state.alpha;
43878         if (this._changed || alpha !== this._alpha) {
43879             this._alpha = alpha;
43880             this._perspective.fov = this._state === State_1.State.Earth ?
43881                 60 :
43882                 this._interpolateFov(this._currentFov, this._previousFov, this._alpha);
43883             this._changed = true;
43884         }
43885         var camera = state.camera;
43886         if (this._camera.diff(camera) > 1e-9) {
43887             this._camera.copy(camera);
43888             this._rotation = this._computeRotation(camera);
43889             this._perspective.up.copy(camera.up);
43890             this._perspective.position.copy(camera.position);
43891             this._perspective.lookAt(camera.lookat);
43892             this._perspective.updateMatrix();
43893             this._perspective.updateMatrixWorld(false);
43894             this._changed = true;
43895         }
43896         if (this._changed) {
43897             this._perspective.updateProjectionMatrix();
43898         }
43899         this._setFrameId(frame.id);
43900     };
43901     RenderCamera.prototype.setRenderMode = function (renderMode) {
43902         this._renderMode = renderMode;
43903         this._perspective.fov = this._computeFov();
43904         this._perspective.updateProjectionMatrix();
43905         this._changed = true;
43906     };
43907     RenderCamera.prototype.setSize = function (size) {
43908         this._perspective.aspect = this._computeAspect(size.width, size.height);
43909         this._perspective.fov = this._computeFov();
43910         this._perspective.updateProjectionMatrix();
43911         this._changed = true;
43912     };
43913     RenderCamera.prototype._computeAspect = function (elementWidth, elementHeight) {
43914         return elementWidth === 0 ? 0 : elementWidth / elementHeight;
43915     };
43916     RenderCamera.prototype._computeCurrentFov = function () {
43917         if (this._perspective.aspect === 0) {
43918             return 0;
43919         }
43920         if (!this._currentNodeId) {
43921             return this._initialFov;
43922         }
43923         return this._currentPano ?
43924             this._yToFov(1, this._zoom) :
43925             this._computeVerticalFov(this._currentProjectedPoints, this._renderMode, this._zoom, this.perspective.aspect);
43926     };
43927     RenderCamera.prototype._computeFov = function () {
43928         this._currentFov = this._computeCurrentFov();
43929         this._previousFov = this._computePreviousFov();
43930         return this._interpolateFov(this._currentFov, this._previousFov, this._alpha);
43931     };
43932     RenderCamera.prototype._computePreviousFov = function () {
43933         if (this._perspective.aspect === 0) {
43934             return 0;
43935         }
43936         if (!this._currentNodeId) {
43937             return this._initialFov;
43938         }
43939         return !this._previousNodeId ?
43940             this._currentFov :
43941             this._previousPano ?
43942                 this._yToFov(1, this._zoom) :
43943                 this._computeVerticalFov(this._previousProjectedPoints, this._renderMode, this._zoom, this.perspective.aspect);
43944     };
43945     RenderCamera.prototype._computeProjectedPoints = function (transform) {
43946         var vertices = [[0.5, 0], [1, 0]];
43947         var directions = [[0.5, 0], [0, 0.5]];
43948         var pointsPerLine = 100;
43949         return Geo_1.Geo.computeProjectedPoints(transform, vertices, directions, pointsPerLine, this._viewportCoords);
43950     };
43951     RenderCamera.prototype._computeRequiredVerticalFov = function (projectedPoint, zoom, aspect) {
43952         var maxY = Math.max(projectedPoint[0] / aspect, projectedPoint[1]);
43953         return this._yToFov(maxY, zoom);
43954     };
43955     RenderCamera.prototype._computeRotation = function (camera) {
43956         var direction = camera.lookat.clone().sub(camera.position);
43957         var up = camera.up.clone();
43958         var phi = this._spatial.azimuthal(direction.toArray(), up.toArray());
43959         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
43960         return { phi: phi, theta: theta };
43961     };
43962     RenderCamera.prototype._computeVerticalFov = function (projectedPoints, renderMode, zoom, aspect) {
43963         var _this = this;
43964         var fovs = projectedPoints
43965             .map(function (projectedPoint) {
43966             return _this._computeRequiredVerticalFov(projectedPoint, zoom, aspect);
43967         });
43968         var fov = renderMode === Render_1.RenderMode.Fill ?
43969             Math.min.apply(Math, fovs) * 0.995 : Math.max.apply(Math, fovs);
43970         return fov;
43971     };
43972     RenderCamera.prototype._yToFov = function (y, zoom) {
43973         return 2 * Math.atan(y / Math.pow(2, zoom)) * 180 / Math.PI;
43974     };
43975     RenderCamera.prototype._interpolateFov = function (v1, v2, alpha) {
43976         return alpha * v1 + (1 - alpha) * v2;
43977     };
43978     RenderCamera.prototype._setFrameId = function (frameId) {
43979         this._frameId = frameId;
43980         if (this._changed) {
43981             this._changed = false;
43982             this._changedForFrame = frameId;
43983         }
43984     };
43985     return RenderCamera;
43986 }());
43987 exports.RenderCamera = RenderCamera;
43988 exports.default = RenderCamera;
43989
43990 },{"../Geo":278,"../Render":281,"../State":282,"three":226}],409:[function(require,module,exports){
43991 "use strict";
43992 Object.defineProperty(exports, "__esModule", { value: true });
43993 /**
43994  * Enumeration for render mode
43995  * @enum {number}
43996  * @readonly
43997  * @description Modes for specifying how rendering is done
43998  * in the viewer. All modes preserves the original aspect
43999  * ratio of the images.
44000  */
44001 var RenderMode;
44002 (function (RenderMode) {
44003     /**
44004      * Displays all content within the viewer.
44005      *
44006      * @description Black bars shown on both
44007      * sides of the content. Bars are shown
44008      * either below and above or to the left
44009      * and right of the content depending on
44010      * the aspect ratio relation between the
44011      * image and the viewer.
44012      */
44013     RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
44014     /**
44015      * Fills the viewer by cropping content.
44016      *
44017      * @description Cropping is done either
44018      * in horizontal or vertical direction
44019      * depending on the aspect ratio relation
44020      * between the image and the viewer.
44021      */
44022     RenderMode[RenderMode["Fill"] = 1] = "Fill";
44023 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
44024 exports.default = RenderMode;
44025
44026 },{}],410:[function(require,module,exports){
44027 "use strict";
44028 Object.defineProperty(exports, "__esModule", { value: true });
44029 var operators_1 = require("rxjs/operators");
44030 var rxjs_1 = require("rxjs");
44031 var Geo_1 = require("../Geo");
44032 var Render_1 = require("../Render");
44033 var RenderService = /** @class */ (function () {
44034     function RenderService(element, currentFrame$, renderMode, renderCamera) {
44035         var _this = this;
44036         this._element = element;
44037         this._currentFrame$ = currentFrame$;
44038         this._spatial = new Geo_1.Spatial();
44039         renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
44040         this._resize$ = new rxjs_1.Subject();
44041         this._renderCameraOperation$ = new rxjs_1.Subject();
44042         this._size$ =
44043             new rxjs_1.BehaviorSubject({
44044                 height: this._element.offsetHeight,
44045                 width: this._element.offsetWidth,
44046             });
44047         this._resize$.pipe(operators_1.map(function () {
44048             return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
44049         }))
44050             .subscribe(this._size$);
44051         this._renderMode$ = new rxjs_1.BehaviorSubject(renderMode);
44052         this._renderCameraHolder$ = this._renderCameraOperation$.pipe(operators_1.startWith(function (rc) {
44053             return rc;
44054         }), operators_1.scan(function (rc, operation) {
44055             return operation(rc);
44056         }, !!renderCamera ? renderCamera : new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode)), operators_1.publishReplay(1), operators_1.refCount());
44057         this._renderCameraFrame$ = this._currentFrame$.pipe(operators_1.withLatestFrom(this._renderCameraHolder$), operators_1.tap(function (_a) {
44058             var frame = _a[0], rc = _a[1];
44059             rc.setFrame(frame);
44060         }), operators_1.map(function (args) {
44061             return args[1];
44062         }), operators_1.publishReplay(1), operators_1.refCount());
44063         this._renderCamera$ = this._renderCameraFrame$.pipe(operators_1.filter(function (rc) {
44064             return rc.changed;
44065         }), operators_1.publishReplay(1), operators_1.refCount());
44066         this._bearing$ = this._renderCamera$.pipe(operators_1.map(function (rc) {
44067             var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(rc.rotation.phi));
44068             return _this._spatial.wrap(bearing, 0, 360);
44069         }), operators_1.publishReplay(1), operators_1.refCount());
44070         this._size$.pipe(operators_1.skip(1), operators_1.map(function (size) {
44071             return function (rc) {
44072                 rc.setSize(size);
44073                 return rc;
44074             };
44075         }))
44076             .subscribe(this._renderCameraOperation$);
44077         this._renderMode$.pipe(operators_1.skip(1), operators_1.map(function (rm) {
44078             return function (rc) {
44079                 rc.setRenderMode(rm);
44080                 return rc;
44081             };
44082         }))
44083             .subscribe(this._renderCameraOperation$);
44084         this._bearing$.subscribe(function () { });
44085         this._renderCameraHolder$.subscribe(function () { });
44086         this._size$.subscribe(function () { });
44087         this._renderMode$.subscribe(function () { });
44088         this._renderCamera$.subscribe(function () { });
44089         this._renderCameraFrame$.subscribe(function () { });
44090     }
44091     Object.defineProperty(RenderService.prototype, "bearing$", {
44092         get: function () {
44093             return this._bearing$;
44094         },
44095         enumerable: true,
44096         configurable: true
44097     });
44098     Object.defineProperty(RenderService.prototype, "element", {
44099         get: function () {
44100             return this._element;
44101         },
44102         enumerable: true,
44103         configurable: true
44104     });
44105     Object.defineProperty(RenderService.prototype, "resize$", {
44106         get: function () {
44107             return this._resize$;
44108         },
44109         enumerable: true,
44110         configurable: true
44111     });
44112     Object.defineProperty(RenderService.prototype, "size$", {
44113         get: function () {
44114             return this._size$;
44115         },
44116         enumerable: true,
44117         configurable: true
44118     });
44119     Object.defineProperty(RenderService.prototype, "renderMode$", {
44120         get: function () {
44121             return this._renderMode$;
44122         },
44123         enumerable: true,
44124         configurable: true
44125     });
44126     Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
44127         get: function () {
44128             return this._renderCameraFrame$;
44129         },
44130         enumerable: true,
44131         configurable: true
44132     });
44133     Object.defineProperty(RenderService.prototype, "renderCamera$", {
44134         get: function () {
44135             return this._renderCamera$;
44136         },
44137         enumerable: true,
44138         configurable: true
44139     });
44140     return RenderService;
44141 }());
44142 exports.RenderService = RenderService;
44143 exports.default = RenderService;
44144
44145
44146 },{"../Geo":278,"../Render":281,"rxjs":27,"rxjs/operators":225}],411:[function(require,module,exports){
44147 "use strict";
44148 Object.defineProperty(exports, "__esModule", { value: true });
44149 var FrameGenerator = /** @class */ (function () {
44150     function FrameGenerator(root) {
44151         if (root.requestAnimationFrame) {
44152             this._cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
44153             this._requestAnimationFrame = root.requestAnimationFrame.bind(root);
44154         }
44155         else if (root.mozRequestAnimationFrame) {
44156             this._cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
44157             this._requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
44158         }
44159         else if (root.webkitRequestAnimationFrame) {
44160             this._cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
44161             this._requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
44162         }
44163         else if (root.msRequestAnimationFrame) {
44164             this._cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
44165             this._requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
44166         }
44167         else if (root.oRequestAnimationFrame) {
44168             this._cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
44169             this._requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
44170         }
44171         else {
44172             this._cancelAnimationFrame = root.clearTimeout.bind(root);
44173             this._requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
44174         }
44175     }
44176     Object.defineProperty(FrameGenerator.prototype, "cancelAnimationFrame", {
44177         get: function () {
44178             return this._cancelAnimationFrame;
44179         },
44180         enumerable: true,
44181         configurable: true
44182     });
44183     Object.defineProperty(FrameGenerator.prototype, "requestAnimationFrame", {
44184         get: function () {
44185             return this._requestAnimationFrame;
44186         },
44187         enumerable: true,
44188         configurable: true
44189     });
44190     return FrameGenerator;
44191 }());
44192 exports.FrameGenerator = FrameGenerator;
44193 exports.default = FrameGenerator;
44194
44195 },{}],412:[function(require,module,exports){
44196 "use strict";
44197 Object.defineProperty(exports, "__esModule", { value: true });
44198 var RotationDelta = /** @class */ (function () {
44199     function RotationDelta(phi, theta) {
44200         this._phi = phi;
44201         this._theta = theta;
44202     }
44203     Object.defineProperty(RotationDelta.prototype, "phi", {
44204         get: function () {
44205             return this._phi;
44206         },
44207         set: function (value) {
44208             this._phi = value;
44209         },
44210         enumerable: true,
44211         configurable: true
44212     });
44213     Object.defineProperty(RotationDelta.prototype, "theta", {
44214         get: function () {
44215             return this._theta;
44216         },
44217         set: function (value) {
44218             this._theta = value;
44219         },
44220         enumerable: true,
44221         configurable: true
44222     });
44223     Object.defineProperty(RotationDelta.prototype, "isZero", {
44224         get: function () {
44225             return this._phi === 0 && this._theta === 0;
44226         },
44227         enumerable: true,
44228         configurable: true
44229     });
44230     RotationDelta.prototype.copy = function (delta) {
44231         this._phi = delta.phi;
44232         this._theta = delta.theta;
44233     };
44234     RotationDelta.prototype.lerp = function (other, alpha) {
44235         this._phi = (1 - alpha) * this._phi + alpha * other.phi;
44236         this._theta = (1 - alpha) * this._theta + alpha * other.theta;
44237     };
44238     RotationDelta.prototype.multiply = function (value) {
44239         this._phi *= value;
44240         this._theta *= value;
44241     };
44242     RotationDelta.prototype.threshold = function (value) {
44243         this._phi = Math.abs(this._phi) > value ? this._phi : 0;
44244         this._theta = Math.abs(this._theta) > value ? this._theta : 0;
44245     };
44246     RotationDelta.prototype.lengthSquared = function () {
44247         return this._phi * this._phi + this._theta * this._theta;
44248     };
44249     RotationDelta.prototype.reset = function () {
44250         this._phi = 0;
44251         this._theta = 0;
44252     };
44253     return RotationDelta;
44254 }());
44255 exports.RotationDelta = RotationDelta;
44256 exports.default = RotationDelta;
44257
44258 },{}],413:[function(require,module,exports){
44259 "use strict";
44260 Object.defineProperty(exports, "__esModule", { value: true });
44261 var State;
44262 (function (State) {
44263     State[State["Earth"] = 0] = "Earth";
44264     State[State["Traversing"] = 1] = "Traversing";
44265     State[State["Waiting"] = 2] = "Waiting";
44266     State[State["WaitingInteractively"] = 3] = "WaitingInteractively";
44267 })(State = exports.State || (exports.State = {}));
44268 exports.default = State;
44269
44270 },{}],414:[function(require,module,exports){
44271 "use strict";
44272 Object.defineProperty(exports, "__esModule", { value: true });
44273 var State_1 = require("../State");
44274 var Geo_1 = require("../Geo");
44275 var StateContext = /** @class */ (function () {
44276     function StateContext(transitionMode) {
44277         this._state = new State_1.TraversingState({
44278             alpha: 1,
44279             camera: new Geo_1.Camera(),
44280             currentIndex: -1,
44281             reference: { alt: 0, lat: 0, lon: 0 },
44282             trajectory: [],
44283             transitionMode: transitionMode == null ? State_1.TransitionMode.Default : transitionMode,
44284             zoom: 0,
44285         });
44286     }
44287     StateContext.prototype.earth = function () {
44288         this._state = this._state.earth();
44289     };
44290     StateContext.prototype.traverse = function () {
44291         this._state = this._state.traverse();
44292     };
44293     StateContext.prototype.wait = function () {
44294         this._state = this._state.wait();
44295     };
44296     StateContext.prototype.waitInteractively = function () {
44297         this._state = this._state.waitInteractively();
44298     };
44299     Object.defineProperty(StateContext.prototype, "state", {
44300         get: function () {
44301             if (this._state instanceof State_1.EarthState) {
44302                 return State_1.State.Earth;
44303             }
44304             else if (this._state instanceof State_1.TraversingState) {
44305                 return State_1.State.Traversing;
44306             }
44307             else if (this._state instanceof State_1.WaitingState) {
44308                 return State_1.State.Waiting;
44309             }
44310             else if (this._state instanceof State_1.InteractiveWaitingState) {
44311                 return State_1.State.WaitingInteractively;
44312             }
44313             throw new Error("Invalid state");
44314         },
44315         enumerable: true,
44316         configurable: true
44317     });
44318     Object.defineProperty(StateContext.prototype, "reference", {
44319         get: function () {
44320             return this._state.reference;
44321         },
44322         enumerable: true,
44323         configurable: true
44324     });
44325     Object.defineProperty(StateContext.prototype, "alpha", {
44326         get: function () {
44327             return this._state.alpha;
44328         },
44329         enumerable: true,
44330         configurable: true
44331     });
44332     Object.defineProperty(StateContext.prototype, "camera", {
44333         get: function () {
44334             return this._state.camera;
44335         },
44336         enumerable: true,
44337         configurable: true
44338     });
44339     Object.defineProperty(StateContext.prototype, "zoom", {
44340         get: function () {
44341             return this._state.zoom;
44342         },
44343         enumerable: true,
44344         configurable: true
44345     });
44346     Object.defineProperty(StateContext.prototype, "currentNode", {
44347         get: function () {
44348             return this._state.currentNode;
44349         },
44350         enumerable: true,
44351         configurable: true
44352     });
44353     Object.defineProperty(StateContext.prototype, "previousNode", {
44354         get: function () {
44355             return this._state.previousNode;
44356         },
44357         enumerable: true,
44358         configurable: true
44359     });
44360     Object.defineProperty(StateContext.prototype, "currentCamera", {
44361         get: function () {
44362             return this._state.currentCamera;
44363         },
44364         enumerable: true,
44365         configurable: true
44366     });
44367     Object.defineProperty(StateContext.prototype, "currentTransform", {
44368         get: function () {
44369             return this._state.currentTransform;
44370         },
44371         enumerable: true,
44372         configurable: true
44373     });
44374     Object.defineProperty(StateContext.prototype, "previousTransform", {
44375         get: function () {
44376             return this._state.previousTransform;
44377         },
44378         enumerable: true,
44379         configurable: true
44380     });
44381     Object.defineProperty(StateContext.prototype, "trajectory", {
44382         get: function () {
44383             return this._state.trajectory;
44384         },
44385         enumerable: true,
44386         configurable: true
44387     });
44388     Object.defineProperty(StateContext.prototype, "currentIndex", {
44389         get: function () {
44390             return this._state.currentIndex;
44391         },
44392         enumerable: true,
44393         configurable: true
44394     });
44395     Object.defineProperty(StateContext.prototype, "lastNode", {
44396         get: function () {
44397             return this._state.trajectory[this._state.trajectory.length - 1];
44398         },
44399         enumerable: true,
44400         configurable: true
44401     });
44402     Object.defineProperty(StateContext.prototype, "nodesAhead", {
44403         get: function () {
44404             return this._state.trajectory.length - 1 - this._state.currentIndex;
44405         },
44406         enumerable: true,
44407         configurable: true
44408     });
44409     Object.defineProperty(StateContext.prototype, "motionless", {
44410         get: function () {
44411             return this._state.motionless;
44412         },
44413         enumerable: true,
44414         configurable: true
44415     });
44416     StateContext.prototype.getCenter = function () {
44417         return this._state.getCenter();
44418     };
44419     StateContext.prototype.setCenter = function (center) {
44420         this._state.setCenter(center);
44421     };
44422     StateContext.prototype.setZoom = function (zoom) {
44423         this._state.setZoom(zoom);
44424     };
44425     StateContext.prototype.update = function (fps) {
44426         this._state.update(fps);
44427     };
44428     StateContext.prototype.append = function (nodes) {
44429         this._state.append(nodes);
44430     };
44431     StateContext.prototype.prepend = function (nodes) {
44432         this._state.prepend(nodes);
44433     };
44434     StateContext.prototype.remove = function (n) {
44435         this._state.remove(n);
44436     };
44437     StateContext.prototype.clear = function () {
44438         this._state.clear();
44439     };
44440     StateContext.prototype.clearPrior = function () {
44441         this._state.clearPrior();
44442     };
44443     StateContext.prototype.cut = function () {
44444         this._state.cut();
44445     };
44446     StateContext.prototype.set = function (nodes) {
44447         this._state.set(nodes);
44448     };
44449     StateContext.prototype.rotate = function (delta) {
44450         this._state.rotate(delta);
44451     };
44452     StateContext.prototype.rotateUnbounded = function (delta) {
44453         this._state.rotateUnbounded(delta);
44454     };
44455     StateContext.prototype.rotateWithoutInertia = function (delta) {
44456         this._state.rotateWithoutInertia(delta);
44457     };
44458     StateContext.prototype.rotateBasic = function (basicRotation) {
44459         this._state.rotateBasic(basicRotation);
44460     };
44461     StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
44462         this._state.rotateBasicUnbounded(basicRotation);
44463     };
44464     StateContext.prototype.rotateBasicWithoutInertia = function (basicRotation) {
44465         this._state.rotateBasicWithoutInertia(basicRotation);
44466     };
44467     StateContext.prototype.rotateToBasic = function (basic) {
44468         this._state.rotateToBasic(basic);
44469     };
44470     StateContext.prototype.move = function (delta) {
44471         this._state.move(delta);
44472     };
44473     StateContext.prototype.moveTo = function (delta) {
44474         this._state.moveTo(delta);
44475     };
44476     StateContext.prototype.zoomIn = function (delta, reference) {
44477         this._state.zoomIn(delta, reference);
44478     };
44479     StateContext.prototype.setSpeed = function (speed) {
44480         this._state.setSpeed(speed);
44481     };
44482     StateContext.prototype.setTransitionMode = function (mode) {
44483         this._state.setTransitionMode(mode);
44484     };
44485     StateContext.prototype.dolly = function (delta) {
44486         this._state.dolly(delta);
44487     };
44488     StateContext.prototype.orbit = function (rotation) {
44489         this._state.orbit(rotation);
44490     };
44491     StateContext.prototype.truck = function (direction) {
44492         this._state.truck(direction);
44493     };
44494     return StateContext;
44495 }());
44496 exports.StateContext = StateContext;
44497
44498 },{"../Geo":278,"../State":282}],415:[function(require,module,exports){
44499 "use strict";
44500 Object.defineProperty(exports, "__esModule", { value: true });
44501 var rxjs_1 = require("rxjs");
44502 var operators_1 = require("rxjs/operators");
44503 var State_1 = require("../State");
44504 var StateService = /** @class */ (function () {
44505     function StateService(transitionMode) {
44506         var _this = this;
44507         this._appendNode$ = new rxjs_1.Subject();
44508         this._start$ = new rxjs_1.Subject();
44509         this._frame$ = new rxjs_1.Subject();
44510         this._fpsSampleRate = 30;
44511         this._contextOperation$ = new rxjs_1.BehaviorSubject(function (context) {
44512             return context;
44513         });
44514         this._context$ = this._contextOperation$.pipe(operators_1.scan(function (context, operation) {
44515             return operation(context);
44516         }, new State_1.StateContext(transitionMode)), operators_1.publishReplay(1), operators_1.refCount());
44517         this._state$ = this._context$.pipe(operators_1.map(function (context) {
44518             return context.state;
44519         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
44520         this._fps$ = this._start$.pipe(operators_1.switchMap(function () {
44521             return _this._frame$.pipe(operators_1.bufferCount(1, _this._fpsSampleRate), operators_1.map(function (frameIds) {
44522                 return new Date().getTime();
44523             }), operators_1.pairwise(), operators_1.map(function (times) {
44524                 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
44525             }), operators_1.startWith(60));
44526         }), operators_1.share());
44527         this._currentState$ = this._frame$.pipe(operators_1.withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
44528             return [frameId, fps, context];
44529         }), operators_1.filter(function (fc) {
44530             return fc[2].currentNode != null;
44531         }), operators_1.tap(function (fc) {
44532             fc[2].update(fc[1]);
44533         }), operators_1.map(function (fc) {
44534             return { fps: fc[1], id: fc[0], state: fc[2] };
44535         }), operators_1.share());
44536         this._lastState$ = this._currentState$.pipe(operators_1.publishReplay(1), operators_1.refCount());
44537         var nodeChanged$ = this._currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (f) {
44538             return f.state.currentNode.key;
44539         }), operators_1.publishReplay(1), operators_1.refCount());
44540         var nodeChangedSubject$ = new rxjs_1.Subject();
44541         nodeChanged$
44542             .subscribe(nodeChangedSubject$);
44543         this._currentKey$ = new rxjs_1.BehaviorSubject(null);
44544         nodeChangedSubject$.pipe(operators_1.map(function (f) {
44545             return f.state.currentNode.key;
44546         }))
44547             .subscribe(this._currentKey$);
44548         this._currentNode$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
44549             return f.state.currentNode;
44550         }), operators_1.publishReplay(1), operators_1.refCount());
44551         this._currentCamera$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
44552             return f.state.currentCamera;
44553         }), operators_1.publishReplay(1), operators_1.refCount());
44554         this._currentTransform$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
44555             return f.state.currentTransform;
44556         }), operators_1.publishReplay(1), operators_1.refCount());
44557         this._reference$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
44558             return f.state.reference;
44559         }), operators_1.distinctUntilChanged(function (r1, r2) {
44560             return r1.lat === r2.lat && r1.lon === r2.lon;
44561         }, function (reference) {
44562             return { lat: reference.lat, lon: reference.lon };
44563         }), operators_1.publishReplay(1), operators_1.refCount());
44564         this._currentNodeExternal$ = nodeChanged$.pipe(operators_1.map(function (f) {
44565             return f.state.currentNode;
44566         }), operators_1.publishReplay(1), operators_1.refCount());
44567         this._appendNode$.pipe(operators_1.map(function (node) {
44568             return function (context) {
44569                 context.append([node]);
44570                 return context;
44571             };
44572         }))
44573             .subscribe(this._contextOperation$);
44574         this._inMotionOperation$ = new rxjs_1.Subject();
44575         nodeChanged$.pipe(operators_1.map(function (frame) {
44576             return true;
44577         }))
44578             .subscribe(this._inMotionOperation$);
44579         this._inMotionOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.filter(function (moving) {
44580             return moving;
44581         }), operators_1.switchMap(function (moving) {
44582             return _this._currentState$.pipe(operators_1.filter(function (frame) {
44583                 return frame.state.nodesAhead === 0;
44584             }), operators_1.map(function (frame) {
44585                 return [frame.state.camera.clone(), frame.state.zoom];
44586             }), operators_1.pairwise(), operators_1.map(function (pair) {
44587                 var c1 = pair[0][0];
44588                 var c2 = pair[1][0];
44589                 var z1 = pair[0][1];
44590                 var z2 = pair[1][1];
44591                 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
44592             }), operators_1.first(function (changed) {
44593                 return !changed;
44594             }));
44595         }))
44596             .subscribe(this._inMotionOperation$);
44597         this._inMotion$ = this._inMotionOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
44598         this._inTranslationOperation$ = new rxjs_1.Subject();
44599         nodeChanged$.pipe(operators_1.map(function (frame) {
44600             return true;
44601         }))
44602             .subscribe(this._inTranslationOperation$);
44603         this._inTranslationOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.filter(function (inTranslation) {
44604             return inTranslation;
44605         }), operators_1.switchMap(function (inTranslation) {
44606             return _this._currentState$.pipe(operators_1.filter(function (frame) {
44607                 return frame.state.nodesAhead === 0;
44608             }), operators_1.map(function (frame) {
44609                 return frame.state.camera.position.clone();
44610             }), operators_1.pairwise(), operators_1.map(function (pair) {
44611                 return pair[0].distanceToSquared(pair[1]) !== 0;
44612             }), operators_1.first(function (changed) {
44613                 return !changed;
44614             }));
44615         }))
44616             .subscribe(this._inTranslationOperation$);
44617         this._inTranslation$ = this._inTranslationOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
44618         this._state$.subscribe(function () { });
44619         this._currentNode$.subscribe(function () { });
44620         this._currentCamera$.subscribe(function () { });
44621         this._currentTransform$.subscribe(function () { });
44622         this._reference$.subscribe(function () { });
44623         this._currentNodeExternal$.subscribe(function () { });
44624         this._lastState$.subscribe(function () { });
44625         this._inMotion$.subscribe(function () { });
44626         this._inTranslation$.subscribe(function () { });
44627         this._frameId = null;
44628         this._frameGenerator = new State_1.FrameGenerator(window);
44629     }
44630     Object.defineProperty(StateService.prototype, "currentState$", {
44631         get: function () {
44632             return this._currentState$;
44633         },
44634         enumerable: true,
44635         configurable: true
44636     });
44637     Object.defineProperty(StateService.prototype, "currentNode$", {
44638         get: function () {
44639             return this._currentNode$;
44640         },
44641         enumerable: true,
44642         configurable: true
44643     });
44644     Object.defineProperty(StateService.prototype, "currentKey$", {
44645         get: function () {
44646             return this._currentKey$;
44647         },
44648         enumerable: true,
44649         configurable: true
44650     });
44651     Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
44652         get: function () {
44653             return this._currentNodeExternal$;
44654         },
44655         enumerable: true,
44656         configurable: true
44657     });
44658     Object.defineProperty(StateService.prototype, "currentCamera$", {
44659         get: function () {
44660             return this._currentCamera$;
44661         },
44662         enumerable: true,
44663         configurable: true
44664     });
44665     Object.defineProperty(StateService.prototype, "currentTransform$", {
44666         get: function () {
44667             return this._currentTransform$;
44668         },
44669         enumerable: true,
44670         configurable: true
44671     });
44672     Object.defineProperty(StateService.prototype, "state$", {
44673         get: function () {
44674             return this._state$;
44675         },
44676         enumerable: true,
44677         configurable: true
44678     });
44679     Object.defineProperty(StateService.prototype, "reference$", {
44680         get: function () {
44681             return this._reference$;
44682         },
44683         enumerable: true,
44684         configurable: true
44685     });
44686     Object.defineProperty(StateService.prototype, "inMotion$", {
44687         get: function () {
44688             return this._inMotion$;
44689         },
44690         enumerable: true,
44691         configurable: true
44692     });
44693     Object.defineProperty(StateService.prototype, "inTranslation$", {
44694         get: function () {
44695             return this._inTranslation$;
44696         },
44697         enumerable: true,
44698         configurable: true
44699     });
44700     Object.defineProperty(StateService.prototype, "appendNode$", {
44701         get: function () {
44702             return this._appendNode$;
44703         },
44704         enumerable: true,
44705         configurable: true
44706     });
44707     StateService.prototype.earth = function () {
44708         this._inMotionOperation$.next(true);
44709         this._invokeContextOperation(function (context) { context.earth(); });
44710     };
44711     StateService.prototype.traverse = function () {
44712         this._inMotionOperation$.next(true);
44713         this._invokeContextOperation(function (context) { context.traverse(); });
44714     };
44715     StateService.prototype.wait = function () {
44716         this._invokeContextOperation(function (context) { context.wait(); });
44717     };
44718     StateService.prototype.waitInteractively = function () {
44719         this._invokeContextOperation(function (context) { context.waitInteractively(); });
44720     };
44721     StateService.prototype.appendNodes = function (nodes) {
44722         this._invokeContextOperation(function (context) { context.append(nodes); });
44723     };
44724     StateService.prototype.prependNodes = function (nodes) {
44725         this._invokeContextOperation(function (context) { context.prepend(nodes); });
44726     };
44727     StateService.prototype.removeNodes = function (n) {
44728         this._invokeContextOperation(function (context) { context.remove(n); });
44729     };
44730     StateService.prototype.clearNodes = function () {
44731         this._invokeContextOperation(function (context) { context.clear(); });
44732     };
44733     StateService.prototype.clearPriorNodes = function () {
44734         this._invokeContextOperation(function (context) { context.clearPrior(); });
44735     };
44736     StateService.prototype.cutNodes = function () {
44737         this._invokeContextOperation(function (context) { context.cut(); });
44738     };
44739     StateService.prototype.setNodes = function (nodes) {
44740         this._invokeContextOperation(function (context) { context.set(nodes); });
44741     };
44742     StateService.prototype.rotate = function (delta) {
44743         this._inMotionOperation$.next(true);
44744         this._invokeContextOperation(function (context) { context.rotate(delta); });
44745     };
44746     StateService.prototype.rotateUnbounded = function (delta) {
44747         this._inMotionOperation$.next(true);
44748         this._invokeContextOperation(function (context) { context.rotateUnbounded(delta); });
44749     };
44750     StateService.prototype.rotateWithoutInertia = function (delta) {
44751         this._inMotionOperation$.next(true);
44752         this._invokeContextOperation(function (context) { context.rotateWithoutInertia(delta); });
44753     };
44754     StateService.prototype.rotateBasic = function (basicRotation) {
44755         this._inMotionOperation$.next(true);
44756         this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
44757     };
44758     StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
44759         this._inMotionOperation$.next(true);
44760         this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
44761     };
44762     StateService.prototype.rotateBasicWithoutInertia = function (basicRotation) {
44763         this._inMotionOperation$.next(true);
44764         this._invokeContextOperation(function (context) { context.rotateBasicWithoutInertia(basicRotation); });
44765     };
44766     StateService.prototype.rotateToBasic = function (basic) {
44767         this._inMotionOperation$.next(true);
44768         this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
44769     };
44770     StateService.prototype.move = function (delta) {
44771         this._inMotionOperation$.next(true);
44772         this._invokeContextOperation(function (context) { context.move(delta); });
44773     };
44774     StateService.prototype.moveTo = function (position) {
44775         this._inMotionOperation$.next(true);
44776         this._invokeContextOperation(function (context) { context.moveTo(position); });
44777     };
44778     StateService.prototype.dolly = function (delta) {
44779         this._inMotionOperation$.next(true);
44780         this._invokeContextOperation(function (context) { context.dolly(delta); });
44781     };
44782     StateService.prototype.orbit = function (rotation) {
44783         this._inMotionOperation$.next(true);
44784         this._invokeContextOperation(function (context) { context.orbit(rotation); });
44785     };
44786     StateService.prototype.truck = function (direction) {
44787         this._inMotionOperation$.next(true);
44788         this._invokeContextOperation(function (context) { context.truck(direction); });
44789     };
44790     /**
44791      * Change zoom level while keeping the reference point position approximately static.
44792      *
44793      * @parameter {number} delta - Change in zoom level.
44794      * @parameter {Array<number>} reference - Reference point in basic coordinates.
44795      */
44796     StateService.prototype.zoomIn = function (delta, reference) {
44797         this._inMotionOperation$.next(true);
44798         this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
44799     };
44800     StateService.prototype.getCenter = function () {
44801         return this._lastState$.pipe(operators_1.first(), operators_1.map(function (frame) {
44802             return frame.state.getCenter();
44803         }));
44804     };
44805     StateService.prototype.getZoom = function () {
44806         return this._lastState$.pipe(operators_1.first(), operators_1.map(function (frame) {
44807             return frame.state.zoom;
44808         }));
44809     };
44810     StateService.prototype.setCenter = function (center) {
44811         this._inMotionOperation$.next(true);
44812         this._invokeContextOperation(function (context) { context.setCenter(center); });
44813     };
44814     StateService.prototype.setSpeed = function (speed) {
44815         this._invokeContextOperation(function (context) { context.setSpeed(speed); });
44816     };
44817     StateService.prototype.setTransitionMode = function (mode) {
44818         this._invokeContextOperation(function (context) { context.setTransitionMode(mode); });
44819     };
44820     StateService.prototype.setZoom = function (zoom) {
44821         this._inMotionOperation$.next(true);
44822         this._invokeContextOperation(function (context) { context.setZoom(zoom); });
44823     };
44824     StateService.prototype.start = function () {
44825         if (this._frameId == null) {
44826             this._start$.next(null);
44827             this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
44828             this._frame$.next(this._frameId);
44829         }
44830     };
44831     StateService.prototype.stop = function () {
44832         if (this._frameId != null) {
44833             this._frameGenerator.cancelAnimationFrame(this._frameId);
44834             this._frameId = null;
44835         }
44836     };
44837     StateService.prototype._invokeContextOperation = function (action) {
44838         this._contextOperation$
44839             .next(function (context) {
44840             action(context);
44841             return context;
44842         });
44843     };
44844     StateService.prototype._frame = function (time) {
44845         this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
44846         this._frame$.next(this._frameId);
44847     };
44848     return StateService;
44849 }());
44850 exports.StateService = StateService;
44851
44852 },{"../State":282,"rxjs":27,"rxjs/operators":225}],416:[function(require,module,exports){
44853 "use strict";
44854 Object.defineProperty(exports, "__esModule", { value: true });
44855 /**
44856  * Enumeration for transition mode
44857  * @enum {number}
44858  * @readonly
44859  * @description Modes for specifying how transitions
44860  * between nodes are performed.
44861  */
44862 var TransitionMode;
44863 (function (TransitionMode) {
44864     /**
44865      * Default transitions.
44866      *
44867      * @description The viewer dynamically determines
44868      * whether transitions should be performed with or
44869      * without motion and blending for each transition
44870      * based on the underlying data.
44871      */
44872     TransitionMode[TransitionMode["Default"] = 0] = "Default";
44873     /**
44874      * Instantaneous transitions.
44875      *
44876      * @description All transitions are performed
44877      * without motion or blending.
44878      */
44879     TransitionMode[TransitionMode["Instantaneous"] = 1] = "Instantaneous";
44880 })(TransitionMode = exports.TransitionMode || (exports.TransitionMode = {}));
44881 exports.default = TransitionMode;
44882
44883 },{}],417:[function(require,module,exports){
44884 "use strict";
44885 var __extends = (this && this.__extends) || (function () {
44886     var extendStatics = function (d, b) {
44887         extendStatics = Object.setPrototypeOf ||
44888             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
44889             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
44890         return extendStatics(d, b);
44891     }
44892     return function (d, b) {
44893         extendStatics(d, b);
44894         function __() { this.constructor = d; }
44895         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
44896     };
44897 })();
44898 Object.defineProperty(exports, "__esModule", { value: true });
44899 var THREE = require("three");
44900 var State_1 = require("../../State");
44901 var EarthState = /** @class */ (function (_super) {
44902     __extends(EarthState, _super);
44903     function EarthState(state) {
44904         var _this = _super.call(this, state) || this;
44905         var viewingDirection = _this._camera.lookat
44906             .clone()
44907             .sub(_this._camera.position)
44908             .normalize();
44909         _this._camera.lookat.copy(_this._camera.position);
44910         _this._camera.position.z = state.camera.position.z + 20;
44911         _this._camera.position.x = state.camera.position.x - 16 * viewingDirection.x;
44912         _this._camera.position.y = state.camera.position.y - 16 * viewingDirection.y;
44913         _this._camera.up.set(0, 0, 1);
44914         return _this;
44915     }
44916     EarthState.prototype.traverse = function () {
44917         return new State_1.TraversingState(this);
44918     };
44919     EarthState.prototype.wait = function () {
44920         return new State_1.WaitingState(this);
44921     };
44922     EarthState.prototype.waitInteractively = function () {
44923         return new State_1.InteractiveWaitingState(this);
44924     };
44925     EarthState.prototype.dolly = function (delta) {
44926         var camera = this._camera;
44927         var offset = new THREE.Vector3()
44928             .copy(camera.position)
44929             .sub(camera.lookat);
44930         var length = offset.length();
44931         var scaled = length * Math.pow(2, -delta);
44932         var clipped = Math.max(1, Math.min(scaled, 1000));
44933         offset.normalize();
44934         offset.multiplyScalar(clipped);
44935         camera.position.copy(camera.lookat).add(offset);
44936     };
44937     EarthState.prototype.orbit = function (rotation) {
44938         var camera = this._camera;
44939         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
44940         var qInverse = q.clone().inverse();
44941         var offset = new THREE.Vector3();
44942         offset.copy(camera.position).sub(camera.lookat);
44943         offset.applyQuaternion(q);
44944         var length = offset.length();
44945         var phi = Math.atan2(offset.y, offset.x);
44946         phi += rotation.phi;
44947         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
44948         theta += rotation.theta;
44949         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
44950         offset.x = Math.sin(theta) * Math.cos(phi);
44951         offset.y = Math.sin(theta) * Math.sin(phi);
44952         offset.z = Math.cos(theta);
44953         offset.applyQuaternion(qInverse);
44954         camera.position.copy(camera.lookat).add(offset.multiplyScalar(length));
44955     };
44956     EarthState.prototype.truck = function (direction) {
44957         this._camera.position.add(new THREE.Vector3().fromArray(direction));
44958         this._camera.lookat.add(new THREE.Vector3().fromArray(direction));
44959     };
44960     EarthState.prototype.update = function () { };
44961     return EarthState;
44962 }(State_1.StateBase));
44963 exports.EarthState = EarthState;
44964 exports.default = EarthState;
44965
44966
44967 },{"../../State":282,"three":226}],418:[function(require,module,exports){
44968 "use strict";
44969 var __extends = (this && this.__extends) || (function () {
44970     var extendStatics = function (d, b) {
44971         extendStatics = Object.setPrototypeOf ||
44972             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
44973             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
44974         return extendStatics(d, b);
44975     }
44976     return function (d, b) {
44977         extendStatics(d, b);
44978         function __() { this.constructor = d; }
44979         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
44980     };
44981 })();
44982 Object.defineProperty(exports, "__esModule", { value: true });
44983 var THREE = require("three");
44984 var State_1 = require("../../State");
44985 var InteractiveStateBase = /** @class */ (function (_super) {
44986     __extends(InteractiveStateBase, _super);
44987     function InteractiveStateBase(state) {
44988         var _this = _super.call(this, state) || this;
44989         _this._animationSpeed = 1 / 40;
44990         _this._rotationDelta = new State_1.RotationDelta(0, 0);
44991         _this._requestedRotationDelta = null;
44992         _this._basicRotation = [0, 0];
44993         _this._requestedBasicRotation = null;
44994         _this._requestedBasicRotationUnbounded = null;
44995         _this._rotationAcceleration = 0.86;
44996         _this._rotationIncreaseAlpha = 0.97;
44997         _this._rotationDecreaseAlpha = 0.9;
44998         _this._rotationThreshold = 1e-3;
44999         _this._unboundedRotationAlpha = 0.8;
45000         _this._desiredZoom = state.zoom;
45001         _this._minZoom = 0;
45002         _this._maxZoom = 3;
45003         _this._lookatDepth = 10;
45004         _this._desiredLookat = null;
45005         _this._desiredCenter = null;
45006         return _this;
45007     }
45008     InteractiveStateBase.prototype.rotate = function (rotationDelta) {
45009         if (this._currentNode == null) {
45010             return;
45011         }
45012         if (rotationDelta.phi === 0 && rotationDelta.theta === 0) {
45013             return;
45014         }
45015         this._desiredZoom = this._zoom;
45016         this._desiredLookat = null;
45017         this._requestedBasicRotation = null;
45018         if (this._requestedRotationDelta != null) {
45019             this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
45020             this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
45021         }
45022         else {
45023             this._requestedRotationDelta = new State_1.RotationDelta(rotationDelta.phi, rotationDelta.theta);
45024         }
45025     };
45026     InteractiveStateBase.prototype.rotateUnbounded = function (delta) {
45027         if (this._currentNode == null) {
45028             return;
45029         }
45030         this._requestedBasicRotation = null;
45031         this._requestedRotationDelta = null;
45032         this._applyRotation(delta, this._currentCamera);
45033         this._applyRotation(delta, this._previousCamera);
45034         if (!this._desiredLookat) {
45035             return;
45036         }
45037         var q = new THREE.Quaternion().setFromUnitVectors(this._currentCamera.up, new THREE.Vector3(0, 0, 1));
45038         var qInverse = q.clone().inverse();
45039         var offset = new THREE.Vector3()
45040             .copy(this._desiredLookat)
45041             .sub(this._camera.position)
45042             .applyQuaternion(q);
45043         var length = offset.length();
45044         var phi = Math.atan2(offset.y, offset.x);
45045         phi += delta.phi;
45046         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
45047         theta += delta.theta;
45048         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
45049         offset.x = Math.sin(theta) * Math.cos(phi);
45050         offset.y = Math.sin(theta) * Math.sin(phi);
45051         offset.z = Math.cos(theta);
45052         offset.applyQuaternion(qInverse);
45053         this._desiredLookat
45054             .copy(this._camera.position)
45055             .add(offset.multiplyScalar(length));
45056     };
45057     InteractiveStateBase.prototype.rotateWithoutInertia = function (rotationDelta) {
45058         if (this._currentNode == null) {
45059             return;
45060         }
45061         this._desiredZoom = this._zoom;
45062         this._desiredLookat = null;
45063         this._requestedBasicRotation = null;
45064         this._requestedRotationDelta = null;
45065         var threshold = Math.PI / (10 * Math.pow(2, this._zoom));
45066         var delta = {
45067             phi: this._spatial.clamp(rotationDelta.phi, -threshold, threshold),
45068             theta: this._spatial.clamp(rotationDelta.theta, -threshold, threshold),
45069         };
45070         this._applyRotation(delta, this._currentCamera);
45071         this._applyRotation(delta, this._previousCamera);
45072     };
45073     InteractiveStateBase.prototype.rotateBasic = function (basicRotation) {
45074         if (this._currentNode == null) {
45075             return;
45076         }
45077         this._desiredZoom = this._zoom;
45078         this._desiredLookat = null;
45079         this._requestedRotationDelta = null;
45080         if (this._requestedBasicRotation != null) {
45081             this._requestedBasicRotation[0] += basicRotation[0];
45082             this._requestedBasicRotation[1] += basicRotation[1];
45083             var threshold = 0.05 / Math.pow(2, this._zoom);
45084             this._requestedBasicRotation[0] =
45085                 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
45086             this._requestedBasicRotation[1] =
45087                 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
45088         }
45089         else {
45090             this._requestedBasicRotation = basicRotation.slice();
45091         }
45092     };
45093     InteractiveStateBase.prototype.rotateBasicUnbounded = function (basicRotation) {
45094         if (this._currentNode == null) {
45095             return;
45096         }
45097         if (this._requestedBasicRotationUnbounded != null) {
45098             this._requestedBasicRotationUnbounded[0] += basicRotation[0];
45099             this._requestedBasicRotationUnbounded[1] += basicRotation[1];
45100         }
45101         else {
45102             this._requestedBasicRotationUnbounded = basicRotation.slice();
45103         }
45104     };
45105     InteractiveStateBase.prototype.rotateBasicWithoutInertia = function (basic) {
45106         if (this._currentNode == null) {
45107             return;
45108         }
45109         this._desiredZoom = this._zoom;
45110         this._desiredLookat = null;
45111         this._requestedRotationDelta = null;
45112         this._requestedBasicRotation = null;
45113         var threshold = 0.05 / Math.pow(2, this._zoom);
45114         var basicRotation = basic.slice();
45115         basicRotation[0] = this._spatial.clamp(basicRotation[0], -threshold, threshold);
45116         basicRotation[1] = this._spatial.clamp(basicRotation[1], -threshold, threshold);
45117         this._applyRotationBasic(basicRotation);
45118     };
45119     InteractiveStateBase.prototype.rotateToBasic = function (basic) {
45120         if (this._currentNode == null) {
45121             return;
45122         }
45123         this._desiredZoom = this._zoom;
45124         this._desiredLookat = null;
45125         basic[0] = this._spatial.clamp(basic[0], 0, 1);
45126         basic[1] = this._spatial.clamp(basic[1], 0, 1);
45127         var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
45128         this._currentCamera.lookat.fromArray(lookat);
45129     };
45130     InteractiveStateBase.prototype.zoomIn = function (delta, reference) {
45131         if (this._currentNode == null) {
45132             return;
45133         }
45134         this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
45135         var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
45136         var currentCenterX = currentCenter[0];
45137         var currentCenterY = currentCenter[1];
45138         var zoom0 = Math.pow(2, this._zoom);
45139         var zoom1 = Math.pow(2, this._desiredZoom);
45140         var refX = reference[0];
45141         var refY = reference[1];
45142         if (this.currentTransform.gpano != null &&
45143             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
45144             if (refX - currentCenterX > 0.5) {
45145                 refX = refX - 1;
45146             }
45147             else if (currentCenterX - refX > 0.5) {
45148                 refX = 1 + refX;
45149             }
45150         }
45151         var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
45152         var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
45153         var gpano = this.currentTransform.gpano;
45154         if (this._currentNode.fullPano) {
45155             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
45156             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
45157         }
45158         else if (gpano != null &&
45159             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
45160             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
45161             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
45162         }
45163         else {
45164             newCenterX = this._spatial.clamp(newCenterX, 0, 1);
45165             newCenterY = this._spatial.clamp(newCenterY, 0, 1);
45166         }
45167         this._desiredLookat = new THREE.Vector3()
45168             .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
45169     };
45170     InteractiveStateBase.prototype.setCenter = function (center) {
45171         this._desiredLookat = null;
45172         this._requestedRotationDelta = null;
45173         this._requestedBasicRotation = null;
45174         this._desiredZoom = this._zoom;
45175         var clamped = [
45176             this._spatial.clamp(center[0], 0, 1),
45177             this._spatial.clamp(center[1], 0, 1),
45178         ];
45179         if (this._currentNode == null) {
45180             this._desiredCenter = clamped;
45181             return;
45182         }
45183         this._desiredCenter = null;
45184         var currentLookat = new THREE.Vector3()
45185             .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
45186         var previousTransform = this.previousTransform != null ?
45187             this.previousTransform :
45188             this.currentTransform;
45189         var previousLookat = new THREE.Vector3()
45190             .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
45191         this._currentCamera.lookat.copy(currentLookat);
45192         this._previousCamera.lookat.copy(previousLookat);
45193     };
45194     InteractiveStateBase.prototype.setZoom = function (zoom) {
45195         this._desiredLookat = null;
45196         this._requestedRotationDelta = null;
45197         this._requestedBasicRotation = null;
45198         this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
45199         this._desiredZoom = this._zoom;
45200     };
45201     InteractiveStateBase.prototype._applyRotation = function (delta, camera) {
45202         if (camera == null) {
45203             return;
45204         }
45205         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
45206         var qInverse = q.clone().inverse();
45207         var offset = new THREE.Vector3();
45208         offset.copy(camera.lookat).sub(camera.position);
45209         offset.applyQuaternion(q);
45210         var length = offset.length();
45211         var phi = Math.atan2(offset.y, offset.x);
45212         phi += delta.phi;
45213         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
45214         theta += delta.theta;
45215         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
45216         offset.x = Math.sin(theta) * Math.cos(phi);
45217         offset.y = Math.sin(theta) * Math.sin(phi);
45218         offset.z = Math.cos(theta);
45219         offset.applyQuaternion(qInverse);
45220         camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
45221     };
45222     InteractiveStateBase.prototype._applyRotationBasic = function (basicRotation) {
45223         var currentNode = this._currentNode;
45224         var previousNode = this._previousNode != null ?
45225             this.previousNode :
45226             this.currentNode;
45227         var currentCamera = this._currentCamera;
45228         var previousCamera = this._previousCamera;
45229         var currentTransform = this.currentTransform;
45230         var previousTransform = this.previousTransform != null ?
45231             this.previousTransform :
45232             this.currentTransform;
45233         var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
45234         var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
45235         var currentGPano = currentTransform.gpano;
45236         var previousGPano = previousTransform.gpano;
45237         if (currentNode.fullPano) {
45238             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
45239             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0.05, 0.95);
45240         }
45241         else if (currentGPano != null &&
45242             currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
45243             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
45244             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
45245         }
45246         else {
45247             currentBasic[0] = this._spatial.clamp(currentBasic[0] + basicRotation[0], 0, 1);
45248             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
45249         }
45250         if (previousNode.fullPano) {
45251             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
45252             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0.05, 0.95);
45253         }
45254         else if (previousGPano != null &&
45255             previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
45256             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
45257             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0, 1);
45258         }
45259         else {
45260             previousBasic[0] = this._spatial.clamp(previousBasic[0] + basicRotation[0], 0, 1);
45261             previousBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
45262         }
45263         var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
45264         currentCamera.lookat.fromArray(currentLookat);
45265         var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
45266         previousCamera.lookat.fromArray(previousLookat);
45267     };
45268     InteractiveStateBase.prototype._updateZoom = function (animationSpeed) {
45269         var diff = this._desiredZoom - this._zoom;
45270         var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
45271         if (diff === 0) {
45272             return;
45273         }
45274         else if (Math.abs(diff) < 2e-3) {
45275             this._zoom = this._desiredZoom;
45276             if (this._desiredLookat != null) {
45277                 this._desiredLookat = null;
45278             }
45279         }
45280         else {
45281             this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
45282         }
45283     };
45284     InteractiveStateBase.prototype._updateLookat = function (animationSpeed) {
45285         if (this._desiredLookat === null) {
45286             return;
45287         }
45288         var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
45289         if (Math.abs(diff) < 1e-6) {
45290             this._currentCamera.lookat.copy(this._desiredLookat);
45291             this._desiredLookat = null;
45292         }
45293         else {
45294             this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
45295         }
45296     };
45297     InteractiveStateBase.prototype._updateRotation = function () {
45298         if (this._requestedRotationDelta != null) {
45299             var length_1 = this._rotationDelta.lengthSquared();
45300             var requestedLength = this._requestedRotationDelta.lengthSquared();
45301             if (requestedLength > length_1) {
45302                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
45303             }
45304             else {
45305                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
45306             }
45307             this._requestedRotationDelta = null;
45308             return;
45309         }
45310         if (this._rotationDelta.isZero) {
45311             return;
45312         }
45313         var alpha = this.currentNode.fullPano ? 1 : this._alpha;
45314         this._rotationDelta.multiply(this._rotationAcceleration * alpha);
45315         this._rotationDelta.threshold(this._rotationThreshold);
45316     };
45317     InteractiveStateBase.prototype._updateRotationBasic = function () {
45318         if (this._requestedBasicRotation != null) {
45319             var x = this._basicRotation[0];
45320             var y = this._basicRotation[1];
45321             var reqX = this._requestedBasicRotation[0];
45322             var reqY = this._requestedBasicRotation[1];
45323             if (Math.abs(reqX) > Math.abs(x)) {
45324                 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
45325             }
45326             else {
45327                 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
45328             }
45329             if (Math.abs(reqY) > Math.abs(y)) {
45330                 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
45331             }
45332             else {
45333                 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
45334             }
45335             this._requestedBasicRotation = null;
45336             return;
45337         }
45338         if (this._requestedBasicRotationUnbounded != null) {
45339             var reqX = this._requestedBasicRotationUnbounded[0];
45340             var reqY = this._requestedBasicRotationUnbounded[1];
45341             if (Math.abs(reqX) > 0) {
45342                 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
45343             }
45344             if (Math.abs(reqY) > 0) {
45345                 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
45346             }
45347             if (this._desiredLookat != null) {
45348                 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
45349                 desiredBasicLookat[0] += reqX;
45350                 desiredBasicLookat[1] += reqY;
45351                 this._desiredLookat = new THREE.Vector3()
45352                     .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
45353             }
45354             this._requestedBasicRotationUnbounded = null;
45355         }
45356         if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
45357             return;
45358         }
45359         this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
45360         this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
45361         if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
45362             Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
45363             this._basicRotation = [0, 0];
45364         }
45365     };
45366     InteractiveStateBase.prototype._clearRotation = function () {
45367         if (this._currentNode.fullPano) {
45368             return;
45369         }
45370         if (this._requestedRotationDelta != null) {
45371             this._requestedRotationDelta = null;
45372         }
45373         if (!this._rotationDelta.isZero) {
45374             this._rotationDelta.reset();
45375         }
45376         if (this._requestedBasicRotation != null) {
45377             this._requestedBasicRotation = null;
45378         }
45379         if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
45380             this._basicRotation = [0, 0];
45381         }
45382     };
45383     InteractiveStateBase.prototype._setDesiredCenter = function () {
45384         if (this._desiredCenter == null) {
45385             return;
45386         }
45387         var lookatDirection = new THREE.Vector3()
45388             .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
45389             .sub(this._currentCamera.position);
45390         this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
45391         this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
45392         this._desiredCenter = null;
45393     };
45394     InteractiveStateBase.prototype._setDesiredZoom = function () {
45395         this._desiredZoom =
45396             this._currentNode.fullPano || this._previousNode == null ?
45397                 this._zoom : 0;
45398     };
45399     return InteractiveStateBase;
45400 }(State_1.StateBase));
45401 exports.InteractiveStateBase = InteractiveStateBase;
45402 exports.default = InteractiveStateBase;
45403
45404
45405 },{"../../State":282,"three":226}],419:[function(require,module,exports){
45406 "use strict";
45407 var __extends = (this && this.__extends) || (function () {
45408     var extendStatics = function (d, b) {
45409         extendStatics = Object.setPrototypeOf ||
45410             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45411             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45412         return extendStatics(d, b);
45413     }
45414     return function (d, b) {
45415         extendStatics(d, b);
45416         function __() { this.constructor = d; }
45417         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45418     };
45419 })();
45420 Object.defineProperty(exports, "__esModule", { value: true });
45421 var State_1 = require("../../State");
45422 var InteractiveWaitingState = /** @class */ (function (_super) {
45423     __extends(InteractiveWaitingState, _super);
45424     function InteractiveWaitingState(state) {
45425         var _this = _super.call(this, state) || this;
45426         _this._adjustCameras();
45427         _this._motionless = _this._motionlessTransition();
45428         return _this;
45429     }
45430     InteractiveWaitingState.prototype.traverse = function () {
45431         return new State_1.TraversingState(this);
45432     };
45433     InteractiveWaitingState.prototype.wait = function () {
45434         return new State_1.WaitingState(this);
45435     };
45436     InteractiveWaitingState.prototype.prepend = function (nodes) {
45437         _super.prototype.prepend.call(this, nodes);
45438         this._motionless = this._motionlessTransition();
45439     };
45440     InteractiveWaitingState.prototype.set = function (nodes) {
45441         _super.prototype.set.call(this, nodes);
45442         this._motionless = this._motionlessTransition();
45443     };
45444     InteractiveWaitingState.prototype.move = function (delta) {
45445         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
45446     };
45447     InteractiveWaitingState.prototype.moveTo = function (position) {
45448         this._alpha = Math.max(0, Math.min(1, position));
45449     };
45450     InteractiveWaitingState.prototype.update = function (fps) {
45451         this._updateRotation();
45452         if (!this._rotationDelta.isZero) {
45453             this._applyRotation(this._rotationDelta, this._previousCamera);
45454             this._applyRotation(this._rotationDelta, this._currentCamera);
45455         }
45456         this._updateRotationBasic();
45457         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
45458             this._applyRotationBasic(this._basicRotation);
45459         }
45460         var animationSpeed = this._animationSpeed * (60 / fps);
45461         this._updateZoom(animationSpeed);
45462         this._updateLookat(animationSpeed);
45463         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
45464     };
45465     InteractiveWaitingState.prototype._getAlpha = function () {
45466         return this._motionless ? Math.round(this._alpha) : this._alpha;
45467     };
45468     InteractiveWaitingState.prototype._setCurrentCamera = function () {
45469         _super.prototype._setCurrentCamera.call(this);
45470         this._adjustCameras();
45471     };
45472     InteractiveWaitingState.prototype._adjustCameras = function () {
45473         if (this._previousNode == null) {
45474             return;
45475         }
45476         if (this._currentNode.fullPano) {
45477             var lookat = this._camera.lookat.clone().sub(this._camera.position);
45478             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
45479         }
45480         if (this._previousNode.fullPano) {
45481             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
45482             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
45483         }
45484     };
45485     return InteractiveWaitingState;
45486 }(State_1.InteractiveStateBase));
45487 exports.InteractiveWaitingState = InteractiveWaitingState;
45488 exports.default = InteractiveWaitingState;
45489
45490 },{"../../State":282}],420:[function(require,module,exports){
45491 "use strict";
45492 Object.defineProperty(exports, "__esModule", { value: true });
45493 var Error_1 = require("../../Error");
45494 var Geo_1 = require("../../Geo");
45495 var State_1 = require("../../State");
45496 var StateBase = /** @class */ (function () {
45497     function StateBase(state) {
45498         this._spatial = new Geo_1.Spatial();
45499         this._geoCoords = new Geo_1.GeoCoords();
45500         this._referenceThreshold = 0.01;
45501         this._transitionMode = state.transitionMode;
45502         this._reference = state.reference;
45503         this._alpha = state.alpha;
45504         this._camera = state.camera.clone();
45505         this._zoom = state.zoom;
45506         this._currentIndex = state.currentIndex;
45507         this._trajectory = state.trajectory.slice();
45508         this._trajectoryTransforms = [];
45509         this._trajectoryCameras = [];
45510         for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
45511             var node = _a[_i];
45512             var translation = this._nodeToTranslation(node, this._reference);
45513             var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image, undefined, node.ck1, node.ck2, node.cameraProjection);
45514             this._trajectoryTransforms.push(transform);
45515             this._trajectoryCameras.push(new Geo_1.Camera(transform));
45516         }
45517         this._currentNode = this._trajectory.length > 0 ?
45518             this._trajectory[this._currentIndex] :
45519             null;
45520         this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
45521             this._trajectory[this._currentIndex - 1] :
45522             null;
45523         this._currentCamera = this._trajectoryCameras.length > 0 ?
45524             this._trajectoryCameras[this._currentIndex].clone() :
45525             new Geo_1.Camera();
45526         this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
45527             this._trajectoryCameras[this._currentIndex - 1].clone() :
45528             this._currentCamera.clone();
45529     }
45530     Object.defineProperty(StateBase.prototype, "reference", {
45531         get: function () {
45532             return this._reference;
45533         },
45534         enumerable: true,
45535         configurable: true
45536     });
45537     Object.defineProperty(StateBase.prototype, "alpha", {
45538         get: function () {
45539             return this._getAlpha();
45540         },
45541         enumerable: true,
45542         configurable: true
45543     });
45544     Object.defineProperty(StateBase.prototype, "camera", {
45545         get: function () {
45546             return this._camera;
45547         },
45548         enumerable: true,
45549         configurable: true
45550     });
45551     Object.defineProperty(StateBase.prototype, "zoom", {
45552         get: function () {
45553             return this._zoom;
45554         },
45555         enumerable: true,
45556         configurable: true
45557     });
45558     Object.defineProperty(StateBase.prototype, "trajectory", {
45559         get: function () {
45560             return this._trajectory;
45561         },
45562         enumerable: true,
45563         configurable: true
45564     });
45565     Object.defineProperty(StateBase.prototype, "currentIndex", {
45566         get: function () {
45567             return this._currentIndex;
45568         },
45569         enumerable: true,
45570         configurable: true
45571     });
45572     Object.defineProperty(StateBase.prototype, "currentNode", {
45573         get: function () {
45574             return this._currentNode;
45575         },
45576         enumerable: true,
45577         configurable: true
45578     });
45579     Object.defineProperty(StateBase.prototype, "previousNode", {
45580         get: function () {
45581             return this._previousNode;
45582         },
45583         enumerable: true,
45584         configurable: true
45585     });
45586     Object.defineProperty(StateBase.prototype, "currentCamera", {
45587         get: function () {
45588             return this._currentCamera;
45589         },
45590         enumerable: true,
45591         configurable: true
45592     });
45593     Object.defineProperty(StateBase.prototype, "currentTransform", {
45594         get: function () {
45595             return this._trajectoryTransforms.length > 0 ?
45596                 this._trajectoryTransforms[this.currentIndex] : null;
45597         },
45598         enumerable: true,
45599         configurable: true
45600     });
45601     Object.defineProperty(StateBase.prototype, "previousTransform", {
45602         get: function () {
45603             return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
45604                 this._trajectoryTransforms[this.currentIndex - 1] : null;
45605         },
45606         enumerable: true,
45607         configurable: true
45608     });
45609     Object.defineProperty(StateBase.prototype, "motionless", {
45610         get: function () {
45611             return this._motionless;
45612         },
45613         enumerable: true,
45614         configurable: true
45615     });
45616     Object.defineProperty(StateBase.prototype, "transitionMode", {
45617         get: function () {
45618             return this._transitionMode;
45619         },
45620         enumerable: true,
45621         configurable: true
45622     });
45623     StateBase.prototype.earth = function () { throw new Error("Not implemented"); };
45624     StateBase.prototype.traverse = function () { throw new Error("Not implemented"); };
45625     StateBase.prototype.wait = function () { throw new Error("Not implemented"); };
45626     StateBase.prototype.waitInteractively = function () { throw new Error("Not implemented"); };
45627     StateBase.prototype.move = function (delta) { };
45628     StateBase.prototype.moveTo = function (position) { };
45629     StateBase.prototype.rotate = function (delta) { };
45630     StateBase.prototype.rotateUnbounded = function (delta) { };
45631     StateBase.prototype.rotateWithoutInertia = function (delta) { };
45632     StateBase.prototype.rotateBasic = function (basicRotation) { };
45633     StateBase.prototype.rotateBasicUnbounded = function (basicRotation) { };
45634     StateBase.prototype.rotateBasicWithoutInertia = function (basicRotation) { };
45635     StateBase.prototype.rotateToBasic = function (basic) { };
45636     StateBase.prototype.setSpeed = function (speed) { };
45637     StateBase.prototype.zoomIn = function (delta, reference) { };
45638     StateBase.prototype.update = function (fps) { };
45639     StateBase.prototype.setCenter = function (center) { };
45640     StateBase.prototype.setZoom = function (zoom) { };
45641     StateBase.prototype.dolly = function (delta) { };
45642     StateBase.prototype.orbit = function (rotation) { };
45643     StateBase.prototype.truck = function (direction) { };
45644     StateBase.prototype.append = function (nodes) {
45645         if (nodes.length < 1) {
45646             throw Error("Trajectory can not be empty");
45647         }
45648         if (this._currentIndex < 0) {
45649             this.set(nodes);
45650         }
45651         else {
45652             this._trajectory = this._trajectory.concat(nodes);
45653             this._appendToTrajectories(nodes);
45654         }
45655     };
45656     StateBase.prototype.prepend = function (nodes) {
45657         if (nodes.length < 1) {
45658             throw Error("Trajectory can not be empty");
45659         }
45660         this._trajectory = nodes.slice().concat(this._trajectory);
45661         this._currentIndex += nodes.length;
45662         this._setCurrentNode();
45663         var referenceReset = this._setReference(this._currentNode);
45664         if (referenceReset) {
45665             this._setTrajectories();
45666         }
45667         else {
45668             this._prependToTrajectories(nodes);
45669         }
45670         this._setCurrentCamera();
45671     };
45672     StateBase.prototype.remove = function (n) {
45673         if (n < 0) {
45674             throw Error("n must be a positive integer");
45675         }
45676         if (this._currentIndex - 1 < n) {
45677             throw Error("Current and previous nodes can not be removed");
45678         }
45679         for (var i = 0; i < n; i++) {
45680             this._trajectory.shift();
45681             this._trajectoryTransforms.shift();
45682             this._trajectoryCameras.shift();
45683             this._currentIndex--;
45684         }
45685         this._setCurrentNode();
45686     };
45687     StateBase.prototype.clearPrior = function () {
45688         if (this._currentIndex > 0) {
45689             this.remove(this._currentIndex - 1);
45690         }
45691     };
45692     StateBase.prototype.clear = function () {
45693         this.cut();
45694         if (this._currentIndex > 0) {
45695             this.remove(this._currentIndex - 1);
45696         }
45697     };
45698     StateBase.prototype.cut = function () {
45699         while (this._trajectory.length - 1 > this._currentIndex) {
45700             this._trajectory.pop();
45701             this._trajectoryTransforms.pop();
45702             this._trajectoryCameras.pop();
45703         }
45704     };
45705     StateBase.prototype.set = function (nodes) {
45706         this._setTrajectory(nodes);
45707         this._setCurrentNode();
45708         this._setReference(this._currentNode);
45709         this._setTrajectories();
45710         this._setCurrentCamera();
45711     };
45712     StateBase.prototype.getCenter = function () {
45713         return this._currentNode != null ?
45714             this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
45715             [0.5, 0.5];
45716     };
45717     StateBase.prototype.setTransitionMode = function (mode) {
45718         this._transitionMode = mode;
45719     };
45720     StateBase.prototype._getAlpha = function () { return 1; };
45721     StateBase.prototype._setCurrent = function () {
45722         this._setCurrentNode();
45723         var referenceReset = this._setReference(this._currentNode);
45724         if (referenceReset) {
45725             this._setTrajectories();
45726         }
45727         this._setCurrentCamera();
45728     };
45729     StateBase.prototype._setCurrentCamera = function () {
45730         this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
45731         this._previousCamera = this._currentIndex > 0 ?
45732             this._trajectoryCameras[this._currentIndex - 1].clone() :
45733             this._currentCamera.clone();
45734     };
45735     StateBase.prototype._motionlessTransition = function () {
45736         var nodesSet = this._currentNode != null && this._previousNode != null;
45737         return nodesSet && (this._transitionMode === State_1.TransitionMode.Instantaneous || !(this._currentNode.merged &&
45738             this._previousNode.merged &&
45739             this._withinOriginalDistance() &&
45740             this._sameConnectedComponent()));
45741     };
45742     StateBase.prototype._setReference = function (node) {
45743         // do not reset reference if node is within threshold distance
45744         if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
45745             Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
45746             return false;
45747         }
45748         // do not reset reference if previous node exist and transition is with motion
45749         if (this._previousNode != null && !this._motionlessTransition()) {
45750             return false;
45751         }
45752         this._reference.lat = node.latLon.lat;
45753         this._reference.lon = node.latLon.lon;
45754         this._reference.alt = node.alt;
45755         return true;
45756     };
45757     StateBase.prototype._setCurrentNode = function () {
45758         this._currentNode = this._trajectory.length > 0 ?
45759             this._trajectory[this._currentIndex] :
45760             null;
45761         this._previousNode = this._currentIndex > 0 ?
45762             this._trajectory[this._currentIndex - 1] :
45763             null;
45764     };
45765     StateBase.prototype._setTrajectory = function (nodes) {
45766         if (nodes.length < 1) {
45767             throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
45768         }
45769         if (this._currentNode != null) {
45770             this._trajectory = [this._currentNode].concat(nodes);
45771             this._currentIndex = 1;
45772         }
45773         else {
45774             this._trajectory = nodes.slice();
45775             this._currentIndex = 0;
45776         }
45777     };
45778     StateBase.prototype._setTrajectories = function () {
45779         this._trajectoryTransforms.length = 0;
45780         this._trajectoryCameras.length = 0;
45781         this._appendToTrajectories(this._trajectory);
45782     };
45783     StateBase.prototype._appendToTrajectories = function (nodes) {
45784         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
45785             var node = nodes_1[_i];
45786             if (!node.assetsCached) {
45787                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
45788             }
45789             var translation = this._nodeToTranslation(node, this.reference);
45790             var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image, undefined, node.ck1, node.ck2, node.cameraProjection);
45791             this._trajectoryTransforms.push(transform);
45792             this._trajectoryCameras.push(new Geo_1.Camera(transform));
45793         }
45794     };
45795     StateBase.prototype._prependToTrajectories = function (nodes) {
45796         for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
45797             var node = _a[_i];
45798             if (!node.assetsCached) {
45799                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
45800             }
45801             var translation = this._nodeToTranslation(node, this.reference);
45802             var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image, undefined, node.ck1, node.ck2, node.cameraProjection);
45803             this._trajectoryTransforms.unshift(transform);
45804             this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
45805         }
45806     };
45807     StateBase.prototype._nodeToTranslation = function (node, reference) {
45808         return Geo_1.Geo.computeTranslation({ alt: node.alt, lat: node.latLon.lat, lon: node.latLon.lon }, node.rotation, reference);
45809     };
45810     StateBase.prototype._sameConnectedComponent = function () {
45811         var current = this._currentNode;
45812         var previous = this._previousNode;
45813         return !!current && !!previous &&
45814             current.mergeCC === previous.mergeCC;
45815     };
45816     StateBase.prototype._withinOriginalDistance = function () {
45817         var current = this._currentNode;
45818         var previous = this._previousNode;
45819         if (!current || !previous) {
45820             return true;
45821         }
45822         // 50 km/h moves 28m in 2s
45823         var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
45824         return distance < 25;
45825     };
45826     return StateBase;
45827 }());
45828 exports.StateBase = StateBase;
45829
45830 },{"../../Error":277,"../../Geo":278,"../../State":282}],421:[function(require,module,exports){
45831 "use strict";
45832 var __extends = (this && this.__extends) || (function () {
45833     var extendStatics = function (d, b) {
45834         extendStatics = Object.setPrototypeOf ||
45835             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45836             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45837         return extendStatics(d, b);
45838     }
45839     return function (d, b) {
45840         extendStatics(d, b);
45841         function __() { this.constructor = d; }
45842         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45843     };
45844 })();
45845 Object.defineProperty(exports, "__esModule", { value: true });
45846 var UnitBezier = require("@mapbox/unitbezier");
45847 var State_1 = require("../../State");
45848 var TraversingState = /** @class */ (function (_super) {
45849     __extends(TraversingState, _super);
45850     function TraversingState(state) {
45851         var _this = _super.call(this, state) || this;
45852         _this._adjustCameras();
45853         _this._motionless = _this._motionlessTransition();
45854         _this._baseAlpha = _this._alpha;
45855         _this._speedCoefficient = 1;
45856         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
45857         _this._useBezier = false;
45858         return _this;
45859     }
45860     TraversingState.prototype.earth = function () {
45861         return new State_1.EarthState(this);
45862     };
45863     TraversingState.prototype.wait = function () {
45864         return new State_1.WaitingState(this);
45865     };
45866     TraversingState.prototype.waitInteractively = function () {
45867         return new State_1.InteractiveWaitingState(this);
45868     };
45869     TraversingState.prototype.append = function (nodes) {
45870         var emptyTrajectory = this._trajectory.length === 0;
45871         if (emptyTrajectory) {
45872             this._resetTransition();
45873         }
45874         _super.prototype.append.call(this, nodes);
45875         if (emptyTrajectory) {
45876             this._setDesiredCenter();
45877             this._setDesiredZoom();
45878         }
45879     };
45880     TraversingState.prototype.prepend = function (nodes) {
45881         var emptyTrajectory = this._trajectory.length === 0;
45882         if (emptyTrajectory) {
45883             this._resetTransition();
45884         }
45885         _super.prototype.prepend.call(this, nodes);
45886         if (emptyTrajectory) {
45887             this._setDesiredCenter();
45888             this._setDesiredZoom();
45889         }
45890     };
45891     TraversingState.prototype.set = function (nodes) {
45892         _super.prototype.set.call(this, nodes);
45893         this._desiredLookat = null;
45894         this._resetTransition();
45895         this._clearRotation();
45896         this._setDesiredCenter();
45897         this._setDesiredZoom();
45898         if (this._trajectory.length < 3) {
45899             this._useBezier = true;
45900         }
45901     };
45902     TraversingState.prototype.setSpeed = function (speed) {
45903         this._speedCoefficient = this._spatial.clamp(speed, 0, 10);
45904     };
45905     TraversingState.prototype.update = function (fps) {
45906         if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
45907             this._currentIndex += 1;
45908             this._useBezier = this._trajectory.length < 3 &&
45909                 this._currentIndex + 1 === this._trajectory.length;
45910             this._setCurrent();
45911             this._resetTransition();
45912             this._clearRotation();
45913             this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
45914             this._desiredLookat = null;
45915         }
45916         var animationSpeed = this._animationSpeed * (60 / fps);
45917         this._baseAlpha = Math.min(1, this._baseAlpha + this._speedCoefficient * animationSpeed);
45918         if (this._useBezier) {
45919             this._alpha = this._unitBezier.solve(this._baseAlpha);
45920         }
45921         else {
45922             this._alpha = this._baseAlpha;
45923         }
45924         this._updateRotation();
45925         if (!this._rotationDelta.isZero) {
45926             this._applyRotation(this._rotationDelta, this._previousCamera);
45927             this._applyRotation(this._rotationDelta, this._currentCamera);
45928         }
45929         this._updateRotationBasic();
45930         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
45931             this._applyRotationBasic(this._basicRotation);
45932         }
45933         this._updateZoom(animationSpeed);
45934         this._updateLookat(animationSpeed);
45935         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
45936     };
45937     TraversingState.prototype._getAlpha = function () {
45938         return this._motionless ? Math.ceil(this._alpha) : this._alpha;
45939     };
45940     TraversingState.prototype._setCurrentCamera = function () {
45941         _super.prototype._setCurrentCamera.call(this);
45942         this._adjustCameras();
45943     };
45944     TraversingState.prototype._adjustCameras = function () {
45945         if (this._previousNode == null) {
45946             return;
45947         }
45948         var lookat = this._camera.lookat.clone().sub(this._camera.position);
45949         this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
45950         if (this._currentNode.fullPano) {
45951             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
45952         }
45953     };
45954     TraversingState.prototype._resetTransition = function () {
45955         this._alpha = 0;
45956         this._baseAlpha = 0;
45957         this._motionless = this._motionlessTransition();
45958     };
45959     return TraversingState;
45960 }(State_1.InteractiveStateBase));
45961 exports.TraversingState = TraversingState;
45962 exports.default = TraversingState;
45963
45964 },{"../../State":282,"@mapbox/unitbezier":2}],422:[function(require,module,exports){
45965 "use strict";
45966 var __extends = (this && this.__extends) || (function () {
45967     var extendStatics = function (d, b) {
45968         extendStatics = Object.setPrototypeOf ||
45969             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45970             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45971         return extendStatics(d, b);
45972     }
45973     return function (d, b) {
45974         extendStatics(d, b);
45975         function __() { this.constructor = d; }
45976         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45977     };
45978 })();
45979 Object.defineProperty(exports, "__esModule", { value: true });
45980 var State_1 = require("../../State");
45981 var WaitingState = /** @class */ (function (_super) {
45982     __extends(WaitingState, _super);
45983     function WaitingState(state) {
45984         var _this = _super.call(this, state) || this;
45985         _this._zoom = 0;
45986         _this._adjustCameras();
45987         _this._motionless = _this._motionlessTransition();
45988         return _this;
45989     }
45990     WaitingState.prototype.traverse = function () {
45991         return new State_1.TraversingState(this);
45992     };
45993     WaitingState.prototype.waitInteractively = function () {
45994         return new State_1.InteractiveWaitingState(this);
45995     };
45996     WaitingState.prototype.prepend = function (nodes) {
45997         _super.prototype.prepend.call(this, nodes);
45998         this._motionless = this._motionlessTransition();
45999     };
46000     WaitingState.prototype.set = function (nodes) {
46001         _super.prototype.set.call(this, nodes);
46002         this._motionless = this._motionlessTransition();
46003     };
46004     WaitingState.prototype.move = function (delta) {
46005         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
46006     };
46007     WaitingState.prototype.moveTo = function (position) {
46008         this._alpha = Math.max(0, Math.min(1, position));
46009     };
46010     WaitingState.prototype.update = function (fps) {
46011         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
46012     };
46013     WaitingState.prototype._getAlpha = function () {
46014         return this._motionless ? Math.round(this._alpha) : this._alpha;
46015     };
46016     WaitingState.prototype._setCurrentCamera = function () {
46017         _super.prototype._setCurrentCamera.call(this);
46018         this._adjustCameras();
46019     };
46020     WaitingState.prototype._adjustCameras = function () {
46021         if (this._previousNode == null) {
46022             return;
46023         }
46024         if (this._currentNode.fullPano) {
46025             var lookat = this._camera.lookat.clone().sub(this._camera.position);
46026             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
46027         }
46028         if (this._previousNode.fullPano) {
46029             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
46030             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
46031         }
46032     };
46033     return WaitingState;
46034 }(State_1.StateBase));
46035 exports.WaitingState = WaitingState;
46036 exports.default = WaitingState;
46037
46038 },{"../../State":282}],423:[function(require,module,exports){
46039 "use strict";
46040 Object.defineProperty(exports, "__esModule", { value: true });
46041 var rxjs_1 = require("rxjs");
46042 /**
46043  * @class ImageTileLoader
46044  *
46045  * @classdesc Represents a loader of image tiles.
46046  */
46047 var ImageTileLoader = /** @class */ (function () {
46048     /**
46049      * Create a new node image tile loader instance.
46050      *
46051      * @param {string} scheme - The URI scheme.
46052      * @param {string} host - The URI host.
46053      * @param {string} [origin] - The origin query param.
46054      */
46055     function ImageTileLoader(scheme, host, origin) {
46056         this._scheme = scheme;
46057         this._host = host;
46058         this._origin = origin != null ? "?origin=" + origin : "";
46059     }
46060     /**
46061      * Retrieve an image tile.
46062      *
46063      * @description Retrieve an image tile by specifying the area
46064      * as well as the scaled size.
46065      *
46066      * @param {string} identifier - The identifier of the image.
46067      * @param {number} x - The top left x pixel coordinate for the tile
46068      * in the original image.
46069      * @param {number} y - The top left y pixel coordinate for the tile
46070      * in the original image.
46071      * @param {number} w - The pixel width of the tile in the original image.
46072      * @param {number} h - The pixel height of the tile in the original image.
46073      * @param {number} scaledW - The scaled width of the returned tile.
46074      * @param {number} scaledH - The scaled height of the returned tile.
46075      */
46076     ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
46077         var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
46078         var url = this._scheme +
46079             "://" +
46080             this._host +
46081             characteristics +
46082             this._origin;
46083         var xmlHTTP = null;
46084         return [rxjs_1.Observable.create(function (subscriber) {
46085                 xmlHTTP = new XMLHttpRequest();
46086                 xmlHTTP.open("GET", url, true);
46087                 xmlHTTP.responseType = "arraybuffer";
46088                 xmlHTTP.timeout = 15000;
46089                 xmlHTTP.onload = function (event) {
46090                     if (xmlHTTP.status !== 200) {
46091                         subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
46092                             ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
46093                         return;
46094                     }
46095                     var image = new Image();
46096                     image.crossOrigin = "Anonymous";
46097                     image.onload = function (e) {
46098                         subscriber.next(image);
46099                         subscriber.complete();
46100                     };
46101                     image.onerror = function (error) {
46102                         subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
46103                     };
46104                     var blob = new Blob([xmlHTTP.response]);
46105                     image.src = window.URL.createObjectURL(blob);
46106                 };
46107                 xmlHTTP.onerror = function (error) {
46108                     subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
46109                 };
46110                 xmlHTTP.ontimeout = function (error) {
46111                     subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
46112                 };
46113                 xmlHTTP.onabort = function (event) {
46114                     subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
46115                 };
46116                 xmlHTTP.send(null);
46117             }),
46118             function () {
46119                 if (xmlHTTP != null) {
46120                     xmlHTTP.abort();
46121                 }
46122             },
46123         ];
46124     };
46125     return ImageTileLoader;
46126 }());
46127 exports.ImageTileLoader = ImageTileLoader;
46128 exports.default = ImageTileLoader;
46129
46130 },{"rxjs":27}],424:[function(require,module,exports){
46131 "use strict";
46132 Object.defineProperty(exports, "__esModule", { value: true });
46133 /**
46134  * @class ImageTileStore
46135  *
46136  * @classdesc Represents a store for image tiles.
46137  */
46138 var ImageTileStore = /** @class */ (function () {
46139     /**
46140      * Create a new node image tile store instance.
46141      */
46142     function ImageTileStore() {
46143         this._images = {};
46144     }
46145     /**
46146      * Add an image tile to the store.
46147      *
46148      * @param {HTMLImageElement} image - The image tile.
46149      * @param {string} key - The identifier for the tile.
46150      * @param {number} level - The level of the tile.
46151      */
46152     ImageTileStore.prototype.addImage = function (image, key, level) {
46153         if (!(level in this._images)) {
46154             this._images[level] = {};
46155         }
46156         this._images[level][key] = image;
46157     };
46158     /**
46159      * Dispose the store.
46160      *
46161      * @description Disposes all cached assets.
46162      */
46163     ImageTileStore.prototype.dispose = function () {
46164         for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
46165             var level = _a[_i];
46166             var levelImages = this._images[level];
46167             for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
46168                 var key = _c[_b];
46169                 window.URL.revokeObjectURL(levelImages[key].src);
46170                 delete levelImages[key];
46171             }
46172             delete this._images[level];
46173         }
46174     };
46175     /**
46176      * Get an image tile from the store.
46177      *
46178      * @param {string} key - The identifier for the tile.
46179      * @param {number} level - The level of the tile.
46180      */
46181     ImageTileStore.prototype.getImage = function (key, level) {
46182         return this._images[level][key];
46183     };
46184     /**
46185      * Check if an image tile exist in the store.
46186      *
46187      * @param {string} key - The identifier for the tile.
46188      * @param {number} level - The level of the tile.
46189      */
46190     ImageTileStore.prototype.hasImage = function (key, level) {
46191         return level in this._images && key in this._images[level];
46192     };
46193     return ImageTileStore;
46194 }());
46195 exports.ImageTileStore = ImageTileStore;
46196 exports.default = ImageTileStore;
46197
46198 },{}],425:[function(require,module,exports){
46199 "use strict";
46200 Object.defineProperty(exports, "__esModule", { value: true });
46201 var Geo_1 = require("../Geo");
46202 /**
46203  * @class RegionOfInterestCalculator
46204  *
46205  * @classdesc Represents a calculator for regions of interest.
46206  */
46207 var RegionOfInterestCalculator = /** @class */ (function () {
46208     function RegionOfInterestCalculator() {
46209         this._viewportCoords = new Geo_1.ViewportCoords();
46210     }
46211     /**
46212      * Compute a region of interest based on the current render camera
46213      * and the viewport size.
46214      *
46215      * @param {RenderCamera} renderCamera - Render camera used for unprojections.
46216      * @param {ISize} size - Viewport size in pixels.
46217      * @param {Transform} transform - Transform used for projections.
46218      *
46219      * @returns {IRegionOfInterest} A region of interest.
46220      */
46221     RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
46222         var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
46223         var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
46224         this._clipBoundingBox(bbox);
46225         var viewportPixelWidth = 2 / size.width;
46226         var viewportPixelHeight = 2 / size.height;
46227         var centralViewportPixel = [
46228             [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
46229             [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
46230             [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
46231             [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
46232         ];
46233         var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
46234         return {
46235             bbox: bbox,
46236             pixelHeight: cpbox.maxY - cpbox.minY,
46237             pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
46238         };
46239     };
46240     RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
46241         var points = [];
46242         var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
46243         var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
46244         for (var side = 0; side < 4; ++side) {
46245             var o = os[side];
46246             var d = ds[side];
46247             for (var i = 0; i < pointsPerSide; ++i) {
46248                 points.push([o[0] + d[0] * i / pointsPerSide,
46249                     o[1] + d[1] * i / pointsPerSide]);
46250             }
46251         }
46252         return points;
46253     };
46254     RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
46255         var _this = this;
46256         var basicPoints = viewportPoints
46257             .map(function (point) {
46258             return _this._viewportCoords
46259                 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
46260         });
46261         if (transform.gpano != null) {
46262             return this._boundingBoxPano(basicPoints);
46263         }
46264         else {
46265             return this._boundingBox(basicPoints);
46266         }
46267     };
46268     RegionOfInterestCalculator.prototype._boundingBox = function (points) {
46269         var bbox = {
46270             maxX: Number.NEGATIVE_INFINITY,
46271             maxY: Number.NEGATIVE_INFINITY,
46272             minX: Number.POSITIVE_INFINITY,
46273             minY: Number.POSITIVE_INFINITY,
46274         };
46275         for (var i = 0; i < points.length; ++i) {
46276             bbox.minX = Math.min(bbox.minX, points[i][0]);
46277             bbox.maxX = Math.max(bbox.maxX, points[i][0]);
46278             bbox.minY = Math.min(bbox.minY, points[i][1]);
46279             bbox.maxY = Math.max(bbox.maxY, points[i][1]);
46280         }
46281         return bbox;
46282     };
46283     RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
46284         var _this = this;
46285         var xs = [];
46286         var ys = [];
46287         for (var i = 0; i < points.length; ++i) {
46288             xs.push(points[i][0]);
46289             ys.push(points[i][1]);
46290         }
46291         xs.sort(function (a, b) { return _this._sign(a - b); });
46292         ys.sort(function (a, b) { return _this._sign(a - b); });
46293         var intervalX = this._intervalPano(xs);
46294         return {
46295             maxX: intervalX[1],
46296             maxY: ys[ys.length - 1],
46297             minX: intervalX[0],
46298             minY: ys[0],
46299         };
46300     };
46301     /**
46302      * Find the max interval between consecutive numbers.
46303      * Assumes numbers are between 0 and 1, sorted and that
46304      * x is equivalent to x + 1.
46305      */
46306     RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
46307         var maxdx = 0;
46308         var maxi = -1;
46309         for (var i = 0; i < xs.length - 1; ++i) {
46310             var dx = xs[i + 1] - xs[i];
46311             if (dx > maxdx) {
46312                 maxdx = dx;
46313                 maxi = i;
46314             }
46315         }
46316         var loopdx = xs[0] + 1 - xs[xs.length - 1];
46317         if (loopdx > maxdx) {
46318             return [xs[0], xs[xs.length - 1]];
46319         }
46320         else {
46321             return [xs[maxi + 1], xs[maxi]];
46322         }
46323     };
46324     RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
46325         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
46326         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
46327         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
46328         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
46329     };
46330     RegionOfInterestCalculator.prototype._sign = function (n) {
46331         return n > 0 ? 1 : n < 0 ? -1 : 0;
46332     };
46333     return RegionOfInterestCalculator;
46334 }());
46335 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
46336 exports.default = RegionOfInterestCalculator;
46337
46338 },{"../Geo":278}],426:[function(require,module,exports){
46339 "use strict";
46340 Object.defineProperty(exports, "__esModule", { value: true });
46341 var operators_1 = require("rxjs/operators");
46342 var THREE = require("three");
46343 var rxjs_1 = require("rxjs");
46344 /**
46345  * @class TextureProvider
46346  *
46347  * @classdesc Represents a provider of textures.
46348  */
46349 var TextureProvider = /** @class */ (function () {
46350     /**
46351      * Create a new node texture provider instance.
46352      *
46353      * @param {string} key - The identifier of the image for which to request tiles.
46354      * @param {number} width - The full width of the original image.
46355      * @param {number} height - The full height of the original image.
46356      * @param {number} tileSize - The size used when requesting tiles.
46357      * @param {HTMLImageElement} background - Image to use as background.
46358      * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
46359      * @param {ImageTileStore} imageTileStore - Store for saving tiles.
46360      * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
46361      */
46362     function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
46363         this._disposed = false;
46364         this._key = key;
46365         if (width <= 0 || height <= 0) {
46366             console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
46367         }
46368         this._width = width;
46369         this._height = height;
46370         this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
46371         this._currentLevel = -1;
46372         this._tileSize = tileSize;
46373         this._updated$ = new rxjs_1.Subject();
46374         this._createdSubject$ = new rxjs_1.Subject();
46375         this._created$ = this._createdSubject$.pipe(operators_1.publishReplay(1), operators_1.refCount());
46376         this._createdSubscription = this._created$.subscribe(function () { });
46377         this._hasSubject$ = new rxjs_1.Subject();
46378         this._has$ = this._hasSubject$.pipe(operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
46379         this._hasSubscription = this._has$.subscribe(function () { });
46380         this._abortFunctions = [];
46381         this._tileSubscriptions = {};
46382         this._renderedCurrentLevelTiles = {};
46383         this._renderedTiles = {};
46384         this._background = background;
46385         this._camera = null;
46386         this._imageTileLoader = imageTileLoader;
46387         this._imageTileStore = imageTileStore;
46388         this._renderer = renderer;
46389         this._renderTarget = null;
46390         this._roi = null;
46391     }
46392     Object.defineProperty(TextureProvider.prototype, "disposed", {
46393         /**
46394          * Get disposed.
46395          *
46396          * @returns {boolean} Value indicating whether provider has
46397          * been disposed.
46398          */
46399         get: function () {
46400             return this._disposed;
46401         },
46402         enumerable: true,
46403         configurable: true
46404     });
46405     Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
46406         /**
46407          * Get hasTexture$.
46408          *
46409          * @returns {Observable<boolean>} Observable emitting
46410          * values indicating when the existance of a texture
46411          * changes.
46412          */
46413         get: function () {
46414             return this._has$;
46415         },
46416         enumerable: true,
46417         configurable: true
46418     });
46419     Object.defineProperty(TextureProvider.prototype, "key", {
46420         /**
46421          * Get key.
46422          *
46423          * @returns {boolean} The identifier of the image for
46424          * which to render textures.
46425          */
46426         get: function () {
46427             return this._key;
46428         },
46429         enumerable: true,
46430         configurable: true
46431     });
46432     Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
46433         /**
46434          * Get textureUpdated$.
46435          *
46436          * @returns {Observable<boolean>} Observable emitting
46437          * values when an existing texture has been updated.
46438          */
46439         get: function () {
46440             return this._updated$;
46441         },
46442         enumerable: true,
46443         configurable: true
46444     });
46445     Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
46446         /**
46447          * Get textureCreated$.
46448          *
46449          * @returns {Observable<boolean>} Observable emitting
46450          * values when a new texture has been created.
46451          */
46452         get: function () {
46453             return this._created$;
46454         },
46455         enumerable: true,
46456         configurable: true
46457     });
46458     /**
46459      * Abort all outstanding image tile requests.
46460      */
46461     TextureProvider.prototype.abort = function () {
46462         for (var key in this._tileSubscriptions) {
46463             if (!this._tileSubscriptions.hasOwnProperty(key)) {
46464                 continue;
46465             }
46466             this._tileSubscriptions[key].unsubscribe();
46467         }
46468         this._tileSubscriptions = {};
46469         for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
46470             var abort = _a[_i];
46471             abort();
46472         }
46473         this._abortFunctions = [];
46474     };
46475     /**
46476      * Dispose the provider.
46477      *
46478      * @description Disposes all cached assets and
46479      * aborts all outstanding image tile requests.
46480      */
46481     TextureProvider.prototype.dispose = function () {
46482         if (this._disposed) {
46483             console.warn("Texture already disposed (" + this._key + ")");
46484             return;
46485         }
46486         this.abort();
46487         if (this._renderTarget != null) {
46488             this._renderTarget.dispose();
46489             this._renderTarget = null;
46490         }
46491         this._imageTileStore.dispose();
46492         this._imageTileStore = null;
46493         this._background = null;
46494         this._camera = null;
46495         this._imageTileLoader = null;
46496         this._renderer = null;
46497         this._roi = null;
46498         this._createdSubscription.unsubscribe();
46499         this._hasSubscription.unsubscribe();
46500         this._disposed = true;
46501     };
46502     /**
46503      * Set the region of interest.
46504      *
46505      * @description When the region of interest is set the
46506      * the tile level is determined and tiles for the region
46507      * are fetched from the store or the loader and renderedLevel
46508      * to the texture.
46509      *
46510      * @param {IRegionOfInterest} roi - Spatial edges to cache.
46511      */
46512     TextureProvider.prototype.setRegionOfInterest = function (roi) {
46513         if (this._width <= 0 || this._height <= 0) {
46514             return;
46515         }
46516         this._roi = roi;
46517         var width = 1 / this._roi.pixelWidth;
46518         var height = 1 / this._roi.pixelHeight;
46519         var size = Math.max(height, width);
46520         var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.ceil(Math.log(size) / Math.log(2))));
46521         if (currentLevel !== this._currentLevel) {
46522             this.abort();
46523             this._currentLevel = currentLevel;
46524             if (!(this._currentLevel in this._renderedTiles)) {
46525                 this._renderedTiles[this._currentLevel] = [];
46526             }
46527             this._renderedCurrentLevelTiles = {};
46528             for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
46529                 var tile = _a[_i];
46530                 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
46531             }
46532         }
46533         var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
46534         var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
46535         var tiles = this._getTiles(topLeft, bottomRight);
46536         if (this._camera == null) {
46537             this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
46538             this._camera.position.z = 1;
46539             var gl = this._renderer.getContext();
46540             var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
46541             var backgroundSize = Math.max(this._width, this._height);
46542             var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
46543             var targetWidth = Math.floor(scale * this._width);
46544             var targetHeight = Math.floor(scale * this._height);
46545             this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
46546                 depthBuffer: false,
46547                 format: THREE.RGBFormat,
46548                 magFilter: THREE.LinearFilter,
46549                 minFilter: THREE.LinearFilter,
46550                 stencilBuffer: false,
46551             });
46552             this._renderToTarget(0, 0, this._width, this._height, this._background);
46553             this._createdSubject$.next(this._renderTarget.texture);
46554             this._hasSubject$.next(true);
46555         }
46556         this._fetchTiles(tiles);
46557     };
46558     TextureProvider.prototype.setTileSize = function (tileSize) {
46559         this._tileSize = tileSize;
46560     };
46561     /**
46562      * Update the image used as background for the texture.
46563      *
46564      * @param {HTMLImageElement} background - The background image.
46565      */
46566     TextureProvider.prototype.updateBackground = function (background) {
46567         this._background = background;
46568     };
46569     /**
46570      * Retrieve an image tile.
46571      *
46572      * @description Retrieve an image tile and render it to the
46573      * texture. Add the tile to the store and emit to the updated
46574      * observable.
46575      *
46576      * @param {Array<number>} tile - The tile coordinates.
46577      * @param {number} level - The tile level.
46578      * @param {number} x - The top left x pixel coordinate of the tile.
46579      * @param {number} y - The top left y pixel coordinate of the tile.
46580      * @param {number} w - The pixel width of the tile.
46581      * @param {number} h - The pixel height of the tile.
46582      * @param {number} scaledW - The scaled width of the returned tile.
46583      * @param {number} scaledH - The scaled height of the returned tile.
46584      */
46585     TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
46586         var _this = this;
46587         var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
46588         var tile$ = getTile[0];
46589         var abort = getTile[1];
46590         this._abortFunctions.push(abort);
46591         var tileKey = this._tileKey(this._tileSize, tile);
46592         var subscription = tile$
46593             .subscribe(function (image) {
46594             _this._renderToTarget(x, y, w, h, image);
46595             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
46596             _this._removeFromArray(abort, _this._abortFunctions);
46597             _this._setTileRendered(tile, _this._currentLevel);
46598             _this._imageTileStore.addImage(image, tileKey, level);
46599             _this._updated$.next(true);
46600         }, function (error) {
46601             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
46602             _this._removeFromArray(abort, _this._abortFunctions);
46603             console.error(error);
46604         });
46605         if (!subscription.closed) {
46606             this._tileSubscriptions[tileKey] = subscription;
46607         }
46608     };
46609     /**
46610      * Retrieve image tiles.
46611      *
46612      * @description Retrieve a image tiles and render them to the
46613      * texture. Retrieve from store if it exists, otherwise Retrieve
46614      * from loader.
46615      *
46616      * @param {Array<Array<number>>} tiles - Array of tile coordinates to
46617      * retrieve.
46618      */
46619     TextureProvider.prototype._fetchTiles = function (tiles) {
46620         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
46621         for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
46622             var tile = tiles_1[_i];
46623             var tileKey = this._tileKey(this._tileSize, tile);
46624             if (tileKey in this._renderedCurrentLevelTiles ||
46625                 tileKey in this._tileSubscriptions) {
46626                 continue;
46627             }
46628             var tileX = tileSize * tile[0];
46629             var tileY = tileSize * tile[1];
46630             var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
46631             var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
46632             if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
46633                 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
46634                 this._setTileRendered(tile, this._currentLevel);
46635                 this._updated$.next(true);
46636                 continue;
46637             }
46638             var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
46639             var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
46640             this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
46641         }
46642     };
46643     /**
46644      * Get tile coordinates for a point using the current level.
46645      *
46646      * @param {Array<number>} point - Point in basic coordinates.
46647      *
46648      * @returns {Array<number>} x and y tile coodinates.
46649      */
46650     TextureProvider.prototype._getTileCoords = function (point) {
46651         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
46652         var maxX = Math.ceil(this._width / tileSize) - 1;
46653         var maxY = Math.ceil(this._height / tileSize) - 1;
46654         return [
46655             Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
46656             Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
46657         ];
46658     };
46659     /**
46660      * Get tile coordinates for all tiles contained in a bounding
46661      * box.
46662      *
46663      * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
46664      * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
46665      *
46666      * @returns {Array<Array<number>>} Array of x, y tile coodinates.
46667      */
46668     TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
46669         var xs = [];
46670         if (topLeft[0] > bottomRight[0]) {
46671             var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
46672             var maxX = Math.ceil(this._width / tileSize) - 1;
46673             for (var x = topLeft[0]; x <= maxX; x++) {
46674                 xs.push(x);
46675             }
46676             for (var x = 0; x <= bottomRight[0]; x++) {
46677                 xs.push(x);
46678             }
46679         }
46680         else {
46681             for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
46682                 xs.push(x);
46683             }
46684         }
46685         var tiles = [];
46686         for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
46687             var x = xs_1[_i];
46688             for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
46689                 tiles.push([x, y]);
46690             }
46691         }
46692         return tiles;
46693     };
46694     /**
46695      * Remove an item from an array if it exists in array.
46696      *
46697      * @param {T} item - Item to remove.
46698      * @param {Array<T>} array - Array from which item should be removed.
46699      */
46700     TextureProvider.prototype._removeFromArray = function (item, array) {
46701         var index = array.indexOf(item);
46702         if (index !== -1) {
46703             array.splice(index, 1);
46704         }
46705     };
46706     /**
46707      * Remove an item from a dictionary.
46708      *
46709      * @param {string} key - Key of the item to remove.
46710      * @param {Object} dict - Dictionary from which item should be removed.
46711      */
46712     TextureProvider.prototype._removeFromDictionary = function (key, dict) {
46713         if (key in dict) {
46714             delete dict[key];
46715         }
46716     };
46717     /**
46718      * Render an image tile to the target texture.
46719      *
46720      * @param {number} x - The top left x pixel coordinate of the tile.
46721      * @param {number} y - The top left y pixel coordinate of the tile.
46722      * @param {number} w - The pixel width of the tile.
46723      * @param {number} h - The pixel height of the tile.
46724      * @param {HTMLImageElement} background - The image tile to render.
46725      */
46726     TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
46727         var texture = new THREE.Texture(image);
46728         texture.minFilter = THREE.LinearFilter;
46729         texture.needsUpdate = true;
46730         var geometry = new THREE.PlaneGeometry(w, h);
46731         var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
46732         var mesh = new THREE.Mesh(geometry, material);
46733         mesh.position.x = -this._width / 2 + x + w / 2;
46734         mesh.position.y = this._height / 2 - y - h / 2;
46735         var scene = new THREE.Scene();
46736         scene.add(mesh);
46737         this._renderer.render(scene, this._camera, this._renderTarget);
46738         this._renderer.setRenderTarget(undefined);
46739         scene.remove(mesh);
46740         geometry.dispose();
46741         material.dispose();
46742         texture.dispose();
46743     };
46744     /**
46745      * Mark a tile as rendered.
46746      *
46747      * @description Clears tiles marked as rendered in other
46748      * levels of the tile pyramid  if they were rendered on
46749      * top of or below the tile.
46750      *
46751      * @param {Arrary<number>} tile - The tile coordinates.
46752      * @param {number} level - Tile level of the tile coordinates.
46753      */
46754     TextureProvider.prototype._setTileRendered = function (tile, level) {
46755         var otherLevels = Object.keys(this._renderedTiles)
46756             .map(function (key) {
46757             return parseInt(key, 10);
46758         })
46759             .filter(function (renderedLevel) {
46760             return renderedLevel !== level;
46761         });
46762         for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
46763             var otherLevel = otherLevels_1[_i];
46764             var scale = Math.pow(2, otherLevel - level);
46765             if (otherLevel < level) {
46766                 var x = Math.floor(scale * tile[0]);
46767                 var y = Math.floor(scale * tile[1]);
46768                 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
46769                     var otherTile = _b[_a];
46770                     if (otherTile[0] === x && otherTile[1] === y) {
46771                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
46772                         this._renderedTiles[otherLevel].splice(index, 1);
46773                     }
46774                 }
46775             }
46776             else {
46777                 var startX = scale * tile[0];
46778                 var endX = startX + scale - 1;
46779                 var startY = scale * tile[1];
46780                 var endY = startY + scale - 1;
46781                 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
46782                     var otherTile = _d[_c];
46783                     if (otherTile[0] >= startX && otherTile[0] <= endX &&
46784                         otherTile[1] >= startY && otherTile[1] <= endY) {
46785                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
46786                         this._renderedTiles[otherLevel].splice(index, 1);
46787                     }
46788                 }
46789             }
46790             if (this._renderedTiles[otherLevel].length === 0) {
46791                 delete this._renderedTiles[otherLevel];
46792             }
46793         }
46794         this._renderedTiles[level].push(tile);
46795         this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
46796     };
46797     /**
46798      * Create a tile key from a tile coordinates.
46799      *
46800      * @description Tile keys are used as a hash for
46801      * storing the tile in a dictionary.
46802      *
46803      * @param {number} tileSize - The tile size.
46804      * @param {Arrary<number>} tile - The tile coordinates.
46805      */
46806     TextureProvider.prototype._tileKey = function (tileSize, tile) {
46807         return tileSize + "-" + tile[0] + "-" + tile[1];
46808     };
46809     return TextureProvider;
46810 }());
46811 exports.TextureProvider = TextureProvider;
46812 exports.default = TextureProvider;
46813
46814 },{"rxjs":27,"rxjs/operators":225,"three":226}],427:[function(require,module,exports){
46815 "use strict";
46816 Object.defineProperty(exports, "__esModule", { value: true });
46817 var DOM = /** @class */ (function () {
46818     function DOM(doc) {
46819         this._document = !!doc ? doc : document;
46820     }
46821     Object.defineProperty(DOM.prototype, "document", {
46822         get: function () {
46823             return this._document;
46824         },
46825         enumerable: true,
46826         configurable: true
46827     });
46828     DOM.prototype.createElement = function (tagName, className, container) {
46829         var element = this._document.createElement(tagName);
46830         if (!!className) {
46831             element.className = className;
46832         }
46833         if (!!container) {
46834             container.appendChild(element);
46835         }
46836         return element;
46837     };
46838     return DOM;
46839 }());
46840 exports.DOM = DOM;
46841 exports.default = DOM;
46842
46843 },{}],428:[function(require,module,exports){
46844 "use strict";
46845 Object.defineProperty(exports, "__esModule", { value: true });
46846 var EventEmitter = /** @class */ (function () {
46847     function EventEmitter() {
46848         this._events = {};
46849     }
46850     /**
46851      * Subscribe to an event by its name.
46852      * @param {string }eventType - The name of the event to subscribe to.
46853      * @param {any} fn - The handler called when the event occurs.
46854      */
46855     EventEmitter.prototype.on = function (eventType, fn) {
46856         this._events[eventType] = this._events[eventType] || [];
46857         this._events[eventType].push(fn);
46858         return;
46859     };
46860     /**
46861      * Unsubscribe from an event by its name.
46862      * @param {string} eventType - The name of the event to subscribe to.
46863      * @param {any} fn - The handler to remove.
46864      */
46865     EventEmitter.prototype.off = function (eventType, fn) {
46866         if (!eventType) {
46867             this._events = {};
46868             return;
46869         }
46870         if (!this._listens(eventType)) {
46871             var idx = this._events[eventType].indexOf(fn);
46872             if (idx >= 0) {
46873                 this._events[eventType].splice(idx, 1);
46874             }
46875             if (this._events[eventType].length) {
46876                 delete this._events[eventType];
46877             }
46878         }
46879         else {
46880             delete this._events[eventType];
46881         }
46882         return;
46883     };
46884     EventEmitter.prototype.fire = function (eventType, data) {
46885         if (!this._listens(eventType)) {
46886             return;
46887         }
46888         for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
46889             var fn = _a[_i];
46890             fn.call(this, data);
46891         }
46892         return;
46893     };
46894     EventEmitter.prototype._listens = function (eventType) {
46895         return !!(this._events && this._events[eventType]);
46896     };
46897     return EventEmitter;
46898 }());
46899 exports.EventEmitter = EventEmitter;
46900 exports.default = EventEmitter;
46901
46902 },{}],429:[function(require,module,exports){
46903 "use strict";
46904 Object.defineProperty(exports, "__esModule", { value: true });
46905 var Viewer_1 = require("../Viewer");
46906 var Settings = /** @class */ (function () {
46907     function Settings() {
46908     }
46909     Settings.setOptions = function (options) {
46910         Settings._baseImageSize = options.baseImageSize != null ?
46911             options.baseImageSize :
46912             Viewer_1.ImageSize.Size640;
46913         Settings._basePanoramaSize = options.basePanoramaSize != null ?
46914             options.basePanoramaSize :
46915             Viewer_1.ImageSize.Size2048;
46916         Settings._maxImageSize = options.maxImageSize != null ?
46917             options.maxImageSize :
46918             Viewer_1.ImageSize.Size2048;
46919     };
46920     Object.defineProperty(Settings, "baseImageSize", {
46921         get: function () {
46922             return Settings._baseImageSize;
46923         },
46924         enumerable: true,
46925         configurable: true
46926     });
46927     Object.defineProperty(Settings, "basePanoramaSize", {
46928         get: function () {
46929             return Settings._basePanoramaSize;
46930         },
46931         enumerable: true,
46932         configurable: true
46933     });
46934     Object.defineProperty(Settings, "maxImageSize", {
46935         get: function () {
46936             return Settings._maxImageSize;
46937         },
46938         enumerable: true,
46939         configurable: true
46940     });
46941     return Settings;
46942 }());
46943 exports.Settings = Settings;
46944 exports.default = Settings;
46945
46946 },{"../Viewer":286}],430:[function(require,module,exports){
46947 "use strict";
46948 Object.defineProperty(exports, "__esModule", { value: true });
46949 function isBrowser() {
46950     return typeof window !== "undefined" && typeof document !== "undefined";
46951 }
46952 exports.isBrowser = isBrowser;
46953 function isArraySupported() {
46954     return !!(Array.prototype &&
46955         Array.prototype.filter &&
46956         Array.prototype.indexOf &&
46957         Array.prototype.map &&
46958         Array.prototype.reverse);
46959 }
46960 exports.isArraySupported = isArraySupported;
46961 function isFunctionSupported() {
46962     return !!(Function.prototype && Function.prototype.bind);
46963 }
46964 exports.isFunctionSupported = isFunctionSupported;
46965 function isJSONSupported() {
46966     return "JSON" in window && "parse" in JSON && "stringify" in JSON;
46967 }
46968 exports.isJSONSupported = isJSONSupported;
46969 function isObjectSupported() {
46970     return !!(Object.keys &&
46971         Object.assign);
46972 }
46973 exports.isObjectSupported = isObjectSupported;
46974 function isBlobSupported() {
46975     return "Blob" in window && "URL" in window;
46976 }
46977 exports.isBlobSupported = isBlobSupported;
46978 var isWebGLSupportedCache = undefined;
46979 function isWebGLSupportedCached() {
46980     if (isWebGLSupportedCache === undefined) {
46981         isWebGLSupportedCache = isWebGLSupported();
46982     }
46983     return isWebGLSupportedCache;
46984 }
46985 exports.isWebGLSupportedCached = isWebGLSupportedCached;
46986 function isWebGLSupported() {
46987     var webGLContextAttributes = {
46988         alpha: false,
46989         antialias: false,
46990         depth: true,
46991         failIfMajorPerformanceCaveat: false,
46992         premultipliedAlpha: true,
46993         preserveDrawingBuffer: false,
46994         stencil: true,
46995     };
46996     var canvas = document.createElement("canvas");
46997     var context = canvas.getContext("webgl", webGLContextAttributes) ||
46998         canvas.getContext("experimental-webgl", webGLContextAttributes);
46999     if (!context) {
47000         return false;
47001     }
47002     var requiredExtensions = [
47003         "OES_standard_derivatives",
47004     ];
47005     var supportedExtensions = context.getSupportedExtensions();
47006     for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) {
47007         var requiredExtension = requiredExtensions_1[_i];
47008         if (supportedExtensions.indexOf(requiredExtension) === -1) {
47009             return false;
47010         }
47011     }
47012     return true;
47013 }
47014 exports.isWebGLSupported = isWebGLSupported;
47015
47016 },{}],431:[function(require,module,exports){
47017 "use strict";
47018 Object.defineProperty(exports, "__esModule", { value: true });
47019 var Urls = /** @class */ (function () {
47020     function Urls() {
47021     }
47022     Object.defineProperty(Urls, "explore", {
47023         get: function () {
47024             return Urls._scheme + "://" + Urls._exploreHost;
47025         },
47026         enumerable: true,
47027         configurable: true
47028     });
47029     Object.defineProperty(Urls, "origin", {
47030         get: function () {
47031             return Urls._origin;
47032         },
47033         enumerable: true,
47034         configurable: true
47035     });
47036     Object.defineProperty(Urls, "tileScheme", {
47037         get: function () {
47038             return Urls._scheme;
47039         },
47040         enumerable: true,
47041         configurable: true
47042     });
47043     Object.defineProperty(Urls, "tileDomain", {
47044         get: function () {
47045             return Urls._imageTileHost;
47046         },
47047         enumerable: true,
47048         configurable: true
47049     });
47050     Urls.atomicReconstruction = function (key) {
47051         return Urls._scheme + "://" + Urls._atomicReconstructionHost + "/" + key + "/sfm/v1.0/atomic_reconstruction.json";
47052     };
47053     Urls.exporeImage = function (key) {
47054         return Urls._scheme + "://" + Urls._exploreHost + "/app/?pKey=" + key + "&focus=photo";
47055     };
47056     Urls.exporeUser = function (username) {
47057         return Urls._scheme + "://" + Urls._exploreHost + "/app/user/" + username;
47058     };
47059     Urls.falcorModel = function (clientId) {
47060         return Urls._scheme + "://" + Urls._apiHost + "/v3/model.json?client_id=" + clientId;
47061     };
47062     Urls.protoMesh = function (key) {
47063         return Urls._scheme + "://" + Urls._meshHost + "/v2/mesh/" + key;
47064     };
47065     Urls.thumbnail = function (key, size, origin) {
47066         var query = !!origin ? "?origin=" + origin : "";
47067         return Urls._scheme + "://" + Urls._imageHost + "/" + key + "/thumb-" + size + ".jpg" + query;
47068     };
47069     Urls.setOptions = function (options) {
47070         if (!options) {
47071             return;
47072         }
47073         if (!!options.apiHost) {
47074             Urls._apiHost = options.apiHost;
47075         }
47076         if (!!options.atomicReconstructionHost) {
47077             Urls._atomicReconstructionHost = options.atomicReconstructionHost;
47078         }
47079         if (!!options.exploreHost) {
47080             Urls._exploreHost = options.exploreHost;
47081         }
47082         if (!!options.imageHost) {
47083             Urls._imageHost = options.imageHost;
47084         }
47085         if (!!options.imageTileHost) {
47086             Urls._imageTileHost = options.imageTileHost;
47087         }
47088         if (!!options.meshHost) {
47089             Urls._meshHost = options.meshHost;
47090         }
47091         if (!!options.scheme) {
47092             Urls._scheme = options.scheme;
47093         }
47094     };
47095     Urls._apiHost = "a.mapillary.com";
47096     Urls._atomicReconstructionHost = "atomic-reconstructions.mapillary.com";
47097     Urls._exploreHost = "www.mapillary.com";
47098     Urls._imageHost = "images.mapillary.com";
47099     Urls._imageTileHost = "loris.mapillary.com";
47100     Urls._meshHost = "meshes.mapillary.com";
47101     Urls._origin = "mapillary.webgl";
47102     Urls._scheme = "https";
47103     return Urls;
47104 }());
47105 exports.Urls = Urls;
47106 exports.default = Urls;
47107
47108 },{}],432:[function(require,module,exports){
47109 "use strict";
47110 Object.defineProperty(exports, "__esModule", { value: true });
47111 /**
47112  * Enumeration for alignments
47113  * @enum {number}
47114  * @readonly
47115  */
47116 var Alignment;
47117 (function (Alignment) {
47118     /**
47119      * Align to bottom
47120      */
47121     Alignment[Alignment["Bottom"] = 0] = "Bottom";
47122     /**
47123      * Align to bottom left
47124      */
47125     Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
47126     /**
47127      * Align to bottom right
47128      */
47129     Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
47130     /**
47131      * Align to center
47132      */
47133     Alignment[Alignment["Center"] = 3] = "Center";
47134     /**
47135      * Align to left
47136      */
47137     Alignment[Alignment["Left"] = 4] = "Left";
47138     /**
47139      * Align to right
47140      */
47141     Alignment[Alignment["Right"] = 5] = "Right";
47142     /**
47143      * Align to top
47144      */
47145     Alignment[Alignment["Top"] = 6] = "Top";
47146     /**
47147      * Align to top left
47148      */
47149     Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
47150     /**
47151      * Align to top right
47152      */
47153     Alignment[Alignment["TopRight"] = 8] = "TopRight";
47154 })(Alignment = exports.Alignment || (exports.Alignment = {}));
47155 exports.default = Alignment;
47156
47157 },{}],433:[function(require,module,exports){
47158 "use strict";
47159 Object.defineProperty(exports, "__esModule", { value: true });
47160 var rxjs_1 = require("rxjs");
47161 var operators_1 = require("rxjs/operators");
47162 var Graph_1 = require("../Graph");
47163 var CacheService = /** @class */ (function () {
47164     function CacheService(graphService, stateService) {
47165         this._graphService = graphService;
47166         this._stateService = stateService;
47167         this._started = false;
47168     }
47169     Object.defineProperty(CacheService.prototype, "started", {
47170         get: function () {
47171             return this._started;
47172         },
47173         enumerable: true,
47174         configurable: true
47175     });
47176     CacheService.prototype.start = function () {
47177         var _this = this;
47178         if (this._started) {
47179             return;
47180         }
47181         this._uncacheSubscription = this._stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
47182             return frame.state.currentNode.key;
47183         }), operators_1.map(function (frame) {
47184             var trajectory = frame.state.trajectory;
47185             var trajectoryKeys = trajectory
47186                 .map(function (n) {
47187                 return n.key;
47188             });
47189             var sequenceKey = trajectory[trajectory.length - 1].sequenceKey;
47190             return [trajectoryKeys, sequenceKey];
47191         }), operators_1.bufferCount(1, 5), operators_1.withLatestFrom(this._graphService.graphMode$), operators_1.switchMap(function (_a) {
47192             var keepBuffer = _a[0], graphMode = _a[1];
47193             var keepKeys = keepBuffer[0][0];
47194             var keepSequenceKey = graphMode === Graph_1.GraphMode.Sequence ?
47195                 keepBuffer[0][1] : undefined;
47196             return _this._graphService.uncache$(keepKeys, keepSequenceKey);
47197         }))
47198             .subscribe(function () { });
47199         this._cacheNodeSubscription = this._graphService.graphMode$.pipe(operators_1.skip(1), operators_1.withLatestFrom(this._stateService.currentState$), operators_1.switchMap(function (_a) {
47200             var mode = _a[0], frame = _a[1];
47201             return mode === Graph_1.GraphMode.Sequence ?
47202                 _this._keyToEdges(frame.state.currentNode.key, function (node) {
47203                     return node.sequenceEdges$;
47204                 }) :
47205                 rxjs_1.from(frame.state.trajectory
47206                     .map(function (node) {
47207                     return node.key;
47208                 })
47209                     .slice(frame.state.currentIndex)).pipe(operators_1.mergeMap(function (key) {
47210                     return _this._keyToEdges(key, function (node) {
47211                         return node.spatialEdges$;
47212                     });
47213                 }, 6));
47214         }))
47215             .subscribe(function () { });
47216         this._started = true;
47217     };
47218     CacheService.prototype.stop = function () {
47219         if (!this._started) {
47220             return;
47221         }
47222         this._uncacheSubscription.unsubscribe();
47223         this._uncacheSubscription = null;
47224         this._cacheNodeSubscription.unsubscribe();
47225         this._cacheNodeSubscription = null;
47226         this._started = false;
47227     };
47228     CacheService.prototype._keyToEdges = function (key, nodeToEdgeMap) {
47229         return this._graphService.cacheNode$(key).pipe(operators_1.switchMap(nodeToEdgeMap), operators_1.first(function (status) {
47230             return status.cached;
47231         }), operators_1.timeout(15000), operators_1.catchError(function (error) {
47232             console.error("Failed to cache edges (" + key + ").", error);
47233             return rxjs_1.empty();
47234         }));
47235     };
47236     return CacheService;
47237 }());
47238 exports.CacheService = CacheService;
47239 exports.default = CacheService;
47240
47241 },{"../Graph":279,"rxjs":27,"rxjs/operators":225}],434:[function(require,module,exports){
47242 "use strict";
47243 Object.defineProperty(exports, "__esModule", { value: true });
47244 var operators_1 = require("rxjs/operators");
47245 var Component_1 = require("../Component");
47246 var ComponentController = /** @class */ (function () {
47247     function ComponentController(container, navigator, observer, key, options, componentService) {
47248         var _this = this;
47249         this._container = container;
47250         this._observer = observer;
47251         this._navigator = navigator;
47252         this._options = options != null ? options : {};
47253         this._key = key;
47254         this._navigable = key == null;
47255         this._componentService = !!componentService ?
47256             componentService :
47257             new Component_1.ComponentService(this._container, this._navigator);
47258         this._coverComponent = this._componentService.getCover();
47259         this._initializeComponents();
47260         if (key) {
47261             this._initilizeCoverComponent();
47262             this._subscribeCoverComponent();
47263         }
47264         else {
47265             this._navigator.movedToKey$.pipe(operators_1.first(function (k) {
47266                 return k != null;
47267             }))
47268                 .subscribe(function (k) {
47269                 _this._key = k;
47270                 _this._componentService.deactivateCover();
47271                 _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden });
47272                 _this._subscribeCoverComponent();
47273                 _this._navigator.stateService.start();
47274                 _this._navigator.cacheService.start();
47275                 _this._navigator.panService.start();
47276                 _this._observer.startEmit();
47277             });
47278         }
47279     }
47280     Object.defineProperty(ComponentController.prototype, "navigable", {
47281         get: function () {
47282             return this._navigable;
47283         },
47284         enumerable: true,
47285         configurable: true
47286     });
47287     ComponentController.prototype.get = function (name) {
47288         return this._componentService.get(name);
47289     };
47290     ComponentController.prototype.activate = function (name) {
47291         this._componentService.activate(name);
47292     };
47293     ComponentController.prototype.activateCover = function () {
47294         this._coverComponent.configure({ state: Component_1.CoverState.Visible });
47295     };
47296     ComponentController.prototype.deactivate = function (name) {
47297         this._componentService.deactivate(name);
47298     };
47299     ComponentController.prototype.deactivateCover = function () {
47300         this._coverComponent.configure({ state: Component_1.CoverState.Loading });
47301     };
47302     ComponentController.prototype._initializeComponents = function () {
47303         var options = this._options;
47304         this._uFalse(options.background, "background");
47305         this._uFalse(options.debug, "debug");
47306         this._uFalse(options.image, "image");
47307         this._uFalse(options.marker, "marker");
47308         this._uFalse(options.navigation, "navigation");
47309         this._uFalse(options.popup, "popup");
47310         this._uFalse(options.route, "route");
47311         this._uFalse(options.slider, "slider");
47312         this._uFalse(options.spatialData, "spatialData");
47313         this._uFalse(options.tag, "tag");
47314         this._uTrue(options.attribution, "attribution");
47315         this._uTrue(options.bearing, "bearing");
47316         this._uTrue(options.cache, "cache");
47317         this._uTrue(options.direction, "direction");
47318         this._uTrue(options.imagePlane, "imagePlane");
47319         this._uTrue(options.keyboard, "keyboard");
47320         this._uTrue(options.loading, "loading");
47321         this._uTrue(options.mouse, "mouse");
47322         this._uTrue(options.sequence, "sequence");
47323         this._uTrue(options.stats, "stats");
47324         this._uTrue(options.zoom, "zoom");
47325     };
47326     ComponentController.prototype._initilizeCoverComponent = function () {
47327         var options = this._options;
47328         this._coverComponent.configure({ key: this._key });
47329         if (options.cover === undefined || options.cover) {
47330             this.activateCover();
47331         }
47332         else {
47333             this.deactivateCover();
47334         }
47335     };
47336     ComponentController.prototype._setNavigable = function (navigable) {
47337         if (this._navigable === navigable) {
47338             return;
47339         }
47340         this._navigable = navigable;
47341         this._observer.navigable$.next(navigable);
47342     };
47343     ComponentController.prototype._subscribeCoverComponent = function () {
47344         var _this = this;
47345         this._coverComponent.configuration$.pipe(operators_1.distinctUntilChanged(undefined, function (c) {
47346             return c.state;
47347         }))
47348             .subscribe(function (conf) {
47349             if (conf.state === Component_1.CoverState.Loading) {
47350                 _this._navigator.stateService.currentKey$.pipe(operators_1.first(), operators_1.switchMap(function (key) {
47351                     var keyChanged = key == null || key !== conf.key;
47352                     if (keyChanged) {
47353                         _this._setNavigable(false);
47354                     }
47355                     return keyChanged ?
47356                         _this._navigator.moveToKey$(conf.key) :
47357                         _this._navigator.stateService.currentNode$.pipe(operators_1.first());
47358                 }))
47359                     .subscribe(function () {
47360                     _this._navigator.stateService.start();
47361                     _this._navigator.cacheService.start();
47362                     _this._navigator.panService.start();
47363                     _this._observer.startEmit();
47364                     _this._coverComponent.configure({ state: Component_1.CoverState.Hidden });
47365                     _this._componentService.deactivateCover();
47366                     _this._setNavigable(true);
47367                 }, function (error) {
47368                     console.error("Failed to deactivate cover.", error);
47369                     _this._coverComponent.configure({ state: Component_1.CoverState.Visible });
47370                 });
47371             }
47372             else if (conf.state === Component_1.CoverState.Visible) {
47373                 _this._observer.stopEmit();
47374                 _this._navigator.stateService.stop();
47375                 _this._navigator.cacheService.stop();
47376                 _this._navigator.playService.stop();
47377                 _this._navigator.panService.stop();
47378                 _this._componentService.activateCover();
47379                 _this._setNavigable(conf.key == null);
47380             }
47381         });
47382     };
47383     ComponentController.prototype._uFalse = function (option, name) {
47384         if (option === undefined) {
47385             this._componentService.deactivate(name);
47386             return;
47387         }
47388         if (typeof option === "boolean") {
47389             if (option) {
47390                 this._componentService.activate(name);
47391             }
47392             else {
47393                 this._componentService.deactivate(name);
47394             }
47395             return;
47396         }
47397         this._componentService.configure(name, option);
47398         this._componentService.activate(name);
47399     };
47400     ComponentController.prototype._uTrue = function (option, name) {
47401         if (option === undefined) {
47402             this._componentService.activate(name);
47403             return;
47404         }
47405         if (typeof option === "boolean") {
47406             if (option) {
47407                 this._componentService.activate(name);
47408             }
47409             else {
47410                 this._componentService.deactivate(name);
47411             }
47412             return;
47413         }
47414         this._componentService.configure(name, option);
47415         this._componentService.activate(name);
47416     };
47417     return ComponentController;
47418 }());
47419 exports.ComponentController = ComponentController;
47420
47421 },{"../Component":275,"rxjs/operators":225}],435:[function(require,module,exports){
47422 "use strict";
47423 Object.defineProperty(exports, "__esModule", { value: true });
47424 var Render_1 = require("../Render");
47425 var Utils_1 = require("../Utils");
47426 var Viewer_1 = require("../Viewer");
47427 var Container = /** @class */ (function () {
47428     function Container(id, stateService, options, dom) {
47429         this.id = id;
47430         this._dom = !!dom ? dom : new Utils_1.DOM();
47431         this._container = this._dom.document.getElementById(id);
47432         if (!this._container) {
47433             throw new Error("Container '" + id + "' not found.");
47434         }
47435         this._container.classList.add("mapillary-js");
47436         this._canvasContainer = this._dom.createElement("div", "mapillary-js-interactive", this._container);
47437         this._domContainer = this._dom.createElement("div", "mapillary-js-dom", this._container);
47438         this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
47439         this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService, this._dom);
47440         this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
47441         this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer);
47442         this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer, document);
47443         this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
47444         this.spriteService = new Viewer_1.SpriteService(options.sprite);
47445     }
47446     Object.defineProperty(Container.prototype, "element", {
47447         get: function () {
47448             return this._container;
47449         },
47450         enumerable: true,
47451         configurable: true
47452     });
47453     Object.defineProperty(Container.prototype, "canvasContainer", {
47454         get: function () {
47455             return this._canvasContainer;
47456         },
47457         enumerable: true,
47458         configurable: true
47459     });
47460     Object.defineProperty(Container.prototype, "domContainer", {
47461         get: function () {
47462             return this._domContainer;
47463         },
47464         enumerable: true,
47465         configurable: true
47466     });
47467     return Container;
47468 }());
47469 exports.Container = Container;
47470 exports.default = Container;
47471
47472 },{"../Render":281,"../Utils":285,"../Viewer":286}],436:[function(require,module,exports){
47473 "use strict";
47474 Object.defineProperty(exports, "__esModule", { value: true });
47475 /**
47476  * Enumeration for image sizes
47477  * @enum {number}
47478  * @readonly
47479  * @description Image sizes in pixels for the long side of the image.
47480  */
47481 var ImageSize;
47482 (function (ImageSize) {
47483     /**
47484      * 320 pixels image size
47485      */
47486     ImageSize[ImageSize["Size320"] = 320] = "Size320";
47487     /**
47488      * 640 pixels image size
47489      */
47490     ImageSize[ImageSize["Size640"] = 640] = "Size640";
47491     /**
47492      * 1024 pixels image size
47493      */
47494     ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
47495     /**
47496      * 2048 pixels image size
47497      */
47498     ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
47499 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
47500
47501 },{}],437:[function(require,module,exports){
47502 "use strict";
47503 Object.defineProperty(exports, "__esModule", { value: true });
47504 var rxjs_1 = require("rxjs");
47505 var KeyboardService = /** @class */ (function () {
47506     function KeyboardService(canvasContainer) {
47507         this._keyDown$ = rxjs_1.fromEvent(canvasContainer, "keydown");
47508         this._keyUp$ = rxjs_1.fromEvent(canvasContainer, "keyup");
47509     }
47510     Object.defineProperty(KeyboardService.prototype, "keyDown$", {
47511         get: function () {
47512             return this._keyDown$;
47513         },
47514         enumerable: true,
47515         configurable: true
47516     });
47517     Object.defineProperty(KeyboardService.prototype, "keyUp$", {
47518         get: function () {
47519             return this._keyUp$;
47520         },
47521         enumerable: true,
47522         configurable: true
47523     });
47524     return KeyboardService;
47525 }());
47526 exports.KeyboardService = KeyboardService;
47527 exports.default = KeyboardService;
47528
47529 },{"rxjs":27}],438:[function(require,module,exports){
47530 "use strict";
47531 Object.defineProperty(exports, "__esModule", { value: true });
47532 var operators_1 = require("rxjs/operators");
47533 var rxjs_1 = require("rxjs");
47534 var LoadingService = /** @class */ (function () {
47535     function LoadingService() {
47536         this._loadersSubject$ = new rxjs_1.Subject();
47537         this._loaders$ = this._loadersSubject$.pipe(operators_1.scan(function (loaders, loader) {
47538             if (loader.task !== undefined) {
47539                 loaders[loader.task] = loader.loading;
47540             }
47541             return loaders;
47542         }, {}), operators_1.startWith({}), operators_1.publishReplay(1), operators_1.refCount());
47543     }
47544     Object.defineProperty(LoadingService.prototype, "loading$", {
47545         get: function () {
47546             return this._loaders$.pipe(operators_1.map(function (loaders) {
47547                 for (var key in loaders) {
47548                     if (!loaders.hasOwnProperty(key)) {
47549                         continue;
47550                     }
47551                     if (loaders[key]) {
47552                         return true;
47553                     }
47554                 }
47555                 return false;
47556             }), operators_1.debounceTime(100), operators_1.distinctUntilChanged());
47557         },
47558         enumerable: true,
47559         configurable: true
47560     });
47561     LoadingService.prototype.taskLoading$ = function (task) {
47562         return this._loaders$.pipe(operators_1.map(function (loaders) {
47563             return !!loaders[task];
47564         }), operators_1.debounceTime(100), operators_1.distinctUntilChanged());
47565     };
47566     LoadingService.prototype.startLoading = function (task) {
47567         this._loadersSubject$.next({ loading: true, task: task });
47568     };
47569     LoadingService.prototype.stopLoading = function (task) {
47570         this._loadersSubject$.next({ loading: false, task: task });
47571     };
47572     return LoadingService;
47573 }());
47574 exports.LoadingService = LoadingService;
47575 exports.default = LoadingService;
47576
47577 },{"rxjs":27,"rxjs/operators":225}],439:[function(require,module,exports){
47578 "use strict";
47579 Object.defineProperty(exports, "__esModule", { value: true });
47580 var rxjs_1 = require("rxjs");
47581 var operators_1 = require("rxjs/operators");
47582 var MouseService = /** @class */ (function () {
47583     function MouseService(container, canvasContainer, domContainer, doc) {
47584         var _this = this;
47585         this._activeSubject$ = new rxjs_1.BehaviorSubject(false);
47586         this._active$ = this._activeSubject$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
47587         this._claimMouse$ = new rxjs_1.Subject();
47588         this._claimWheel$ = new rxjs_1.Subject();
47589         this._deferPixelClaims$ = new rxjs_1.Subject();
47590         this._deferPixels$ = this._deferPixelClaims$.pipe(operators_1.scan(function (claims, claim) {
47591             if (claim.deferPixels == null) {
47592                 delete claims[claim.name];
47593             }
47594             else {
47595                 claims[claim.name] = claim.deferPixels;
47596             }
47597             return claims;
47598         }, {}), operators_1.map(function (claims) {
47599             var deferPixelMax = -1;
47600             for (var key in claims) {
47601                 if (!claims.hasOwnProperty(key)) {
47602                     continue;
47603                 }
47604                 var deferPixels = claims[key];
47605                 if (deferPixels > deferPixelMax) {
47606                     deferPixelMax = deferPixels;
47607                 }
47608             }
47609             return deferPixelMax;
47610         }), operators_1.startWith(-1), operators_1.publishReplay(1), operators_1.refCount());
47611         this._deferPixels$.subscribe(function () { });
47612         this._documentMouseMove$ = rxjs_1.fromEvent(doc, "mousemove");
47613         this._documentMouseUp$ = rxjs_1.fromEvent(doc, "mouseup");
47614         this._mouseDown$ = rxjs_1.fromEvent(canvasContainer, "mousedown");
47615         this._mouseLeave$ = rxjs_1.fromEvent(canvasContainer, "mouseleave");
47616         this._mouseMove$ = rxjs_1.fromEvent(canvasContainer, "mousemove");
47617         this._mouseUp$ = rxjs_1.fromEvent(canvasContainer, "mouseup");
47618         this._mouseOut$ = rxjs_1.fromEvent(canvasContainer, "mouseout");
47619         this._mouseOver$ = rxjs_1.fromEvent(canvasContainer, "mouseover");
47620         this._domMouseDown$ = rxjs_1.fromEvent(domContainer, "mousedown");
47621         this._domMouseMove$ = rxjs_1.fromEvent(domContainer, "mousemove");
47622         this._click$ = rxjs_1.fromEvent(canvasContainer, "click");
47623         this._contextMenu$ = rxjs_1.fromEvent(canvasContainer, "contextmenu");
47624         this._dblClick$ = rxjs_1.merge(rxjs_1.fromEvent(container, "click"), rxjs_1.fromEvent(canvasContainer, "dblclick")).pipe(operators_1.bufferCount(3, 1), operators_1.filter(function (events) {
47625             var event1 = events[0];
47626             var event2 = events[1];
47627             var event3 = events[2];
47628             return event1.type === "click" &&
47629                 event2.type === "click" &&
47630                 event3.type === "dblclick" &&
47631                 event1.target.parentNode === canvasContainer &&
47632                 event2.target.parentNode === canvasContainer;
47633         }), operators_1.map(function (events) {
47634             return events[2];
47635         }), operators_1.share());
47636         rxjs_1.merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
47637             .subscribe(function (event) {
47638             event.preventDefault();
47639         });
47640         this._mouseWheel$ = rxjs_1.merge(rxjs_1.fromEvent(canvasContainer, "wheel"), rxjs_1.fromEvent(domContainer, "wheel")).pipe(operators_1.share());
47641         this._consistentContextMenu$ = rxjs_1.merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$).pipe(operators_1.bufferCount(3, 1), operators_1.filter(function (events) {
47642             // fire context menu on mouse up both on mac and windows
47643             return events[0].type === "mousedown" &&
47644                 events[1].type === "contextmenu" &&
47645                 events[2].type === "mouseup";
47646         }), operators_1.map(function (events) {
47647             return events[1];
47648         }), operators_1.share());
47649         var dragStop$ = rxjs_1.merge(rxjs_1.fromEvent(window, "blur"), this._documentMouseUp$.pipe(operators_1.filter(function (e) {
47650             return e.button === 0;
47651         }))).pipe(operators_1.share());
47652         var mouseDragInitiate$ = this._createMouseDragInitiate$(this._mouseDown$, dragStop$, true).pipe(operators_1.share());
47653         this._mouseDragStart$ = this._createMouseDragStart$(mouseDragInitiate$).pipe(operators_1.share());
47654         this._mouseDrag$ = this._createMouseDrag$(mouseDragInitiate$, dragStop$).pipe(operators_1.share());
47655         this._mouseDragEnd$ = this._createMouseDragEnd$(this._mouseDragStart$, dragStop$).pipe(operators_1.share());
47656         var domMouseDragInitiate$ = this._createMouseDragInitiate$(this._domMouseDown$, dragStop$, false).pipe(operators_1.share());
47657         this._domMouseDragStart$ = this._createMouseDragStart$(domMouseDragInitiate$).pipe(operators_1.share());
47658         this._domMouseDrag$ = this._createMouseDrag$(domMouseDragInitiate$, dragStop$).pipe(operators_1.share());
47659         this._domMouseDragEnd$ = this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$).pipe(operators_1.share());
47660         this._proximateClick$ = this._mouseDown$.pipe(operators_1.switchMap(function (mouseDown) {
47661             return _this._click$.pipe(operators_1.takeUntil(_this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$)), operators_1.take(1));
47662         }), operators_1.share());
47663         this._staticClick$ = this._mouseDown$.pipe(operators_1.switchMap(function (e) {
47664             return _this._click$.pipe(operators_1.takeUntil(_this._documentMouseMove$), operators_1.take(1));
47665         }), operators_1.share());
47666         this._mouseDragStart$.subscribe();
47667         this._mouseDrag$.subscribe();
47668         this._mouseDragEnd$.subscribe();
47669         this._domMouseDragStart$.subscribe();
47670         this._domMouseDrag$.subscribe();
47671         this._domMouseDragEnd$.subscribe();
47672         this._staticClick$.subscribe();
47673         this._mouseOwner$ = this._createOwner$(this._claimMouse$).pipe(operators_1.publishReplay(1), operators_1.refCount());
47674         this._wheelOwner$ = this._createOwner$(this._claimWheel$).pipe(operators_1.publishReplay(1), operators_1.refCount());
47675         this._mouseOwner$.subscribe(function () { });
47676         this._wheelOwner$.subscribe(function () { });
47677     }
47678     Object.defineProperty(MouseService.prototype, "active$", {
47679         get: function () {
47680             return this._active$;
47681         },
47682         enumerable: true,
47683         configurable: true
47684     });
47685     Object.defineProperty(MouseService.prototype, "activate$", {
47686         get: function () {
47687             return this._activeSubject$;
47688         },
47689         enumerable: true,
47690         configurable: true
47691     });
47692     Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
47693         get: function () {
47694             return this._documentMouseMove$;
47695         },
47696         enumerable: true,
47697         configurable: true
47698     });
47699     Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
47700         get: function () {
47701             return this._documentMouseUp$;
47702         },
47703         enumerable: true,
47704         configurable: true
47705     });
47706     Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
47707         get: function () {
47708             return this._domMouseDragStart$;
47709         },
47710         enumerable: true,
47711         configurable: true
47712     });
47713     Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
47714         get: function () {
47715             return this._domMouseDrag$;
47716         },
47717         enumerable: true,
47718         configurable: true
47719     });
47720     Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
47721         get: function () {
47722             return this._domMouseDragEnd$;
47723         },
47724         enumerable: true,
47725         configurable: true
47726     });
47727     Object.defineProperty(MouseService.prototype, "domMouseDown$", {
47728         get: function () {
47729             return this._domMouseDown$;
47730         },
47731         enumerable: true,
47732         configurable: true
47733     });
47734     Object.defineProperty(MouseService.prototype, "domMouseMove$", {
47735         get: function () {
47736             return this._domMouseMove$;
47737         },
47738         enumerable: true,
47739         configurable: true
47740     });
47741     Object.defineProperty(MouseService.prototype, "mouseOwner$", {
47742         get: function () {
47743             return this._mouseOwner$;
47744         },
47745         enumerable: true,
47746         configurable: true
47747     });
47748     Object.defineProperty(MouseService.prototype, "mouseDown$", {
47749         get: function () {
47750             return this._mouseDown$;
47751         },
47752         enumerable: true,
47753         configurable: true
47754     });
47755     Object.defineProperty(MouseService.prototype, "mouseMove$", {
47756         get: function () {
47757             return this._mouseMove$;
47758         },
47759         enumerable: true,
47760         configurable: true
47761     });
47762     Object.defineProperty(MouseService.prototype, "mouseLeave$", {
47763         get: function () {
47764             return this._mouseLeave$;
47765         },
47766         enumerable: true,
47767         configurable: true
47768     });
47769     Object.defineProperty(MouseService.prototype, "mouseOut$", {
47770         get: function () {
47771             return this._mouseOut$;
47772         },
47773         enumerable: true,
47774         configurable: true
47775     });
47776     Object.defineProperty(MouseService.prototype, "mouseOver$", {
47777         get: function () {
47778             return this._mouseOver$;
47779         },
47780         enumerable: true,
47781         configurable: true
47782     });
47783     Object.defineProperty(MouseService.prototype, "mouseUp$", {
47784         get: function () {
47785             return this._mouseUp$;
47786         },
47787         enumerable: true,
47788         configurable: true
47789     });
47790     Object.defineProperty(MouseService.prototype, "click$", {
47791         get: function () {
47792             return this._click$;
47793         },
47794         enumerable: true,
47795         configurable: true
47796     });
47797     Object.defineProperty(MouseService.prototype, "dblClick$", {
47798         get: function () {
47799             return this._dblClick$;
47800         },
47801         enumerable: true,
47802         configurable: true
47803     });
47804     Object.defineProperty(MouseService.prototype, "contextMenu$", {
47805         get: function () {
47806             return this._consistentContextMenu$;
47807         },
47808         enumerable: true,
47809         configurable: true
47810     });
47811     Object.defineProperty(MouseService.prototype, "mouseWheel$", {
47812         get: function () {
47813             return this._mouseWheel$;
47814         },
47815         enumerable: true,
47816         configurable: true
47817     });
47818     Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
47819         get: function () {
47820             return this._mouseDragStart$;
47821         },
47822         enumerable: true,
47823         configurable: true
47824     });
47825     Object.defineProperty(MouseService.prototype, "mouseDrag$", {
47826         get: function () {
47827             return this._mouseDrag$;
47828         },
47829         enumerable: true,
47830         configurable: true
47831     });
47832     Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
47833         get: function () {
47834             return this._mouseDragEnd$;
47835         },
47836         enumerable: true,
47837         configurable: true
47838     });
47839     Object.defineProperty(MouseService.prototype, "proximateClick$", {
47840         get: function () {
47841             return this._proximateClick$;
47842         },
47843         enumerable: true,
47844         configurable: true
47845     });
47846     Object.defineProperty(MouseService.prototype, "staticClick$", {
47847         get: function () {
47848             return this._staticClick$;
47849         },
47850         enumerable: true,
47851         configurable: true
47852     });
47853     MouseService.prototype.claimMouse = function (name, zindex) {
47854         this._claimMouse$.next({ name: name, zindex: zindex });
47855     };
47856     MouseService.prototype.unclaimMouse = function (name) {
47857         this._claimMouse$.next({ name: name, zindex: null });
47858     };
47859     MouseService.prototype.deferPixels = function (name, deferPixels) {
47860         this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels });
47861     };
47862     MouseService.prototype.undeferPixels = function (name) {
47863         this._deferPixelClaims$.next({ name: name, deferPixels: null });
47864     };
47865     MouseService.prototype.claimWheel = function (name, zindex) {
47866         this._claimWheel$.next({ name: name, zindex: zindex });
47867     };
47868     MouseService.prototype.unclaimWheel = function (name) {
47869         this._claimWheel$.next({ name: name, zindex: null });
47870     };
47871     MouseService.prototype.filtered$ = function (name, observable$) {
47872         return this._filtered(name, observable$, this._mouseOwner$);
47873     };
47874     MouseService.prototype.filteredWheel$ = function (name, observable$) {
47875         return this._filtered(name, observable$, this._wheelOwner$);
47876     };
47877     MouseService.prototype._createDeferredMouseMove$ = function (origin, mouseMove$) {
47878         return mouseMove$.pipe(operators_1.map(function (mouseMove) {
47879             var deltaX = mouseMove.clientX - origin.clientX;
47880             var deltaY = mouseMove.clientY - origin.clientY;
47881             return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)];
47882         }), operators_1.withLatestFrom(this._deferPixels$), operators_1.filter(function (_a) {
47883             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
47884             return delta > deferPixels;
47885         }), operators_1.map(function (_a) {
47886             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
47887             return mouseMove;
47888         }));
47889     };
47890     MouseService.prototype._createMouseDrag$ = function (mouseDragStartInitiate$, stop$) {
47891         var _this = this;
47892         return mouseDragStartInitiate$.pipe(operators_1.map(function (_a) {
47893             var mouseDown = _a[0], mouseMove = _a[1];
47894             return mouseMove;
47895         }), operators_1.switchMap(function (mouseMove) {
47896             return rxjs_1.concat(rxjs_1.of(mouseMove), _this._documentMouseMove$).pipe(operators_1.takeUntil(stop$));
47897         }));
47898     };
47899     MouseService.prototype._createMouseDragEnd$ = function (mouseDragStart$, stop$) {
47900         return mouseDragStart$.pipe(operators_1.switchMap(function (event) {
47901             return stop$.pipe(operators_1.first());
47902         }));
47903     };
47904     MouseService.prototype._createMouseDragStart$ = function (mouseDragStartInitiate$) {
47905         return mouseDragStartInitiate$.pipe(operators_1.map(function (_a) {
47906             var mouseDown = _a[0], mouseMove = _a[1];
47907             return mouseDown;
47908         }));
47909     };
47910     MouseService.prototype._createMouseDragInitiate$ = function (mouseDown$, stop$, defer) {
47911         var _this = this;
47912         return mouseDown$.pipe(operators_1.filter(function (mouseDown) {
47913             return mouseDown.button === 0;
47914         }), operators_1.switchMap(function (mouseDown) {
47915             return rxjs_1.combineLatest(rxjs_1.of(mouseDown), defer ?
47916                 _this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$) :
47917                 _this._documentMouseMove$).pipe(operators_1.takeUntil(stop$), operators_1.take(1));
47918         }));
47919     };
47920     MouseService.prototype._createOwner$ = function (claim$) {
47921         return claim$.pipe(operators_1.scan(function (claims, claim) {
47922             if (claim.zindex == null) {
47923                 delete claims[claim.name];
47924             }
47925             else {
47926                 claims[claim.name] = claim.zindex;
47927             }
47928             return claims;
47929         }, {}), operators_1.map(function (claims) {
47930             var owner = null;
47931             var zIndexMax = -1;
47932             for (var name_1 in claims) {
47933                 if (!claims.hasOwnProperty(name_1)) {
47934                     continue;
47935                 }
47936                 if (claims[name_1] > zIndexMax) {
47937                     zIndexMax = claims[name_1];
47938                     owner = name_1;
47939                 }
47940             }
47941             return owner;
47942         }), operators_1.startWith(null));
47943     };
47944     MouseService.prototype._filtered = function (name, observable$, owner$) {
47945         return observable$.pipe(operators_1.withLatestFrom(owner$), operators_1.filter(function (_a) {
47946             var item = _a[0], owner = _a[1];
47947             return owner === name;
47948         }), operators_1.map(function (_a) {
47949             var item = _a[0], owner = _a[1];
47950             return item;
47951         }));
47952     };
47953     return MouseService;
47954 }());
47955 exports.MouseService = MouseService;
47956 exports.default = MouseService;
47957
47958 },{"rxjs":27,"rxjs/operators":225}],440:[function(require,module,exports){
47959 "use strict";
47960 Object.defineProperty(exports, "__esModule", { value: true });
47961 var rxjs_1 = require("rxjs");
47962 var operators_1 = require("rxjs/operators");
47963 var API_1 = require("../API");
47964 var Graph_1 = require("../Graph");
47965 var Edge_1 = require("../Edge");
47966 var Error_1 = require("../Error");
47967 var State_1 = require("../State");
47968 var Viewer_1 = require("../Viewer");
47969 var PanService_1 = require("./PanService");
47970 var Navigator = /** @class */ (function () {
47971     function Navigator(clientId, options, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService, playService, panService) {
47972         this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
47973         this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
47974         this._graphService = graphService != null ?
47975             graphService :
47976             new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
47977         this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
47978         this._loadingName = "navigator";
47979         this._stateService = stateService != null ? stateService : new State_1.StateService(options.transitionMode);
47980         this._cacheService = cacheService != null ?
47981             cacheService :
47982             new Viewer_1.CacheService(this._graphService, this._stateService);
47983         this._playService = playService != null ?
47984             playService :
47985             new Viewer_1.PlayService(this._graphService, this._stateService);
47986         this._panService = panService != null ?
47987             panService :
47988             new PanService_1.PanService(this._graphService, this._stateService, options.combinedPanning);
47989         this._keyRequested$ = new rxjs_1.BehaviorSubject(null);
47990         this._movedToKey$ = new rxjs_1.BehaviorSubject(null);
47991         this._request$ = null;
47992         this._requestSubscription = null;
47993         this._nodeRequestSubscription = null;
47994     }
47995     Object.defineProperty(Navigator.prototype, "apiV3", {
47996         get: function () {
47997             return this._apiV3;
47998         },
47999         enumerable: true,
48000         configurable: true
48001     });
48002     Object.defineProperty(Navigator.prototype, "cacheService", {
48003         get: function () {
48004             return this._cacheService;
48005         },
48006         enumerable: true,
48007         configurable: true
48008     });
48009     Object.defineProperty(Navigator.prototype, "graphService", {
48010         get: function () {
48011             return this._graphService;
48012         },
48013         enumerable: true,
48014         configurable: true
48015     });
48016     Object.defineProperty(Navigator.prototype, "imageLoadingService", {
48017         get: function () {
48018             return this._imageLoadingService;
48019         },
48020         enumerable: true,
48021         configurable: true
48022     });
48023     Object.defineProperty(Navigator.prototype, "loadingService", {
48024         get: function () {
48025             return this._loadingService;
48026         },
48027         enumerable: true,
48028         configurable: true
48029     });
48030     Object.defineProperty(Navigator.prototype, "movedToKey$", {
48031         get: function () {
48032             return this._movedToKey$;
48033         },
48034         enumerable: true,
48035         configurable: true
48036     });
48037     Object.defineProperty(Navigator.prototype, "panService", {
48038         get: function () {
48039             return this._panService;
48040         },
48041         enumerable: true,
48042         configurable: true
48043     });
48044     Object.defineProperty(Navigator.prototype, "playService", {
48045         get: function () {
48046             return this._playService;
48047         },
48048         enumerable: true,
48049         configurable: true
48050     });
48051     Object.defineProperty(Navigator.prototype, "stateService", {
48052         get: function () {
48053             return this._stateService;
48054         },
48055         enumerable: true,
48056         configurable: true
48057     });
48058     Navigator.prototype.moveToKey$ = function (key) {
48059         this._abortRequest("to key " + key);
48060         this._loadingService.startLoading(this._loadingName);
48061         var node$ = this._moveToKey$(key);
48062         return this._makeRequest$(node$);
48063     };
48064     Navigator.prototype.moveDir$ = function (direction) {
48065         var _this = this;
48066         this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
48067         this._loadingService.startLoading(this._loadingName);
48068         var node$ = this.stateService.currentNode$.pipe(operators_1.first(), operators_1.mergeMap(function (node) {
48069             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
48070                 node.sequenceEdges$ :
48071                 node.spatialEdges$).pipe(operators_1.first(), operators_1.map(function (status) {
48072                 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
48073                     var edge = _a[_i];
48074                     if (edge.data.direction === direction) {
48075                         return edge.to;
48076                     }
48077                 }
48078                 return null;
48079             }));
48080         }), operators_1.mergeMap(function (directionKey) {
48081             if (directionKey == null) {
48082                 _this._loadingService.stopLoading(_this._loadingName);
48083                 return rxjs_1.throwError(new Error("Direction (" + direction + ") does not exist for current node."));
48084             }
48085             return _this._moveToKey$(directionKey);
48086         }));
48087         return this._makeRequest$(node$);
48088     };
48089     Navigator.prototype.moveCloseTo$ = function (lat, lon) {
48090         var _this = this;
48091         this._abortRequest("to lat " + lat + ", lon " + lon);
48092         this._loadingService.startLoading(this._loadingName);
48093         var node$ = this.apiV3.imageCloseTo$(lat, lon).pipe(operators_1.mergeMap(function (fullNode) {
48094             if (fullNode == null) {
48095                 _this._loadingService.stopLoading(_this._loadingName);
48096                 return rxjs_1.throwError(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
48097             }
48098             return _this._moveToKey$(fullNode.key);
48099         }));
48100         return this._makeRequest$(node$);
48101     };
48102     Navigator.prototype.setFilter$ = function (filter) {
48103         var _this = this;
48104         this._stateService.clearNodes();
48105         return this._movedToKey$.pipe(operators_1.first(), operators_1.mergeMap(function (key) {
48106             if (key != null) {
48107                 return _this._trajectoryKeys$().pipe(operators_1.mergeMap(function (keys) {
48108                     return _this._graphService.setFilter$(filter).pipe(operators_1.mergeMap(function () {
48109                         return _this._cacheKeys$(keys);
48110                     }));
48111                 }), operators_1.last());
48112             }
48113             return _this._keyRequested$.pipe(operators_1.first(), operators_1.mergeMap(function (requestedKey) {
48114                 if (requestedKey != null) {
48115                     return _this._graphService.setFilter$(filter).pipe(operators_1.mergeMap(function () {
48116                         return _this._graphService.cacheNode$(requestedKey);
48117                     }));
48118                 }
48119                 return _this._graphService.setFilter$(filter).pipe(operators_1.map(function () {
48120                     return undefined;
48121                 }));
48122             }));
48123         }), operators_1.map(function (node) {
48124             return undefined;
48125         }));
48126     };
48127     Navigator.prototype.setToken$ = function (token) {
48128         var _this = this;
48129         this._abortRequest("to set token");
48130         this._stateService.clearNodes();
48131         return this._movedToKey$.pipe(operators_1.first(), operators_1.tap(function (key) {
48132             _this._apiV3.setToken(token);
48133         }), operators_1.mergeMap(function (key) {
48134             return key == null ?
48135                 _this._graphService.reset$([]) :
48136                 _this._trajectoryKeys$().pipe(operators_1.mergeMap(function (keys) {
48137                     return _this._graphService.reset$(keys).pipe(operators_1.mergeMap(function () {
48138                         return _this._cacheKeys$(keys);
48139                     }));
48140                 }), operators_1.last(), operators_1.map(function (node) {
48141                     return undefined;
48142                 }));
48143         }));
48144     };
48145     Navigator.prototype._cacheKeys$ = function (keys) {
48146         var _this = this;
48147         var cacheNodes$ = keys
48148             .map(function (key) {
48149             return _this._graphService.cacheNode$(key);
48150         });
48151         return rxjs_1.from(cacheNodes$).pipe(operators_1.mergeAll());
48152     };
48153     Navigator.prototype._abortRequest = function (reason) {
48154         if (this._requestSubscription != null) {
48155             this._requestSubscription.unsubscribe();
48156             this._requestSubscription = null;
48157         }
48158         if (this._nodeRequestSubscription != null) {
48159             this._nodeRequestSubscription.unsubscribe();
48160             this._nodeRequestSubscription = null;
48161         }
48162         if (this._request$ != null) {
48163             if (!(this._request$.isStopped || this._request$.hasError)) {
48164                 this._request$.error(new Error_1.AbortMapillaryError("Request aborted by a subsequent request " + reason + "."));
48165             }
48166             this._request$ = null;
48167         }
48168     };
48169     Navigator.prototype._makeRequest$ = function (node$) {
48170         var _this = this;
48171         var request$ = new rxjs_1.ReplaySubject(1);
48172         this._requestSubscription = request$
48173             .subscribe(undefined, function () { });
48174         this._request$ = request$;
48175         this._nodeRequestSubscription = node$
48176             .subscribe(function (node) {
48177             _this._request$ = null;
48178             request$.next(node);
48179             request$.complete();
48180         }, function (error) {
48181             _this._request$ = null;
48182             request$.error(error);
48183         });
48184         return request$;
48185     };
48186     Navigator.prototype._moveToKey$ = function (key) {
48187         var _this = this;
48188         this._keyRequested$.next(key);
48189         return this._graphService.cacheNode$(key).pipe(operators_1.tap(function (node) {
48190             _this._stateService.setNodes([node]);
48191             _this._movedToKey$.next(node.key);
48192         }), operators_1.finalize(function () {
48193             _this._loadingService.stopLoading(_this._loadingName);
48194         }));
48195     };
48196     Navigator.prototype._trajectoryKeys$ = function () {
48197         return this._stateService.currentState$.pipe(operators_1.first(), operators_1.map(function (frame) {
48198             return frame.state.trajectory
48199                 .map(function (node) {
48200                 return node.key;
48201             });
48202         }));
48203     };
48204     return Navigator;
48205 }());
48206 exports.Navigator = Navigator;
48207 exports.default = Navigator;
48208
48209 },{"../API":274,"../Edge":276,"../Error":277,"../Graph":279,"../State":282,"../Viewer":286,"./PanService":442,"rxjs":27,"rxjs/operators":225}],441:[function(require,module,exports){
48210 "use strict";
48211 Object.defineProperty(exports, "__esModule", { value: true });
48212 var rxjs_1 = require("rxjs");
48213 var operators_1 = require("rxjs/operators");
48214 var Viewer_1 = require("../Viewer");
48215 var Observer = /** @class */ (function () {
48216     function Observer(eventEmitter, navigator, container) {
48217         var _this = this;
48218         this._container = container;
48219         this._eventEmitter = eventEmitter;
48220         this._navigator = navigator;
48221         this._projection = new Viewer_1.Projection();
48222         this._started = false;
48223         this._navigable$ = new rxjs_1.Subject();
48224         // navigable and loading should always emit, also when cover is activated.
48225         this._navigable$
48226             .subscribe(function (navigable) {
48227             _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable);
48228         });
48229         this._navigator.loadingService.loading$
48230             .subscribe(function (loading) {
48231             _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
48232         });
48233     }
48234     Object.defineProperty(Observer.prototype, "started", {
48235         get: function () {
48236             return this._started;
48237         },
48238         enumerable: true,
48239         configurable: true
48240     });
48241     Object.defineProperty(Observer.prototype, "navigable$", {
48242         get: function () {
48243             return this._navigable$;
48244         },
48245         enumerable: true,
48246         configurable: true
48247     });
48248     Observer.prototype.projectBasic$ = function (basicPoint) {
48249         var _this = this;
48250         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.first(), operators_1.map(function (_a) {
48251             var render = _a[0], transform = _a[1];
48252             var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
48253             return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
48254         }));
48255     };
48256     Observer.prototype.startEmit = function () {
48257         var _this = this;
48258         if (this._started) {
48259             return;
48260         }
48261         this._started = true;
48262         this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
48263             .subscribe(function (node) {
48264             _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
48265         });
48266         this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$.pipe(operators_1.switchMap(function (node) {
48267             return node.sequenceEdges$;
48268         }))
48269             .subscribe(function (status) {
48270             _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
48271         });
48272         this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$.pipe(operators_1.switchMap(function (node) {
48273             return node.spatialEdges$;
48274         }))
48275             .subscribe(function (status) {
48276             _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
48277         });
48278         this._moveSubscription = rxjs_1.combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$).pipe(operators_1.map(function (values) {
48279             return values[0] || values[1] || values[2];
48280         }), operators_1.distinctUntilChanged())
48281             .subscribe(function (started) {
48282             if (started) {
48283                 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
48284             }
48285             else {
48286                 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
48287             }
48288         });
48289         this._bearingSubscription = this._container.renderService.bearing$.pipe(operators_1.auditTime(100), operators_1.distinctUntilChanged(function (b1, b2) {
48290             return Math.abs(b2 - b1) < 1;
48291         }))
48292             .subscribe(function (bearing) {
48293             _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
48294         });
48295         var mouseMove$ = this._container.mouseService.active$.pipe(operators_1.switchMap(function (active) {
48296             return active ?
48297                 rxjs_1.empty() :
48298                 _this._container.mouseService.mouseMove$;
48299         }));
48300         this._viewerMouseEventSubscription = rxjs_1.merge(this._mapMouseEvent$(Viewer_1.Viewer.click, this._container.mouseService.staticClick$), this._mapMouseEvent$(Viewer_1.Viewer.contextmenu, this._container.mouseService.contextMenu$), this._mapMouseEvent$(Viewer_1.Viewer.dblclick, this._container.mouseService.dblClick$), this._mapMouseEvent$(Viewer_1.Viewer.mousedown, this._container.mouseService.mouseDown$), this._mapMouseEvent$(Viewer_1.Viewer.mousemove, mouseMove$), this._mapMouseEvent$(Viewer_1.Viewer.mouseout, this._container.mouseService.mouseOut$), this._mapMouseEvent$(Viewer_1.Viewer.mouseover, this._container.mouseService.mouseOver$), this._mapMouseEvent$(Viewer_1.Viewer.mouseup, this._container.mouseService.mouseUp$)).pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
48301             var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
48302             var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
48303             return {
48304                 basicPoint: unprojection.basicPoint,
48305                 latLon: unprojection.latLon,
48306                 originalEvent: event,
48307                 pixelPoint: unprojection.pixelPoint,
48308                 target: _this._eventEmitter,
48309                 type: type,
48310             };
48311         }))
48312             .subscribe(function (event) {
48313             _this._eventEmitter.fire(event.type, event);
48314         });
48315     };
48316     Observer.prototype.stopEmit = function () {
48317         if (!this.started) {
48318             return;
48319         }
48320         this._started = false;
48321         this._bearingSubscription.unsubscribe();
48322         this._currentNodeSubscription.unsubscribe();
48323         this._moveSubscription.unsubscribe();
48324         this._sequenceEdgesSubscription.unsubscribe();
48325         this._spatialEdgesSubscription.unsubscribe();
48326         this._viewerMouseEventSubscription.unsubscribe();
48327         this._bearingSubscription = null;
48328         this._currentNodeSubscription = null;
48329         this._moveSubscription = null;
48330         this._sequenceEdgesSubscription = null;
48331         this._spatialEdgesSubscription = null;
48332         this._viewerMouseEventSubscription = null;
48333     };
48334     Observer.prototype.unproject$ = function (canvasPoint) {
48335         var _this = this;
48336         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$).pipe(operators_1.first(), operators_1.map(function (_a) {
48337             var render = _a[0], reference = _a[1], transform = _a[2];
48338             var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
48339             return unprojection.latLon;
48340         }));
48341     };
48342     Observer.prototype.unprojectBasic$ = function (canvasPoint) {
48343         var _this = this;
48344         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.first(), operators_1.map(function (_a) {
48345             var render = _a[0], transform = _a[1];
48346             return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
48347         }));
48348     };
48349     Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
48350         return mouseEvent$.pipe(operators_1.map(function (event) {
48351             return [type, event];
48352         }));
48353     };
48354     return Observer;
48355 }());
48356 exports.Observer = Observer;
48357 exports.default = Observer;
48358
48359 },{"../Viewer":286,"rxjs":27,"rxjs/operators":225}],442:[function(require,module,exports){
48360 "use strict";
48361 Object.defineProperty(exports, "__esModule", { value: true });
48362 var rxjs_1 = require("rxjs");
48363 var operators_1 = require("rxjs/operators");
48364 var Geo = require("../geo/Geo");
48365 var GeoCoords_1 = require("../geo/GeoCoords");
48366 var GraphCalculator_1 = require("../graph/GraphCalculator");
48367 var Spatial_1 = require("../geo/Spatial");
48368 var Transform_1 = require("../geo/Transform");
48369 var ViewportCoords_1 = require("../geo/ViewportCoords");
48370 var PanMode;
48371 (function (PanMode) {
48372     PanMode[PanMode["Disabled"] = 0] = "Disabled";
48373     PanMode[PanMode["Enabled"] = 1] = "Enabled";
48374     PanMode[PanMode["Started"] = 2] = "Started";
48375 })(PanMode || (PanMode = {}));
48376 var PanService = /** @class */ (function () {
48377     function PanService(graphService, stateService, enabled, geoCoords, graphCalculator, spatial, viewportCoords) {
48378         this._graphService = graphService;
48379         this._stateService = stateService;
48380         this._geoCoords = !!geoCoords ? geoCoords : new GeoCoords_1.default();
48381         this._graphCalculator = !!graphCalculator ? graphCalculator : new GraphCalculator_1.default(this._geoCoords);
48382         this._spatial = !!spatial ? spatial : new Spatial_1.default();
48383         this._viewportCoords = !!viewportCoords ? viewportCoords : new ViewportCoords_1.default();
48384         this._mode = enabled !== false ? PanMode.Enabled : PanMode.Disabled;
48385         this._panNodesSubject$ = new rxjs_1.Subject();
48386         this._panNodes$ = this._panNodesSubject$.pipe(operators_1.startWith([]), operators_1.publishReplay(1), operators_1.refCount());
48387         this._panNodes$.subscribe();
48388     }
48389     Object.defineProperty(PanService.prototype, "panNodes$", {
48390         get: function () {
48391             return this._panNodes$;
48392         },
48393         enumerable: true,
48394         configurable: true
48395     });
48396     PanService.prototype.enable = function () {
48397         if (this._mode !== PanMode.Disabled) {
48398             return;
48399         }
48400         this._mode = PanMode.Enabled;
48401         this.start();
48402     };
48403     PanService.prototype.disable = function () {
48404         if (this._mode === PanMode.Disabled) {
48405             return;
48406         }
48407         this.stop();
48408         this._mode = PanMode.Disabled;
48409     };
48410     PanService.prototype.start = function () {
48411         var _this = this;
48412         if (this._mode !== PanMode.Enabled) {
48413             return;
48414         }
48415         var panNodes$ = this._stateService.currentNode$.pipe(operators_1.switchMap(function (current) {
48416             if (!current.merged) {
48417                 return rxjs_1.of([]);
48418             }
48419             var current$ = rxjs_1.of(current);
48420             var bounds = _this._graphCalculator.boundingBoxCorners(current.latLon, 20);
48421             var adjacent$ = _this._graphService
48422                 .cacheBoundingBox$(bounds[0], bounds[1]).pipe(operators_1.catchError(function (error) {
48423                 console.error("Failed to cache periphery bounding box (" + current.key + ")", error);
48424                 return rxjs_1.empty();
48425             }), operators_1.map(function (nodes) {
48426                 if (current.pano) {
48427                     return [];
48428                 }
48429                 var potential = [];
48430                 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
48431                     var node = nodes_1[_i];
48432                     if (node.key === current.key) {
48433                         continue;
48434                     }
48435                     if (node.mergeCC !== current.mergeCC) {
48436                         continue;
48437                     }
48438                     if (node.pano) {
48439                         continue;
48440                     }
48441                     if (_this._distance(node, current) > 4) {
48442                         continue;
48443                     }
48444                     potential.push(node);
48445                 }
48446                 return potential;
48447             }));
48448             return rxjs_1.combineLatest(current$, adjacent$).pipe(operators_1.withLatestFrom(_this._stateService.reference$), operators_1.map(function (_a) {
48449                 var _b = _a[0], cn = _b[0], adjacent = _b[1], reference = _a[1];
48450                 var currentDirection = _this._spatial.viewingDirection(cn.rotation);
48451                 var currentTranslation = Geo.computeTranslation({ lat: cn.latLon.lat, lon: cn.latLon.lon, alt: cn.alt }, cn.rotation, reference);
48452                 var currentTransform = _this._createTransform(cn, currentTranslation);
48453                 var currentAzimuthal = _this._spatial.wrap(_this._spatial.azimuthal(currentDirection.toArray(), currentTransform.upVector().toArray()), 0, 2 * Math.PI);
48454                 var currentProjectedPoints = _this._computeProjectedPoints(currentTransform);
48455                 var currentHFov = _this._computeHorizontalFov(currentProjectedPoints) / 180 * Math.PI;
48456                 var preferredOverlap = Math.PI / 8;
48457                 var left = undefined;
48458                 var right = undefined;
48459                 for (var _i = 0, adjacent_1 = adjacent; _i < adjacent_1.length; _i++) {
48460                     var a = adjacent_1[_i];
48461                     var translation = Geo.computeTranslation({ lat: a.latLon.lat, lon: a.latLon.lon, alt: a.alt }, a.rotation, reference);
48462                     var transform = _this._createTransform(a, translation);
48463                     var projectedPoints = _this._computeProjectedPoints(transform);
48464                     var hFov = _this._computeHorizontalFov(projectedPoints) / 180 * Math.PI;
48465                     var direction = _this._spatial.viewingDirection(a.rotation);
48466                     var azimuthal = _this._spatial.wrap(_this._spatial.azimuthal(direction.toArray(), transform.upVector().toArray()), 0, 2 * Math.PI);
48467                     var directionChange = _this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
48468                     var overlap = Number.NEGATIVE_INFINITY;
48469                     if (directionChange > 0) {
48470                         if (currentAzimuthal > azimuthal) {
48471                             overlap = currentAzimuthal - 2 * Math.PI + currentHFov / 2 - (azimuthal - hFov / 2);
48472                         }
48473                         else {
48474                             overlap = currentAzimuthal + currentHFov / 2 - (azimuthal - hFov / 2);
48475                         }
48476                     }
48477                     else {
48478                         if (currentAzimuthal < azimuthal) {
48479                             overlap = azimuthal + hFov / 2 - (currentAzimuthal + 2 * Math.PI - currentHFov / 2);
48480                         }
48481                         else {
48482                             overlap = azimuthal + hFov / 2 - (currentAzimuthal - currentHFov / 2);
48483                         }
48484                     }
48485                     var nonOverlap = Math.abs(hFov - overlap);
48486                     var distanceCost = _this._distance(a, cn);
48487                     var timeCost = Math.min(_this._timeDifference(a, cn), 4);
48488                     var overlapCost = 20 * Math.abs(overlap - preferredOverlap);
48489                     var fovCost = Math.min(5, 1 / Math.min(hFov / currentHFov, 1));
48490                     var nonOverlapCost = overlap > 0 ? -2 * nonOverlap : 0;
48491                     var cost = distanceCost + timeCost + overlapCost + fovCost + nonOverlapCost;
48492                     if (overlap > 0 &&
48493                         overlap < 0.5 * currentHFov &&
48494                         overlap < 0.5 * hFov &&
48495                         nonOverlap > 0.5 * currentHFov) {
48496                         if (directionChange > 0) {
48497                             if (!left) {
48498                                 left = [cost, a, transform, hFov];
48499                             }
48500                             else {
48501                                 if (cost < left[0]) {
48502                                     left = [cost, a, transform, hFov];
48503                                 }
48504                             }
48505                         }
48506                         else {
48507                             if (!right) {
48508                                 right = [cost, a, transform, hFov];
48509                             }
48510                             else {
48511                                 if (cost < right[0]) {
48512                                     right = [cost, a, transform, hFov];
48513                                 }
48514                             }
48515                         }
48516                     }
48517                 }
48518                 var panNodes = [];
48519                 if (!!left) {
48520                     panNodes.push([left[1], left[2], left[3]]);
48521                 }
48522                 if (!!right) {
48523                     panNodes.push([right[1], right[2], right[3]]);
48524                 }
48525                 return panNodes;
48526             }), operators_1.startWith([]));
48527         }));
48528         this._panNodesSubscription = this._stateService.currentState$.pipe(operators_1.map(function (frame) {
48529             return frame.state.nodesAhead > 0;
48530         }), operators_1.distinctUntilChanged(), operators_1.switchMap(function (traversing) {
48531             return traversing ? rxjs_1.of([]) : panNodes$;
48532         }))
48533             .subscribe(function (panNodes) {
48534             _this._panNodesSubject$.next(panNodes);
48535         });
48536         this._mode = PanMode.Started;
48537     };
48538     PanService.prototype.stop = function () {
48539         if (this._mode !== PanMode.Started) {
48540             return;
48541         }
48542         this._panNodesSubscription.unsubscribe();
48543         this._panNodesSubject$.next([]);
48544         this._mode = PanMode.Enabled;
48545     };
48546     PanService.prototype._distance = function (node, reference) {
48547         var _a = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, reference.latLon.lat, reference.latLon.lon, reference.alt), x = _a[0], y = _a[1], z = _a[2];
48548         return Math.sqrt(x * x + y * y + z * z);
48549     };
48550     PanService.prototype._timeDifference = function (node, reference) {
48551         return Math.abs(node.capturedAt - reference.capturedAt) / (1000 * 60 * 60 * 24 * 30);
48552     };
48553     PanService.prototype._createTransform = function (node, translation) {
48554         return new Transform_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.assetsCached ? node.image : undefined, undefined, node.ck1, node.ck2, node.cameraProjection);
48555     };
48556     PanService.prototype._computeProjectedPoints = function (transform) {
48557         var vertices = [[1, 0]];
48558         var directions = [[0, 0.5]];
48559         var pointsPerLine = 20;
48560         return Geo.computeProjectedPoints(transform, vertices, directions, pointsPerLine, this._viewportCoords);
48561     };
48562     PanService.prototype._computeHorizontalFov = function (projectedPoints) {
48563         var _this = this;
48564         var fovs = projectedPoints
48565             .map(function (projectedPoint) {
48566             return _this._coordToFov(projectedPoint[0]);
48567         });
48568         var fov = Math.min.apply(Math, fovs);
48569         return fov;
48570     };
48571     PanService.prototype._coordToFov = function (x) {
48572         return 2 * Math.atan(x) * 180 / Math.PI;
48573     };
48574     return PanService;
48575 }());
48576 exports.PanService = PanService;
48577
48578 },{"../geo/Geo":384,"../geo/GeoCoords":385,"../geo/Spatial":387,"../geo/Transform":388,"../geo/ViewportCoords":389,"../graph/GraphCalculator":392,"rxjs":27,"rxjs/operators":225}],443:[function(require,module,exports){
48579 "use strict";
48580 Object.defineProperty(exports, "__esModule", { value: true });
48581 var rxjs_1 = require("rxjs");
48582 var operators_1 = require("rxjs/operators");
48583 var Edge_1 = require("../Edge");
48584 var Graph_1 = require("../Graph");
48585 var PlayService = /** @class */ (function () {
48586     function PlayService(graphService, stateService, graphCalculator) {
48587         this._graphService = graphService;
48588         this._stateService = stateService;
48589         this._graphCalculator = !!graphCalculator ? graphCalculator : new Graph_1.GraphCalculator();
48590         this._directionSubject$ = new rxjs_1.Subject();
48591         this._direction$ = this._directionSubject$.pipe(operators_1.startWith(Edge_1.EdgeDirection.Next), operators_1.publishReplay(1), operators_1.refCount());
48592         this._direction$.subscribe();
48593         this._playing = false;
48594         this._playingSubject$ = new rxjs_1.Subject();
48595         this._playing$ = this._playingSubject$.pipe(operators_1.startWith(this._playing), operators_1.publishReplay(1), operators_1.refCount());
48596         this._playing$.subscribe();
48597         this._speed = 0.5;
48598         this._speedSubject$ = new rxjs_1.Subject();
48599         this._speed$ = this._speedSubject$.pipe(operators_1.startWith(this._speed), operators_1.publishReplay(1), operators_1.refCount());
48600         this._speed$.subscribe();
48601         this._nodesAhead = this._mapNodesAhead(this._mapSpeed(this._speed));
48602         this._bridging$ = null;
48603     }
48604     Object.defineProperty(PlayService.prototype, "playing", {
48605         get: function () {
48606             return this._playing;
48607         },
48608         enumerable: true,
48609         configurable: true
48610     });
48611     Object.defineProperty(PlayService.prototype, "direction$", {
48612         get: function () {
48613             return this._direction$;
48614         },
48615         enumerable: true,
48616         configurable: true
48617     });
48618     Object.defineProperty(PlayService.prototype, "playing$", {
48619         get: function () {
48620             return this._playing$;
48621         },
48622         enumerable: true,
48623         configurable: true
48624     });
48625     Object.defineProperty(PlayService.prototype, "speed$", {
48626         get: function () {
48627             return this._speed$;
48628         },
48629         enumerable: true,
48630         configurable: true
48631     });
48632     PlayService.prototype.play = function () {
48633         var _this = this;
48634         if (this._playing) {
48635             return;
48636         }
48637         this._stateService.cutNodes();
48638         var stateSpeed = this._setSpeed(this._speed);
48639         this._stateService.setSpeed(stateSpeed);
48640         this._graphModeSubscription = this._speed$.pipe(operators_1.map(function (speed) {
48641             return speed > PlayService.sequenceSpeed ? Graph_1.GraphMode.Sequence : Graph_1.GraphMode.Spatial;
48642         }), operators_1.distinctUntilChanged())
48643             .subscribe(function (mode) {
48644             _this._graphService.setGraphMode(mode);
48645         });
48646         this._cacheSubscription = rxjs_1.combineLatest(this._stateService.currentNode$.pipe(operators_1.map(function (node) {
48647             return [node.sequenceKey, node.key];
48648         }), operators_1.distinctUntilChanged(undefined, function (_a) {
48649             var sequenceKey = _a[0], nodeKey = _a[1];
48650             return sequenceKey;
48651         })), this._graphService.graphMode$, this._direction$).pipe(operators_1.switchMap(function (_a) {
48652             var _b = _a[0], sequenceKey = _b[0], nodeKey = _b[1], mode = _a[1], direction = _a[2];
48653             if (direction !== Edge_1.EdgeDirection.Next && direction !== Edge_1.EdgeDirection.Prev) {
48654                 return rxjs_1.of([undefined, direction]);
48655             }
48656             var sequence$ = (mode === Graph_1.GraphMode.Sequence ?
48657                 _this._graphService.cacheSequenceNodes$(sequenceKey, nodeKey) :
48658                 _this._graphService.cacheSequence$(sequenceKey)).pipe(operators_1.retry(3), operators_1.catchError(function (error) {
48659                 console.error(error);
48660                 return rxjs_1.of(undefined);
48661             }));
48662             return rxjs_1.combineLatest(sequence$, rxjs_1.of(direction));
48663         }), operators_1.switchMap(function (_a) {
48664             var sequence = _a[0], direction = _a[1];
48665             if (sequence === undefined) {
48666                 return rxjs_1.empty();
48667             }
48668             var sequenceKeys = sequence.keys.slice();
48669             if (direction === Edge_1.EdgeDirection.Prev) {
48670                 sequenceKeys.reverse();
48671             }
48672             return _this._stateService.currentState$.pipe(operators_1.map(function (frame) {
48673                 return [frame.state.trajectory[frame.state.trajectory.length - 1].key, frame.state.nodesAhead];
48674             }), operators_1.scan(function (_a, _b) {
48675                 var lastRequestKey = _a[0], previousRequestKeys = _a[1];
48676                 var lastTrajectoryKey = _b[0], nodesAhead = _b[1];
48677                 if (lastRequestKey === undefined) {
48678                     lastRequestKey = lastTrajectoryKey;
48679                 }
48680                 var lastIndex = sequenceKeys.length - 1;
48681                 if (nodesAhead >= _this._nodesAhead || sequenceKeys[lastIndex] === lastRequestKey) {
48682                     return [lastRequestKey, []];
48683                 }
48684                 var current = sequenceKeys.indexOf(lastTrajectoryKey);
48685                 var start = sequenceKeys.indexOf(lastRequestKey) + 1;
48686                 var end = Math.min(lastIndex, current + _this._nodesAhead - nodesAhead) + 1;
48687                 if (end <= start) {
48688                     return [lastRequestKey, []];
48689                 }
48690                 return [sequenceKeys[end - 1], sequenceKeys.slice(start, end)];
48691             }, [undefined, []]), operators_1.mergeMap(function (_a) {
48692                 var lastRequestKey = _a[0], newRequestKeys = _a[1];
48693                 return rxjs_1.from(newRequestKeys);
48694             }));
48695         }), operators_1.mergeMap(function (key) {
48696             return _this._graphService.cacheNode$(key).pipe(operators_1.catchError(function () {
48697                 return rxjs_1.empty();
48698             }));
48699         }, 6))
48700             .subscribe();
48701         this._playingSubscription = this._stateService.currentState$.pipe(operators_1.filter(function (frame) {
48702             return frame.state.nodesAhead < _this._nodesAhead;
48703         }), operators_1.distinctUntilChanged(undefined, function (frame) {
48704             return frame.state.lastNode.key;
48705         }), operators_1.map(function (frame) {
48706             var lastNode = frame.state.lastNode;
48707             var trajectory = frame.state.trajectory;
48708             var increasingTime = undefined;
48709             for (var i = trajectory.length - 2; i >= 0; i--) {
48710                 var node = trajectory[i];
48711                 if (node.sequenceKey !== lastNode.sequenceKey) {
48712                     break;
48713                 }
48714                 if (node.capturedAt !== lastNode.capturedAt) {
48715                     increasingTime = node.capturedAt < lastNode.capturedAt;
48716                     break;
48717                 }
48718             }
48719             return [frame.state.lastNode, increasingTime];
48720         }), operators_1.withLatestFrom(this._direction$), operators_1.switchMap(function (_a) {
48721             var _b = _a[0], node = _b[0], increasingTime = _b[1], direction = _a[1];
48722             return rxjs_1.zip(([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
48723                 node.sequenceEdges$ :
48724                 node.spatialEdges$).pipe(operators_1.first(function (status) {
48725                 return status.cached;
48726             }), operators_1.timeout(15000)), rxjs_1.of(direction)).pipe(operators_1.map(function (_a) {
48727                 var s = _a[0], d = _a[1];
48728                 for (var _i = 0, _b = s.edges; _i < _b.length; _i++) {
48729                     var edge = _b[_i];
48730                     if (edge.data.direction === d) {
48731                         return edge.to;
48732                     }
48733                 }
48734                 return null;
48735             }), operators_1.switchMap(function (key) {
48736                 return key != null ?
48737                     _this._graphService.cacheNode$(key) :
48738                     _this._bridge$(node, increasingTime).pipe(operators_1.filter(function (n) {
48739                         return !!n;
48740                     }));
48741             }));
48742         }))
48743             .subscribe(function (node) {
48744             _this._stateService.appendNodes([node]);
48745         }, function (error) {
48746             console.error(error);
48747             _this.stop();
48748         });
48749         this._clearSubscription = this._stateService.currentNode$.pipe(operators_1.bufferCount(1, 10))
48750             .subscribe(function (nodes) {
48751             _this._stateService.clearPriorNodes();
48752         });
48753         this._setPlaying(true);
48754         var currentLastNodes$ = this._stateService.currentState$.pipe(operators_1.map(function (frame) {
48755             return frame.state;
48756         }), operators_1.distinctUntilChanged(function (_a, _b) {
48757             var kc1 = _a[0], kl1 = _a[1];
48758             var kc2 = _b[0], kl2 = _b[1];
48759             return kc1 === kc2 && kl1 === kl2;
48760         }, function (state) {
48761             return [state.currentNode.key, state.lastNode.key];
48762         }), operators_1.filter(function (state) {
48763             return state.currentNode.key === state.lastNode.key &&
48764                 state.currentIndex === state.trajectory.length - 1;
48765         }), operators_1.map(function (state) {
48766             return state.currentNode;
48767         }));
48768         this._stopSubscription = rxjs_1.combineLatest(currentLastNodes$, this._direction$).pipe(operators_1.switchMap(function (_a) {
48769             var node = _a[0], direction = _a[1];
48770             var edgeStatus$ = ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
48771                 node.sequenceEdges$ :
48772                 node.spatialEdges$).pipe(operators_1.first(function (status) {
48773                 return status.cached;
48774             }), operators_1.timeout(15000), operators_1.catchError(function (error) {
48775                 console.error(error);
48776                 return rxjs_1.of({ cached: false, edges: [] });
48777             }));
48778             return rxjs_1.combineLatest(rxjs_1.of(direction), edgeStatus$).pipe(operators_1.map(function (_a) {
48779                 var d = _a[0], es = _a[1];
48780                 for (var _i = 0, _b = es.edges; _i < _b.length; _i++) {
48781                     var edge = _b[_i];
48782                     if (edge.data.direction === d) {
48783                         return true;
48784                     }
48785                 }
48786                 return false;
48787             }));
48788         }), operators_1.mergeMap(function (hasEdge) {
48789             if (hasEdge || !_this._bridging$) {
48790                 return rxjs_1.of(hasEdge);
48791             }
48792             return _this._bridging$.pipe(operators_1.map(function (node) {
48793                 return node != null;
48794             }), operators_1.catchError(function (error) {
48795                 console.error(error);
48796                 return rxjs_1.of(false);
48797             }));
48798         }), operators_1.first(function (hasEdge) {
48799             return !hasEdge;
48800         }))
48801             .subscribe(undefined, undefined, function () { _this.stop(); });
48802         if (this._stopSubscription.closed) {
48803             this._stopSubscription = null;
48804         }
48805     };
48806     PlayService.prototype.setDirection = function (direction) {
48807         this._directionSubject$.next(direction);
48808     };
48809     PlayService.prototype.setSpeed = function (speed) {
48810         speed = Math.max(0, Math.min(1, speed));
48811         if (speed === this._speed) {
48812             return;
48813         }
48814         var stateSpeed = this._setSpeed(speed);
48815         if (this._playing) {
48816             this._stateService.setSpeed(stateSpeed);
48817         }
48818         this._speedSubject$.next(this._speed);
48819     };
48820     PlayService.prototype.stop = function () {
48821         if (!this._playing) {
48822             return;
48823         }
48824         if (!!this._stopSubscription) {
48825             if (!this._stopSubscription.closed) {
48826                 this._stopSubscription.unsubscribe();
48827             }
48828             this._stopSubscription = null;
48829         }
48830         this._graphModeSubscription.unsubscribe();
48831         this._graphModeSubscription = null;
48832         this._cacheSubscription.unsubscribe();
48833         this._cacheSubscription = null;
48834         this._playingSubscription.unsubscribe();
48835         this._playingSubscription = null;
48836         this._clearSubscription.unsubscribe();
48837         this._clearSubscription = null;
48838         this._stateService.setSpeed(1);
48839         this._stateService.cutNodes();
48840         this._graphService.setGraphMode(Graph_1.GraphMode.Spatial);
48841         this._setPlaying(false);
48842     };
48843     PlayService.prototype._bridge$ = function (node, increasingTime) {
48844         var _this = this;
48845         if (increasingTime === undefined) {
48846             return rxjs_1.of(null);
48847         }
48848         var boundingBox = this._graphCalculator.boundingBoxCorners(node.latLon, 25);
48849         this._bridging$ = this._graphService.cacheBoundingBox$(boundingBox[0], boundingBox[1]).pipe(operators_1.mergeMap(function (nodes) {
48850             var nextNode = null;
48851             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
48852                 var n = nodes_1[_i];
48853                 if (n.sequenceKey === node.sequenceKey ||
48854                     !n.cameraUuid ||
48855                     n.cameraUuid !== node.cameraUuid ||
48856                     n.capturedAt === node.capturedAt ||
48857                     n.capturedAt > node.capturedAt !== increasingTime) {
48858                     continue;
48859                 }
48860                 var delta = Math.abs(n.capturedAt - node.capturedAt);
48861                 if (delta > 15000) {
48862                     continue;
48863                 }
48864                 if (!nextNode || delta < Math.abs(nextNode.capturedAt - node.capturedAt)) {
48865                     nextNode = n;
48866                 }
48867             }
48868             return !!nextNode ?
48869                 _this._graphService.cacheNode$(nextNode.key) :
48870                 rxjs_1.of(null);
48871         }), operators_1.finalize(function () {
48872             _this._bridging$ = null;
48873         }), operators_1.publish(), operators_1.refCount());
48874         return this._bridging$;
48875     };
48876     PlayService.prototype._mapSpeed = function (speed) {
48877         var x = 2 * speed - 1;
48878         return Math.pow(10, x) - 0.2 * x;
48879     };
48880     PlayService.prototype._mapNodesAhead = function (stateSpeed) {
48881         return Math.round(Math.max(10, Math.min(50, 8 + 6 * stateSpeed)));
48882     };
48883     PlayService.prototype._setPlaying = function (playing) {
48884         this._playing = playing;
48885         this._playingSubject$.next(playing);
48886     };
48887     PlayService.prototype._setSpeed = function (speed) {
48888         this._speed = speed;
48889         var stateSpeed = this._mapSpeed(this._speed);
48890         this._nodesAhead = this._mapNodesAhead(stateSpeed);
48891         return stateSpeed;
48892     };
48893     PlayService.sequenceSpeed = 0.54;
48894     return PlayService;
48895 }());
48896 exports.PlayService = PlayService;
48897 exports.default = PlayService;
48898
48899 },{"../Edge":276,"../Graph":279,"rxjs":27,"rxjs/operators":225}],444:[function(require,module,exports){
48900 "use strict";
48901 Object.defineProperty(exports, "__esModule", { value: true });
48902 var THREE = require("three");
48903 var Geo_1 = require("../Geo");
48904 var Projection = /** @class */ (function () {
48905     function Projection(geoCoords, viewportCoords) {
48906         this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
48907         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
48908     }
48909     Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
48910         return this._viewportCoords
48911             .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
48912     };
48913     Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
48914         var basicPoint = this._viewportCoords
48915             .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
48916         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
48917             basicPoint = null;
48918         }
48919         return basicPoint;
48920     };
48921     Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
48922         var pixelPoint = this._viewportCoords.canvasPosition(event, container);
48923         return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
48924     };
48925     Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
48926         var canvasX = canvasPoint[0];
48927         var canvasY = canvasPoint[1];
48928         var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
48929         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
48930             .unproject(render.perspective);
48931         var basicPoint = transform.projectBasic(point3d.toArray());
48932         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
48933             basicPoint = null;
48934         }
48935         var direction3d = point3d.clone().sub(render.camera.position).normalize();
48936         var dist = -2 / direction3d.z;
48937         var latLon = null;
48938         if (dist > 0 && dist < 100 && !!basicPoint) {
48939             var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
48940             var latLonArray = this._geoCoords
48941                 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
48942                 .slice(0, 2);
48943             latLon = { lat: latLonArray[0], lon: latLonArray[1] };
48944         }
48945         var unprojection = {
48946             basicPoint: basicPoint,
48947             latLon: latLon,
48948             pixelPoint: [canvasX, canvasY],
48949         };
48950         return unprojection;
48951     };
48952     return Projection;
48953 }());
48954 exports.Projection = Projection;
48955 exports.default = Projection;
48956
48957 },{"../Geo":278,"three":226}],445:[function(require,module,exports){
48958 "use strict";
48959 Object.defineProperty(exports, "__esModule", { value: true });
48960 var operators_1 = require("rxjs/operators");
48961 var THREE = require("three");
48962 var vd = require("virtual-dom");
48963 var rxjs_1 = require("rxjs");
48964 var Viewer_1 = require("../Viewer");
48965 var SpriteAtlas = /** @class */ (function () {
48966     function SpriteAtlas() {
48967     }
48968     Object.defineProperty(SpriteAtlas.prototype, "json", {
48969         set: function (value) {
48970             this._json = value;
48971         },
48972         enumerable: true,
48973         configurable: true
48974     });
48975     Object.defineProperty(SpriteAtlas.prototype, "image", {
48976         set: function (value) {
48977             this._image = value;
48978             this._texture = new THREE.Texture(this._image);
48979             this._texture.minFilter = THREE.NearestFilter;
48980         },
48981         enumerable: true,
48982         configurable: true
48983     });
48984     Object.defineProperty(SpriteAtlas.prototype, "loaded", {
48985         get: function () {
48986             return !!(this._image && this._json);
48987         },
48988         enumerable: true,
48989         configurable: true
48990     });
48991     SpriteAtlas.prototype.getGLSprite = function (name) {
48992         if (!this.loaded) {
48993             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
48994         }
48995         var definition = this._json[name];
48996         if (!definition) {
48997             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
48998             return new THREE.Object3D();
48999         }
49000         var texture = this._texture.clone();
49001         texture.needsUpdate = true;
49002         var width = this._image.width;
49003         var height = this._image.height;
49004         texture.offset.x = definition.x / width;
49005         texture.offset.y = (height - definition.y - definition.height) / height;
49006         texture.repeat.x = definition.width / width;
49007         texture.repeat.y = definition.height / height;
49008         var material = new THREE.SpriteMaterial({ map: texture });
49009         return new THREE.Sprite(material);
49010     };
49011     SpriteAtlas.prototype.getDOMSprite = function (name, float) {
49012         if (!this.loaded) {
49013             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
49014         }
49015         if (float == null) {
49016             float = Viewer_1.Alignment.Center;
49017         }
49018         var definition = this._json[name];
49019         if (!definition) {
49020             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
49021             return vd.h("div", {}, []);
49022         }
49023         var clipTop = definition.y;
49024         var clipRigth = definition.x + definition.width;
49025         var clipBottom = definition.y + definition.height;
49026         var clipLeft = definition.x;
49027         var left = -definition.x;
49028         var top = -definition.y;
49029         var height = this._image.height;
49030         var width = this._image.width;
49031         switch (float) {
49032             case Viewer_1.Alignment.Bottom:
49033             case Viewer_1.Alignment.Center:
49034             case Viewer_1.Alignment.Top:
49035                 left -= definition.width / 2;
49036                 break;
49037             case Viewer_1.Alignment.BottomLeft:
49038             case Viewer_1.Alignment.Left:
49039             case Viewer_1.Alignment.TopLeft:
49040                 left -= definition.width;
49041                 break;
49042             case Viewer_1.Alignment.BottomRight:
49043             case Viewer_1.Alignment.Right:
49044             case Viewer_1.Alignment.TopRight:
49045             default:
49046                 break;
49047         }
49048         switch (float) {
49049             case Viewer_1.Alignment.Center:
49050             case Viewer_1.Alignment.Left:
49051             case Viewer_1.Alignment.Right:
49052                 top -= definition.height / 2;
49053                 break;
49054             case Viewer_1.Alignment.Top:
49055             case Viewer_1.Alignment.TopLeft:
49056             case Viewer_1.Alignment.TopRight:
49057                 top -= definition.height;
49058                 break;
49059             case Viewer_1.Alignment.Bottom:
49060             case Viewer_1.Alignment.BottomLeft:
49061             case Viewer_1.Alignment.BottomRight:
49062             default:
49063                 break;
49064         }
49065         var pixelRatioInverse = 1 / definition.pixelRatio;
49066         clipTop *= pixelRatioInverse;
49067         clipRigth *= pixelRatioInverse;
49068         clipBottom *= pixelRatioInverse;
49069         clipLeft *= pixelRatioInverse;
49070         left *= pixelRatioInverse;
49071         top *= pixelRatioInverse;
49072         height *= pixelRatioInverse;
49073         width *= pixelRatioInverse;
49074         var properties = {
49075             src: this._image.src,
49076             style: {
49077                 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
49078                 height: height + "px",
49079                 left: left + "px",
49080                 position: "absolute",
49081                 top: top + "px",
49082                 width: width + "px",
49083             },
49084         };
49085         return vd.h("img", properties, []);
49086     };
49087     return SpriteAtlas;
49088 }());
49089 var SpriteService = /** @class */ (function () {
49090     function SpriteService(sprite) {
49091         var _this = this;
49092         this._retina = window.devicePixelRatio > 1;
49093         this._spriteAtlasOperation$ = new rxjs_1.Subject();
49094         this._spriteAtlas$ = this._spriteAtlasOperation$.pipe(operators_1.startWith(function (atlas) {
49095             return atlas;
49096         }), operators_1.scan(function (atlas, operation) {
49097             return operation(atlas);
49098         }, new SpriteAtlas()), operators_1.publishReplay(1), operators_1.refCount());
49099         this._spriteAtlas$.subscribe(function () { });
49100         if (sprite == null) {
49101             return;
49102         }
49103         var format = this._retina ? "@2x" : "";
49104         var imageXmlHTTP = new XMLHttpRequest();
49105         imageXmlHTTP.open("GET", sprite + format + ".png", true);
49106         imageXmlHTTP.responseType = "arraybuffer";
49107         imageXmlHTTP.onload = function () {
49108             var image = new Image();
49109             image.onload = function () {
49110                 _this._spriteAtlasOperation$.next(function (atlas) {
49111                     atlas.image = image;
49112                     return atlas;
49113                 });
49114             };
49115             var blob = new Blob([imageXmlHTTP.response]);
49116             image.src = window.URL.createObjectURL(blob);
49117         };
49118         imageXmlHTTP.onerror = function (error) {
49119             console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
49120         };
49121         imageXmlHTTP.send();
49122         var jsonXmlHTTP = new XMLHttpRequest();
49123         jsonXmlHTTP.open("GET", sprite + format + ".json", true);
49124         jsonXmlHTTP.responseType = "text";
49125         jsonXmlHTTP.onload = function () {
49126             var json = JSON.parse(jsonXmlHTTP.response);
49127             _this._spriteAtlasOperation$.next(function (atlas) {
49128                 atlas.json = json;
49129                 return atlas;
49130             });
49131         };
49132         jsonXmlHTTP.onerror = function (error) {
49133             console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
49134         };
49135         jsonXmlHTTP.send();
49136     }
49137     Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
49138         get: function () {
49139             return this._spriteAtlas$;
49140         },
49141         enumerable: true,
49142         configurable: true
49143     });
49144     return SpriteService;
49145 }());
49146 exports.SpriteService = SpriteService;
49147 exports.default = SpriteService;
49148
49149
49150 },{"../Viewer":286,"rxjs":27,"rxjs/operators":225,"three":226,"virtual-dom":231}],446:[function(require,module,exports){
49151 "use strict";
49152 Object.defineProperty(exports, "__esModule", { value: true });
49153 var rxjs_1 = require("rxjs");
49154 var operators_1 = require("rxjs/operators");
49155 var TouchService = /** @class */ (function () {
49156     function TouchService(canvasContainer, domContainer) {
49157         var _this = this;
49158         this._activeSubject$ = new rxjs_1.BehaviorSubject(false);
49159         this._active$ = this._activeSubject$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
49160         rxjs_1.fromEvent(domContainer, "touchmove")
49161             .subscribe(function (event) {
49162             event.preventDefault();
49163         });
49164         this._touchStart$ = rxjs_1.fromEvent(canvasContainer, "touchstart");
49165         this._touchMove$ = rxjs_1.fromEvent(canvasContainer, "touchmove");
49166         this._touchEnd$ = rxjs_1.fromEvent(canvasContainer, "touchend");
49167         this._touchCancel$ = rxjs_1.fromEvent(canvasContainer, "touchcancel");
49168         var tapStart$ = this._touchStart$.pipe(operators_1.filter(function (te) {
49169             return te.touches.length === 1 && te.targetTouches.length === 1;
49170         }), operators_1.share());
49171         this._doubleTap$ = tapStart$.pipe(operators_1.bufferWhen(function () {
49172             return tapStart$.pipe(operators_1.first(), operators_1.switchMap(function (event) {
49173                 return rxjs_1.merge(rxjs_1.timer(300), tapStart$).pipe(operators_1.take(1));
49174             }));
49175         }), operators_1.filter(function (events) {
49176             return events.length === 2;
49177         }), operators_1.map(function (events) {
49178             return events[events.length - 1];
49179         }), operators_1.share());
49180         this._doubleTap$
49181             .subscribe(function (event) {
49182             event.preventDefault();
49183         });
49184         this._singleTouchMove$ = this._touchMove$.pipe(operators_1.filter(function (te) {
49185             return te.touches.length === 1 && te.targetTouches.length === 1;
49186         }), operators_1.share());
49187         var singleTouchStart$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
49188             return te.touches.length === 1 && te.targetTouches.length === 1;
49189         }));
49190         var multipleTouchStart$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
49191             return te.touches.length >= 1;
49192         }));
49193         var touchStop$ = rxjs_1.merge(this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
49194             return te.touches.length === 0;
49195         }));
49196         this._singleTouchDragStart$ = singleTouchStart$.pipe(operators_1.mergeMap(function (e) {
49197             return _this._singleTouchMove$.pipe(operators_1.takeUntil(rxjs_1.merge(touchStop$, multipleTouchStart$)), operators_1.take(1));
49198         }));
49199         this._singleTouchDragEnd$ = singleTouchStart$.pipe(operators_1.mergeMap(function (e) {
49200             return rxjs_1.merge(touchStop$, multipleTouchStart$).pipe(operators_1.first());
49201         }));
49202         this._singleTouchDrag$ = singleTouchStart$.pipe(operators_1.switchMap(function (te) {
49203             return _this._singleTouchMove$.pipe(operators_1.skip(1), operators_1.takeUntil(rxjs_1.merge(multipleTouchStart$, touchStop$)));
49204         }));
49205         var touchesChanged$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
49206         this._pinchStart$ = touchesChanged$.pipe(operators_1.filter(function (te) {
49207             return te.touches.length === 2 && te.targetTouches.length === 2;
49208         }));
49209         this._pinchEnd$ = touchesChanged$.pipe(operators_1.filter(function (te) {
49210             return te.touches.length !== 2 || te.targetTouches.length !== 2;
49211         }));
49212         this._pinchOperation$ = new rxjs_1.Subject();
49213         this._pinch$ = this._pinchOperation$.pipe(operators_1.scan(function (pinch, operation) {
49214             return operation(pinch);
49215         }, {
49216             changeX: 0,
49217             changeY: 0,
49218             clientX: 0,
49219             clientY: 0,
49220             distance: 0,
49221             distanceChange: 0,
49222             distanceX: 0,
49223             distanceY: 0,
49224             originalEvent: null,
49225             pageX: 0,
49226             pageY: 0,
49227             screenX: 0,
49228             screenY: 0,
49229             touch1: null,
49230             touch2: null,
49231         }));
49232         this._touchMove$.pipe(operators_1.filter(function (te) {
49233             return te.touches.length === 2 && te.targetTouches.length === 2;
49234         }), operators_1.map(function (te) {
49235             return function (previous) {
49236                 var touch1 = te.touches[0];
49237                 var touch2 = te.touches[1];
49238                 var minX = Math.min(touch1.clientX, touch2.clientX);
49239                 var maxX = Math.max(touch1.clientX, touch2.clientX);
49240                 var minY = Math.min(touch1.clientY, touch2.clientY);
49241                 var maxY = Math.max(touch1.clientY, touch2.clientY);
49242                 var centerClientX = minX + (maxX - minX) / 2;
49243                 var centerClientY = minY + (maxY - minY) / 2;
49244                 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
49245                 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
49246                 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
49247                 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
49248                 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
49249                 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
49250                 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
49251                 var distanceChange = distance - previous.distance;
49252                 var changeX = distanceX - previous.distanceX;
49253                 var changeY = distanceY - previous.distanceY;
49254                 var current = {
49255                     changeX: changeX,
49256                     changeY: changeY,
49257                     clientX: centerClientX,
49258                     clientY: centerClientY,
49259                     distance: distance,
49260                     distanceChange: distanceChange,
49261                     distanceX: distanceX,
49262                     distanceY: distanceY,
49263                     originalEvent: te,
49264                     pageX: centerPageX,
49265                     pageY: centerPageY,
49266                     screenX: centerScreenX,
49267                     screenY: centerScreenY,
49268                     touch1: touch1,
49269                     touch2: touch2,
49270                 };
49271                 return current;
49272             };
49273         }))
49274             .subscribe(this._pinchOperation$);
49275         this._pinchChange$ = this._pinchStart$.pipe(operators_1.switchMap(function (te) {
49276             return _this._pinch$.pipe(operators_1.skip(1), operators_1.takeUntil(_this._pinchEnd$));
49277         }));
49278     }
49279     Object.defineProperty(TouchService.prototype, "active$", {
49280         get: function () {
49281             return this._active$;
49282         },
49283         enumerable: true,
49284         configurable: true
49285     });
49286     Object.defineProperty(TouchService.prototype, "activate$", {
49287         get: function () {
49288             return this._activeSubject$;
49289         },
49290         enumerable: true,
49291         configurable: true
49292     });
49293     Object.defineProperty(TouchService.prototype, "doubleTap$", {
49294         get: function () {
49295             return this._doubleTap$;
49296         },
49297         enumerable: true,
49298         configurable: true
49299     });
49300     Object.defineProperty(TouchService.prototype, "touchStart$", {
49301         get: function () {
49302             return this._touchStart$;
49303         },
49304         enumerable: true,
49305         configurable: true
49306     });
49307     Object.defineProperty(TouchService.prototype, "touchMove$", {
49308         get: function () {
49309             return this._touchMove$;
49310         },
49311         enumerable: true,
49312         configurable: true
49313     });
49314     Object.defineProperty(TouchService.prototype, "touchEnd$", {
49315         get: function () {
49316             return this._touchEnd$;
49317         },
49318         enumerable: true,
49319         configurable: true
49320     });
49321     Object.defineProperty(TouchService.prototype, "touchCancel$", {
49322         get: function () {
49323             return this._touchCancel$;
49324         },
49325         enumerable: true,
49326         configurable: true
49327     });
49328     Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
49329         get: function () {
49330             return this._singleTouchDragStart$;
49331         },
49332         enumerable: true,
49333         configurable: true
49334     });
49335     Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
49336         get: function () {
49337             return this._singleTouchDrag$;
49338         },
49339         enumerable: true,
49340         configurable: true
49341     });
49342     Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
49343         get: function () {
49344             return this._singleTouchDragEnd$;
49345         },
49346         enumerable: true,
49347         configurable: true
49348     });
49349     Object.defineProperty(TouchService.prototype, "pinch$", {
49350         get: function () {
49351             return this._pinchChange$;
49352         },
49353         enumerable: true,
49354         configurable: true
49355     });
49356     Object.defineProperty(TouchService.prototype, "pinchStart$", {
49357         get: function () {
49358             return this._pinchStart$;
49359         },
49360         enumerable: true,
49361         configurable: true
49362     });
49363     Object.defineProperty(TouchService.prototype, "pinchEnd$", {
49364         get: function () {
49365             return this._pinchEnd$;
49366         },
49367         enumerable: true,
49368         configurable: true
49369     });
49370     return TouchService;
49371 }());
49372 exports.TouchService = TouchService;
49373
49374 },{"rxjs":27,"rxjs/operators":225}],447:[function(require,module,exports){
49375 "use strict";
49376 var __extends = (this && this.__extends) || (function () {
49377     var extendStatics = function (d, b) {
49378         extendStatics = Object.setPrototypeOf ||
49379             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
49380             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
49381         return extendStatics(d, b);
49382     }
49383     return function (d, b) {
49384         extendStatics(d, b);
49385         function __() { this.constructor = d; }
49386         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
49387     };
49388 })();
49389 Object.defineProperty(exports, "__esModule", { value: true });
49390 var rxjs_1 = require("rxjs");
49391 var operators_1 = require("rxjs/operators");
49392 var when = require("when");
49393 var Viewer_1 = require("../Viewer");
49394 var Utils_1 = require("../Utils");
49395 /**
49396  * @class Viewer
49397  *
49398  * @classdesc The Viewer object represents the navigable image viewer.
49399  * Create a Viewer by specifying a container, client ID, image key and
49400  * other options. The viewer exposes methods and events for programmatic
49401  * interaction.
49402  *
49403  * In the case of asynchronous methods, MapillaryJS returns promises to
49404  * the results. Notifications are always emitted through JavaScript events.
49405  *
49406  * The viewer works with a few different coordinate systems.
49407  *
49408  * Container pixel coordinates
49409  *
49410  * Pixel coordinates are coordinates on the viewer container. The origin is
49411  * in the top left corner of the container. The axes are
49412  * directed according to the following for a viewer container with a width
49413  * of 640 pixels and height of 480 pixels.
49414  *
49415  * ```
49416  * (0,0)                          (640, 0)
49417  *      +------------------------>
49418  *      |
49419  *      |
49420  *      |
49421  *      v                        +
49422  * (0, 480)                       (640, 480)
49423  * ```
49424  *
49425  * Basic image coordinates
49426  *
49427  * Basic image coordinates represents points in the original image adjusted for
49428  * orientation. They range from 0 to 1 on both axes. The origin is in the top left
49429  * corner of the image and the axes are directed
49430  * according to the following for all image types.
49431  *
49432  * ```
49433  * (0,0)                          (1, 0)
49434  *      +------------------------>
49435  *      |
49436  *      |
49437  *      |
49438  *      v                        +
49439  * (0, 1)                         (1, 1)
49440  * ```
49441  *
49442  * For every camera viewing direction it is possible to convert between these
49443  * two coordinate systems for the current node. The image can be panned and
49444  * zoomed independently of the size of the viewer container resulting in
49445  * different conversion results for different viewing directions.
49446  */
49447 var Viewer = /** @class */ (function (_super) {
49448     __extends(Viewer, _super);
49449     /**
49450      * Create a new viewer instance.
49451      *
49452      * @description It is possible to initialize the viewer with or
49453      * without a key.
49454      *
49455      * When you want to show a specific image in the viewer from
49456      * the start you should initialize it with a key.
49457      *
49458      * When you do not know the first image key at implementation
49459      * time, e.g. in a map-viewer application you should initialize
49460      * the viewer without a key and call `moveToKey` instead.
49461      *
49462      * When initializing with a key the viewer is bound to that key
49463      * until the node for that key has been successfully loaded.
49464      * Also, a cover with the image of the key will be shown.
49465      * If the data for that key can not be loaded because the key is
49466      * faulty or other errors occur it is not possible to navigate
49467      * to another key because the viewer is not navigable. The viewer
49468      * becomes navigable when the data for the key has been loaded and
49469      * the image is shown in the viewer. This way of initializing
49470      * the viewer is mostly for embedding in blog posts and similar
49471      * where one wants to show a specific image initially.
49472      *
49473      * If the viewer is initialized without a key (with null or
49474      * undefined) it is not bound to any particular key and it is
49475      * possible to move to any key with `viewer.moveToKey("<my-image-key>")`.
49476      * If the first move to a key fails it is possible to move to another
49477      * key. The viewer will show a black background until a move
49478      * succeeds. This way of intitializing is suited for a map-viewer
49479      * application when the initial key is not known at implementation
49480      * time.
49481      *
49482      * @param {string} id - Required `id` of a DOM element which will
49483      * be transformed into the viewer.
49484      * @param {string} clientId - Required `Mapillary API ClientID`. Can
49485      * be obtained from https://www.mapillary.com/app/settings/developers.
49486      * @param {string} key - Optional `image-key` to start from. The key
49487      * can be any Mapillary image. If a key is provided the viewer is
49488      * bound to that key until it has been fully loaded. If null is provided
49489      * no image is loaded at viewer initialization and the viewer is not
49490      * bound to any particular key. Any image can then be navigated to
49491      * with e.g. `viewer.moveToKey("<my-image-key>")`.
49492      * @param {IViewerOptions} options - Optional configuration object
49493      * specifing Viewer's and the components' initial setup.
49494      * @param {string} token - Optional bearer token for API requests of
49495      * protected resources.
49496      *
49497      * @example
49498      * ```
49499      * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<image-key>");
49500      * ```
49501      */
49502     function Viewer(id, clientId, key, options, token) {
49503         var _this = _super.call(this) || this;
49504         options = options != null ? options : {};
49505         Utils_1.Settings.setOptions(options);
49506         Utils_1.Urls.setOptions(options.url);
49507         _this._navigator = new Viewer_1.Navigator(clientId, options, token);
49508         _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
49509         _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
49510         _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
49511         return _this;
49512     }
49513     Object.defineProperty(Viewer.prototype, "isNavigable", {
49514         /**
49515          * Return a boolean indicating if the viewer is in a navigable state.
49516          *
49517          * @description The navigable state indicates if the viewer supports
49518          * moving, i.e. calling the {@link moveToKey}, {@link moveDir}
49519          * and {@link moveCloseTo} methods or changing the authentication state,
49520          * i.e. calling {@link setAuthToken}. The viewer will not be in a navigable
49521          * state if the cover is activated and the viewer has been supplied a key.
49522          * When the cover is deactivated or the viewer is activated without being
49523          * supplied a key it will be navigable.
49524          *
49525          * @returns {boolean} Boolean indicating whether the viewer is navigable.
49526          */
49527         get: function () {
49528             return this._componentController.navigable;
49529         },
49530         enumerable: true,
49531         configurable: true
49532     });
49533     /**
49534      * Activate the combined panning functionality.
49535      *
49536      * @description The combined panning functionality is active by default.
49537      */
49538     Viewer.prototype.activateCombinedPanning = function () {
49539         this._navigator.panService.enable();
49540     };
49541     /**
49542      * Activate a component.
49543      *
49544      * @param {string} name - Name of the component which will become active.
49545      *
49546      * @example
49547      * ```
49548      * viewer.activateComponent("marker");
49549      * ```
49550      */
49551     Viewer.prototype.activateComponent = function (name) {
49552         this._componentController.activate(name);
49553     };
49554     /**
49555      * Activate the cover (deactivates all other components).
49556      */
49557     Viewer.prototype.activateCover = function () {
49558         this._componentController.activateCover();
49559     };
49560     /**
49561      * Deactivate the combined panning functionality.
49562      *
49563      * @description Deactivating the combined panning functionality
49564      * could be needed in scenarios involving sequence only navigation.
49565      */
49566     Viewer.prototype.deactivateCombinedPanning = function () {
49567         this._navigator.panService.disable();
49568     };
49569     /**
49570      * Deactivate a component.
49571      *
49572      * @param {string} name - Name of component which become inactive.
49573      *
49574      * @example
49575      * ```
49576      * viewer.deactivateComponent("mouse");
49577      * ```
49578      */
49579     Viewer.prototype.deactivateComponent = function (name) {
49580         this._componentController.deactivate(name);
49581     };
49582     /**
49583      * Deactivate the cover (activates all components marked as active).
49584      */
49585     Viewer.prototype.deactivateCover = function () {
49586         this._componentController.deactivateCover();
49587     };
49588     /**
49589      * Get the bearing of the current viewer camera.
49590      *
49591      * @description The bearing depends on how the camera
49592      * is currently rotated and does not correspond
49593      * to the compass angle of the current node if the view
49594      * has been panned.
49595      *
49596      * Bearing is measured in degrees clockwise with respect to
49597      * north.
49598      *
49599      * @returns {Promise<number>} Promise to the bearing
49600      * of the current viewer camera.
49601      *
49602      * @example
49603      * ```
49604      * viewer.getBearing().then((b) => { console.log(b); });
49605      * ```
49606      */
49607     Viewer.prototype.getBearing = function () {
49608         var _this = this;
49609         return when.promise(function (resolve, reject) {
49610             _this._container.renderService.bearing$.pipe(operators_1.first())
49611                 .subscribe(function (bearing) {
49612                 resolve(bearing);
49613             }, function (error) {
49614                 reject(error);
49615             });
49616         });
49617     };
49618     /**
49619      * Get the basic coordinates of the current image that is
49620      * at the center of the viewport.
49621      *
49622      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
49623      * and have the origin point, (0, 0), at the top left corner and the
49624      * maximum value, (1, 1), at the bottom right corner of the original
49625      * image.
49626      *
49627      * @returns {Promise<number[]>} Promise to the basic coordinates
49628      * of the current image at the center for the viewport.
49629      *
49630      * @example
49631      * ```
49632      * viewer.getCenter().then((c) => { console.log(c); });
49633      * ```
49634      */
49635     Viewer.prototype.getCenter = function () {
49636         var _this = this;
49637         return when.promise(function (resolve, reject) {
49638             _this._navigator.stateService.getCenter()
49639                 .subscribe(function (center) {
49640                 resolve(center);
49641             }, function (error) {
49642                 reject(error);
49643             });
49644         });
49645     };
49646     /**
49647      * Get a component.
49648      *
49649      * @param {string} name - Name of component.
49650      * @returns {Component} The requested component.
49651      *
49652      * @example
49653      * ```
49654      * var mouseComponent = viewer.getComponent("mouse");
49655      * ```
49656      */
49657     Viewer.prototype.getComponent = function (name) {
49658         return this._componentController.get(name);
49659     };
49660     /**
49661      * Returns the viewer's containing HTML element.
49662      *
49663      * @returns {HTMLElement} The viewer's container.
49664      */
49665     Viewer.prototype.getContainer = function () {
49666         return this._container.element;
49667     };
49668     /**
49669      * Get the image's current zoom level.
49670      *
49671      * @returns {Promise<number>} Promise to the viewers's current
49672      * zoom level.
49673      *
49674      * @example
49675      * ```
49676      * viewer.getZoom().then((z) => { console.log(z); });
49677      * ```
49678      */
49679     Viewer.prototype.getZoom = function () {
49680         var _this = this;
49681         return when.promise(function (resolve, reject) {
49682             _this._navigator.stateService.getZoom()
49683                 .subscribe(function (zoom) {
49684                 resolve(zoom);
49685             }, function (error) {
49686                 reject(error);
49687             });
49688         });
49689     };
49690     /**
49691      * Move close to given latitude and longitude.
49692      *
49693      * @description Because the method propagates IO errors, these potential errors
49694      * need to be handled by the method caller (see example).
49695      *
49696      * @param {Number} lat - Latitude, in degrees.
49697      * @param {Number} lon - Longitude, in degrees.
49698      * @returns {Promise<Node>} Promise to the node that was navigated to.
49699      * @throws {Error} If no nodes exist close to provided latitude
49700      * longitude.
49701      * @throws {Error} Propagates any IO errors to the caller.
49702      * @throws {Error} When viewer is not navigable.
49703      * @throws  {@link AbortMapillaryError} When a subsequent move request is made
49704      * before the move close to call has completed.
49705      *
49706      * @example
49707      * ```
49708      * viewer.moveCloseTo(0, 0).then(
49709      *     (n) => { console.log(n); },
49710      *     (e) => { console.error(e); });
49711      * ```
49712      */
49713     Viewer.prototype.moveCloseTo = function (lat, lon) {
49714         var moveCloseTo$ = this.isNavigable ?
49715             this._navigator.moveCloseTo$(lat, lon) :
49716             rxjs_1.throwError(new Error("Calling moveCloseTo is not supported when viewer is not navigable."));
49717         return when.promise(function (resolve, reject) {
49718             moveCloseTo$.subscribe(function (node) {
49719                 resolve(node);
49720             }, function (error) {
49721                 reject(error);
49722             });
49723         });
49724     };
49725     /**
49726      * Navigate in a given direction.
49727      *
49728      * @description This method has to be called through EdgeDirection enumeration as in the example.
49729      *
49730      * @param {EdgeDirection} dir - Direction in which which to move.
49731      * @returns {Promise<Node>} Promise to the node that was navigated to.
49732      * @throws {Error} If the current node does not have the edge direction
49733      * or the edges has not yet been cached.
49734      * @throws {Error} Propagates any IO errors to the caller.
49735      * @throws {Error} When viewer is not navigable.
49736      * @throws  {@link AbortMapillaryError} When a subsequent move request is made
49737      * before the move dir call has completed.
49738      *
49739      * @example
49740      * ```
49741      * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
49742      *     (n) => { console.log(n); },
49743      *     (e) => { console.error(e); });
49744      * ```
49745      */
49746     Viewer.prototype.moveDir = function (dir) {
49747         var moveDir$ = this.isNavigable ?
49748             this._navigator.moveDir$(dir) :
49749             rxjs_1.throwError(new Error("Calling moveDir is not supported when viewer is not navigable."));
49750         return when.promise(function (resolve, reject) {
49751             moveDir$.subscribe(function (node) {
49752                 resolve(node);
49753             }, function (error) {
49754                 reject(error);
49755             });
49756         });
49757     };
49758     /**
49759      * Navigate to a given image key.
49760      *
49761      * @param {string} key - A valid Mapillary image key.
49762      * @returns {Promise<Node>} Promise to the node that was navigated to.
49763      * @throws {Error} Propagates any IO errors to the caller.
49764      * @throws {Error} When viewer is not navigable.
49765      * @throws  {@link AbortMapillaryError} When a subsequent move request is made
49766      * before the move to key call has completed.
49767      *
49768      * @example
49769      * ```
49770      * viewer.moveToKey("<my key>").then(
49771      *     (n) => { console.log(n); },
49772      *     (e) => { console.error(e); });
49773      * ```
49774      */
49775     Viewer.prototype.moveToKey = function (key) {
49776         var moveToKey$ = this.isNavigable ?
49777             this._navigator.moveToKey$(key) :
49778             rxjs_1.throwError(new Error("Calling moveToKey is not supported when viewer is not navigable."));
49779         return when.promise(function (resolve, reject) {
49780             moveToKey$.subscribe(function (node) {
49781                 resolve(node);
49782             }, function (error) {
49783                 reject(error);
49784             });
49785         });
49786     };
49787     /**
49788      * Project basic image coordinates for the current node to canvas pixel
49789      * coordinates.
49790      *
49791      * @description The basic image coordinates may not always correspond to a
49792      * pixel point that lies in the visible area of the viewer container.
49793      *
49794      * @param {Array<number>} basicPoint - Basic images coordinates to project.
49795      * @returns {Promise<Array<number>>} Promise to the pixel coordinates corresponding
49796      * to the basic image point.
49797      *
49798      * @example
49799      * ```
49800      * viewer.projectFromBasic([0.3, 0.7])
49801      *     .then((pixelPoint) => { console.log(pixelPoint); });
49802      * ```
49803      */
49804     Viewer.prototype.projectFromBasic = function (basicPoint) {
49805         var _this = this;
49806         return when.promise(function (resolve, reject) {
49807             _this._observer.projectBasic$(basicPoint)
49808                 .subscribe(function (pixelPoint) {
49809                 resolve(pixelPoint);
49810             }, function (error) {
49811                 reject(error);
49812             });
49813         });
49814     };
49815     /**
49816      * Detect the viewer's new width and height and resize it.
49817      *
49818      * @description The components will also detect the viewer's
49819      * new size and resize their rendered elements if needed.
49820      *
49821      * @example
49822      * ```
49823      * viewer.resize();
49824      * ```
49825      */
49826     Viewer.prototype.resize = function () {
49827         this._container.renderService.resize$.next(null);
49828     };
49829     /**
49830      * Set a bearer token for authenticated API requests of
49831      * protected resources.
49832      *
49833      * @description When the supplied token is null or undefined,
49834      * any previously set bearer token will be cleared and the
49835      * viewer will make unauthenticated requests.
49836      *
49837      * Calling setAuthToken aborts all outstanding move requests.
49838      * The promises of those move requests will be rejected with a
49839      * {@link AbortMapillaryError} the rejections need to be caught.
49840      *
49841      * Calling setAuthToken also resets the complete viewer cache
49842      * so it should not be called repeatedly.
49843      *
49844      * @param {string} [token] token - Bearer token.
49845      * @returns {Promise<void>} Promise that resolves after token
49846      * is set.
49847      *
49848      * @throws {Error} When viewer is not navigable.
49849      *
49850      * @example
49851      * ```
49852      * viewer.setAuthToken("<my token>")
49853      *     .then(() => { console.log("token set"); });
49854      * ```
49855      */
49856     Viewer.prototype.setAuthToken = function (token) {
49857         var setToken$ = this.isNavigable ?
49858             this._navigator.setToken$(token) :
49859             rxjs_1.throwError(new Error("Calling setAuthToken is not supported when viewer is not navigable."));
49860         return when.promise(function (resolve, reject) {
49861             setToken$
49862                 .subscribe(function () {
49863                 resolve(undefined);
49864             }, function (error) {
49865                 reject(error);
49866             });
49867         });
49868     };
49869     /**
49870      * Set the basic coordinates of the current image to be in the
49871      * center of the viewport.
49872      *
49873      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
49874      * and has the origin point, (0, 0), at the top left corner and the
49875      * maximum value, (1, 1), at the bottom right corner of the original
49876      * image.
49877      *
49878      * @param {number[]} The basic coordinates of the current
49879      * image to be at the center for the viewport.
49880      *
49881      * @example
49882      * ```
49883      * viewer.setCenter([0.5, 0.5]);
49884      * ```
49885      */
49886     Viewer.prototype.setCenter = function (center) {
49887         this._navigator.stateService.setCenter(center);
49888     };
49889     /**
49890      * Set the filter selecting nodes to use when calculating
49891      * the spatial edges.
49892      *
49893      * @description The following filter types are supported:
49894      *
49895      * Comparison
49896      *
49897      * `["==", key, value]` equality: `node[key] = value`
49898      *
49899      * `["!=", key, value]` inequality: `node[key] â‰  value`
49900      *
49901      * `["<", key, value]` less than: `node[key] < value`
49902      *
49903      * `["<=", key, value]` less than or equal: `node[key] â‰¤ value`
49904      *
49905      * `[">", key, value]` greater than: `node[key] > value`
49906      *
49907      * `[">=", key, value]` greater than or equal: `node[key] â‰¥ value`
49908      *
49909      * Set membership
49910      *
49911      * `["in", key, v0, ..., vn]` set inclusion: `node[key] âˆˆ {v0, ..., vn}`
49912      *
49913      * `["!in", key, v0, ..., vn]` set exclusion: `node[key] âˆ‰ {v0, ..., vn}`
49914      *
49915      * Combining
49916      *
49917      * `["all", f0, ..., fn]` logical `AND`: `f0 âˆ§ ... âˆ§ fn`
49918      *
49919      * A key must be a string that identifies a property name of a
49920      * simple {@link Node} property. A value must be a string, number, or
49921      * boolean. Strictly-typed comparisons are used. The values
49922      * `f0, ..., fn` of the combining filter must be filter expressions.
49923      *
49924      * Clear the filter by setting it to null or empty array.
49925      *
49926      * Commonly used filter properties (see the {@link Node} class
49927      * documentation for a full list of properties that can be used
49928      * in a filter) and common use cases:
49929      *
49930      * ```
49931      * fullPano        // Show only full 360 panoramas or not
49932      * organizationKey // Show images from one or several organizations
49933      * sequenceKey     // Show images from one or several sequences
49934      * userKey         // Show images from one or several users
49935      * capturedAt      // Show images from a certain time interval
49936      * ```
49937      *
49938      * @param {FilterExpression} filter - The filter expression.
49939      * @returns {Promise<void>} Promise that resolves after filter is applied.
49940      *
49941      * @example
49942      * ```
49943      * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
49944      *
49945      * // Other examples
49946      * // viewer.setFilter(["==", "organizationKey", "<my organization key>"]);
49947      * // viewer.setFilter(["in", "userKey", "<my user key #1>", "<my user key #2>"]);
49948      * // viewer.setFilter(["==", "fullPano", true]);
49949      * // viewer.setFilter([">=", "capturedAt", <my time stamp>]);
49950      * ```
49951      */
49952     Viewer.prototype.setFilter = function (filter) {
49953         var _this = this;
49954         return when.promise(function (resolve, reject) {
49955             _this._navigator.setFilter$(filter)
49956                 .subscribe(function () {
49957                 resolve(undefined);
49958             }, function (error) {
49959                 reject(error);
49960             });
49961         });
49962     };
49963     /**
49964      * Set the viewer's render mode.
49965      *
49966      * @param {RenderMode} renderMode - Render mode.
49967      *
49968      * @example
49969      * ```
49970      * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
49971      * ```
49972      */
49973     Viewer.prototype.setRenderMode = function (renderMode) {
49974         this._container.renderService.renderMode$.next(renderMode);
49975     };
49976     /**
49977      * Set the viewer's transition mode.
49978      *
49979      * @param {TransitionMode} transitionMode - Transition mode.
49980      *
49981      * @example
49982      * ```
49983      * viewer.setTransitionMode(Mapillary.TransitionMode.Instantaneous);
49984      * ```
49985      */
49986     Viewer.prototype.setTransitionMode = function (transitionMode) {
49987         this._navigator.stateService.setTransitionMode(transitionMode);
49988     };
49989     /**
49990      * Set the image's current zoom level.
49991      *
49992      * @description Possible zoom level values are on the [0, 3] interval.
49993      * Zero means zooming out to fit the image to the view whereas three
49994      * shows the highest level of detail.
49995      *
49996      * @param {number} The image's current zoom level.
49997      *
49998      * @example
49999      * ```
50000      * viewer.setZoom(2);
50001      * ```
50002      */
50003     Viewer.prototype.setZoom = function (zoom) {
50004         this._navigator.stateService.setZoom(zoom);
50005     };
50006     /**
50007      * Unproject canvas pixel coordinates to an ILatLon representing geographical
50008      * coordinates.
50009      *
50010      * @description The pixel point may not always correspond to geographical
50011      * coordinates. In the case of no correspondence the returned value will
50012      * be `null`.
50013      *
50014      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
50015      * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
50016      *
50017      * @example
50018      * ```
50019      * viewer.unproject([100, 100])
50020      *     .then((latLon) => { console.log(latLon); });
50021      * ```
50022      */
50023     Viewer.prototype.unproject = function (pixelPoint) {
50024         var _this = this;
50025         return when.promise(function (resolve, reject) {
50026             _this._observer.unproject$(pixelPoint)
50027                 .subscribe(function (latLon) {
50028                 resolve(latLon);
50029             }, function (error) {
50030                 reject(error);
50031             });
50032         });
50033     };
50034     /**
50035      * Unproject canvas pixel coordinates to basic image coordinates for the
50036      * current node.
50037      *
50038      * @description The pixel point may not always correspond to basic image
50039      * coordinates. In the case of no correspondence the returned value will
50040      * be `null`.
50041      *
50042      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
50043      * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
50044      * to the pixel point.
50045      *
50046      * @example
50047      * ```
50048      * viewer.unprojectToBasic([100, 100])
50049      *     .then((basicPoint) => { console.log(basicPoint); });
50050      * ```
50051      */
50052     Viewer.prototype.unprojectToBasic = function (pixelPoint) {
50053         var _this = this;
50054         return when.promise(function (resolve, reject) {
50055             _this._observer.unprojectBasic$(pixelPoint)
50056                 .subscribe(function (basicPoint) {
50057                 resolve(basicPoint);
50058             }, function (error) {
50059                 reject(error);
50060             });
50061         });
50062     };
50063     /**
50064      * Fired when the viewing direction of the camera changes.
50065      *
50066      * @description Related to the computed compass angle
50067      * ({@link Node.computedCA}) from SfM, not the original EXIF compass
50068      * angle.
50069      *
50070      * @event
50071      * @type {number} bearing - Value indicating the current bearing
50072      * measured in degrees clockwise with respect to north.
50073      */
50074     Viewer.bearingchanged = "bearingchanged";
50075     /**
50076      * Fired when a pointing device (usually a mouse) is pressed and released at
50077      * the same point in the viewer.
50078      * @event
50079      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
50080      */
50081     Viewer.click = "click";
50082     /**
50083      * Fired when the right button of the mouse is clicked within the viewer.
50084      * @event
50085      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
50086      */
50087     Viewer.contextmenu = "contextmenu";
50088     /**
50089      * Fired when a pointing device (usually a mouse) is clicked twice at
50090      * the same point in the viewer.
50091      * @event
50092      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
50093      */
50094     Viewer.dblclick = "dblclick";
50095     /**
50096      * Fired when the viewer is loading more data.
50097      * @event
50098      * @type {boolean} loading - Boolean indicating whether the viewer is loading.
50099      */
50100     Viewer.loadingchanged = "loadingchanged";
50101     /**
50102      * Fired when a pointing device (usually a mouse) is pressed within the viewer.
50103      * @event
50104      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
50105      */
50106     Viewer.mousedown = "mousedown";
50107     /**
50108      * Fired when a pointing device (usually a mouse) is moved within the viewer.
50109      * @description Will not fire when the mouse is actively used, e.g. for drag pan.
50110      * @event
50111      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
50112      */
50113     Viewer.mousemove = "mousemove";
50114     /**
50115      * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
50116      * @event
50117      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
50118      */
50119     Viewer.mouseout = "mouseout";
50120     /**
50121      * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
50122      * @event
50123      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
50124      */
50125     Viewer.mouseover = "mouseover";
50126     /**
50127      * Fired when a pointing device (usually a mouse) is released within the viewer.
50128      * @event
50129      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
50130      */
50131     Viewer.mouseup = "mouseup";
50132     /**
50133      * Fired when the viewer motion stops and it is in a fixed
50134      * position with a fixed point of view.
50135      * @event
50136      */
50137     Viewer.moveend = "moveend";
50138     /**
50139      * Fired when the motion from one view to another start,
50140      * either by changing the position (e.g. when changing node) or
50141      * when changing point of view (e.g. by interaction such as pan and zoom).
50142      * @event
50143      */
50144     Viewer.movestart = "movestart";
50145     /**
50146      * Fired when the navigable state of the viewer changes.
50147      *
50148      * @description The navigable state indicates if the viewer supports
50149      * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
50150      * methods. The viewer will not be in a navigable state if the cover
50151      * is activated and the viewer has been supplied a key. When the cover
50152      * is deactivated or activated without being supplied a key it will
50153      * be navigable.
50154      *
50155      * @event
50156      * @type {boolean} navigable - Boolean indicating whether the viewer is navigable.
50157      */
50158     Viewer.navigablechanged = "navigablechanged";
50159     /**
50160      * Fired every time the viewer navigates to a new node.
50161      * @event
50162      * @type  {@link Node} node - Current node.
50163      */
50164     Viewer.nodechanged = "nodechanged";
50165     /**
50166      * Fired every time the sequence edges of the current node changes.
50167      * @event
50168      * @type  {@link IEdgeStatus} status - The edge status object.
50169      */
50170     Viewer.sequenceedgeschanged = "sequenceedgeschanged";
50171     /**
50172      * Fired every time the spatial edges of the current node changes.
50173      * @event
50174      * @type  {@link IEdgeStatus} status - The edge status object.
50175      */
50176     Viewer.spatialedgeschanged = "spatialedgeschanged";
50177     return Viewer;
50178 }(Utils_1.EventEmitter));
50179 exports.Viewer = Viewer;
50180
50181 },{"../Utils":285,"../Viewer":286,"rxjs":27,"rxjs/operators":225,"when":272}]},{},[280])(280)
50182 });
50183 //# sourceMappingURL=mapillary.js.map