diff --git a/.gitignore b/.gitignore index d288dfc..66e6069 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules/* bower_components/* +CLAUDE.md diff --git a/build/encom-globe.js b/build/encom-globe.js index fb3c726..ce2af6a 100644 --- a/build/encom-globe.js +++ b/build/encom-globe.js @@ -1,43520 +1,47724 @@ -(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0){ - nf = new Face(prev[j-1], prev[j], bottom[j]); - newFaces.push(nf); - } - } - } - } - - faces = newFaces; - - var newPoints = {}; - for(var p in points){ - var np = points[p].project(radius); - newPoints[np] = np; - } - - points = newPoints; - - this.tiles = []; - - for(var p in points){ - this.tiles.push(new Tile(points[p], hexSize)); - } - -}; - -module.exports = Hexasphere; - -},{"./face":2,"./point":4,"./tile":5}],4:[function(require,module,exports){ -var Point = function(x,y,z){ - if(x !== undefined && y !== undefined && z !== undefined){ - this.x = x; - this.y = y; - this.z = z; - - } - - this.faces = []; -} - -Point.prototype.subdivide = function(point, count, checkPoint){ - - var segments = []; - segments.push(this); - - for(var i = 1; i< count; i++){ - var np = new Point(this.x * (1-(i/count)) + point.x * (i/count), - this.y * (1-(i/count)) + point.y * (i/count), - this.z * (1-(i/count)) + point.z * (i/count)); - np = checkPoint(np); - segments.push(np); - } - - segments.push(point); - - return segments; - -} - -Point.prototype.segment = function(point, percent){ - var newPoint = new Point(); - percent = Math.max(0.01, Math.min(1, percent)); - - newPoint.x = point.x * (1-percent) + this.x * percent; - newPoint.y = point.y * (1-percent) + this.y * percent; - newPoint.z = point.z * (1-percent) + this.z * percent; - return newPoint; - -}; - -Point.prototype.midpoint = function(point, location){ - return this.segment(point, .5); -} - - -Point.prototype.project = function(radius, percent){ - if(percent == undefined){ - percent = 1.0; - } - - percent = Math.max(0, Math.min(1, percent)); - var yx = this.y / this.x; - var zx = this.z / this.x; - var yz = this.z / this.y; - - var mag = Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2) + Math.pow(this.z, 2)); - var ratio = radius/ mag; - - this.x = this.x * ratio * percent; - this.y = this.y * ratio * percent; - this.z = this.z * ratio * percent; - return this; - -}; - -Point.prototype.registerFace = function(face){ - this.faces.push(face); -} - -Point.prototype.getOrderedFaces = function(){ - var workingArray = this.faces.slice(); - var ret = []; - - var i = 0; - while(i < this.faces.length){ - if(i == 0){ - ret.push(workingArray[i]); - workingArray.splice(i,1); - } else { - var hit = false; - var j = 0; - while(j < workingArray.length && !hit){ - if(workingArray[j].isAdjacentTo(ret[i-1])){ - hit = true; - ret.push(workingArray[j]); - workingArray.splice(j, 1); - } - j++; - } - } - i++; - } - - return ret; -} - -Point.prototype.findCommonFace = function(other, notThisFace){ - for(var i = 0; i< this.faces.length; i++){ - for(var j = 0; j< other.faces.length; j++){ - if(this.faces[i].id === other.faces[j].id && this.faces[i].id !== notThisFace.id){ - return this.faces[i]; - } - } - } - - return null; -} - - - -Point.prototype.toString = function(){ - return "" + Math.round(this.x*100)/100 + "," + Math.round(this.y*100)/100 + "," + Math.round(this.z*100)/100; - -} - -module.exports = Point; - -},{}],5:[function(require,module,exports){ -var Point = require('./point'); - -var Tile = function(centerPoint, hexSize){ - - if(hexSize == undefined){ - hexSize = 1; - } - - hexSize = Math.max(.01, Math.min(1.0, hexSize)); - - this.centerPoint = centerPoint; - this.faces = centerPoint.getOrderedFaces(); - this.boundary = []; - - this.triangles = []; - - - for(var f=0; f< this.faces.length; f++){ - this.boundary.push(this.faces[f].getCentroid().segment(this.centerPoint, hexSize)); - } - -}; - -Tile.prototype.getLatLon = function(radius, boundaryNum){ - var point = this.centerPoint; - if(typeof boundaryNum == "number" && boundaryNum < this.boundary.length){ - point = this.boundary[boundaryNum]; - } - var phi = Math.acos(point.y / radius); //lat - var theta = (Math.atan2(point.x, point.z) + Math.PI + Math.PI / 2) % (Math.PI * 2) - Math.PI; // lon - - // theta is a hack, since I want to rotate by Math.PI/2 to start. sorryyyyyyyyyyy - return { - lat: 180 * phi / Math.PI - 90, - lon: 180 * theta / Math.PI - }; -}; - - - -Tile.prototype.scaledBoundary = function(scale){ - - scale = Math.max(0, Math.min(1, scale)); - - var ret = []; - for(var i = 0; i < this.boundary.length; i++){ - ret.push(this.centerPoint.segment(this.boundary[i], 1 - scale)); - } - - return ret; -}; - -Tile.prototype.toString = function(){ - return this.centerPoint.toString(); -}; - -module.exports = Tile; - -},{"./point":4}],6:[function(require,module,exports){ -/* ---------------------------------------------------------------------------- - pusher.color.js - A color parsing and manipulation library - ---------------------------------------------------------------------------- - The MIT License (MIT). Copyright (c) 2013, Pusher Inc. -*/ -/* - Permission is hereby granted, free of charge, to any person obtaining a copy of - this software and associated documentation files (the "Software"), to deal in - the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do - so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - ---------------------------------------------------------------------------- -*/ -(function() { - - //-----------------------------------------------------------------------// - // Local Misc. Utility Functions - //-----------------------------------------------------------------------// - - function normalize360(v) - { - v = v % 360; - return (v < 0) ? 360 + v : v; - } - - function unsigned(i) - { - // the >>> operator will force unsigned - return i >>> 0; - } - - function trimLc(s) - { - return s.replace(/^\s+/,'').replace(/\s+$/,'').toLowerCase(); - } - - function slice(obj, index) - { - return Array.prototype.slice.call(obj, index); - } - - function append(arr, value) - { - arr.push(value); - return arr; - } - - function clamp(x,a,b) - { - return !(x > a) ? a : !(x < b) ? b : x; - } - - function mix(x,y,a) - { - return (1 - a) * x + a * y; - } - - // Float to byte - function f2b(f) - { - f = Math.round(255 * f); - if (!(f > 0)) return 0; - else if (!(f < 255)) return 255; - else return f & 0xFF; - }; - - // Byte to float - function b2f(b) - { - return b / 255.0; - }; - - //-----------------------------------------------------------------------// - // Color conversion functions - //-----------------------------------------------------------------------// - - /** - * Converts an RGB color value to HSL. Conversion formula - * adapted from http://en.wikipedia.org/wiki/HSL_color_space. - * - * @param Number r The red color value - * @param Number g The green color value - * @param Number b The blue color value - * @return Array The HSL representation - * - * @credit http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript - */ - function rgbToHsl(r, g, b) - { - var max = Math.max(r, g, b), - min = Math.min(r, g, b); - var h, s, l = (max + min) / 2; - - if(max == min) - { - h = s = 0; // achromatic - } - else - { - var d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - switch (max) - { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; - } - h /= 6; - } - - return [h, s, l]; - } - - /** - * Converts an HSL color value to RGB. Conversion formula - * adapted from http://en.wikipedia.org/wiki/HSL_color_space. - * - * @param Number h The hue - * @param Number s The saturation - * @param Number l The lightness - * @return Array The RGB representation - * @credit http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript - */ - function hslToRgb(h, s, l) - { - var r, g, b; - - if (s == 0) - { - r = g = b = l; // achromatic - } - else - { - function hue2rgb(p, q, t){ - if(t < 0) t += 1; - if(t > 1) t -= 1; - if(t < 1/6) return p + (q - p) * 6 * t; - if(t < 1/2) return q; - if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; - } - - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hue2rgb(p, q, h + 1/3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1/3); - } - - return [r, g, b]; - } - - function hex4ToRgba(color) - { - var rgba = [ - parseInt(color.substr(1,1), 16), - parseInt(color.substr(2,1), 16), - parseInt(color.substr(3,1), 16), - 1.0 - ]; - for (var i = 0; i < 3; ++i) - rgba[i] = (rgba[i] * 16 + rgba[i]) / 255.0; - return rgba; - }; - - function hex7ToRgba(color) - { - return [ - parseInt(color.substr(1,2), 16) / 255, - parseInt(color.substr(3,2), 16) / 255, - parseInt(color.substr(5,2), 16) / 255, - 1.0 - ]; - }; - - var namedColors = - { - "aliceblue": [240, 248, 255 ], - "antiquewhite": [250, 235, 215 ], - "aqua": [0, 255, 255 ], - "aquamarine": [127, 255, 212 ], - "azure": [240, 255, 255 ], - "beige": [245, 245, 220 ], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 216], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [216, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] - }; - - - /* - Credit: http://matthaynes.net/blog/2008/08/07/javascript-colour-functions/ - */ - function rgbaToHsva(rgba) - { - var r = rgba[0]; - var g = rgba[1]; - var b = rgba[2]; - - var min = Math.min(Math.min(r, g), b), - max = Math.max(Math.max(r, g), b), - delta = max - min; - - var value = max; - var saturation, hue; - - // Hue - if (max == min) { - hue = 0; - } else if (max == r) { - hue = (60 * ((g - b) / (max - min))) % 360; - } else if (max == g) { - hue = 60 * ((b - r) / (max - min)) + 120; - } else if (max == b) { - hue = 60 * ((r - g) / (max - min)) + 240; - } - - if (hue < 0) { - hue += 360; - } - - // Saturation - if (max == 0) { - saturation = 0; - } else { - saturation = 1 - (min / max); - } - return [ - Math.round(hue), - Math.round(saturation * 100), - Math.round(value * 100), - rgba[3] - ]; - }; - - /* - Credit: http://matthaynes.net/blog/2008/08/07/javascript-colour-functions/ - */ - function hsvaToRgba (hsva) - { - var h = normalize360(hsva[0]); - var s = hsva[1]; - var v = hsva[2]; - - var s = s / 100; - var v = v / 100; - - var hi = Math.floor((h / 60) % 6); - var f = (h / 60) - hi; - var p = v * (1 - s); - var q = v * (1 - f * s); - var t = v * (1 - (1 - f) * s); - - var rgb = []; - - switch (hi) { - case 0: rgb = [v, t, p]; break; - case 1: rgb = [q, v, p]; break; - case 2: rgb = [p, v, t]; break; - case 3: rgb = [p, q, v]; break; - case 4: rgb = [t, p, v]; break; - case 5: rgb = [v, p, q]; break; - } - - return [ - rgb[0], - rgb[1], - rgb[2], - hsva[3] - ]; - }; - - function rgbaToHsl(c) - { - var hsl = rgbToHsl(c[0], c[1], c[2]); - hsl[0] = normalize360( Math.floor(hsl[0] * 360) ); - hsl[1] = Math.floor(hsl[1] * 100); - hsl[2] = Math.floor(hsl[2] * 100); - return hsl; - } - - function rgbaToHsla(c) - { - var hsl = rgbaToHsl(c); - hsl.push(c[3]); - return hsl; - } - - function hslToRgba(c) - { - var h = parseFloat(c[0]) / 360; - var s = parseFloat(c[1]) / 100; - var l = parseFloat(c[2]) / 100; - var rgb = hslToRgb(h, s, l); - return [ - rgb[0], - rgb[1], - rgb[2], - 1 - ]; - } - - function hslaToRgba(c) - { - var h = parseFloat(c[0]) / 360; - var s = parseFloat(c[1]) / 100; - var l = parseFloat(c[2]) / 100; - var rgb = hslToRgb(h, s, l); - return [ - rgb[0], - rgb[1], - rgb[2], - parseFloat(c[3]) - ]; - } - - //-----------------------------------------------------------------------// - // String parsers - //-----------------------------------------------------------------------// - - var parse = - { - byteOrPercent : function (s) - { - var m; - if (typeof s == 'string' && (m = s.match(/^([0-9]+)%$/))) - return Math.floor( parseFloat(m[1]) * 255 / 100 ); - else - return parseFloat(s); +var _encomBundle = (function() { + function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; + } + var browserify$1 = {}; + var tween = {}; + var hasRequiredTween; + function requireTween() { + if (hasRequiredTween) return tween; + hasRequiredTween = 1; + Object.defineProperty(tween, "__esModule", { value: true }); + var Easing = Object.freeze({ + Linear: Object.freeze({ + None: function(amount) { + return amount; }, - - floatOrPercent : function (s) - { - var m; - if (typeof s == 'string' && (m = s.match(/^([0-9]+)%$/))) - return parseFloat(m[1]) / 100; - else - return parseFloat(s); + In: function(amount) { + return amount; }, - - numberOrPercent : function (s, scale) - { - var m; - if (typeof s == 'string' && (m = s.match(/^([0-9]+)%$/))) - return (parseFloat(m[1]) / 100) * scale; - else - return parseFloat(s); + Out: function(amount) { + return amount; }, - - rgba : function(v) - { - for (var i = 0; i < 3; ++i) - v[i] = b2f( parse.byteOrPercent(v[i]) ); - v[3] = parse.floatOrPercent(v[i]); - return new Color(v); + InOut: function(amount) { + return amount; + } + }), + Quadratic: Object.freeze({ + In: function(amount) { + return amount * amount; }, - - rgba8 : function(v) - { - return new Color([ - b2f( parse.byteOrPercent(v[0]) ), - b2f( parse.byteOrPercent(v[1]) ), - b2f( parse.byteOrPercent(v[2]) ), - b2f( parse.byteOrPercent(v[3]) ) - ]); + Out: function(amount) { + return amount * (2 - amount); }, - - float3 : function (v) - { - for (var i = 0; i < 3; ++i) - v[i] = parse.floatOrPercent(v[i]); - v[3] = 1.0; - return new Color(v); + InOut: function(amount) { + if ((amount *= 2) < 1) { + return 0.5 * amount * amount; + } + return -0.5 * (--amount * (amount - 2) - 1); + } + }), + Cubic: Object.freeze({ + In: function(amount) { + return amount * amount * amount; }, - - float4 : function (v) - { - for (var i = 0; i < 3; ++i) - v[i] = parse.floatOrPercent(v[i]); - v[3] = parse.floatOrPercent(v[i]); - return new Color(v); + Out: function(amount) { + return --amount * amount * amount + 1; }, - - hsla : function(v) - { - v[0] = parse.numberOrPercent(v[0], 360); - v[1] = parse.numberOrPercent(v[1], 100); - v[2] = parse.numberOrPercent(v[2], 100); - v[3] = parse.numberOrPercent(v[3], 1); - return new Color( hslaToRgba(v) ); + InOut: function(amount) { + if ((amount *= 2) < 1) { + return 0.5 * amount * amount * amount; + } + return 0.5 * ((amount -= 2) * amount * amount + 2); + } + }), + Quartic: Object.freeze({ + In: function(amount) { + return amount * amount * amount * amount; }, - - hsva : function(v) - { - // 0-360, 0-100, 0-100, 0-1 - v[0] = normalize360( parseFloat(v[0]) ); - v[1] = Math.max( 0, Math.min( 100, parseFloat(v[1]) )); - v[2] = Math.max( 0, Math.min( 100, parseFloat(v[2]) )); - v[3] = parse.floatOrPercent(v[3]); - return new Color( hsvaToRgba(v) ); - } - } - - //-----------------------------------------------------------------------// - // Format helpers - //-----------------------------------------------------------------------// - - var supportedFormats = - { - 'keyword' : {}, - 'hex3' : {}, - 'hex7' : {}, - 'rgb' : { - parse : function(v) { v = v.slice(0); v.push(1); return parse.rgba(v); } + Out: function(amount) { + return 1 - --amount * amount * amount * amount; }, - 'rgba' : { - parse : parse.rgba + InOut: function(amount) { + if ((amount *= 2) < 1) { + return 0.5 * amount * amount * amount * amount; + } + return -0.5 * ((amount -= 2) * amount * amount * amount - 2); + } + }), + Quintic: Object.freeze({ + In: function(amount) { + return amount * amount * amount * amount * amount; }, - 'hsl' : { - parse : function(v) { v = v.slice(0); v.push(1); return parse.hsla(v); } + Out: function(amount) { + return --amount * amount * amount * amount * amount + 1; }, - 'hsla' : { - parse : parse.hsla + InOut: function(amount) { + if ((amount *= 2) < 1) { + return 0.5 * amount * amount * amount * amount * amount; + } + return 0.5 * ((amount -= 2) * amount * amount * amount * amount + 2); + } + }), + Sinusoidal: Object.freeze({ + In: function(amount) { + return 1 - Math.sin((1 - amount) * Math.PI / 2); }, - - 'hsv' : { - parse : function(v) { v = v.slice(0); v.push(1); return parse.hsva(v); } + Out: function(amount) { + return Math.sin(amount * Math.PI / 2); }, - 'hsva' : { - parse : parse.hsva + InOut: function(amount) { + return 0.5 * (1 - Math.sin(Math.PI * (0.5 - amount))); + } + }), + Exponential: Object.freeze({ + In: function(amount) { + return amount === 0 ? 0 : Math.pow(1024, amount - 1); }, - 'rgb8' : { - parse : function(v) { v = v.slice(0); v.push(1); return parse.rgba(v); } + Out: function(amount) { + return amount === 1 ? 1 : 1 - Math.pow(2, -10 * amount); }, - 'rgba8' : { - parse : function(v) { return parse.rgba8(v); } + InOut: function(amount) { + if (amount === 0) { + return 0; + } + if (amount === 1) { + return 1; + } + if ((amount *= 2) < 1) { + return 0.5 * Math.pow(1024, amount - 1); + } + return 0.5 * (-Math.pow(2, -10 * (amount - 1)) + 2); + } + }), + Circular: Object.freeze({ + In: function(amount) { + return 1 - Math.sqrt(1 - amount * amount); }, - 'packed_rgba' : { - parse : function (v) { - v = [ (v >> 24) & 255, (v >> 16) & 255, (v >> 8) & 255, (v & 255) / 255]; - return parse.rgba(v); - }, - output : function(v) { - return unsigned((f2b(v[0]) << 24) | (f2b(v[1]) << 16) | (f2b(v[2]) << 8) | f2b(v[3])); - } + Out: function(amount) { + return Math.sqrt(1 - --amount * amount); }, - 'packed_argb' : { - parse : function (v) { - v = [ (v >> 16) & 255, (v >> 8) & 255, (v >> 0) & 255, ((v >> 24) & 255) / 255]; - return parse.rgba(v); - }, - output : function(v) { - return unsigned((f2b(v[3]) << 24) | (f2b(v[0]) << 16) | (f2b(v[1]) << 8) | f2b(v[2])); - } + InOut: function(amount) { + if ((amount *= 2) < 1) { + return -0.5 * (Math.sqrt(1 - amount * amount) - 1); + } + return 0.5 * (Math.sqrt(1 - (amount -= 2) * amount) + 1); + } + }), + Elastic: Object.freeze({ + In: function(amount) { + if (amount === 0) { + return 0; + } + if (amount === 1) { + return 1; + } + return -Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI); }, - 'float3' : { - parse : parse.float3 + Out: function(amount) { + if (amount === 0) { + return 0; + } + if (amount === 1) { + return 1; + } + return Math.pow(2, -10 * amount) * Math.sin((amount - 0.1) * 5 * Math.PI) + 1; }, - 'float4' : { - parse : parse.float4 - } - }; - - - //-----------------------------------------------------------------------// - // Color object - //-----------------------------------------------------------------------// - - function Color(value) - { - this._value = value; - } - - //-----------------------------------------------------------------------// - // color function - //-----------------------------------------------------------------------// - - var color = function() - { - var match = null; - - if (arguments[0] instanceof Color) - { - return new Color( arguments[0]._value ); + InOut: function(amount) { + if (amount === 0) { + return 0; + } + if (amount === 1) { + return 1; + } + amount *= 2; + if (amount < 1) { + return -0.5 * Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI); + } + return 0.5 * Math.pow(2, -10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI) + 1; } - else if (typeof arguments[0] == 'string') - { - var first = arguments[0][0]; - // Hex3 E.g. #08C - if (first == '#') - { - if (match = arguments[0].match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/i)) - { - return new Color( hex4ToRgba(match[0]) ); - } - - // Hex6 e.g. #0088CC - else if (match = arguments[0].match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/i)) - { - return new Color( hex7ToRgba(match[0]) ); - } - } - - // Format string with additional args, e.g. 'rgb' - else if (match = supportedFormats[arguments[0].toLowerCase()]) - { - if (arguments.length == 2) - return match.parse(arguments[1]); - else - return match.parse(slice(arguments, 1)); - } - - // Format + 1 param string, e.g. "packed_rgba(0x00FF00FF)" - else if (match = arguments[0].match(/^\s*([A-Z][A-Z0-9_]+)\s*\(\s*([\-0-9A-FX]+)\s*\)\s*$/i)) - { - var format = supportedFormats[match[1].toLowerCase()]; - return format.parse(match[2]); - } - - // Format + 3/4 params string, e.g. "rgba(255, 255, 0, .4)" - else if (match = arguments[0].match(/^\s*([A-Z][A-Z0-9]+)\s*\(\s*([0-9\.]+%?)\s*,\s*([0-9\.]+%?)\s*,\s*([0-9\.]+%?)\s*(,\s*([0-9\.]+%?)\s*)?\)\s*$/i)) - { - var format = supportedFormats[match[1].toLowerCase()]; - if (match[5] === undefined) - { - var v = [ match[2], match[3], match[4] ]; - return format.parse(v); - } - else - { - var v = [ match[2], match[3], match[4], match[6] ]; - return format.parse(v); - } - } - - // Named color, e.g. "goldenrod" - else if (arguments.length == 1 && (match = namedColors[trimLc(arguments[0])])) - { - var v = match; - return new Color([ b2f(v[0]), b2f(v[1]), b2f(v[2]), 1 ]); - } - } - - throw "Could not parse color '" + arguments[0] + "'"; - }; - - - // - // Method helpers - // - var fixed = - { - white : color('white'), - black : color('black'), - gray : color('gray') - } - - function modifyComponent(index, arg) - { - if (arg == undefined) - return f2b(this._value[index]); - - // First clone the internal data - var v = slice(this._value, 0); - - if (typeof arg == 'string') - { - var m; - if (m = arg.match(/^([+\-\\*]=?)([0-9.]+)/)) - { - var op = m[1]; - var offset = parseFloat(m[2]); - switch (op[0]) - { - case '+': v[index] += offset / 255; break; - case '-': v[index] -= offset / 255; break; - case '*': v[index] *= offset; break; - } - - if (op[1] == '=') - { - this._value = v; - return this; - } - else - return new Color(v); - } - } - else - { - var clone = this.clone(); - clone._value[index] = arg; - return clone; - } - } - - function modifyHsva(i) - { - return function () - { - function change(obj, op, value) - { - value = parseFloat(value); - var hsva = rgbaToHsva(obj._value); - - var c = 0; - switch (op) - { - case '=' : hsva[i] = value; c = 1; break; - case '+' : hsva[i] += value; c = 1; break; - case '+=' : hsva[i] += value; break; - case '-' : hsva[i] -= value; c = 1; break; - case '-=' : hsva[i] -= value; break; - case '*' : hsva[i] *= value; c = 1; break; - case '*=' : hsva[i] *= value; break; - default: - throw "Bad op " + op; - } - if (i == 0) - hsva[i] = normalize360(hsva[i]); - else if (i == 1 || i == 2) - { - if (hsva[i] < 0) hsva[i] = 0; - else if (hsva[i] > 99) hsva[i] = 99; - } - - if (c) - obj = obj.clone(); - obj._value = hsvaToRgba(hsva); - return obj; - } - - if (arguments.length == 0) - return rgbaToHsva(this._value)[i]; - else if (arguments.length == 1) - { - var m; - if (typeof arguments[0] == 'string' && (m = arguments[0].match(/^([\+\-\*]=?)([0-9.]+)/))) - return change(this, m[1], m[2]); - else - return change(this, '=', arguments[0]); - } - else if (arguments.length == 2) - return change(this, arguments[0], arguments[1]); - }; - } - - // - // Object methods - // - var methods = - { - 'clone' : function() - { - return new Color( this._value.slice(0) ); - }, - - /* - By design, the 'html' method returns only valid CSS3 type (e.g. 'hsv' is not - a valid format for this method. - */ - 'html' : function() - { - var self = this; - var v = this._value; - - var _fmt = - { - 'hex3' : function() { return self.hex3(); }, - 'hex6' : function() { return self.hex6(); }, - - 'rgb' : function() { return "rgb(" + self.rgb().join(',') + ")"; }, - 'rgba' : function() { return "rgba(" + self.rgba().join(',') + ")"; }, - - 'hsl' : function() { return 'hsl(' + rgbaToHsl(v).join(',') + ')'; }, - 'hsla' : function() { return 'hsla(' + rgbaToHsla(v).join(',') + ')'; }, - - 'keyword' : function() - { - // Do a linear search by closest in RGB space. Not very efficient. - var dist = 3 * (255 * 255) + 1; - var keyword; - - for (name in namedColors) - { - var c = namedColors[name]; - var d = 0; - for (var i = 0; i < 3; ++i) - { - var t = v[i] - b2f(c[i]); - d += t * t; - } - - if (d < dist) - { - keyword = name; - dist = d; - } - } - - return keyword; - } - }; - var type = arguments[0] || 'rgba'; - return _fmt[type](); + }), + Back: Object.freeze({ + In: function(amount) { + var s = 1.70158; + return amount === 1 ? 1 : amount * amount * ((s + 1) * amount - s); }, - - - 'red' : function() - { - return modifyComponent.call(this, 0, arguments[0]); + Out: function(amount) { + var s = 1.70158; + return amount === 0 ? 0 : --amount * amount * ((s + 1) * amount + s) + 1; }, - - 'green' : function() - { - return modifyComponent.call(this, 1, arguments[0]); + InOut: function(amount) { + var s = 1.70158 * 1.525; + if ((amount *= 2) < 1) { + return 0.5 * (amount * amount * ((s + 1) * amount - s)); + } + return 0.5 * ((amount -= 2) * amount * ((s + 1) * amount + s) + 2); + } + }), + Bounce: Object.freeze({ + In: function(amount) { + return 1 - Easing.Bounce.Out(1 - amount); }, - - 'blue' : function() - { - return modifyComponent.call(this, 2, arguments[0]); + Out: function(amount) { + if (amount < 1 / 2.75) { + return 7.5625 * amount * amount; + } else if (amount < 2 / 2.75) { + return 7.5625 * (amount -= 1.5 / 2.75) * amount + 0.75; + } else if (amount < 2.5 / 2.75) { + return 7.5625 * (amount -= 2.25 / 2.75) * amount + 0.9375; + } else { + return 7.5625 * (amount -= 2.625 / 2.75) * amount + 0.984375; + } }, - - 'alpha' : function() - { - if (arguments.length == 1) - { - c = this.clone(); - c._value[3] = parse.floatOrPercent(arguments[0]); - return c; + InOut: function(amount) { + if (amount < 0.5) { + return Easing.Bounce.In(amount * 2) * 0.5; + } + return Easing.Bounce.Out(amount * 2 - 1) * 0.5 + 0.5; + } + }), + generatePow: function(power) { + if (power === void 0) { + power = 4; + } + power = power < Number.EPSILON ? Number.EPSILON : power; + power = power > 1e4 ? 1e4 : power; + return { + In: function(amount) { + return Math.pow(amount, power); + }, + Out: function(amount) { + return 1 - Math.pow(1 - amount, power); + }, + InOut: function(amount) { + if (amount < 0.5) { + return Math.pow(amount * 2, power) / 2; } - else - return this._value[3]; - }, - - 'alpha8' : function() - { - if (arguments.length == 1) - { - c = this.clone(); - c._value[3] = parse.byteOrPercent(arguments[0]) / 255.0; - return c; + return (1 - Math.pow(2 - amount * 2, power)) / 2 + 0.5; + } + }; + } + }); + var now = function() { + return performance.now(); + }; + var Group = ( + /** @class */ + (function() { + function Group2() { + var tweens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tweens[_i] = arguments[_i]; + } + this._tweens = {}; + this._tweensAddedDuringUpdate = {}; + this.add.apply(this, tweens); + } + Group2.prototype.getAll = function() { + var _this2 = this; + return Object.keys(this._tweens).map(function(tweenId) { + return _this2._tweens[tweenId]; + }); + }; + Group2.prototype.removeAll = function() { + this._tweens = {}; + }; + Group2.prototype.add = function() { + var _a; + var tweens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tweens[_i] = arguments[_i]; + } + for (var _b = 0, tweens_1 = tweens; _b < tweens_1.length; _b++) { + var tween2 = tweens_1[_b]; + (_a = tween2._group) === null || _a === void 0 ? void 0 : _a.remove(tween2); + tween2._group = this; + this._tweens[tween2.getId()] = tween2; + this._tweensAddedDuringUpdate[tween2.getId()] = tween2; + } + }; + Group2.prototype.remove = function() { + var tweens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tweens[_i] = arguments[_i]; + } + for (var _a = 0, tweens_2 = tweens; _a < tweens_2.length; _a++) { + var tween2 = tweens_2[_a]; + tween2._group = void 0; + delete this._tweens[tween2.getId()]; + delete this._tweensAddedDuringUpdate[tween2.getId()]; + } + }; + Group2.prototype.allStopped = function() { + return this.getAll().every(function(tween2) { + return !tween2.isPlaying(); + }); + }; + Group2.prototype.update = function(time, preserve) { + if (time === void 0) { + time = now(); + } + if (preserve === void 0) { + preserve = true; + } + var tweenIds = Object.keys(this._tweens); + if (tweenIds.length === 0) + return; + while (tweenIds.length > 0) { + this._tweensAddedDuringUpdate = {}; + for (var i = 0; i < tweenIds.length; i++) { + var tween2 = this._tweens[tweenIds[i]]; + var autoStart = !preserve; + if (tween2 && tween2.update(time, autoStart) === false && !preserve) + this.remove(tween2); } - else - return Math.floor(this._value[3] * 255); - }, - - 'grayvalue' : function() - { - var c = this._value; - return (c[0] + c[1] + c[2]) / 3; - }, - - 'grayvalue8' : function() - { - return f2b( this.grayvalue() ); - }, - - 'luminance' : function() - { - var c = this._value; - return c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722; - }, - - 'luminance8' : function() - { - return f2b( this.luminance() ); - }, - - 'hsv' : function() - { - return rgbaToHsva(this._value).slice(0,3); - }, - 'hsva' : function() - { - return rgbaToHsva(this._value); - }, - - 'packed_rgba' : function() { return supportedFormats.packed_rgba.output(this._value); }, - 'packed_argb' : function() { return supportedFormats.packed_argb.output(this._value); }, - - 'hue' : modifyHsva(0), - 'saturation' : modifyHsva(1), - 'value' : modifyHsva(2), - - 'clamp' : function() - { - var v = this._value; - return new Color([ - clamp(v[0], 0, 1), - clamp(v[1], 0, 1), - clamp(v[2], 0, 1), - clamp(v[3], 0, 1) - ]); - }, - - 'blend' : function(colorToBlend, amount) - { - if (typeof amount !== 'number') - amount = parse.floatOrPercent(amount); - - var c = this; - var c2 = color(colorToBlend); - return new Color([ - mix(c._value[0], c2._value[0], amount), - mix(c._value[1], c2._value[1], amount), - mix(c._value[2], c2._value[2], amount), - mix(c._value[3], c2._value[3], amount) - ]); - }, - - 'add' : function (d) - { - var u = this._value; - var v = color(d)._value; - return new Color([ - u[0] + v[0] * v[3], - u[1] + v[1] * v[3], - u[2] + v[2] * v[3], - u[3] - ]); - }, - - 'inc' : function (d) - { - var u = this._value; - var v = color(d)._value; - u[0] += v[0] * v[3]; - u[1] += v[1] * v[3]; - u[2] += v[2] * v[3]; - return this; - }, - - 'dec' : function (d) - { - var u = this._value; - var v = color(d)._value; - u[0] -= v[0] * v[3]; - u[1] -= v[1] * v[3]; - u[2] -= v[2] * v[3]; - return this; - }, - - 'subtract' : function (d) - { - var u = this._value; - var v = color(d)._value; - return new Color([ - u[0] - v[0] * v[3], - u[1] - v[1] * v[3], - u[2] - v[2] * v[3], - u[3] - ]); - }, - - 'multiply' : function (d) - { - var u = this._value; - var v = color(d)._value; - return new Color([ - u[0] * v[0], - u[1] * v[1], - u[2] * v[2], - u[3] * v[3] - ]); - }, - - 'scale' : function (d) - { - var u = this._value; - return new Color([ - u[0] * d, - u[1] * d, - u[2] * d, - u[3] - ]); - }, - - 'xor' : function (d) - { - var u = this.rgba8(); - var v = color(d).rgba8(); - return color('rgba8', u[0] ^ v[0], u[1] ^ v[1], u[2] ^ v[2], u[3]); - }, - - 'tint' : function(amount) - { - return this.blend( fixed.white, amount ); - }, - 'shade' : function(amount) - { - return this.blend( fixed.black, amount ); - }, - 'tone' : function(amount) - { - return this.blend( fixed.gray, amount ); - }, - 'complement' : function() - { - var hsva = this.hsva(); - hsva[0] = normalize360(hsva[0] + 180); - return new Color( hsvaToRgba(hsva) ); - }, - 'triad' : function() - { - return [ - new Color(this._value), - this.hue('+120'), - this.hue('+240') - ]; - }, - - 'hueSet' : function() - { - var h = 0; - var set = []; - for (var s = 100; s >= 30; s -= 35) - for (var v = 100; v >= 30; v -= 35) - set.push( this.hue('+', h).saturation(s).value(v) ); - return set; - }, - - 'hueRange' : function(range, count) - { - var base = this.hue(); - var set = []; - for (var i = 0; i < count; ++i) - { - var h = base + (2 * (i/(count-1) - .5) * range); - set.push( this.hue('=', h) ); - } - return set; - }, - - 'contrastWhiteBlack' : function() - { - return (this.value() < 50) ? color('white') : color('black'); + tweenIds = Object.keys(this._tweensAddedDuringUpdate); + } + }; + return Group2; + })() + ); + var Interpolation = { + Linear: function(v, k) { + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + var fn = Interpolation.Utils.Linear; + if (k < 0) { + return fn(v[0], v[1], f); + } + if (k > 1) { + return fn(v[m], v[m - 1], m - f); + } + return fn(v[i], v[i + 1 > m ? m : i + 1], f - i); + }, + Bezier: function(v, k) { + var b = 0; + var n = v.length - 1; + var pw = Math.pow; + var bn = Interpolation.Utils.Bernstein; + for (var i = 0; i <= n; i++) { + b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i); + } + return b; + }, + CatmullRom: function(v, k) { + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + var fn = Interpolation.Utils.CatmullRom; + if (v[0] === v[m]) { + if (k < 0) { + i = Math.floor(f = m * (1 + k)); + } + return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i); + } else { + if (k < 0) { + return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]); + } + if (k > 1) { + return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]); + } + return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + }, + Utils: { + Linear: function(p0, p1, t) { + return (p1 - p0) * t + p0; }, - - 'contrastGray' : function() - { - var hsva = this.hsva(); - var value = (hsva[2] < 30) ? (hsva[2] + 20) : (hsva[2] - 20); - return new Color( hsvaToRgba([ hsva[0], 0, value, hsva[3] ]) ); + Bernstein: function(n, i) { + var fc = Interpolation.Utils.Factorial; + return fc(n) / fc(i) / fc(n - i); }, - - 'hex3' : function() - { - function hex(d, max) { - return Math.min(Math.round(f2b(d) / 16), 15).toString(16); + Factorial: /* @__PURE__ */ (function() { + var a = [1]; + return function(n) { + var s = 1; + if (a[n]) { + return a[n]; } - return "#" + hex(this._value[0]) + hex(this._value[1]) + hex(this._value[2]); - }, - 'hex6' : function() - { - function hex(d, max) { - var h = f2b(d).toString(16); - return (h.length < 2) ? "0" + h : h; + for (var i = n; i > 1; i--) { + s *= i; } - return "#" + hex(this._value[0]) + hex(this._value[1]) + hex(this._value[2]); - }, - - 'rgb' : function() - { - var v = this._value; - return [ f2b(v[0]), f2b(v[1]), f2b(v[2]) ]; - }, - - 'rgba' : function() - { - var v = this._value; - return [ f2b(v[0]), f2b(v[1]), f2b(v[2]), v[3] ]; - }, - - 'rgb8' : function() - { - var v = this._value; - return [ f2b(v[0]), f2b(v[1]), f2b(v[2]) ]; - }, - - 'rgba8' : function() - { - var v = this._value; - return [ f2b(v[0]), f2b(v[1]), f2b(v[2]), this.alpha8() ]; - }, - - 'float3' : function() - { - return [ this._value[0], this._value[1], this._value[2] ]; - }, - - 'float4' : function() - { - return [ this._value[0], this._value[1], this._value[2], this._value[3] ]; + a[n] = s; + return s; + }; + })(), + CatmullRom: function(p0, p1, p2, p3, t) { + var v0 = (p2 - p0) * 0.5; + var v1 = (p3 - p1) * 0.5; + var t2 = t * t; + var t3 = t * t2; + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; } + } }; - - // Aliases - methods['sub'] = methods['subtract']; - methods['mul'] = methods['multiply']; - - for (var name in methods) - Color.prototype[name] = methods[name]; - - /* - Lower-level, less flexible, but faster routines - */ - color.float3 = function(r,g,b) - { - return new Color([ r, g, b, 1.0 ]); - }; - color.float4 = function(r,g,b,a) - { - return new Color([ r, g, b, a ]); - }; - - // - // Export - // - color.version = "0.2.4"; - color.Color = Color; - - // Determine if this is the node.js or the browser - if (typeof module !== "undefined" && module.exports ) { - module.exports = color; - } - else if (typeof window !== "undefined") { - window.pusher = window.pusher || {}; - window.pusher.color = color; - } -})(); - - -},{}],7:[function(require,module,exports){ -;(function inject(clean, precision, undef) { - - var isArray = function (a) { - return Object.prototype.toString.call(a) === "[object Array]"; - }; - - function Vec2(x, y) { - if (!(this instanceof Vec2)) { - return new Vec2(x, y); - } - - if (isArray(x)) { - y = x[1]; - x = x[0]; - } else if('object' === typeof x && x) { - y = x.y; - x = x.x; - } - - this.x = Vec2.clean(x || 0); - this.y = Vec2.clean(y || 0); - } - - Vec2.prototype = { - change : function(fn) { - if (fn) { - if (this.observers) { - this.observers.push(fn); - } else { - this.observers = [fn]; + var Sequence = ( + /** @class */ + (function() { + function Sequence2() { } - } else if (this.observers) { - for (var i=this.observers.length-1; i>=0; i--) { - this.observers[i](this); - } - } - - return this; - }, - - ignore : function(fn) { - if (this.observers) { - var o = this.observers, l = o.length; - while(l--) { - o[l] === fn && o.splice(l, 1); + Sequence2.nextId = function() { + return Sequence2._nextId++; + }; + Sequence2._nextId = 0; + return Sequence2; + })() + ); + var mainGroup = new Group(); + var Tween = ( + /** @class */ + (function() { + function Tween2(object, group) { + this._isPaused = false; + this._pauseStart = 0; + this._valuesStart = {}; + this._valuesEnd = {}; + this._valuesStartRepeat = {}; + this._duration = 1e3; + this._isDynamic = false; + this._initialRepeat = 0; + this._repeat = 0; + this._yoyo = false; + this._isPlaying = false; + this._reversed = false; + this._delayTime = 0; + this._startTime = 0; + this._easingFunction = Easing.Linear.None; + this._interpolationFunction = Interpolation.Linear; + this._chainedTweens = []; + this._onStartCallbackFired = false; + this._onEveryStartCallbackFired = false; + this._id = Sequence.nextId(); + this._isChainStopped = false; + this._propertiesAreSetUp = false; + this._goToEnd = false; + this._object = object; + if (typeof group === "object") { + this._group = group; + group.add(this); + } else if (group === true) { + this._group = mainGroup; + mainGroup.add(this); + } } - } - return this; - }, - - // set x and y - set: function(x, y, silent) { - if('number' != typeof x) { - silent = y; - y = x.y; - x = x.x; - } - - if(this.x === x && this.y === y) { - return this; - } - - this.x = Vec2.clean(x); - this.y = Vec2.clean(y); - - if(silent !== false) { - return this.change(); - } - }, - - // reset x and y to zero - zero : function() { - return this.set(0, 0); - }, - - // return a new vector with the same component values - // as this one - clone : function() { - return new (this.constructor)(this.x, this.y); - }, - - // negate the values of this vector - negate : function(returnNew) { - if (returnNew) { - return new (this.constructor)(-this.x, -this.y); - } else { - return this.set(-this.x, -this.y); - } - }, - - // Add the incoming `vec2` vector to this vector - add : function(vec2, returnNew) { - if (!returnNew) { - this.x += vec2.x; this.y += vec2.y; - return this.change(); - } else { - // Return a new vector if `returnNew` is truthy - return new (this.constructor)( - this.x + vec2.x, - this.y + vec2.y - ); - } - }, - - // Subtract the incoming `vec2` from this vector - subtract : function(vec2, returnNew) { - if (!returnNew) { - this.x -= vec2.x; this.y -= vec2.y; - return this.change(); - } else { - // Return a new vector if `returnNew` is truthy - return new (this.constructor)( - this.x - vec2.x, - this.y - vec2.y - ); - } - }, - - // Multiply this vector by the incoming `vec2` - multiply : function(vec2, returnNew) { - var x,y; - if ('number' !== typeof vec2) { //.x !== undef) { - x = vec2.x; - y = vec2.y; - - // Handle incoming scalars - } else { - x = y = vec2; - } - - if (!returnNew) { - return this.set(this.x * x, this.y * y); - } else { - return new (this.constructor)( - this.x * x, - this.y * y - ); - } - }, - - // Rotate this vector. Accepts a `Rotation` or angle in radians. - // - // Passing a truthy `inverse` will cause the rotation to - // be reversed. - // - // If `returnNew` is truthy, a new - // `Vec2` will be created with the values resulting from - // the rotation. Otherwise the rotation will be applied - // to this vector directly, and this vector will be returned. - rotate : function(r, inverse, returnNew) { - var - x = this.x, - y = this.y, - cos = Math.cos(r), - sin = Math.sin(r), - rx, ry; - - inverse = (inverse) ? -1 : 1; - - rx = cos * x - (inverse * sin) * y; - ry = (inverse * sin) * x + cos * y; - - if (returnNew) { - return new (this.constructor)(rx, ry); - } else { - return this.set(rx, ry); - } - }, - - // Calculate the length of this vector - length : function() { - var x = this.x, y = this.y; - return Math.sqrt(x * x + y * y); - }, - - // Get the length squared. For performance, use this instead of `Vec2#length` (if possible). - lengthSquared : function() { - var x = this.x, y = this.y; - return x*x+y*y; - }, - - // Return the distance betwen this `Vec2` and the incoming vec2 vector - // and return a scalar - distance : function(vec2) { - var x = this.x - vec2.x; - var y = this.y - vec2.y; - return Math.sqrt(x*x + y*y); - }, - - // Convert this vector into a unit vector. - // Returns the length. - normalize : function(returnNew) { - var length = this.length(); - - // Collect a ratio to shrink the x and y coords - var invertedLength = (length < Number.MIN_VALUE) ? 0 : 1/length; - - if (!returnNew) { - // Convert the coords to be greater than zero - // but smaller than or equal to 1.0 - return this.set(this.x * invertedLength, this.y * invertedLength); - } else { - return new (this.constructor)(this.x * invertedLength, this.y * invertedLength); - } - }, - - // Determine if another `Vec2`'s components match this one's - // also accepts 2 scalars - equal : function(v, w) { - if (w === undef) { - w = v.y; - v = v.x; - } - - return (Vec2.clean(v) === this.x && Vec2.clean(w) === this.y); - }, - - // Return a new `Vec2` that contains the absolute value of - // each of this vector's parts - abs : function(returnNew) { - var x = Math.abs(this.x), y = Math.abs(this.y); - - if (returnNew) { - return new (this.constructor)(x, y); - } else { - return this.set(x, y); - } - }, - - // Return a new `Vec2` consisting of the smallest values - // from this vector and the incoming - // - // When returnNew is truthy, a new `Vec2` will be returned - // otherwise the minimum values in either this or `v` will - // be applied to this vector. - min : function(v, returnNew) { - var - tx = this.x, - ty = this.y, - vx = v.x, - vy = v.y, - x = tx < vx ? tx : vx, - y = ty < vy ? ty : vy; - - if (returnNew) { - return new (this.constructor)(x, y); - } else { - return this.set(x, y); - } - }, - - // Return a new `Vec2` consisting of the largest values - // from this vector and the incoming - // - // When returnNew is truthy, a new `Vec2` will be returned - // otherwise the minimum values in either this or `v` will - // be applied to this vector. - max : function(v, returnNew) { - var - tx = this.x, - ty = this.y, - vx = v.x, - vy = v.y, - x = tx > vx ? tx : vx, - y = ty > vy ? ty : vy; - - if (returnNew) { - return new (this.constructor)(x, y); - } else { - return this.set(x, y); - } - }, - - // Clamp values into a range. - // If this vector's values are lower than the `low`'s - // values, then raise them. If they are higher than - // `high`'s then lower them. - // - // Passing returnNew as true will cause a new Vec2 to be - // returned. Otherwise, this vector's values will be clamped - clamp : function(low, high, returnNew) { - var ret = this.min(high, true).max(low); - if (returnNew) { - return ret; - } else { - return this.set(ret.x, ret.y); - } - }, - - // Perform linear interpolation between two vectors - // amount is a decimal between 0 and 1 - lerp : function(vec, amount) { - return this.add(vec.subtract(this, true).multiply(amount), true); - }, - - // Get the skew vector such that dot(skew_vec, other) == cross(vec, other) - skew : function() { - // Returns a new vector. - return new (this.constructor)(-this.y, this.x); - }, - - // calculate the dot product between - // this vector and the incoming - dot : function(b) { - return Vec2.clean(this.x * b.x + b.y * this.y); - }, - - // calculate the perpendicular dot product between - // this vector and the incoming - perpDot : function(b) { - return Vec2.clean(this.x * b.y - this.y * b.x); - }, - - // Determine the angle between two vec2s - angleTo : function(vec) { - return Math.atan2(this.perpDot(vec), this.dot(vec)); - }, - - // Divide this vector's components by a scalar - divide : function(vec2, returnNew) { - var x,y; - if ('number' !== typeof vec2) { - x = vec2.x; - y = vec2.y; - - // Handle incoming scalars - } else { - x = y = vec2; - } - - if (x === 0 || y === 0) { - throw new Error('division by zero') - } - - if (isNaN(x) || isNaN(y)) { - throw new Error('NaN detected'); - } - - if (returnNew) { - return new (this.constructor)(this.x / x, this.y / y); - } - - return this.set(this.x / x, this.y / y); - }, - - isPointOnLine : function(start, end) { - return (start.y - this.y) * (start.x - end.x) === - (start.y - end.y) * (start.x - this.x); - }, - - toArray: function() { - return [this.x, this.y]; - }, - - fromArray: function(array) { - return this.set(array[0], array[1]); - }, - toJSON: function () { - return {x: this.x, y: this.y}; - }, - toString: function() { - return '(' + this.x + ', ' + this.y + ')'; - }, - constructor : Vec2 - }; - - Vec2.fromArray = function(array, ctor) { - return new (ctor || Vec2)(array[0], array[1]); - }; - - // Floating point stability - Vec2.precision = precision || 8; - var p = Math.pow(10, Vec2.precision); - - Vec2.clean = clean || function(val) { - if (isNaN(val)) { - throw new Error('NaN detected'); - } - - if (!isFinite(val)) { - throw new Error('Infinity detected'); - } - - if(Math.round(val) === val) { - return val; - } - - return Math.round(val * p)/p; - }; - - Vec2.inject = inject; - - if(!clean) { - Vec2.fast = inject(function (k) { return k; }); - - // Expose, but also allow creating a fresh Vec2 subclass. - if (typeof module !== 'undefined' && typeof module.exports == 'object') { - module.exports = Vec2; - } else { - window.Vec2 = window.Vec2 || Vec2; - } - } - return Vec2; -})(); - -},{}],8:[function(require,module,exports){ -var Vec2 = require('vec2'), - Quadtree2Helper = require('./quadtree2helper'), - Quadtree2Validator = require('./quadtree2validator'), - Quadtree2Quadrant = require('./quadtree2quadrant'), - Quadtree2; - -Quadtree2 = function Quadtree2(size, quadrantObjectsLimit, quadrantLevelLimit) { - var id, - - // Container for private data. - data = { - objects_ : {}, - quadrants_ : {}, - ids_ : 1, - quadrantIds_ : 1, - autoId_ : true, - inited_ : false, - debug_ : false, - size_ : undefined, - root_ : undefined, - quadrantObjectsLimit_ : undefined, - quadrantLevelLimit_ : undefined, - quadrantSizeLimit_ : undefined - }, - - validator = new Quadtree2Validator(), - - // Inserted object keys. - k = { - p : 'pos_', - r : 'rad_', - id : 'id_' - }, - - // Property definitions. - constraints = { - data : { - necessary : { - size_ : validator.isVec2, - quadrantObjectsLimit_ : validator.isNumber, - quadrantLevelLimit_ : validator.isNumber - } - }, - - k : { - necessary : { - p : validator.isVec2 - }, - - c : { - necessary : { - r : validator.isNumber - }, - } - } - }, - - // Private function definitions. - fns = { - nextId : function nextId() { - return data.ids_++; - }, - - nextQuadrantId : function nextQuadrantId(sum) { - var id = data.quadrantIds_; - data.quadrantIds_ += sum || 4; - - return id; - }, - - hasCollision : function hasCollision(objA, objB) { - return objA[k.r] + objB[k.r] > objA[k.p].distance(objB[k.p]); - }, - - removeQuadrantParentQuadrants : function removeQuadrantParentQuadrants(quadrant, quadrants) { - if (!quadrant.parent_) { return; } - - if (quadrants[quadrant.parent_.id_]) { - delete quadrants[quadrant.parent_.id_]; - fns.removeQuadrantParentQuadrants(quadrant.parent_, quadrants); + Tween2.prototype.getId = function() { + return this._id; + }; + Tween2.prototype.isPlaying = function() { + return this._isPlaying; + }; + Tween2.prototype.isPaused = function() { + return this._isPaused; + }; + Tween2.prototype.getDuration = function() { + return this._duration; + }; + Tween2.prototype.to = function(target, duration) { + if (duration === void 0) { + duration = 1e3; } - }, - - getSubtreeTopQuadrant : function getSubtreeTopQuadrant(quadrant, quadrants) { - if (!quadrant.parent_ || !quadrants[quadrant.parent_.id_]) { return quadrant; } - return getSubtreeTopQuadrant(quadrant.parent_, quadrants); - }, - - removeQuadrantChildtree : function removeQuadrantChildtree(quadrant, quadrants) { - var i, - children = quadrant.getChildren(); - - for (i = 0; i < children.length; i++) { - if (!quadrants[children[i].id_]) { return; } - delete quadrants[children[i].id_]; - fns.removeQuadrantChildtree(children[i], quadrants); + if (this._isPlaying) + throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first."); + this._valuesEnd = target; + this._propertiesAreSetUp = false; + this._duration = duration < 0 ? 0 : duration; + return this; + }; + Tween2.prototype.duration = function(duration) { + if (duration === void 0) { + duration = 1e3; } - }, - - getIntersectingQuadrants: function getIntersectingQuadrants(obj, quadrant, result) { - var i, - children; - - if (!quadrant.intersects(obj[k.p], obj[k.r])) { - fns.removeQuadrantParentQuadrants(quadrant, result.biggest); - return; + this._duration = duration < 0 ? 0 : duration; + return this; + }; + Tween2.prototype.dynamic = function(dynamic) { + if (dynamic === void 0) { + dynamic = false; } - - result.biggest[quadrant.id_] = quadrant; - children = quadrant.getChildren(); - - if (children.length) { - for (i = 0; i < children.length; i++) { - getIntersectingQuadrants(obj, children[i], result); - } - } else { - result.leaves[quadrant.id_] = quadrant; + this._isDynamic = dynamic; + return this; + }; + Tween2.prototype.start = function(time, overrideStartingValues) { + if (time === void 0) { + time = now(); } - }, - - getSmallestIntersectingQuadrants : function getSmallestIntersectingQuadrants(obj, quadrant, result) { - var id, - top; - - if (!quadrant) { quadrant = data.root_; } - if (!result) { result = { leaves : {}, biggest : {} }; } - - fns.getIntersectingQuadrants(obj, quadrant, result); - - for (id in result.leaves) { - if (!result.biggest[id]) { continue; } - top = fns.getSubtreeTopQuadrant(result.leaves[id], result.biggest); - fns.removeQuadrantChildtree(top, result.biggest); + if (overrideStartingValues === void 0) { + overrideStartingValues = false; } - - return result.biggest; - }, - - removeQuadrantObjects : function removeQuadrantObjects(quadrant) { - var i, - removed = quadrant.removeObjects([], 1); - - for (i = 0; i < removed.length; i++) { - delete data.quadrants_[removed[i].obj[k.id]][removed[i].quadrant.id_]; + if (this._isPlaying) { + return this; } - - return removed; - }, - - removeObjectFromQuadrants : function removeObjectFromQuadrants(obj, quadrants) { - var id; - - if (quadrants === undefined) { quadrants = data.quadrants_[obj[k.id]]; } - - for (id in quadrants) { fns.removeObjectFromQuadrant(obj, quadrants[id]); } - }, - - removeObjectFromQuadrant : function removeObjectFromQuadrant(obj, quadrant) { - quadrant.removeObject(obj[k.id]); - - delete data.quadrants_[obj[k.id]][quadrant.id_]; - - if (quadrant.hasChildren() || !quadrant.parent_) { return; } - - fns.refactorSubtree(quadrant.parent_); - }, - - refactorSubtree : function refactorSubtree(quadrant) { - var i, - id, - count, - child, - obj; - - if (quadrant.refactoring_) { return; } - - // Lets check for grandchildren. - for (i = 0; i < quadrant.children_.length; i++) { - child = quadrant.children_[i]; - - if (child.hasChildren()) { - return; + this._repeat = this._initialRepeat; + if (this._reversed) { + this._reversed = false; + for (var property in this._valuesStartRepeat) { + this._swapEndStartRepeatValues(property); + this._valuesStart[property] = this._valuesStartRepeat[property]; } } - - count = quadrant.getObjectCountForLimit(); - - if (count > data.quadrantObjectsLimit_) { return; } - - quadrant.refactoring_ = true; - - for (i = 0; i < quadrant.children_.length; i++) { - child = quadrant.children_[i]; - - for (id in child.objects_) { - obj = child.objects_[id]; - fns.removeObjectFromQuadrant(obj, child); - fns.addObjectToQuadrant(obj, quadrant); + this._isPlaying = true; + this._isPaused = false; + this._onStartCallbackFired = false; + this._onEveryStartCallbackFired = false; + this._isChainStopped = false; + this._startTime = time; + this._startTime += this._delayTime; + if (!this._propertiesAreSetUp || overrideStartingValues) { + this._propertiesAreSetUp = true; + if (!this._isDynamic) { + var tmp = {}; + for (var prop in this._valuesEnd) + tmp[prop] = this._valuesEnd[prop]; + this._valuesEnd = tmp; } + this._setupProperties(this._object, this._valuesStart, this._valuesEnd, this._valuesStartRepeat, overrideStartingValues); } - - quadrant.looseChildren(); - - quadrant.refactoring_ = false; - - if (!quadrant.parent_) { return; } - - fns.refactorSubtree(quadrant.parent_); - }, - - updateObjectQuadrants : function updateObjectQuadrants(obj) { - var oldQuadrants = data.quadrants_[obj[k.id]], - newQuadrants = fns.getSmallestIntersectingQuadrants(obj), - oldIds = Quadtree2Helper.getIdsOfObjects(oldQuadrants), - newIds = Quadtree2Helper.getIdsOfObjects(newQuadrants), - diffIds = Quadtree2Helper.arrayDiffs(oldIds, newIds), - removeIds = diffIds[0], - addIds = diffIds[1], - i; - - for (i = 0; i < addIds.length; i++) { - fns.populateSubtree(obj, newQuadrants[addIds[i]]); - } - - for (i = 0; i < removeIds.length; i++) { - if (!oldQuadrants[removeIds[i]]) { continue; } - fns.removeObjectFromQuadrant(obj, oldQuadrants[removeIds[i]]); - } - }, - - addObjectToQuadrant : function addObjectToQuadrant(obj, quadrant) { - var id = obj[k.id]; - if (data.quadrants_[id] === undefined) data.quadrants_[id] = {}; - data.quadrants_[id][quadrant.id_] = quadrant; - quadrant.addObject(id, obj); - }, - - populateSubtree : function populateSubtree(obj, quadrant) { - var i, - id, - addBySubtree, - smallestQs, - intersectingChildren, - removed; - - if (!quadrant) { quadrant = data.root_; } - - if (quadrant.hasChildren()) { - // Get smallest quadrants which intersect. - smallestQs = fns.getSmallestIntersectingQuadrants(obj, quadrant); - - for (id in smallestQs) { - if (smallestQs[id] === quadrant) { - // If its myself because all my children would intersect with - // it, then no point storing the obj in children => addObject. - fns.addObjectToQuadrant(obj, quadrant); - return; + return this; + }; + Tween2.prototype.startFromCurrentValues = function(time) { + return this.start(time, true); + }; + Tween2.prototype._setupProperties = function(_object, _valuesStart, _valuesEnd, _valuesStartRepeat, overrideStartingValues) { + for (var property in _valuesEnd) { + var startValue = _object[property]; + var startValueIsArray = Array.isArray(startValue); + var propType = startValueIsArray ? "array" : typeof startValue; + var isInterpolationList = !startValueIsArray && Array.isArray(_valuesEnd[property]); + if (propType === "undefined" || propType === "function") { + continue; + } + if (isInterpolationList) { + var endValues = _valuesEnd[property]; + if (endValues.length === 0) { + continue; + } + var temp = [startValue]; + for (var i = 0, l = endValues.length; i < l; i += 1) { + var value = this._handleRelativeValue(startValue, endValues[i]); + if (isNaN(value)) { + isInterpolationList = false; + console.warn("Found invalid interpolation list. Skipping."); + break; + } + temp.push(value); + } + if (isInterpolationList) { + _valuesEnd[property] = temp; } - // Propagate further to children - fns.populateSubtree(obj, smallestQs[id]); } - - } else if (quadrant.getObjectCount() < data.quadrantObjectsLimit_ || quadrant.size_.x < data.quadrantSizeLimit_.x ) { - // Has no children but still got place, so store it. - fns.addObjectToQuadrant(obj, quadrant); - - } else { - // Got no place so lets make children. - quadrant.makeChildren(fns.nextQuadrantId()); - - // Remove all the stored objects until the parent. - removed = fns.removeQuadrantObjects(quadrant); - removed.push({ obj : obj, quadrant : quadrant }); - - // Recalculate all objects which were stored before. - for (i = 0; i < removed.length; i++) { - fns.populateSubtree(removed[i].obj, removed[i].quadrant); + if ((propType === "object" || startValueIsArray) && startValue && !isInterpolationList) { + _valuesStart[property] = startValueIsArray ? [] : {}; + var nestedObject = startValue; + for (var prop in nestedObject) { + _valuesStart[property][prop] = nestedObject[prop]; + } + _valuesStartRepeat[property] = startValueIsArray ? [] : {}; + var endValues = _valuesEnd[property]; + if (!this._isDynamic) { + var tmp = {}; + for (var prop in endValues) + tmp[prop] = endValues[prop]; + _valuesEnd[property] = endValues = tmp; + } + this._setupProperties(nestedObject, _valuesStart[property], endValues, _valuesStartRepeat[property], overrideStartingValues); + } else { + if (typeof _valuesStart[property] === "undefined" || overrideStartingValues) { + _valuesStart[property] = startValue; + } + if (!startValueIsArray) { + _valuesStart[property] *= 1; + } + if (isInterpolationList) { + _valuesStartRepeat[property] = _valuesEnd[property].slice().reverse(); + } else { + _valuesStartRepeat[property] = _valuesStart[property] || 0; + } } } - }, - - init : function init() { - var divider; - - if (!data.quadrantLevelLimit_) data.quadrantLevelLimit_ = 6; - - validator.byCallbackObject(data, constraints.data.necessary); - - data.root_ = new Quadtree2Quadrant(new Vec2(0,0), data.size_.clone(), fns.nextQuadrantId(1)); - - divider = Math.pow(2, data.quadrantLevelLimit_); - data.quadrantSizeLimit_ = data.size_.clone().divide(divider); - - data.inited_ = true; - }, - - checkInit : function checkInit(init) { - if (init && !data.inited_) { fns.init(); } - return data.inited_; - }, - - checkObjectKeys : function checkObjectKeys(obj) { - validator.isNumber(obj[k.id], k.id); - validator.isNumber(obj[k.r], k.r); - validator.hasNoKey(data.objects_, obj[k.id], k.id); - validator.byCallbackObject(obj, constraints.k.necessary, k); - }, - - setObjId : function setObjId(obj) { - if (data.autoId_ && !obj[k.id]) { - obj[k.id] = fns.nextId(); + }; + Tween2.prototype.stop = function() { + if (!this._isChainStopped) { + this._isChainStopped = true; + this.stopChainedTweens(); } - }, - - removeObjectById : function removeObjectById(id) { - validator.hasKey(data.objects_, id, k.id); - - fns.removeObjectFromQuadrants(data.objects_[id]); - - delete data.objects_[id]; - }, - - updateObjectById : function updateObjectById(id) { - validator.hasKey(data.objects_, id, k.id); - - fns.updateObjectQuadrants(data.objects_[id]); - }, - - getObjectsByObject : function getObjectsByObject(obj) { - var i, - id, - quadrants = data.quadrants_[obj[k.id]], - result = { objects : {}, quadrants : {} }; - - for (id in quadrants) { - quadrants[id].getObjectsUp(result); - - for (i = 0; i < quadrants[id].children_.length; i++) { - quadrants[id].children_[i].getObjectsDown(result); - } + if (!this._isPlaying) { + return this; } - - delete result.objects[obj[k.id]]; - - return result.objects; - } - }, - - // Debug functions - debugFns = { - getQuadrants: function getQuadrants() { - return data.root_.getChildren(true, [data.root_]); - }, - - getLeafQuadrants : function getLeafQuadrants() { - return debugFns.getQuadrants().filter(function(q){ - return !q.hasChildren(); - }); - } - }, - - // Public function definitions - publicFns = { - getQuadrantObjectsLimit: function getQuadrantObjectsLimit() { - return data.quadrantObjectsLimit_; - }, - - setQuadrantObjectsLimit : function getQuadrantObjectsLimit(quadrantObjectsLimit) { - if (quadrantObjectsLimit === undefined) { return; } - - validator.isNumber(quadrantObjectsLimit, 'quadrantObjectsLimit_'); - - data.quadrantObjectsLimit_ = quadrantObjectsLimit; - }, - - getQuadrantLevelLimit : function getQuadrantLevelLimit() { - return data.quadrantLevelLimit_; - }, - - setQuadrantLevelLimit: function setQuadrantLevelLimit(quadrantLevelLimit) { - if (quadrantLevelLimit === undefined) { return; } - - validator.isNumber(quadrantLevelLimit, 'quadrantLevelLimit_'); - - data.quadrantLevelLimit_ = quadrantLevelLimit; - }, - - - setObjectKey : function setObjectKey(key, val) { - validator.fnFalse(fns.checkInit); - if (val === undefined) { return; } - - validator.hasKey(k, key, key); - validator.isString(val, key); - - if (key === 'id') { data.autoId_ = false; } - k[key] = val; - }, - - getSize : function getSize() { - return data.size_.clone(); - }, - - setSize : function setSize(size) { - if (size === undefined) { return; } - - validator.isVec2(size, 'size_'); - - data.size_ = size.clone(); - }, - - addObjects : function addObject(objs) { - objs.forEach(function(obj) { - publicFns.addObject(obj); - }); - }, - - addObject : function addObject(obj) { - validator.isDefined(obj, 'obj'); - validator.isObject(obj, 'obj'); - - fns.checkInit(true); - fns.setObjId(obj); - fns.checkObjectKeys(obj); - - fns.populateSubtree(obj); - - data.objects_[obj[k.id]] = obj; - }, - - removeObjects : function removeObjects(objs) { - var i; - - for (i = 0; i < objs.length; i++) { - publicFns.removeObject(objs[i]); + this._isPlaying = false; + this._isPaused = false; + if (this._onStopCallback) { + this._onStopCallback(this._object); } - }, - - removeObject : function removeObject(obj) { - fns.checkInit(true); - validator.hasKey(obj, k.id, k.id); - - fns.removeObjectById(obj[k.id]); - }, - - updateObjects : function updateObjects(objs) { - var i; - - for(i = 0; i < objs.length; i++) { - publicFns.updateObject(objs[i]); + return this; + }; + Tween2.prototype.end = function() { + this._goToEnd = true; + this.update(this._startTime + this._duration); + return this; + }; + Tween2.prototype.pause = function(time) { + if (time === void 0) { + time = now(); } - }, - - updateObject : function updateObject(obj) { - fns.checkInit(true); - validator.hasKey(obj, k.id, k.id); - - fns.updateObjectById(obj[k.id]); - }, - - getPossibleCollisionsForObject : function getPossibleCollisionsForObject(obj) { - fns.checkInit(true); - validator.hasKey(obj, k.id, k.id); - - return fns.getObjectsByObject(obj); - }, - - getCollisionsForObject : function getCollisionsForObject(obj) { - var id, objects; - - fns.checkInit(true); - validator.hasKey(obj, k.id, k.id); - - objects = fns.getObjectsByObject(obj); - - for (id in objects) { - if (!fns.hasCollision(obj, objects[id])) { delete objects[id]; } + if (this._isPaused || !this._isPlaying) { + return this; } - - return objects; - }, - - getCount : function getCount() { - return Object.keys(data.objects_).length; - }, - - // Copies and returns data.objects_; - getObjects : function getObjects() { - var id, - result = {}; - - for (id in data.objects_) { - result[id] = data.objects_[id]; + this._isPaused = true; + this._pauseStart = time; + return this; + }; + Tween2.prototype.resume = function(time) { + if (time === void 0) { + time = now(); } - - return result; - }, - - getQuadrantCount : function getQuadrantCount(obj) { - if (obj) { return Object.keys(data.quadrants_[obj[k.id]]).length; } - return 1 + data.root_.getChildCount(true); - }, - - getQuadrantObjectCount : function getQuadrantObjectCount() { - return data.root_.getObjectCount(true); - }, - - debug : function debug(val) { - var id; - - if(val !== undefined){ - data.debug_ = val; - - // For testing purpose allow exposing private functions. - fns.checkInit(true); - for (id in debugFns) { this[id] = debugFns[id]; } - for (id in fns) { this[id] = fns[id]; } - - this.data_ = data; + if (!this._isPaused || !this._isPlaying) { + return this; } - - return data.debug_; - } - }; - - // Generate public functions. - for (id in publicFns) { this[id] = publicFns[id]; } - - this.setSize(size); - this.setQuadrantObjectsLimit(quadrantObjectsLimit); - this.setQuadrantLevelLimit(quadrantLevelLimit); -}; - -module.exports = Quadtree2; - -},{"./quadtree2helper":9,"./quadtree2quadrant":10,"./quadtree2validator":11,"vec2":7}],9:[function(require,module,exports){ -var Quadtree2Helper = { - fnName : function fnName(fn) { - var ret = fn.toString(); - ret = ret.substr('function '.length); - ret = ret.substr(0, ret.indexOf('(')); - return ret; - }, - - // A verbose exception generator helper. - thrower : function thrower(code, message, key) { - var error = code; - - if(key) { error += '_' + key; } - if(message) { error += ' - '; } - if(message && key) { error += key + ': '; } - if(message) { error += message; } - - throw new Error(error); - }, - - getIdsOfObjects : function getIdsOfObjects(hash) { - var result = []; - - for (var id in hash) { - result.push(hash[id].id_); - } - - return result; - }, - - compare : function compare(a,b) { - return a - b; - }, - - arrayDiffs : function arrayDiffs(arrA, arrB) { - var i = 0, - j = 0, - retA = [], - retB = []; - - arrA.sort(this.compare); - arrB.sort(this.compare); - - while (i < arrA.length && j < arrB.length) { - if (arrA[i] === arrB[j]) { - i++; - j++; - continue; - } - - if (arrA[i] < arrB[j]) { - retA.push(arrA[i]); - i++; - continue; - } else { - retB.push(arrB[j]); - j++; + this._isPaused = false; + this._startTime += time - this._pauseStart; + this._pauseStart = 0; + return this; + }; + Tween2.prototype.stopChainedTweens = function() { + for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) { + this._chainedTweens[i].stop(); + } + return this; + }; + Tween2.prototype.group = function(group) { + if (!group) { + console.warn("tween.group() without args has been removed, use group.add(tween) instead."); + return this; + } + group.add(this); + return this; + }; + Tween2.prototype.remove = function() { + var _a; + (_a = this._group) === null || _a === void 0 ? void 0 : _a.remove(this); + return this; + }; + Tween2.prototype.delay = function(amount) { + if (amount === void 0) { + amount = 0; + } + this._delayTime = amount; + return this; + }; + Tween2.prototype.repeat = function(times) { + if (times === void 0) { + times = 0; + } + this._initialRepeat = times; + this._repeat = times; + return this; + }; + Tween2.prototype.repeatDelay = function(amount) { + this._repeatDelayTime = amount; + return this; + }; + Tween2.prototype.yoyo = function(yoyo) { + if (yoyo === void 0) { + yoyo = false; + } + this._yoyo = yoyo; + return this; + }; + Tween2.prototype.easing = function(easingFunction) { + if (easingFunction === void 0) { + easingFunction = Easing.Linear.None; + } + this._easingFunction = easingFunction; + return this; + }; + Tween2.prototype.interpolation = function(interpolationFunction) { + if (interpolationFunction === void 0) { + interpolationFunction = Interpolation.Linear; + } + this._interpolationFunction = interpolationFunction; + return this; + }; + Tween2.prototype.chain = function() { + var tweens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tweens[_i] = arguments[_i]; + } + this._chainedTweens = tweens; + return this; + }; + Tween2.prototype.onStart = function(callback) { + this._onStartCallback = callback; + return this; + }; + Tween2.prototype.onEveryStart = function(callback) { + this._onEveryStartCallback = callback; + return this; + }; + Tween2.prototype.onUpdate = function(callback) { + this._onUpdateCallback = callback; + return this; + }; + Tween2.prototype.onRepeat = function(callback) { + this._onRepeatCallback = callback; + return this; + }; + Tween2.prototype.onComplete = function(callback) { + this._onCompleteCallback = callback; + return this; + }; + Tween2.prototype.onStop = function(callback) { + this._onStopCallback = callback; + return this; + }; + Tween2.prototype.update = function(time, autoStart) { + var _this2 = this; + var _a; + if (time === void 0) { + time = now(); + } + if (autoStart === void 0) { + autoStart = Tween2.autoStartOnUpdate; + } + if (this._isPaused) + return true; + var property; + if (!this._goToEnd && !this._isPlaying) { + if (autoStart) + this.start(time, true); + else + return false; + } + this._goToEnd = false; + if (time < this._startTime) { + return true; + } + if (this._onStartCallbackFired === false) { + if (this._onStartCallback) { + this._onStartCallback(this._object); + } + this._onStartCallbackFired = true; + } + if (this._onEveryStartCallbackFired === false) { + if (this._onEveryStartCallback) { + this._onEveryStartCallback(this._object); + } + this._onEveryStartCallbackFired = true; + } + var elapsedTime = time - this._startTime; + var durationAndDelay = this._duration + ((_a = this._repeatDelayTime) !== null && _a !== void 0 ? _a : this._delayTime); + var totalTime = this._duration + this._repeat * durationAndDelay; + var calculateElapsedPortion = function() { + if (_this2._duration === 0) + return 1; + if (elapsedTime > totalTime) { + return 1; + } + var timesRepeated = Math.trunc(elapsedTime / durationAndDelay); + var timeIntoCurrentRepeat = elapsedTime - timesRepeated * durationAndDelay; + var portion = Math.min(timeIntoCurrentRepeat / _this2._duration, 1); + if (portion === 0 && elapsedTime === _this2._duration) { + return 1; + } + return portion; + }; + var elapsed = calculateElapsedPortion(); + var value = this._easingFunction(elapsed); + this._updateProperties(this._object, this._valuesStart, this._valuesEnd, value); + if (this._onUpdateCallback) { + this._onUpdateCallback(this._object, elapsed); + } + if (this._duration === 0 || elapsedTime >= this._duration) { + if (this._repeat > 0) { + var completeCount = Math.min(Math.trunc((elapsedTime - this._duration) / durationAndDelay) + 1, this._repeat); + if (isFinite(this._repeat)) { + this._repeat -= completeCount; + } + for (property in this._valuesStartRepeat) { + if (!this._yoyo && typeof this._valuesEnd[property] === "string") { + this._valuesStartRepeat[property] = // eslint-disable-next-line + // @ts-ignore FIXME? + this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]); + } + if (this._yoyo) { + this._swapEndStartRepeatValues(property); + } + this._valuesStart[property] = this._valuesStartRepeat[property]; + } + if (this._yoyo) { + this._reversed = !this._reversed; + } + this._startTime += durationAndDelay * completeCount; + if (this._onRepeatCallback) { + this._onRepeatCallback(this._object); + } + this._onEveryStartCallbackFired = false; + return true; + } else { + if (this._onCompleteCallback) { + this._onCompleteCallback(this._object); + } + for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) { + this._chainedTweens[i].start(this._startTime + this._duration, false); + } + this._isPlaying = false; + return false; + } + } + return true; + }; + Tween2.prototype._updateProperties = function(_object, _valuesStart, _valuesEnd, value) { + for (var property in _valuesEnd) { + if (_valuesStart[property] === void 0) { + continue; + } + var start = _valuesStart[property] || 0; + var end = _valuesEnd[property]; + var startIsArray = Array.isArray(_object[property]); + var endIsArray = Array.isArray(end); + var isInterpolationList = !startIsArray && endIsArray; + if (isInterpolationList) { + _object[property] = this._interpolationFunction(end, value); + } else if (typeof end === "object" && end) { + this._updateProperties(_object[property], start, end, value); + } else { + end = this._handleRelativeValue(start, end); + if (typeof end === "number") { + _object[property] = start + (end - start) * value; + } + } + } + }; + Tween2.prototype._handleRelativeValue = function(start, end) { + if (typeof end !== "string") { + return end; + } + if (end.charAt(0) === "+" || end.charAt(0) === "-") { + return start + parseFloat(end); + } + return parseFloat(end); + }; + Tween2.prototype._swapEndStartRepeatValues = function(property) { + var tmp = this._valuesStartRepeat[property]; + var endValue = this._valuesEnd[property]; + if (typeof endValue === "string") { + this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(endValue); + } else { + this._valuesStartRepeat[property] = this._valuesEnd[property]; + } + this._valuesEnd[property] = tmp; + }; + Tween2.autoStartOnUpdate = false; + return Tween2; + })() + ); + var VERSION = "25.0.0"; + var nextId = Sequence.nextId; + var TWEEN = mainGroup; + var getAll = TWEEN.getAll.bind(TWEEN); + var removeAll = TWEEN.removeAll.bind(TWEEN); + var add = TWEEN.add.bind(TWEEN); + var remove = TWEEN.remove.bind(TWEEN); + var update = TWEEN.update.bind(TWEEN); + var exports$1 = { + Easing, + Group, + Interpolation, + now, + Sequence, + nextId, + Tween, + VERSION, + /** + * @deprecated The global TWEEN Group will be removed in a following major + * release. To migrate, create a `new Group()` instead of using `TWEEN` as a + * group. + * + * Old code: + * + * ```js + * import * as TWEEN from '@tweenjs/tween.js' + * + * //... + * + * const tween = new TWEEN.Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * TWEEN.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + * + * New code: + * + * ```js + * import {Tween, Group} from '@tweenjs/tween.js' + * + * //... + * + * const tween = new Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * const group = new Group() + * group.add(tween) + * group.add(tween2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * group.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + */ + getAll, + /** + * @deprecated The global TWEEN Group will be removed in a following major + * release. To migrate, create a `new Group()` instead of using `TWEEN` as a + * group. + * + * Old code: + * + * ```js + * import * as TWEEN from '@tweenjs/tween.js' + * + * //... + * + * const tween = new TWEEN.Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * TWEEN.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + * + * New code: + * + * ```js + * import {Tween, Group} from '@tweenjs/tween.js' + * + * //... + * + * const tween = new Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * const group = new Group() + * group.add(tween) + * group.add(tween2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * group.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + */ + removeAll, + /** + * @deprecated The global TWEEN Group will be removed in a following major + * release. To migrate, create a `new Group()` instead of using `TWEEN` as a + * group. + * + * Old code: + * + * ```js + * import * as TWEEN from '@tweenjs/tween.js' + * + * //... + * + * const tween = new TWEEN.Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * TWEEN.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + * + * New code: + * + * ```js + * import {Tween, Group} from '@tweenjs/tween.js' + * + * //... + * + * const tween = new Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * const group = new Group() + * group.add(tween) + * group.add(tween2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * group.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + */ + add, + /** + * @deprecated The global TWEEN Group will be removed in a following major + * release. To migrate, create a `new Group()` instead of using `TWEEN` as a + * group. + * + * Old code: + * + * ```js + * import * as TWEEN from '@tweenjs/tween.js' + * + * //... + * + * const tween = new TWEEN.Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * TWEEN.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + * + * New code: + * + * ```js + * import {Tween, Group} from '@tweenjs/tween.js' + * + * //... + * + * const tween = new Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * const group = new Group() + * group.add(tween) + * group.add(tween2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * group.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + */ + remove, + /** + * @deprecated The global TWEEN Group will be removed in a following major + * release. To migrate, create a `new Group()` instead of using `TWEEN` as a + * group. + * + * Old code: + * + * ```js + * import * as TWEEN from '@tweenjs/tween.js' + * + * //... + * + * const tween = new TWEEN.Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * TWEEN.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + * + * New code: + * + * ```js + * import {Tween, Group} from '@tweenjs/tween.js' + * + * //... + * + * const tween = new Tween(obj) + * const tween2 = new TWEEN.Tween(obj2) + * + * //... + * + * const group = new Group() + * group.add(tween) + * group.add(tween2) + * + * //... + * + * requestAnimationFrame(function loop(time) { + * group.update(time) + * requestAnimationFrame(loop) + * }) + * ``` + */ + update + }; + tween.Easing = Easing; + tween.Group = Group; + tween.Interpolation = Interpolation; + tween.Sequence = Sequence; + tween.Tween = Tween; + tween.VERSION = VERSION; + tween.add = add; + tween.default = exports$1; + tween.getAll = getAll; + tween.nextId = nextId; + tween.now = now; + tween.remove = remove; + tween.removeAll = removeAll; + tween.update = update; + return tween; + } + var three = {}; + /** + * @license + * Copyright 2010-2026 Three.js Authors + * SPDX-License-Identifier: MIT + */ + var hasRequiredThree; + function requireThree() { + if (hasRequiredThree) return three; + hasRequiredThree = 1; + const REVISION = "184"; + const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; + const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; + const CullFaceNone = 0; + const CullFaceBack = 1; + const CullFaceFront = 2; + const CullFaceFrontBack = 3; + const BasicShadowMap = 0; + const PCFShadowMap = 1; + const PCFSoftShadowMap = 2; + const VSMShadowMap = 3; + const FrontSide = 0; + const BackSide = 1; + const DoubleSide = 2; + const NoBlending = 0; + const NormalBlending = 1; + const AdditiveBlending = 2; + const SubtractiveBlending = 3; + const MultiplyBlending = 4; + const CustomBlending = 5; + const MaterialBlending = 6; + const AddEquation = 100; + const SubtractEquation = 101; + const ReverseSubtractEquation = 102; + const MinEquation = 103; + const MaxEquation = 104; + const ZeroFactor = 200; + const OneFactor = 201; + const SrcColorFactor = 202; + const OneMinusSrcColorFactor = 203; + const SrcAlphaFactor = 204; + const OneMinusSrcAlphaFactor = 205; + const DstAlphaFactor = 206; + const OneMinusDstAlphaFactor = 207; + const DstColorFactor = 208; + const OneMinusDstColorFactor = 209; + const SrcAlphaSaturateFactor = 210; + const ConstantColorFactor = 211; + const OneMinusConstantColorFactor = 212; + const ConstantAlphaFactor = 213; + const OneMinusConstantAlphaFactor = 214; + const NeverDepth = 0; + const AlwaysDepth = 1; + const LessDepth = 2; + const LessEqualDepth = 3; + const EqualDepth = 4; + const GreaterEqualDepth = 5; + const GreaterDepth = 6; + const NotEqualDepth = 7; + const MultiplyOperation = 0; + const MixOperation = 1; + const AddOperation = 2; + const NoToneMapping = 0; + const LinearToneMapping = 1; + const ReinhardToneMapping = 2; + const CineonToneMapping = 3; + const ACESFilmicToneMapping = 4; + const CustomToneMapping = 5; + const AgXToneMapping = 6; + const NeutralToneMapping = 7; + const AttachedBindMode = "attached"; + const DetachedBindMode = "detached"; + const UVMapping = 300; + const CubeReflectionMapping = 301; + const CubeRefractionMapping = 302; + const EquirectangularReflectionMapping = 303; + const EquirectangularRefractionMapping = 304; + const CubeUVReflectionMapping = 306; + const RepeatWrapping = 1e3; + const ClampToEdgeWrapping = 1001; + const MirroredRepeatWrapping = 1002; + const NearestFilter = 1003; + const NearestMipmapNearestFilter = 1004; + const NearestMipMapNearestFilter = 1004; + const NearestMipmapLinearFilter = 1005; + const NearestMipMapLinearFilter = 1005; + const LinearFilter = 1006; + const LinearMipmapNearestFilter = 1007; + const LinearMipMapNearestFilter = 1007; + const LinearMipmapLinearFilter = 1008; + const LinearMipMapLinearFilter = 1008; + const UnsignedByteType = 1009; + const ByteType = 1010; + const ShortType = 1011; + const UnsignedShortType = 1012; + const IntType = 1013; + const UnsignedIntType = 1014; + const FloatType = 1015; + const HalfFloatType = 1016; + const UnsignedShort4444Type = 1017; + const UnsignedShort5551Type = 1018; + const UnsignedInt248Type = 1020; + const UnsignedInt5999Type = 35902; + const UnsignedInt101111Type = 35899; + const AlphaFormat = 1021; + const RGBFormat = 1022; + const RGBAFormat = 1023; + const DepthFormat = 1026; + const DepthStencilFormat = 1027; + const RedFormat = 1028; + const RedIntegerFormat = 1029; + const RGFormat = 1030; + const RGIntegerFormat = 1031; + const RGBIntegerFormat = 1032; + const RGBAIntegerFormat = 1033; + const RGB_S3TC_DXT1_Format = 33776; + const RGBA_S3TC_DXT1_Format = 33777; + const RGBA_S3TC_DXT3_Format = 33778; + const RGBA_S3TC_DXT5_Format = 33779; + const RGB_PVRTC_4BPPV1_Format = 35840; + const RGB_PVRTC_2BPPV1_Format = 35841; + const RGBA_PVRTC_4BPPV1_Format = 35842; + const RGBA_PVRTC_2BPPV1_Format = 35843; + const RGB_ETC1_Format = 36196; + const RGB_ETC2_Format = 37492; + const RGBA_ETC2_EAC_Format = 37496; + const R11_EAC_Format = 37488; + const SIGNED_R11_EAC_Format = 37489; + const RG11_EAC_Format = 37490; + const SIGNED_RG11_EAC_Format = 37491; + const RGBA_ASTC_4x4_Format = 37808; + const RGBA_ASTC_5x4_Format = 37809; + const RGBA_ASTC_5x5_Format = 37810; + const RGBA_ASTC_6x5_Format = 37811; + const RGBA_ASTC_6x6_Format = 37812; + const RGBA_ASTC_8x5_Format = 37813; + const RGBA_ASTC_8x6_Format = 37814; + const RGBA_ASTC_8x8_Format = 37815; + const RGBA_ASTC_10x5_Format = 37816; + const RGBA_ASTC_10x6_Format = 37817; + const RGBA_ASTC_10x8_Format = 37818; + const RGBA_ASTC_10x10_Format = 37819; + const RGBA_ASTC_12x10_Format = 37820; + const RGBA_ASTC_12x12_Format = 37821; + const RGBA_BPTC_Format = 36492; + const RGB_BPTC_SIGNED_Format = 36494; + const RGB_BPTC_UNSIGNED_Format = 36495; + const RED_RGTC1_Format = 36283; + const SIGNED_RED_RGTC1_Format = 36284; + const RED_GREEN_RGTC2_Format = 36285; + const SIGNED_RED_GREEN_RGTC2_Format = 36286; + const LoopOnce = 2200; + const LoopRepeat = 2201; + const LoopPingPong = 2202; + const InterpolateDiscrete = 2300; + const InterpolateLinear = 2301; + const InterpolateSmooth = 2302; + const InterpolateBezier = 2303; + const ZeroCurvatureEnding = 2400; + const ZeroSlopeEnding = 2401; + const WrapAroundEnding = 2402; + const NormalAnimationBlendMode = 2500; + const AdditiveAnimationBlendMode = 2501; + const TrianglesDrawMode = 0; + const TriangleStripDrawMode = 1; + const TriangleFanDrawMode = 2; + const BasicDepthPacking = 3200; + const RGBADepthPacking = 3201; + const RGBDepthPacking = 3202; + const RGDepthPacking = 3203; + const TangentSpaceNormalMap = 0; + const ObjectSpaceNormalMap = 1; + const NoColorSpace = ""; + const SRGBColorSpace = "srgb"; + const LinearSRGBColorSpace = "srgb-linear"; + const LinearTransfer = "linear"; + const SRGBTransfer = "srgb"; + const NoNormalPacking = ""; + const NormalRGPacking = "rg"; + const NormalGAPacking = "ga"; + const ZeroStencilOp = 0; + const KeepStencilOp = 7680; + const ReplaceStencilOp = 7681; + const IncrementStencilOp = 7682; + const DecrementStencilOp = 7683; + const IncrementWrapStencilOp = 34055; + const DecrementWrapStencilOp = 34056; + const InvertStencilOp = 5386; + const NeverStencilFunc = 512; + const LessStencilFunc = 513; + const EqualStencilFunc = 514; + const LessEqualStencilFunc = 515; + const GreaterStencilFunc = 516; + const NotEqualStencilFunc = 517; + const GreaterEqualStencilFunc = 518; + const AlwaysStencilFunc = 519; + const NeverCompare = 512; + const LessCompare = 513; + const EqualCompare = 514; + const LessEqualCompare = 515; + const GreaterCompare = 516; + const NotEqualCompare = 517; + const GreaterEqualCompare = 518; + const AlwaysCompare = 519; + const StaticDrawUsage = 35044; + const DynamicDrawUsage = 35048; + const StreamDrawUsage = 35040; + const StaticReadUsage = 35045; + const DynamicReadUsage = 35049; + const StreamReadUsage = 35041; + const StaticCopyUsage = 35046; + const DynamicCopyUsage = 35050; + const StreamCopyUsage = 35042; + const GLSL1 = "100"; + const GLSL3 = "300 es"; + const WebGLCoordinateSystem = 2e3; + const WebGPUCoordinateSystem = 2001; + const TimestampQuery = { + COMPUTE: "compute", + RENDER: "render" + }; + const InterpolationSamplingType = { + PERSPECTIVE: "perspective", + LINEAR: "linear", + FLAT: "flat" + }; + const InterpolationSamplingMode = { + NORMAL: "normal", + CENTROID: "centroid", + SAMPLE: "sample", + FIRST: "first", + EITHER: "either" + }; + const Compatibility = { + TEXTURE_COMPARE: "depthTextureCompare" + }; + function arrayNeedsUint32(array) { + for (let i = array.length - 1; i >= 0; --i) { + if (array[i] >= 65535) return true; } + return false; } - - if(i < arrA.length) { - retA.push.apply(retA, arrA.slice(i, arrA.length)); - } else { - retB.push.apply(retB, arrB.slice(j, arrB.length)); + const TYPED_ARRAYS = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array + }; + function getTypedArray(type, buffer) { + return new TYPED_ARRAYS[type](buffer); } - - return [retA, retB]; - } -}; - -module.exports = Quadtree2Helper; - -},{}],10:[function(require,module,exports){ -var Quadtree2Quadrant = function Quadtree2Quadrant(leftTop, size, id, parent) { - this.leftTop_ = leftTop.clone(); - this.children_ = []; - this.objects_ = {}; - this.objectCount_ = 0; - this.id_ = id || 0; - this.parent_ = parent; - this.refactoring_ = false; - - this.setSize(size); -}; - -Quadtree2Quadrant.prototype = { - setSize : function setSize(size) { - if(!size) { return; } - - this.size_ = size; - this.rad_ = size.multiply(0.5, true); - this.center_ = this.leftTop_.add(this.rad_, true); - - this.leftBot_ = this.leftTop_.clone(); - this.leftBot_.y += size.y; - this.rightTop_ = this.leftTop_.clone(); - this.rightTop_.x += size.x; - this.rightBot_ = this.leftTop_.add(size, true); - - this.leftMid_ = this.center_.clone(); - this.leftMid_.x = this.leftTop_.x; - this.topMid_ = this.center_.clone(); - this.topMid_.y = this.leftTop_.y; - }, - - makeChildren : function makeChildren(id) { - if (this.children_.length > 0) { return false; } - - this.children_.push( - new Quadtree2Quadrant(this.leftTop_, this.rad_, id++, this), - new Quadtree2Quadrant(this.topMid_, this.rad_, id++, this), - new Quadtree2Quadrant(this.leftMid_, this.rad_, id++, this), - new Quadtree2Quadrant(this.center_, this.rad_, id++, this) - ); - - return id; - }, - - looseChildren : function looseChildren() { - this.children_ = []; - }, - - addObjects : function addObjects(objs) { - var id; - - for (id in objs) { - this.addObject(id, objs[id]); + function isTypedArray(array) { + return ArrayBuffer.isView(array) && !(array instanceof DataView); } - }, - - addObject : function addObject(id, obj) { - this.objectCount_++; - this.objects_[id] = obj; - }, - - removeObjects : function removeObjects(removed, dir) { - var id; - - if (!removed) { removed = []; } - - for (id in this.objects_) { - removed.push({ obj : this.objects_[id], quadrant : this }); - delete this.objects_[id]; + function createElementNS(name) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name); } - - this.objectCount_ = 0; - - if (!dir || dir === 1) { - if (this.parent_) { this.parent_.removeObjects(removed, 1); } + function createCanvasElement() { + const canvas = createElementNS("canvas"); + canvas.style.display = "block"; + return canvas; } - - if (!dir || dir === -1) { - this.children_.forEach(function(child) { - child.removeObjects(removed, -1); - }); + const _cache = {}; + let _setConsoleFunction = null; + function setConsoleFunction(fn) { + _setConsoleFunction = fn; } - - return removed; - }, - - removeObject : function removeObject(id) { - var result = this.objects_[id]; - this.objectCount_--; - delete(this.objects_[id]); - return result; - }, - - getObjectCountForLimit : function getObjectCountForLimit() { - var i, - id, - objects = {}; - - for (id in this.objects_) { - objects[id] = true; + function getConsoleFunction() { + return _setConsoleFunction; } - - for (i = 0; i < this.children_.length; i++) { - for (id in this.children_[i].objects_) { - objects[id] = true; + function log(...params) { + const message = "THREE." + params.shift(); + if (_setConsoleFunction) { + _setConsoleFunction("log", message, ...params); + } else { + console.log(message, ...params); } } - - return Object.keys(objects).length; - }, - - getObjectCount : function getObjectCount(recursive, onelevel) { - var result = this.objectCount_; - - if (recursive) { - this.children_.forEach(function(child) { - result += child.getObjectCount(!onelevel && recursive); - }); + function enhanceLogMessage(params) { + const message = params[0]; + if (typeof message === "string" && message.startsWith("TSL:")) { + const stackTrace = params[1]; + if (stackTrace && stackTrace.isStackTrace) { + params[0] += " " + stackTrace.getLocation(); + } else { + params[1] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'; + } + } + return params; } - - return result; - }, - - intersectingChildren : function intersectingChildren(pos, rad) { - return this.children_.filter(function(child) { - return child.intersects(pos, rad); - }); - }, - - intersects : function intersects(pos, rad) { - var dist = pos.subtract(this.center_, true).abs(), - cornerDist; - - if (dist.x > this.rad_.x + rad) { return false; } - if (dist.y > this.rad_.y + rad) { return false; } - - if (dist.x <= this.rad_.x) { return true; } - if (dist.y <= this.rad_.y) { return true; } - - cornerDistSq = Math.pow(dist.x - this.rad_.x, 2) + Math.pow(dist.y - this.rad_.y, 2); - return cornerDistSq <= Math.pow(rad, 2); - }, - - hasChildren : function hasChildren() { - return this.getChildCount() !== 0; - }, - - getChildCount : function getChildCount(recursive) { - var count = this.children_.length; - - if (recursive) { - this.children_.forEach(function(child) { - count += child.getChildCount(recursive); - }); + function warn(...params) { + params = enhanceLogMessage(params); + const message = "THREE." + params.shift(); + if (_setConsoleFunction) { + _setConsoleFunction("warn", message, ...params); + } else { + const stackTrace = params[0]; + if (stackTrace && stackTrace.isStackTrace) { + console.warn(stackTrace.getError(message)); + } else { + console.warn(message, ...params); + } + } } - - return count; - }, - - getChildren : function getChildren(recursive, result) { - if (!result) result = []; - - result.push.apply(result, this.children_); - - if (recursive) { - this.children_.forEach(function(child) { - child.getChildren(recursive, result); + function error(...params) { + params = enhanceLogMessage(params); + const message = "THREE." + params.shift(); + if (_setConsoleFunction) { + _setConsoleFunction("error", message, ...params); + } else { + const stackTrace = params[0]; + if (stackTrace && stackTrace.isStackTrace) { + console.error(stackTrace.getError(message)); + } else { + console.error(message, ...params); + } + } + } + function warnOnce(...params) { + const message = params.join(" "); + if (message in _cache) return; + _cache[message] = true; + warn(...params); + } + function probeAsync(gl, sync, interval) { + return new Promise(function(resolve, reject) { + function probe() { + switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case gl.WAIT_FAILED: + reject(); + break; + case gl.TIMEOUT_EXPIRED: + setTimeout(probe, interval); + break; + default: + resolve(); + } + } + setTimeout(probe, interval); }); } - - return result; - }, - - getObjectsUp : function getObjectsUp(result) { - var id; - - if (result.quadrants[this.id_]) { - return; + const ReversedDepthFuncs = { + [NeverDepth]: AlwaysDepth, + [LessDepth]: GreaterDepth, + [EqualDepth]: NotEqualDepth, + [LessEqualDepth]: GreaterEqualDepth, + [AlwaysDepth]: NeverDepth, + [GreaterDepth]: LessDepth, + [NotEqualDepth]: EqualDepth, + [GreaterEqualDepth]: LessEqualDepth + }; + class EventDispatcher { + /** + * Adds the given event listener to the given event type. + * + * @param {string} type - The type of event to listen to. + * @param {Function} listener - The function that gets called when the event is fired. + */ + addEventListener(type, listener) { + if (this._listeners === void 0) this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === void 0) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + /** + * Returns `true` if the given event listener has been added to the given event type. + * + * @param {string} type - The type of event. + * @param {Function} listener - The listener to check. + * @return {boolean} Whether the given event listener has been added to the given event type. + */ + hasEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === void 0) return false; + return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1; + } + /** + * Removes the given event listener from the given event type. + * + * @param {string} type - The type of event. + * @param {Function} listener - The listener to remove. + */ + removeEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === void 0) return; + const listenerArray = listeners[type]; + if (listenerArray !== void 0) { + const index = listenerArray.indexOf(listener); + if (index !== -1) { + listenerArray.splice(index, 1); + } + } + } + /** + * Dispatches an event object. + * + * @param {Object} event - The event that gets fired. + */ + dispatchEvent(event) { + const listeners = this._listeners; + if (listeners === void 0) return; + const listenerArray = listeners[event.type]; + if (listenerArray !== void 0) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l = array.length; i < l; i++) { + array[i].call(this, event); + } + event.target = null; + } + } } - - result.quadrants[this.id_] = true; - - for (id in this.objects_) { - result.objects[id] = this.objects_[id]; + const _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; + let _seed = 1234567; + const DEG2RAD = Math.PI / 180; + const RAD2DEG = 180 / Math.PI; + function generateUUID() { + const d0 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d2 = Math.random() * 4294967295 | 0; + const d3 = Math.random() * 4294967295 | 0; + const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255]; + return uuid.toLowerCase(); } - - if (this.parent_) { - this.parent_.getObjectsUp(result); + function clamp(value, min, max) { + return Math.max(min, Math.min(max, value)); } - }, - - getObjectsDown : function getObjectsDown(result) { - var id; - - if (result.quadrants[this.id_]) { - return; + function euclideanModulo(n, m) { + return (n % m + m) % m; } - - result.quadrants[this.id_] = true; - - for (id in this.objects_) { - result.objects[id] = this.objects_[id]; + function mapLinear(x, a1, a2, b1, b2) { + return b1 + (x - a1) * (b2 - b1) / (a2 - a1); } - - for (id = 0; id < this.children_.length; id++) { - this.children_[id].getObjectsDown(result); + function inverseLerp(x, y, value) { + if (x !== y) { + return (value - x) / (y - x); + } else { + return 0; + } } - } -}; - -module.exports = Quadtree2Quadrant; - -},{}],11:[function(require,module,exports){ -var Vec2 = require('vec2'), - Quadtree2Helper = require('./quadtree2helper'), - Quadtree2Validator = function Quadtree2Validator() {}; - -Quadtree2Validator.prototype = { - isNumber : function isNumber(param, key) { - if ('number' !== typeof param) { - Quadtree2Helper.thrower('NaN', 'Not a Number', key); + function lerp(x, y, t) { + return (1 - t) * x + t * y; } - }, - - isString : function isString(param, key) { - if (!(typeof param === 'string' || param instanceof String)) { - Quadtree2Helper.thrower('NaS', 'Not a String', key); + function damp(x, y, lambda, dt) { + return lerp(x, y, 1 - Math.exp(-lambda * dt)); } - }, - - isVec2 : function isVec2(param, key) { - var throwIt = false; - - throwIt = 'object' !== typeof param || param.x === undefined || param.y === undefined; - - if(throwIt) { - Quadtree2Helper.thrower('NaV', 'Not a Vec2', key); + function pingpong(x, length = 1) { + return length - Math.abs(euclideanModulo(x, length * 2) - length); } - }, - - isDefined : function isDefined(param, key) { - if (param === undefined) { - Quadtree2Helper.thrower('ND', 'Not defined', key); + function smoothstep(x, min, max) { + if (x <= min) return 0; + if (x >= max) return 1; + x = (x - min) / (max - min); + return x * x * (3 - 2 * x); } - }, - - isObject : function isObject(param, key) { - if ('object' !== typeof param) { - Quadtree2Helper.thrower('NaO', 'Not an Object', key); + function smootherstep(x, min, max) { + if (x <= min) return 0; + if (x >= max) return 1; + x = (x - min) / (max - min); + return x * x * x * (x * (x * 6 - 15) + 10); } - }, - - hasKey : function hasKey(obj, k, key) { - this.isDefined(obj, 'obj'); - if ( Object.keys(obj).indexOf(k.toString()) === -1 ) { - Quadtree2Helper.thrower('OhnK', 'Object has no key', key + k); + function randInt(low, high) { + return low + Math.floor(Math.random() * (high - low + 1)); } - }, - - hasNoKey : function hasNoKey(obj, k, key) { - this.isDefined(obj, 'obj'); - if ( Object.keys(obj).indexOf(k.toString()) !== -1 ) { - Quadtree2Helper.thrower('OhK', 'Object has key', key + k); + function randFloat(low, high) { + return low + Math.random() * (high - low); } - }, - - fnFalse : function fn(cb) { - if(cb()) { - Quadtree2Helper.thrower('FarT', 'function already returns true', Quadtree2Helper.fnName(cb)); + function randFloatSpread(range) { + return range * (0.5 - Math.random()); } - }, - - byCallbackObject : function byCallbackObject(obj, cbObj, keyTable) { - var key; - for (key in cbObj) { - if (keyTable !== undefined) { - cbObj[key](obj[keyTable[key]], keyTable[key]); - } else { - cbObj[key](obj[key], key); + function seededRandom(s) { + if (s !== void 0) _seed = s; + let t = _seed += 1831565813; + t = Math.imul(t ^ t >>> 15, t | 1); + t ^= t + Math.imul(t ^ t >>> 7, t | 61); + return ((t ^ t >>> 14) >>> 0) / 4294967296; + } + function degToRad(degrees) { + return degrees * DEG2RAD; + } + function radToDeg(radians) { + return radians * RAD2DEG; + } + function isPowerOfTwo(value) { + return (value & value - 1) === 0 && value !== 0; + } + function ceilPowerOfTwo(value) { + return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); + } + function floorPowerOfTwo(value) { + return Math.pow(2, Math.floor(Math.log(value) / Math.LN2)); + } + function setQuaternionFromProperEuler(q, a, b, c, order) { + const cos = Math.cos; + const sin = Math.sin; + const c2 = cos(b / 2); + const s2 = sin(b / 2); + const c13 = cos((a + c) / 2); + const s13 = sin((a + c) / 2); + const c1_3 = cos((a - c) / 2); + const s1_3 = sin((a - c) / 2); + const c3_1 = cos((c - a) / 2); + const s3_1 = sin((c - a) / 2); + switch (order) { + case "XYX": + q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13); + break; + case "YZY": + q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13); + break; + case "ZXZ": + q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13); + break; + case "XZX": + q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13); + break; + case "YXY": + q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13); + break; + case "ZYZ": + q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13); + break; + default: + warn("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); } } - } -}; - -module.exports = Quadtree2Validator; - -},{"./quadtree2helper":9,"vec2":7}],12:[function(require,module,exports){ -var self = self || {};/** - * @author mrdoob / http://mrdoob.com/ - * @author Larry Battle / http://bateru.com/news - * @author bhouston / http://exocortex.com - */ - -var THREE = { REVISION: '66' }; - -self.console = self.console || { - - info: function () {}, - log: function () {}, - debug: function () {}, - warn: function () {}, - error: function () {} - -}; - -// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ -// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating - -// requestAnimationFrame polyfill by Erik Möller -// fixes from Paul Irish and Tino Zijdel -// using 'self' instead of 'window' for compatibility with both NodeJS and IE10. -( function () { - - var lastTime = 0; - var vendors = [ 'ms', 'moz', 'webkit', 'o' ]; - - for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) { - - self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ]; - self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ]; - - } - - if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) { - - self.requestAnimationFrame = function ( callback ) { - - var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) ); - var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall ); - lastTime = currTime + timeToCall; - return id; - - }; - - } - - if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) { - - self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) }; - - } - -}() ); - -// GL STATE CONSTANTS - -THREE.CullFaceNone = 0; -THREE.CullFaceBack = 1; -THREE.CullFaceFront = 2; -THREE.CullFaceFrontBack = 3; - -THREE.FrontFaceDirectionCW = 0; -THREE.FrontFaceDirectionCCW = 1; - -// SHADOWING TYPES - -THREE.BasicShadowMap = 0; -THREE.PCFShadowMap = 1; -THREE.PCFSoftShadowMap = 2; - -// MATERIAL CONSTANTS - -// side - -THREE.FrontSide = 0; -THREE.BackSide = 1; -THREE.DoubleSide = 2; - -// shading - -THREE.NoShading = 0; -THREE.FlatShading = 1; -THREE.SmoothShading = 2; - -// colors - -THREE.NoColors = 0; -THREE.FaceColors = 1; -THREE.VertexColors = 2; - -// blending modes - -THREE.NoBlending = 0; -THREE.NormalBlending = 1; -THREE.AdditiveBlending = 2; -THREE.SubtractiveBlending = 3; -THREE.MultiplyBlending = 4; -THREE.CustomBlending = 5; - -// custom blending equations -// (numbers start from 100 not to clash with other -// mappings to OpenGL constants defined in Texture.js) - -THREE.AddEquation = 100; -THREE.SubtractEquation = 101; -THREE.ReverseSubtractEquation = 102; - -// custom blending destination factors - -THREE.ZeroFactor = 200; -THREE.OneFactor = 201; -THREE.SrcColorFactor = 202; -THREE.OneMinusSrcColorFactor = 203; -THREE.SrcAlphaFactor = 204; -THREE.OneMinusSrcAlphaFactor = 205; -THREE.DstAlphaFactor = 206; -THREE.OneMinusDstAlphaFactor = 207; - -// custom blending source factors - -//THREE.ZeroFactor = 200; -//THREE.OneFactor = 201; -//THREE.SrcAlphaFactor = 204; -//THREE.OneMinusSrcAlphaFactor = 205; -//THREE.DstAlphaFactor = 206; -//THREE.OneMinusDstAlphaFactor = 207; -THREE.DstColorFactor = 208; -THREE.OneMinusDstColorFactor = 209; -THREE.SrcAlphaSaturateFactor = 210; - - -// TEXTURE CONSTANTS - -THREE.MultiplyOperation = 0; -THREE.MixOperation = 1; -THREE.AddOperation = 2; - -// Mapping modes - -THREE.UVMapping = function () {}; - -THREE.CubeReflectionMapping = function () {}; -THREE.CubeRefractionMapping = function () {}; - -THREE.SphericalReflectionMapping = function () {}; -THREE.SphericalRefractionMapping = function () {}; - -// Wrapping modes - -THREE.RepeatWrapping = 1000; -THREE.ClampToEdgeWrapping = 1001; -THREE.MirroredRepeatWrapping = 1002; - -// Filters - -THREE.NearestFilter = 1003; -THREE.NearestMipMapNearestFilter = 1004; -THREE.NearestMipMapLinearFilter = 1005; -THREE.LinearFilter = 1006; -THREE.LinearMipMapNearestFilter = 1007; -THREE.LinearMipMapLinearFilter = 1008; - -// Data types - -THREE.UnsignedByteType = 1009; -THREE.ByteType = 1010; -THREE.ShortType = 1011; -THREE.UnsignedShortType = 1012; -THREE.IntType = 1013; -THREE.UnsignedIntType = 1014; -THREE.FloatType = 1015; - -// Pixel types - -//THREE.UnsignedByteType = 1009; -THREE.UnsignedShort4444Type = 1016; -THREE.UnsignedShort5551Type = 1017; -THREE.UnsignedShort565Type = 1018; - -// Pixel formats - -THREE.AlphaFormat = 1019; -THREE.RGBFormat = 1020; -THREE.RGBAFormat = 1021; -THREE.LuminanceFormat = 1022; -THREE.LuminanceAlphaFormat = 1023; - -// Compressed texture formats - -THREE.RGB_S3TC_DXT1_Format = 2001; -THREE.RGBA_S3TC_DXT1_Format = 2002; -THREE.RGBA_S3TC_DXT3_Format = 2003; -THREE.RGBA_S3TC_DXT5_Format = 2004; - -/* -// Potential future PVRTC compressed texture formats -THREE.RGB_PVRTC_4BPPV1_Format = 2100; -THREE.RGB_PVRTC_2BPPV1_Format = 2101; -THREE.RGBA_PVRTC_4BPPV1_Format = 2102; -THREE.RGBA_PVRTC_2BPPV1_Format = 2103; -*/ -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Color = function ( color ) { - - if ( arguments.length === 3 ) { - - return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] ); - - } - - return this.set( color ) - -}; - -THREE.Color.prototype = { - - constructor: THREE.Color, - - r: 1, g: 1, b: 1, - - set: function ( value ) { - - if ( value instanceof THREE.Color ) { - - this.copy( value ); - - } else if ( typeof value === 'number' ) { - - this.setHex( value ); - - } else if ( typeof value === 'string' ) { - - this.setStyle( value ); - - } - - return this; - - }, - - setHex: function ( hex ) { - - hex = Math.floor( hex ); - - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; - - return this; - - }, - - setRGB: function ( r, g, b ) { - - this.r = r; - this.g = g; - this.b = b; - - return this; - - }, - - setHSL: function ( h, s, l ) { - - // h,s,l ranges are in 0.0 - 1.0 - - if ( s === 0 ) { - - this.r = this.g = this.b = l; - - } else { - - var hue2rgb = function ( p, q, t ) { - - if ( t < 0 ) t += 1; - if ( t > 1 ) t -= 1; - if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; - if ( t < 1 / 2 ) return q; - if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); - return p; - - }; - - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; - - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); - - } - - return this; - - }, - - setStyle: function ( style ) { - - // rgb(255,0,0) - - if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) { - - var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style ); - - this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; - this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; - this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - - return this; - - } - - // rgb(100%,0%,0%) - - if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) { - - var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style ); - - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; - - return this; - - } - - // #ff0000 - - if ( /^\#([0-9a-f]{6})$/i.test( style ) ) { - - var color = /^\#([0-9a-f]{6})$/i.exec( style ); - - this.setHex( parseInt( color[ 1 ], 16 ) ); - - return this; - - } - - // #f00 - - if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) { - - var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style ); - - this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) ); - - return this; - - } - - // red - - if ( /^(\w+)$/i.test( style ) ) { - - this.setHex( THREE.ColorKeywords[ style ] ); - - return this; - - } - - - }, - - copy: function ( color ) { - - this.r = color.r; - this.g = color.g; - this.b = color.b; - - return this; - - }, - - copyGammaToLinear: function ( color ) { - - this.r = color.r * color.r; - this.g = color.g * color.g; - this.b = color.b * color.b; - - return this; - - }, - - copyLinearToGamma: function ( color ) { - - this.r = Math.sqrt( color.r ); - this.g = Math.sqrt( color.g ); - this.b = Math.sqrt( color.b ); - - return this; - - }, - - convertGammaToLinear: function () { - - var r = this.r, g = this.g, b = this.b; - - this.r = r * r; - this.g = g * g; - this.b = b * b; - - return this; - - }, - - convertLinearToGamma: function () { - - this.r = Math.sqrt( this.r ); - this.g = Math.sqrt( this.g ); - this.b = Math.sqrt( this.b ); - - return this; - - }, - - getHex: function () { - - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - - }, - - getHexString: function () { - - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - - }, - - getHSL: function ( optionalTarget ) { - - // h,s,l ranges are in 0.0 - 1.0 - - var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; - - var r = this.r, g = this.g, b = this.b; - - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); - - var hue, saturation; - var lightness = ( min + max ) / 2.0; - - if ( min === max ) { - - hue = 0; - saturation = 0; - - } else { - - var delta = max - min; - - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - - switch ( max ) { - - case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; - case g: hue = ( b - r ) / delta + 2; break; - case b: hue = ( r - g ) / delta + 4; break; - - } - - hue /= 6; - - } - - hsl.h = hue; - hsl.s = saturation; - hsl.l = lightness; - - return hsl; - - }, - - getStyle: function () { - - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - - }, - - offsetHSL: function ( h, s, l ) { - - var hsl = this.getHSL(); - - hsl.h += h; hsl.s += s; hsl.l += l; - - this.setHSL( hsl.h, hsl.s, hsl.l ); - - return this; - - }, - - add: function ( color ) { - - this.r += color.r; - this.g += color.g; - this.b += color.b; - - return this; - - }, - - addColors: function ( color1, color2 ) { - - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; - - return this; - - }, - - addScalar: function ( s ) { - - this.r += s; - this.g += s; - this.b += s; - - return this; - - }, - - multiply: function ( color ) { - - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; - - return this; - - }, - - multiplyScalar: function ( s ) { - - this.r *= s; - this.g *= s; - this.b *= s; - - return this; - - }, - - lerp: function ( color, alpha ) { - - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; - - return this; - - }, - - equals: function ( c ) { - - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - - }, - - fromArray: function ( array ) { - - this.r = array[ 0 ]; - this.g = array[ 1 ]; - this.b = array[ 2 ]; - - return this; - - }, - - toArray: function () { - - return [ this.r, this.g, this.b ]; - - }, - - clone: function () { - - return new THREE.Color().setRGB( this.r, this.g, this.b ); - - } - -}; - -THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF, -"beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2, -"brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50, -"cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B, -"darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B, -"darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F, -"darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3, -"deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222, -"floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700, -"goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4, -"indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00, -"lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3, -"lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA, -"lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32, -"linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3, -"mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC, -"mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD, -"navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6, -"palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9, -"peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F, -"royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE, -"sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA, -"springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0, -"violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 }; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com - */ - -THREE.Quaternion = function ( x, y, z, w ) { - - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._w = ( w !== undefined ) ? w : 1; - -}; - -THREE.Quaternion.prototype = { - - constructor: THREE.Quaternion, - - _x: 0,_y: 0, _z: 0, _w: 0, - - _euler: undefined, - - _updateEuler: function ( callback ) { - - if ( this._euler !== undefined ) { - - this._euler.setFromQuaternion( this, undefined, false ); - - } - - }, - - get x () { - - return this._x; - - }, - - set x ( value ) { - - this._x = value; - this._updateEuler(); - - }, - - get y () { - - return this._y; - - }, - - set y ( value ) { - - this._y = value; - this._updateEuler(); - - }, - - get z () { - - return this._z; - - }, - - set z ( value ) { - - this._z = value; - this._updateEuler(); - - }, - - get w () { - - return this._w; - - }, - - set w ( value ) { - - this._w = value; - this._updateEuler(); - - }, - - set: function ( x, y, z, w ) { - - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - this._updateEuler(); - - return this; - - }, - - copy: function ( quaternion ) { - - this._x = quaternion._x; - this._y = quaternion._y; - this._z = quaternion._z; - this._w = quaternion._w; - - this._updateEuler(); - - return this; - - }, - - setFromEuler: function ( euler, update ) { - - if ( euler instanceof THREE.Euler === false ) { - - throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' ); - } - - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m - - var c1 = Math.cos( euler._x / 2 ); - var c2 = Math.cos( euler._y / 2 ); - var c3 = Math.cos( euler._z / 2 ); - var s1 = Math.sin( euler._x / 2 ); - var s2 = Math.sin( euler._y / 2 ); - var s3 = Math.sin( euler._z / 2 ); - - if ( euler.order === 'XYZ' ) { - - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - - } else if ( euler.order === 'YXZ' ) { - - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - - } else if ( euler.order === 'ZXY' ) { - - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - - } else if ( euler.order === 'ZYX' ) { - - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - - } else if ( euler.order === 'YZX' ) { - - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - - } else if ( euler.order === 'XZY' ) { - - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - - } - - if ( update !== false ) this._updateEuler(); - - return this; - - }, - - setFromAxisAngle: function ( axis, angle ) { - - // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - // axis have to be normalized - - var halfAngle = angle / 2, s = Math.sin( halfAngle ); - - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); - - this._updateEuler(); - - return this; - - }, - - setFromRotationMatrix: function ( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - var te = m.elements, - - m11 = te[0], m12 = te[4], m13 = te[8], - m21 = te[1], m22 = te[5], m23 = te[9], - m31 = te[2], m32 = te[6], m33 = te[10], - - trace = m11 + m22 + m33, - s; - - if ( trace > 0 ) { - - s = 0.5 / Math.sqrt( trace + 1.0 ); - - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; - - } else if ( m11 > m22 && m11 > m33 ) { - - s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - - this._w = (m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = (m12 + m21 ) / s; - this._z = (m13 + m31 ) / s; - - } else if ( m22 > m33 ) { - - s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - - this._w = (m13 - m31 ) / s; - this._x = (m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = (m23 + m32 ) / s; - - } else { - - s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; - - } - - this._updateEuler(); - - return this; - - }, - - inverse: function () { - - this.conjugate().normalize(); - - return this; - - }, - - conjugate: function () { - - this._x *= -1; - this._y *= -1; - this._z *= -1; - - this._updateEuler(); - - return this; - - }, - - 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 l = this.length(); - - if ( l === 0 ) { - - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; - - } else { - - l = 1 / l; - - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; - - } - - return this; - - }, - - multiply: function ( q, p ) { - - if ( p !== undefined ) { - - console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); - - } - - return this.multiplyQuaternions( this, q ); - - }, - - multiplyQuaternions: function ( a, b ) { - - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - - var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - - this._updateEuler(); - - return this; - - }, - - multiplyVector3: function ( vector ) { - - console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); - - }, - - slerp: function ( qb, t ) { - - var x = this._x, y = this._y, z = this._z, w = this._w; - - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - - var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - - if ( cosHalfTheta < 0 ) { - - this._w = -qb._w; - this._x = -qb._x; - this._y = -qb._y; - this._z = -qb._z; - - cosHalfTheta = -cosHalfTheta; - - } else { - - this.copy( qb ); - - } - - if ( cosHalfTheta >= 1.0 ) { - - this._w = w; - this._x = x; - this._y = y; - this._z = z; - - return this; - - } - - var halfTheta = Math.acos( cosHalfTheta ); - var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); - - if ( Math.abs( sinHalfTheta ) < 0.001 ) { - - this._w = 0.5 * ( w + this._w ); - this._x = 0.5 * ( x + this._x ); - this._y = 0.5 * ( y + this._y ); - this._z = 0.5 * ( z + this._z ); - - return this; - - } - - var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - - this._w = ( w * ratioA + this._w * ratioB ); - this._x = ( x * ratioA + this._x * ratioB ); - this._y = ( y * ratioA + this._y * ratioB ); - this._z = ( z * ratioA + this._z * ratioB ); - - this._updateEuler(); - - return this; - - }, - - equals: function ( quaternion ) { - - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - - }, - - fromArray: function ( array ) { - - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - this._w = array[ 3 ]; - - this._updateEuler(); - - return this; - - }, - - toArray: function () { - - return [ this._x, this._y, this._z, this._w ]; - - }, - - clone: function () { - - return new THREE.Quaternion( this._x, this._y, this._z, this._w ); - - } - -}; - -THREE.Quaternion.slerp = function ( qa, qb, qm, t ) { - - return qm.copy( qa ).slerp( qb, t ); - -} -/** - * @author mrdoob / http://mrdoob.com/ - * @author philogb / http://blog.thejit.org/ - * @author egraether / http://egraether.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ - -THREE.Vector2 = function ( x, y ) { - - this.x = x || 0; - this.y = y || 0; - -}; - -THREE.Vector2.prototype = { - - constructor: THREE.Vector2, - - set: function ( x, y ) { - - this.x = x; - this.y = y; - - return this; - - }, - - setX: function ( x ) { - - this.x = x; - - return this; - - }, - - setY: function ( y ) { - - this.y = y; - - return this; - - }, - - - setComponent: function ( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( "index is out of range: " + index ); - - } - - }, - - getComponent: function ( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - default: throw new Error( "index is out of range: " + index ); - - } - - }, - - copy: function ( v ) { - - this.x = v.x; - this.y = v.y; - - return this; - - }, - - add: function ( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - - return this; - - }, - - addVectors: function ( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - - return this; - - }, - - addScalar: function ( s ) { - - this.x += s; - this.y += s; - - return this; - - }, - - sub: function ( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - - return this; - - }, - - subVectors: function ( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - - return this; - - }, - - multiplyScalar: function ( s ) { - - this.x *= s; - this.y *= s; - - return this; - - }, - - divideScalar: function ( scalar ) { - - if ( scalar !== 0 ) { - - var invScalar = 1 / scalar; - - this.x *= invScalar; - this.y *= invScalar; - - } else { - - this.x = 0; - this.y = 0; - - } - - return this; - - }, - - min: function ( v ) { - - if ( this.x > v.x ) { - - this.x = v.x; - - } - - if ( this.y > v.y ) { - - this.y = v.y; - - } - - return this; - - }, - - max: function ( v ) { - - if ( this.x < v.x ) { - - this.x = v.x; - - } - - if ( this.y < v.y ) { - - this.y = v.y; - - } - - return this; - - }, - - clamp: function ( min, max ) { - - // This function assumes min < max, if this assumption isn't true it will not operate correctly - - if ( this.x < min.x ) { - - this.x = min.x; - - } else if ( this.x > max.x ) { - - this.x = max.x; - - } - - if ( this.y < min.y ) { - - this.y = min.y; - - } else if ( this.y > max.y ) { - - this.y = max.y; - - } - - return this; - }, - - clampScalar: ( function () { - - var min, max; - - return function ( minVal, maxVal ) { - - if ( min === undefined ) { - - min = new THREE.Vector2(); - max = new THREE.Vector2(); - - } - - min.set( minVal, minVal ); - max.set( maxVal, maxVal ); - - return this.clamp( min, max ); - - }; - - } )(), - - floor: function () { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - - return this; - - }, - - ceil: function () { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - - return this; - - }, - - round: function () { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - - return this; - - }, - - roundToZero: function () { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - - return this; - - }, - - negate: function () { - - return this.multiplyScalar( - 1 ); - - }, - - dot: function ( v ) { - - return this.x * v.x + this.y * v.y; - - }, - - lengthSq: function () { - - return this.x * this.x + this.y * this.y; - - }, - - length: function () { - - return Math.sqrt( this.x * this.x + this.y * this.y ); - - }, - - normalize: function () { - - return this.divideScalar( this.length() ); - - }, - - distanceTo: function ( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - }, - - distanceToSquared: function ( v ) { - - var dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; - - }, - - setLength: function ( l ) { - - var oldLength = this.length(); - - if ( oldLength !== 0 && l !== oldLength ) { - - this.multiplyScalar( l / oldLength ); - } - - return this; - - }, - - lerp: function ( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - - return this; - - }, - - equals: function( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) ); - - }, - - fromArray: function ( array ) { - - this.x = array[ 0 ]; - this.y = array[ 1 ]; - - return this; - - }, - - toArray: function () { - - return [ this.x, this.y ]; - - }, - - clone: function () { - - return new THREE.Vector2( this.x, this.y ); - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author *kile / http://kile.stravaganza.org/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ - -THREE.Vector3 = function ( x, y, z ) { - - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - -}; - -THREE.Vector3.prototype = { - - constructor: THREE.Vector3, - - set: function ( x, y, z ) { - - this.x = x; - this.y = y; - this.z = z; - - return this; - - }, - - setX: function ( x ) { - - this.x = x; - - return this; - - }, - - setY: function ( y ) { - - this.y = y; - - return this; - - }, - - setZ: function ( z ) { - - this.z = z; - - return this; - - }, - - setComponent: function ( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( "index is out of range: " + index ); - - } - - }, - - getComponent: function ( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - default: throw new Error( "index is out of range: " + index ); - - } - - }, - - copy: function ( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; - - return this; - - }, - - add: function ( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - this.z += v.z; - - return this; - - }, - - addScalar: function ( s ) { - - this.x += s; - this.y += s; - this.z += s; - - 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; - - }, - - sub: function ( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - - 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 ( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); - - } - - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - - return this; - - }, - - multiplyScalar: function ( scalar ) { - - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - - 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 quaternion; - - return function ( euler ) { - - if ( euler instanceof THREE.Euler === false ) { - - console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' ); - - } - - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); - - this.applyQuaternion( quaternion.setFromEuler( euler ) ); - - return this; - - }; - - }(), - - applyAxisAngle: function () { - - var quaternion; - - return function ( axis, angle ) { - - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); - - this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); - - return this; - - }; - - }(), - - applyMatrix3: function ( m ) { - - var x = this.x; - var y = this.y; - var z = this.z; - - var e = m.elements; - - this.x = e[0] * x + e[3] * y + e[6] * z; - this.y = e[1] * x + e[4] * y + e[7] * z; - this.z = e[2] * x + e[5] * y + e[8] * z; - - return this; - - }, - - applyMatrix4: function ( m ) { - - // input: THREE.Matrix4 affine matrix - - var x = this.x, y = this.y, z = this.z; - - var e = m.elements; - - this.x = e[0] * x + e[4] * y + e[8] * z + e[12]; - this.y = e[1] * x + e[5] * y + e[9] * z + e[13]; - this.z = e[2] * x + e[6] * y + e[10] * z + e[14]; - - return this; - - }, - - applyProjection: function ( m ) { - - // input: THREE.Matrix4 projection matrix - - var x = this.x, y = this.y, z = this.z; - - var e = m.elements; - var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide - - this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d; - this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d; - this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d; - - return this; - - }, - - applyQuaternion: function ( q ) { - - var x = this.x; - var y = this.y; - var z = this.z; - - var qx = q.x; - var qy = q.y; - var qz = q.z; - var qw = q.w; - - // calculate quat * vector - - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = -qx * x - qy * y - qz * z; - - // calculate result * inverse quat - - this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; - this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; - this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; - - return this; - - }, - - transformDirection: function ( m ) { - - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction - - var x = this.x, y = this.y, z = this.z; - - var e = m.elements; - - this.x = e[0] * x + e[4] * y + e[8] * z; - this.y = e[1] * x + e[5] * y + e[9] * z; - this.z = e[2] * x + e[6] * y + e[10] * z; - - this.normalize(); - - return this; - - }, - - divide: function ( v ) { - - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; - - return this; - - }, - - divideScalar: function ( scalar ) { - - if ( scalar !== 0 ) { - - var invScalar = 1 / scalar; - - this.x *= invScalar; - this.y *= invScalar; - this.z *= invScalar; - - } else { - - this.x = 0; - this.y = 0; - this.z = 0; - - } - - return this; - - }, - - min: function ( v ) { - - if ( this.x > v.x ) { - - this.x = v.x; - - } - - if ( this.y > v.y ) { - - this.y = v.y; - - } - - if ( this.z > v.z ) { - - this.z = v.z; - - } - - return this; - - }, - - max: function ( v ) { - - if ( this.x < v.x ) { - - this.x = v.x; - - } - - if ( this.y < v.y ) { - - this.y = v.y; - - } - - if ( this.z < v.z ) { - - this.z = v.z; - - } - - return this; - - }, - - clamp: function ( min, max ) { - - // This function assumes min < max, if this assumption isn't true it will not operate correctly - - if ( this.x < min.x ) { - - this.x = min.x; - - } else if ( this.x > max.x ) { - - this.x = max.x; - - } - - if ( this.y < min.y ) { - - this.y = min.y; - - } else if ( this.y > max.y ) { - - this.y = max.y; - - } - - if ( this.z < min.z ) { - - this.z = min.z; - - } else if ( this.z > max.z ) { - - this.z = max.z; - - } - - return this; - - }, - - clampScalar: ( function () { - - var min, max; - - return function ( minVal, maxVal ) { - - if ( min === undefined ) { - - min = new THREE.Vector3(); - max = new THREE.Vector3(); - - } - - min.set( minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal ); - - return this.clamp( min, max ); - - }; - - } )(), - - floor: function () { - - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - - return this; - - }, - - ceil: function () { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - - return this; - - }, - - round: function () { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - - return this; - - }, - - roundToZero: function () { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - - return this; - - }, - - negate: function () { - - return this.multiplyScalar( - 1 ); - - }, - - dot: function ( v ) { - - return this.x * v.x + this.y * v.y + this.z * v.z; - - }, - - lengthSq: function () { - - return this.x * this.x + this.y * this.y + this.z * this.z; - - }, - - length: function () { - - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - - }, - - lengthManhattan: function () { - - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - - }, - - normalize: function () { - - return this.divideScalar( this.length() ); - - }, - - setLength: function ( l ) { - - var oldLength = this.length(); - - if ( oldLength !== 0 && l !== oldLength ) { - - this.multiplyScalar( l / oldLength ); - } - - return this; - - }, - - lerp: function ( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - - return this; - - }, - - cross: function ( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); - - } - - var x = this.x, y = this.y, z = this.z; - - this.x = y * v.z - z * v.y; - this.y = z * v.x - x * v.z; - this.z = x * v.y - y * v.x; - - return this; - - }, - - crossVectors: function ( a, b ) { - - var ax = a.x, ay = a.y, az = a.z; - var bx = b.x, by = b.y, bz = b.z; - - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; - - return this; - - }, - - projectOnVector: function () { - - var v1, dot; - - return function ( vector ) { - - if ( v1 === undefined ) v1 = new THREE.Vector3(); - - v1.copy( vector ).normalize(); - - dot = this.dot( v1 ); - - return this.copy( v1 ).multiplyScalar( dot ); - - }; - - }(), - - projectOnPlane: function () { - - var v1; - - return function ( planeNormal ) { - - if ( v1 === undefined ) v1 = new THREE.Vector3(); - - v1.copy( this ).projectOnVector( planeNormal ); - - return this.sub( v1 ); - - } - - }(), - - reflect: function () { - - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length - - var v1; - - return function ( normal ) { - - if ( v1 === undefined ) v1 = new THREE.Vector3(); - - return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - - } - - }(), - - angleTo: function ( v ) { - - var theta = this.dot( v ) / ( this.length() * v.length() ); - - // clamp, to handle numerical problems - - return Math.acos( THREE.Math.clamp( theta, -1, 1 ) ); - - }, - - distanceTo: function ( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - }, - - distanceToSquared: function ( v ) { - - var dx = this.x - v.x; - var dy = this.y - v.y; - var dz = this.z - v.z; - - return dx * dx + dy * dy + dz * dz; - - }, - - setEulerFromRotationMatrix: function ( m, order ) { - - console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code."); - - }, - - setEulerFromQuaternion: function ( q, order ) { - - console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code."); - - }, - - getPositionFromMatrix: function ( m ) { - - console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." ); - - return this.setFromMatrixPosition( m ); - - }, - - getScaleFromMatrix: function ( m ) { - - console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." ); - - return this.setFromMatrixScale( m ); - }, - - getColumnFromMatrix: function ( index, matrix ) { - - console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." ); - - return this.setFromMatrixColumn( index, matrix ); - - }, - - setFromMatrixPosition: function ( m ) { - - this.x = m.elements[ 12 ]; - this.y = m.elements[ 13 ]; - this.z = m.elements[ 14 ]; - - return this; - - }, - - setFromMatrixScale: function ( m ) { - - var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length(); - var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length(); - var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length(); - - this.x = sx; - this.y = sy; - this.z = sz; - - return this; - }, - - setFromMatrixColumn: function ( index, matrix ) { - - var offset = index * 4; - - var me = matrix.elements; - - this.x = me[ offset ]; - this.y = me[ offset + 1 ]; - this.z = me[ offset + 2 ]; - - return this; - - }, - - equals: function ( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - - }, - - fromArray: function ( array ) { - - this.x = array[ 0 ]; - this.y = array[ 1 ]; - this.z = array[ 2 ]; - - return this; - - }, - - toArray: function () { - - return [ this.x, this.y, this.z ]; - - }, - - clone: function () { - - return new THREE.Vector3( this.x, this.y, this.z ); - - } - -};/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ - -THREE.Vector4 = function ( x, y, z, w ) { - - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; - -}; - -THREE.Vector4.prototype = { - - constructor: THREE.Vector4, - - set: function ( x, y, z, w ) { - - this.x = x; - this.y = y; - this.z = z; - this.w = w; - - return this; - - }, - - setX: function ( x ) { - - this.x = x; - - return this; - - }, - - setY: function ( y ) { - - this.y = y; - - return this; - - }, - - setZ: function ( z ) { - - this.z = z; - - return this; - - }, - - setW: function ( w ) { - - this.w = w; - - return this; - - }, - - setComponent: function ( index, value ) { - - switch ( index ) { - - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - case 3: this.w = value; break; - default: throw new Error( "index is out of range: " + index ); - - } - - }, - - getComponent: function ( index ) { - - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - case 3: return this.w; - default: throw new Error( "index is out of range: " + index ); - - } - - }, - - copy: function ( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; - - return this; - - }, - - add: function ( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } - - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; - - return this; - - }, - - addScalar: function ( s ) { - - this.x += s; - this.y += s; - this.z += s; - this.w += s; - - 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; - - }, - - sub: function ( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } - - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; - - 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 ( scalar ) { - - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; - - return this; - - }, - - applyMatrix4: function ( m ) { - - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; - - var e = m.elements; - - this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; - this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; - this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; - this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; - - return this; - - }, - - divideScalar: function ( scalar ) { - - if ( scalar !== 0 ) { - - var invScalar = 1 / scalar; - - this.x *= invScalar; - this.y *= invScalar; - this.z *= invScalar; - this.w *= invScalar; - - } else { - - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 1; - - } - - return this; - - }, - - setAxisAngleFromQuaternion: function ( q ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - - // q is assumed to be normalized - - this.w = 2 * Math.acos( q.w ); - - var s = Math.sqrt( 1 - q.w * q.w ); - - if ( s < 0.0001 ) { - - this.x = 1; - this.y = 0; - this.z = 0; - - } else { - - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; - - } - - return this; - - }, - - setAxisAngleFromRotationMatrix: function ( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - var angle, x, y, z, // variables for result - epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - - te = m.elements, - - m11 = te[0], m12 = te[4], m13 = te[8], - m21 = te[1], m22 = te[5], m23 = te[9], - m31 = te[2], m32 = te[6], m33 = te[10]; - - if ( ( Math.abs( m12 - m21 ) < epsilon ) - && ( Math.abs( m13 - m31 ) < epsilon ) - && ( Math.abs( m23 - m32 ) < epsilon ) ) { - - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms - - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) - && ( Math.abs( m13 + m31 ) < epsilon2 ) - && ( Math.abs( m23 + m32 ) < epsilon2 ) - && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - - // this singularity is identity matrix so angle = 0 - - this.set( 1, 0, 0, 0 ); - - return this; // zero angle, arbitrary axis - - } - - // otherwise this singularity is angle = 180 - - angle = Math.PI; - - var xx = ( m11 + 1 ) / 2; - var yy = ( m22 + 1 ) / 2; - var zz = ( m33 + 1 ) / 2; - var xy = ( m12 + m21 ) / 4; - var xz = ( m13 + m31 ) / 4; - var yz = ( m23 + m32 ) / 4; - - if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term - - if ( xx < epsilon ) { - - x = 0; - y = 0.707106781; - z = 0.707106781; - - } else { - - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; - - } - - } else if ( yy > zz ) { // m22 is the largest diagonal term - - if ( yy < epsilon ) { - - x = 0.707106781; - y = 0; - z = 0.707106781; - - } else { - - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; - - } - - } else { // m33 is the largest diagonal term so base result on this - - if ( zz < epsilon ) { - - x = 0.707106781; - y = 0.707106781; - z = 0; - - } else { - - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; - - } - - } - - this.set( x, y, z, angle ); - - return this; // return 180 deg rotation - - } - - // as we have reached here there are no singularities so we can handle normally - - var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) - + ( m13 - m31 ) * ( m13 - m31 ) - + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - - if ( Math.abs( s ) < 0.001 ) s = 1; - - // prevent divide by zero, should not happen if matrix is orthogonal and should be - // caught by singularity test above, but I've left it in just in case - - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - - return this; - - }, - - min: function ( v ) { - - if ( this.x > v.x ) { - - this.x = v.x; - - } - - if ( this.y > v.y ) { - - this.y = v.y; - - } - - if ( this.z > v.z ) { - - this.z = v.z; - - } - - if ( this.w > v.w ) { - - this.w = v.w; - - } - - return this; - - }, - - max: function ( v ) { - - if ( this.x < v.x ) { - - this.x = v.x; - - } - - if ( this.y < v.y ) { - - this.y = v.y; - - } - - if ( this.z < v.z ) { - - this.z = v.z; - - } - - if ( this.w < v.w ) { - - this.w = v.w; - - } - - return this; - - }, - - clamp: function ( min, max ) { - - // This function assumes min < max, if this assumption isn't true it will not operate correctly - - if ( this.x < min.x ) { - - this.x = min.x; - - } else if ( this.x > max.x ) { - - this.x = max.x; - - } - - if ( this.y < min.y ) { - - this.y = min.y; - - } else if ( this.y > max.y ) { - - this.y = max.y; - - } - - if ( this.z < min.z ) { - - this.z = min.z; - - } else if ( this.z > max.z ) { - - this.z = max.z; - - } - - if ( this.w < min.w ) { - - this.w = min.w; - - } else if ( this.w > max.w ) { - - this.w = max.w; - - } - - return this; - - }, - - clampScalar: ( function () { - - var min, max; - - return function ( minVal, maxVal ) { - - if ( min === undefined ) { - - min = new THREE.Vector4(); - max = new THREE.Vector4(); - - } - - min.set( minVal, minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal, maxVal ); - - return this.clamp( min, max ); - - }; - - } )(), - - 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 ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); - - return this; - - }, - - roundToZero: function () { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - - return this; - - }, - - negate: function () { - - return this.multiplyScalar( -1 ); - - }, - - dot: function ( v ) { - - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - - }, - - lengthSq: function () { - - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - - }, - - length: function () { - - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - - }, - - lengthManhattan: function () { - - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - - }, - - normalize: function () { - - return this.divideScalar( this.length() ); - - }, - - setLength: function ( l ) { - - var oldLength = this.length(); - - if ( oldLength !== 0 && l !== oldLength ) { - - this.multiplyScalar( l / oldLength ); - - } - - return this; - - }, - - lerp: function ( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - this.w += ( v.w - this.w ) * alpha; - - return this; - - }, - - equals: function ( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - - }, - - fromArray: function ( array ) { - - this.x = array[ 0 ]; - this.y = array[ 1 ]; - this.z = array[ 2 ]; - this.w = array[ 3 ]; - - return this; - - }, - - toArray: function () { - - return [ this.x, this.y, this.z, this.w ]; - - }, - - clone: function () { - - return new THREE.Vector4( this.x, this.y, this.z, this.w ); - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com - */ - -THREE.Euler = function ( x, y, z, order ) { - - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._order = order || THREE.Euler.DefaultOrder; - -}; - -THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - -THREE.Euler.DefaultOrder = 'XYZ'; - -THREE.Euler.prototype = { - - constructor: THREE.Euler, - - _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder, - - _quaternion: undefined, - - _updateQuaternion: function () { - - if ( this._quaternion !== undefined ) { - - this._quaternion.setFromEuler( this, false ); - - } - - }, - - get x () { - - return this._x; - - }, - - set x ( value ) { - - this._x = value; - this._updateQuaternion(); - - }, - - get y () { - - return this._y; - - }, - - set y ( value ) { - - this._y = value; - this._updateQuaternion(); - - }, - - get z () { - - return this._z; - - }, - - set z ( value ) { - - this._z = value; - this._updateQuaternion(); - - }, - - get order () { - - return this._order; - - }, - - set order ( value ) { - - this._order = value; - this._updateQuaternion(); - - }, - - set: function ( x, y, z, order ) { - - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; - - this._updateQuaternion(); - - return this; - - }, - - copy: function ( euler ) { - - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; - - this._updateQuaternion(); - - return this; - - }, - - setFromVector: function( v, order ) { - - this._x = v.x; - this._y = v.y; - this._z = v.z; - this._order = order || this._order; - - this._updateQuaternion(); - - return this; - - }, - - setFromRotationMatrix: function ( m, order ) { - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - // clamp, to handle numerical problems - - function clamp( x ) { - - return Math.min( Math.max( x, -1 ), 1 ); - - } - - var te = m.elements; - var m11 = te[0], m12 = te[4], m13 = te[8]; - var m21 = te[1], m22 = te[5], m23 = te[9]; - var m31 = te[2], m32 = te[6], m33 = te[10]; - - order = order || this._order; - - if ( order === 'XYZ' ) { - - this._y = Math.asin( clamp( m13 ) ); - - if ( Math.abs( m13 ) < 0.99999 ) { - - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); - - } else { - - this._x = Math.atan2( m32, m22 ); - this._z = 0; - - } - - } else if ( order === 'YXZ' ) { - - this._x = Math.asin( - clamp( m23 ) ); - - if ( Math.abs( m23 ) < 0.99999 ) { - - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); - - } else { - - this._y = Math.atan2( - m31, m11 ); - this._z = 0; - - } - - } else if ( order === 'ZXY' ) { - - this._x = Math.asin( clamp( m32 ) ); - - if ( Math.abs( m32 ) < 0.99999 ) { - - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); - - } else { - - this._y = 0; - this._z = Math.atan2( m21, m11 ); - - } - - } else if ( order === 'ZYX' ) { - - this._y = Math.asin( - clamp( m31 ) ); - - if ( Math.abs( m31 ) < 0.99999 ) { - - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); - - } else { - - this._x = 0; - this._z = Math.atan2( - m12, m22 ); - - } - - } else if ( order === 'YZX' ) { - - this._z = Math.asin( clamp( m21 ) ); - - if ( Math.abs( m21 ) < 0.99999 ) { - - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); - - } else { - - this._x = 0; - this._y = Math.atan2( m13, m33 ); - - } - - } else if ( order === 'XZY' ) { - - this._z = Math.asin( - clamp( m12 ) ); - - if ( Math.abs( m12 ) < 0.99999 ) { - - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); - - } else { - - this._x = Math.atan2( - m23, m33 ); - this._y = 0; - - } - - } else { - - console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order ) - - } - - this._order = order; - - this._updateQuaternion(); - - return this; - - }, - - setFromQuaternion: function ( q, order, update ) { - - // q is assumed to be normalized - - // clamp, to handle numerical problems - - function clamp( x ) { - - return Math.min( Math.max( x, -1 ), 1 ); - - } - - // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m - - var sqx = q.x * q.x; - var sqy = q.y * q.y; - var sqz = q.z * q.z; - var sqw = q.w * q.w; - - order = order || this._order; - - if ( order === 'XYZ' ) { - - this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) ); - this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) ); - this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) ); - - } else if ( order === 'YXZ' ) { - - this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) ); - this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) ); - this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) ); - - } else if ( order === 'ZXY' ) { - - this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) ); - this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) ); - this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) ); - - } else if ( order === 'ZYX' ) { - - this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) ); - this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) ); - this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) ); - - } else if ( order === 'YZX' ) { - - this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) ); - this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) ); - this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) ); - - } else if ( order === 'XZY' ) { - - this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) ); - this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) ); - this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) ); - - } else { - - console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order ) - - } - - this._order = order; - - if ( update !== false ) this._updateQuaternion(); - - return this; - - }, - - reorder: function () { - - // WARNING: this discards revolution information -bhouston - - var q = new THREE.Quaternion(); - - return function ( newOrder ) { - - q.setFromEuler( this ); - this.setFromQuaternion( q, newOrder ); - - }; - - - }(), - - fromArray: function ( array ) { - - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - - this._updateQuaternion(); - - return this; - - }, - - toArray: function () { - - return [ this._x, this._y, this._z, this._order ]; - - }, - - equals: function ( euler ) { - - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - - }, - - clone: function () { - - return new THREE.Euler( this._x, this._y, this._z, this._order ); - - } - -}; -/** - * @author bhouston / http://exocortex.com - */ - -THREE.Line3 = function ( start, end ) { - - this.start = ( start !== undefined ) ? start : new THREE.Vector3(); - this.end = ( end !== undefined ) ? end : new THREE.Vector3(); - -}; - -THREE.Line3.prototype = { - - constructor: THREE.Line3, - - set: function ( start, end ) { - - this.start.copy( start ); - this.end.copy( end ); - - return this; - - }, - - copy: function ( line ) { - - this.start.copy( line.start ); - this.end.copy( line.end ); - - return this; - - }, - - center: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - - }, - - delta: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.end, this.start ); - - }, - - distanceSq: function () { - - return this.start.distanceToSquared( this.end ); - - }, - - distance: function () { - - return this.start.distanceTo( this.end ); - - }, - - at: function ( t, optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - - return this.delta( result ).multiplyScalar( t ).add( this.start ); - - }, - - closestPointToPointParameter: function() { - - var startP = new THREE.Vector3(); - var startEnd = new THREE.Vector3(); - - return function ( point, clampToLine ) { - - startP.subVectors( point, this.start ); - startEnd.subVectors( this.end, this.start ); - - var startEnd2 = startEnd.dot( startEnd ); - var startEnd_startP = startEnd.dot( startP ); - - var t = startEnd_startP / startEnd2; - - if ( clampToLine ) { - - t = THREE.Math.clamp( t, 0, 1 ); - - } - - return t; - - }; - - }(), - - closestPointToPoint: function ( point, clampToLine, optionalTarget ) { - - var t = this.closestPointToPointParameter( point, clampToLine ); - - var result = optionalTarget || new THREE.Vector3(); - - return this.delta( result ).multiplyScalar( t ).add( this.start ); - - }, - - applyMatrix4: function ( matrix ) { - - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); - - return this; - - }, - - equals: function ( line ) { - - return line.start.equals( this.start ) && line.end.equals( this.end ); - - }, - - clone: function () { - - return new THREE.Line3().copy( this ); - - } - -}; -/** - * @author bhouston / http://exocortex.com - */ - -THREE.Box2 = function ( min, max ) { - - this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity ); - -}; - -THREE.Box2.prototype = { - - constructor: THREE.Box2, - - set: function ( min, max ) { - - this.min.copy( min ); - this.max.copy( max ); - - return this; - - }, - - setFromPoints: function ( points ) { - - if ( points.length > 0 ) { - - var point = points[ 0 ]; - - this.min.copy( point ); - this.max.copy( point ); - - for ( var i = 1, il = points.length; i < il; i ++ ) { - - point = points[ i ]; - - if ( point.x < this.min.x ) { - - this.min.x = point.x; - - } else if ( point.x > this.max.x ) { - - this.max.x = point.x; - - } - - if ( point.y < this.min.y ) { - - this.min.y = point.y; - - } else if ( point.y > this.max.y ) { - - this.max.y = point.y; - - } - - } - - } else { - - this.makeEmpty(); - - } - - return this; - - }, - - setFromCenterAndSize: function () { - - var v1 = new THREE.Vector2(); - - return function ( center, size ) { - - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); - - return this; - - }; - - }(), - - copy: function ( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - }, - - makeEmpty: function () { - - this.min.x = this.min.y = Infinity; - this.max.x = this.max.y = -Infinity; - - return this; - - }, - - empty: function () { - - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - - }, - - center: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Vector2(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - - }, - - size: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Vector2(); - return result.subVectors( this.max, this.min ); - - }, - - expandByPoint: function ( point ) { - - this.min.min( point ); - this.max.max( point ); - - return this; - }, - - expandByVector: function ( vector ) { - - this.min.sub( vector ); - this.max.add( vector ); - - return this; - }, - - expandByScalar: function ( scalar ) { - - this.min.addScalar( -scalar ); - this.max.addScalar( scalar ); - - return this; - }, - - containsPoint: function ( point ) { - - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ) { - - return false; - - } - - return true; - - }, - - containsBox: function ( box ) { - - if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && - ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) { - - return true; - - } - - return false; - - }, - - getParameter: function ( point, optionalTarget ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. - - var result = optionalTarget || new THREE.Vector2(); - - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ) - ); - - }, - - isIntersectionBox: function ( box ) { - - // using 6 splitting planes to rule out intersections. - - if ( box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ) { - - return false; - - } - - return true; - - }, - - clampPoint: function ( point, optionalTarget ) { - - var result = optionalTarget || new THREE.Vector2(); - return result.copy( point ).clamp( this.min, this.max ); - - }, - - distanceToPoint: function () { - - var v1 = new THREE.Vector2(); - - return function ( point ) { - - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); - - }; - - }(), - - intersect: function ( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); - - return this; - - }, - - union: function ( box ) { - - this.min.min( box.min ); - this.max.max( box.max ); - - return this; - - }, - - translate: function ( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; - - }, - - equals: function ( box ) { - - return box.min.equals( this.min ) && box.max.equals( this.max ); - - }, - - clone: function () { - - return new THREE.Box2().copy( this ); - - } - -}; -/** - * @author bhouston / http://exocortex.com - * @author WestLangley / http://github.com/WestLangley - */ - -THREE.Box3 = function ( min, max ) { - - this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity ); - -}; - -THREE.Box3.prototype = { - - constructor: THREE.Box3, - - set: function ( min, max ) { - - this.min.copy( min ); - this.max.copy( max ); - - return this; - - }, - - addPoint: function ( point ) { - - if ( point.x < this.min.x ) { - - this.min.x = point.x; - - } else if ( point.x > this.max.x ) { - - this.max.x = point.x; - - } - - if ( point.y < this.min.y ) { - - this.min.y = point.y; - - } else if ( point.y > this.max.y ) { - - this.max.y = point.y; - - } - - if ( point.z < this.min.z ) { - - this.min.z = point.z; - - } else if ( point.z > this.max.z ) { - - this.max.z = point.z; - - } - - }, - - setFromPoints: function ( points ) { - - if ( points.length > 0 ) { - - var point = points[ 0 ]; - - this.min.copy( point ); - this.max.copy( point ); - - for ( var i = 1, il = points.length; i < il; i ++ ) { - - this.addPoint( points[ i ] ) - - } - - } else { - - this.makeEmpty(); - - } - - return this; - - }, - - setFromCenterAndSize: function() { - - var v1 = new THREE.Vector3(); - - return function ( center, size ) { - - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); - - return this; - - }; - - }(), - - setFromObject: function() { - - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and childrens', world transforms - - var v1 = new THREE.Vector3(); - - return function( object ) { - - var scope = this; - - object.updateMatrixWorld( true ); - - this.makeEmpty(); - - object.traverse( function ( node ) { - - if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) { - - var vertices = node.geometry.vertices; - - for ( var i = 0, il = vertices.length; i < il; i++ ) { - - v1.copy( vertices[ i ] ); - - v1.applyMatrix4( node.matrixWorld ); - - scope.expandByPoint( v1 ); - - } - - } - - } ); - - return this; - - }; - - }(), - - copy: function ( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - }, - - makeEmpty: function () { - - this.min.x = this.min.y = this.min.z = Infinity; - this.max.x = this.max.y = this.max.z = -Infinity; - - return this; - - }, - - empty: function () { - - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - - }, - - center: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - - }, - - size: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.max, this.min ); - - }, - - expandByPoint: function ( point ) { - - this.min.min( point ); - this.max.max( point ); - - return this; - - }, - - expandByVector: function ( vector ) { - - this.min.sub( vector ); - this.max.add( vector ); - - return this; - - }, - - expandByScalar: function ( scalar ) { - - this.min.addScalar( -scalar ); - this.max.addScalar( scalar ); - - return this; - - }, - - containsPoint: function ( point ) { - - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y || - point.z < this.min.z || point.z > this.max.z ) { - - return false; - - } - - return true; - - }, - - containsBox: function ( box ) { - - if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && - ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) && - ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) { - - return true; - - } - - return false; - - }, - - getParameter: function ( point, optionalTarget ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. - - var result = optionalTarget || new THREE.Vector3(); - - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ), - ( point.z - this.min.z ) / ( this.max.z - this.min.z ) - ); - - }, - - isIntersectionBox: function ( box ) { - - // using 6 splitting planes to rule out intersections. - - if ( box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y || - box.max.z < this.min.z || box.min.z > this.max.z ) { - - return false; - - } - - return true; - - }, - - clampPoint: function ( point, optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - return result.copy( point ).clamp( this.min, this.max ); - - }, - - distanceToPoint: function() { - - var v1 = new THREE.Vector3(); - - return function ( point ) { - - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); - - }; - - }(), - - getBoundingSphere: function() { - - var v1 = new THREE.Vector3(); - - return function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Sphere(); - - result.center = this.center(); - result.radius = this.size( v1 ).length() * 0.5; - - return result; - - }; - - }(), - - intersect: function ( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); - - return this; - - }, - - union: function ( box ) { - - this.min.min( box.min ); - this.max.max( box.max ); - - return this; - - }, - - applyMatrix4: function() { - - var points = [ - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3() - ]; - - return function ( matrix ) { - - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 - - this.makeEmpty(); - this.setFromPoints( points ); - - return this; - - }; - - }(), - - translate: function ( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; - - }, - - equals: function ( box ) { - - return box.min.equals( this.min ) && box.max.equals( this.max ); - - }, - - clone: function () { - - return new THREE.Box3().copy( this ); - - } - -}; -/** - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com - */ - -THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - - this.elements = new Float32Array(9); - - this.set( - - ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, - n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, - n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1 - - ); -}; - -THREE.Matrix3.prototype = { - - constructor: THREE.Matrix3, - - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - - var te = this.elements; - - te[0] = n11; te[3] = n12; te[6] = n13; - te[1] = n21; te[4] = n22; te[7] = n23; - te[2] = n31; te[5] = n32; te[8] = n33; - - return this; - - }, - - identity: function () { - - this.set( - - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - - ); - - return this; - - }, - - copy: function ( m ) { - - var me = m.elements; - - this.set( - - me[0], me[3], me[6], - me[1], me[4], me[7], - me[2], me[5], me[8] - - ); - - return this; - - }, - - multiplyVector3: function ( vector ) { - - console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); - - }, - - multiplyVector3Array: function() { - - var v1 = new THREE.Vector3(); - - return function ( a ) { - - for ( var i = 0, il = a.length; i < il; i += 3 ) { - - v1.x = a[ i ]; - v1.y = a[ i + 1 ]; - v1.z = a[ i + 2 ]; - - v1.applyMatrix3(this); - - a[ i ] = v1.x; - a[ i + 1 ] = v1.y; - a[ i + 2 ] = v1.z; - - } - - return a; - - }; - - }(), - - multiplyScalar: function ( s ) { - - var te = this.elements; - - te[0] *= s; te[3] *= s; te[6] *= s; - te[1] *= s; te[4] *= s; te[7] *= s; - te[2] *= s; te[5] *= s; te[8] *= s; - - return this; - - }, - - determinant: function () { - - var te = this.elements; - - var a = te[0], b = te[1], c = te[2], - d = te[3], e = te[4], f = te[5], - g = te[6], h = te[7], i = te[8]; - - return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g; - - }, - - getInverse: function ( matrix, throwOnInvertible ) { - - // input: THREE.Matrix4 - // ( based on http://code.google.com/p/webgl-mjs/ ) - - var me = matrix.elements; - var te = this.elements; - - te[ 0 ] = me[10] * me[5] - me[6] * me[9]; - te[ 1 ] = - me[10] * me[1] + me[2] * me[9]; - te[ 2 ] = me[6] * me[1] - me[2] * me[5]; - te[ 3 ] = - me[10] * me[4] + me[6] * me[8]; - te[ 4 ] = me[10] * me[0] - me[2] * me[8]; - te[ 5 ] = - me[6] * me[0] + me[2] * me[4]; - te[ 6 ] = me[9] * me[4] - me[5] * me[8]; - te[ 7 ] = - me[9] * me[0] + me[1] * me[8]; - te[ 8 ] = me[5] * me[0] - me[1] * me[4]; - - var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ]; - - // no inverse - - if ( det === 0 ) { - - var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0"; - - if ( throwOnInvertible || false ) { - - throw new Error( msg ); - - } else { - - console.warn( msg ); - - } - - this.identity(); - - return this; - - } - - this.multiplyScalar( 1.0 / det ); - - return this; - - }, - - transpose: function () { - - var tmp, m = this.elements; - - tmp = m[1]; m[1] = m[3]; m[3] = tmp; - tmp = m[2]; m[2] = m[6]; m[6] = tmp; - tmp = m[5]; m[5] = m[7]; m[7] = tmp; - - return this; - - }, - - getNormalMatrix: function ( m ) { - - // input: THREE.Matrix4 - - this.getInverse( m ).transpose(); - - return this; - - }, - - transposeIntoArray: function ( r ) { - - var m = this.elements; - - r[ 0 ] = m[ 0 ]; - r[ 1 ] = m[ 3 ]; - r[ 2 ] = m[ 6 ]; - r[ 3 ] = m[ 1 ]; - r[ 4 ] = m[ 4 ]; - r[ 5 ] = m[ 7 ]; - r[ 6 ] = m[ 2 ]; - r[ 7 ] = m[ 5 ]; - r[ 8 ] = m[ 8 ]; - - return this; - - }, - - fromArray: function ( array ) { - - this.elements.set( array ); - - return this; - - }, - - toArray: function () { - - var te = this.elements; - - return [ - te[ 0 ], te[ 1 ], te[ 2 ], - te[ 3 ], te[ 4 ], te[ 5 ], - te[ 6 ], te[ 7 ], te[ 8 ] - ]; - - }, - - clone: function () { - - var te = this.elements; - - return new THREE.Matrix3( - - te[0], te[3], te[6], - te[1], te[4], te[7], - te[2], te[5], te[8] - - ); - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author jordi_ros / http://plattsoft.com - * @author D1plo1d / http://github.com/D1plo1d - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author timknip / http://www.floorplanner.com/ - * @author bhouston / http://exocortex.com - * @author WestLangley / http://github.com/WestLangley - */ - - -THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - - this.elements = new Float32Array( 16 ); - - // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix - // we should not support semi specification of Matrix4, it is just weird. - - var te = this.elements; - - te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0; - te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0; - te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0; - te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1; - -}; - -THREE.Matrix4.prototype = { - - constructor: THREE.Matrix4, - - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - - var te = this.elements; - - te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14; - te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24; - te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34; - te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44; - - return this; - - }, - - identity: function () { - - this.set( - - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - }, - - copy: function ( m ) { - - this.elements.set( m.elements ); - - return this; - - }, - - extractPosition: function ( m ) { - - console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); - - }, - - copyPosition: function ( m ) { - - var te = this.elements; - var me = m.elements; - - te[12] = me[12]; - te[13] = me[13]; - te[14] = me[14]; - - return this; - - }, - - extractRotation: function () { - - var v1 = new THREE.Vector3(); - - return function ( m ) { - - var te = this.elements; - var me = m.elements; - - var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length(); - var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length(); - var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length(); - - te[0] = me[0] * scaleX; - te[1] = me[1] * scaleX; - te[2] = me[2] * scaleX; - - te[4] = me[4] * scaleY; - te[5] = me[5] * scaleY; - te[6] = me[6] * scaleY; - - te[8] = me[8] * scaleZ; - te[9] = me[9] * scaleZ; - te[10] = me[10] * scaleZ; - - return this; - - }; - - }(), - - makeRotationFromEuler: function ( euler ) { - - if ( euler instanceof THREE.Euler === false ) { - - console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' ); - - } - - var te = this.elements; - - var x = euler.x, y = euler.y, z = euler.z; - var a = Math.cos( x ), b = Math.sin( x ); - var c = Math.cos( y ), d = Math.sin( y ); - var e = Math.cos( z ), f = Math.sin( z ); - - if ( euler.order === 'XYZ' ) { - - var ae = a * e, af = a * f, be = b * e, bf = b * f; - - te[0] = c * e; - te[4] = - c * f; - te[8] = d; - - te[1] = af + be * d; - te[5] = ae - bf * d; - te[9] = - b * c; - - te[2] = bf - ae * d; - te[6] = be + af * d; - te[10] = a * c; - - } else if ( euler.order === 'YXZ' ) { - - var ce = c * e, cf = c * f, de = d * e, df = d * f; - - te[0] = ce + df * b; - te[4] = de * b - cf; - te[8] = a * d; - - te[1] = a * f; - te[5] = a * e; - te[9] = - b; - - te[2] = cf * b - de; - te[6] = df + ce * b; - te[10] = a * c; - - } else if ( euler.order === 'ZXY' ) { - - var ce = c * e, cf = c * f, de = d * e, df = d * f; - - te[0] = ce - df * b; - te[4] = - a * f; - te[8] = de + cf * b; - - te[1] = cf + de * b; - te[5] = a * e; - te[9] = df - ce * b; - - te[2] = - a * d; - te[6] = b; - te[10] = a * c; - - } else if ( euler.order === 'ZYX' ) { - - var ae = a * e, af = a * f, be = b * e, bf = b * f; - - te[0] = c * e; - te[4] = be * d - af; - te[8] = ae * d + bf; - - te[1] = c * f; - te[5] = bf * d + ae; - te[9] = af * d - be; - - te[2] = - d; - te[6] = b * c; - te[10] = a * c; - - } else if ( euler.order === 'YZX' ) { - - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - - te[0] = c * e; - te[4] = bd - ac * f; - te[8] = bc * f + ad; - - te[1] = f; - te[5] = a * e; - te[9] = - b * e; - - te[2] = - d * e; - te[6] = ad * f + bc; - te[10] = ac - bd * f; - - } else if ( euler.order === 'XZY' ) { - - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - - te[0] = c * e; - te[4] = - f; - te[8] = d * e; - - te[1] = ac * f + bd; - te[5] = a * e; - te[9] = ad * f - bc; - - te[2] = bc * f - ad; - te[6] = b * e; - te[10] = bd * f + ac; - - } - - // last column - te[3] = 0; - te[7] = 0; - te[11] = 0; - - // bottom row - te[12] = 0; - te[13] = 0; - te[14] = 0; - te[15] = 1; - - return this; - - }, - - setRotationFromQuaternion: function ( q ) { - - console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' ); - - return this.makeRotationFromQuaternion( q ); - - }, - - makeRotationFromQuaternion: function ( q ) { - - var te = this.elements; - - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x, y2 = y + y, z2 = z + z; - var xx = x * x2, xy = x * y2, xz = x * z2; - var yy = y * y2, yz = y * z2, zz = z * z2; - var wx = w * x2, wy = w * y2, wz = w * z2; - - te[0] = 1 - ( yy + zz ); - te[4] = xy - wz; - te[8] = xz + wy; - - te[1] = xy + wz; - te[5] = 1 - ( xx + zz ); - te[9] = yz - wx; - - te[2] = xz - wy; - te[6] = yz + wx; - te[10] = 1 - ( xx + yy ); - - // last column - te[3] = 0; - te[7] = 0; - te[11] = 0; - - // bottom row - te[12] = 0; - te[13] = 0; - te[14] = 0; - te[15] = 1; - - return this; - - }, - - lookAt: function() { - - var x = new THREE.Vector3(); - var y = new THREE.Vector3(); - var z = new THREE.Vector3(); - - return function ( eye, target, up ) { - - var te = this.elements; - - z.subVectors( eye, target ).normalize(); - - if ( z.length() === 0 ) { - - z.z = 1; - - } - - x.crossVectors( up, z ).normalize(); - - if ( x.length() === 0 ) { - - z.x += 0.0001; - x.crossVectors( up, z ).normalize(); - - } - - y.crossVectors( z, x ); - - - te[0] = x.x; te[4] = y.x; te[8] = z.x; - te[1] = x.y; te[5] = y.y; te[9] = z.y; - te[2] = x.z; te[6] = y.z; te[10] = z.z; - - return this; - - }; - - }(), - - multiply: function ( m, n ) { - - if ( n !== undefined ) { - - console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); - - } - - return this.multiplyMatrices( this, m ); - - }, - - multiplyMatrices: function ( a, b ) { - - var ae = a.elements; - var be = b.elements; - var te = this.elements; - - var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; - var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; - var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; - var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; - - var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; - var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; - var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; - var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; - - te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - - te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - - te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - - te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - - return this; - - }, - - multiplyToArray: function ( a, b, r ) { - - var te = this.elements; - - this.multiplyMatrices( a, b ); - - r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3]; - r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7]; - r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11]; - r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15]; - - return this; - - }, - - multiplyScalar: function ( s ) { - - var te = this.elements; - - te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s; - te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s; - te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s; - te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s; - - return this; - - }, - - multiplyVector3: function ( vector ) { - - console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); - return vector.applyProjection( this ); - - }, - - multiplyVector4: function ( vector ) { - - console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - - }, - - multiplyVector3Array: function() { - - var v1 = new THREE.Vector3(); - - return function ( a ) { - - for ( var i = 0, il = a.length; i < il; i += 3 ) { - - v1.x = a[ i ]; - v1.y = a[ i + 1 ]; - v1.z = a[ i + 2 ]; - - v1.applyProjection( this ); - - a[ i ] = v1.x; - a[ i + 1 ] = v1.y; - a[ i + 2 ] = v1.z; - - } - - return a; - - }; - - }(), - - rotateAxis: function ( v ) { - - console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - - v.transformDirection( this ); - - }, - - crossVector: function ( vector ) { - - console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - - }, - - determinant: function () { - - var te = this.elements; - - var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; - var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; - var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; - var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; - - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - - return ( - n41 * ( - +n14 * n23 * n32 - -n13 * n24 * n32 - -n14 * n22 * n33 - +n12 * n24 * n33 - +n13 * n22 * n34 - -n12 * n23 * n34 - ) + - n42 * ( - +n11 * n23 * n34 - -n11 * n24 * n33 - +n14 * n21 * n33 - -n13 * n21 * n34 - +n13 * n24 * n31 - -n14 * n23 * n31 - ) + - n43 * ( - +n11 * n24 * n32 - -n11 * n22 * n34 - -n14 * n21 * n32 - +n12 * n21 * n34 - +n14 * n22 * n31 - -n12 * n24 * n31 - ) + - n44 * ( - -n13 * n22 * n31 - -n11 * n23 * n32 - +n11 * n22 * n33 - +n13 * n21 * n32 - -n12 * n21 * n33 - +n12 * n23 * n31 - ) - - ); - - }, - - transpose: function () { - - var te = this.elements; - var tmp; - - tmp = te[1]; te[1] = te[4]; te[4] = tmp; - tmp = te[2]; te[2] = te[8]; te[8] = tmp; - tmp = te[6]; te[6] = te[9]; te[9] = tmp; - - tmp = te[3]; te[3] = te[12]; te[12] = tmp; - tmp = te[7]; te[7] = te[13]; te[13] = tmp; - tmp = te[11]; te[11] = te[14]; te[14] = tmp; - - return this; - - }, - - flattenToArray: function ( flat ) { - - var te = this.elements; - flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3]; - flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7]; - flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11]; - flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15]; - - return flat; - - }, - - flattenToArrayOffset: function( flat, offset ) { - - var te = this.elements; - flat[ offset ] = te[0]; - flat[ offset + 1 ] = te[1]; - flat[ offset + 2 ] = te[2]; - flat[ offset + 3 ] = te[3]; - - flat[ offset + 4 ] = te[4]; - flat[ offset + 5 ] = te[5]; - flat[ offset + 6 ] = te[6]; - flat[ offset + 7 ] = te[7]; - - flat[ offset + 8 ] = te[8]; - flat[ offset + 9 ] = te[9]; - flat[ offset + 10 ] = te[10]; - flat[ offset + 11 ] = te[11]; - - flat[ offset + 12 ] = te[12]; - flat[ offset + 13 ] = te[13]; - flat[ offset + 14 ] = te[14]; - flat[ offset + 15 ] = te[15]; - - return flat; - - }, - - getPosition: function() { - - var v1 = new THREE.Vector3(); - - return function () { - - console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - - var te = this.elements; - return v1.set( te[12], te[13], te[14] ); - - }; - - }(), - - setPosition: function ( v ) { - - var te = this.elements; - - te[12] = v.x; - te[13] = v.y; - te[14] = v.z; - - return this; - - }, - - getInverse: function ( m, throwOnInvertible ) { - - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements; - var me = m.elements; - - var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12]; - var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13]; - var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14]; - var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15]; - - te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44; - te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44; - te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44; - te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34; - te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44; - te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44; - te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44; - te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34; - te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44; - te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44; - te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44; - te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34; - te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43; - te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43; - te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43; - te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33; - - var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ]; - - if ( det == 0 ) { - - var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0"; - - if ( throwOnInvertible || false ) { - - throw new Error( msg ); - - } else { - - console.warn( msg ); - - } - - this.identity(); - - return this; - } - - this.multiplyScalar( 1 / det ); - - return this; - - }, - - translate: function ( v ) { - - console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.'); - - }, - - rotateX: function ( angle ) { - - console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.'); - - }, - - rotateY: function ( angle ) { - - console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.'); - - }, - - rotateZ: function ( angle ) { - - console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.'); - - }, - - rotateByAxis: function ( axis, angle ) { - - console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.'); - - }, - - scale: function ( v ) { - - var te = this.elements; - var x = v.x, y = v.y, z = v.z; - - te[0] *= x; te[4] *= y; te[8] *= z; - te[1] *= x; te[5] *= y; te[9] *= z; - te[2] *= x; te[6] *= y; te[10] *= z; - te[3] *= x; te[7] *= y; te[11] *= z; - - return this; - - }, - - getMaxScaleOnAxis: function () { - - var te = this.elements; - - var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; - var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; - var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; - - return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) ); - - }, - - makeTranslation: function ( x, y, z ) { - - this.set( - - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 - - ); - - return this; - - }, - - makeRotationX: function ( theta ) { - - var c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - 1, 0, 0, 0, - 0, c, -s, 0, - 0, s, c, 0, - 0, 0, 0, 1 - - ); - - return this; - - }, - - makeRotationY: function ( theta ) { - - var c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - c, 0, s, 0, - 0, 1, 0, 0, - -s, 0, c, 0, - 0, 0, 0, 1 - - ); - - return this; - - }, - - makeRotationZ: function ( theta ) { - - var c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( - - c, -s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - - ); - - return this; - - }, - - makeRotationAxis: function ( axis, angle ) { - - // Based on http://www.gamedev.net/reference/articles/article1199.asp - - var c = Math.cos( angle ); - var s = Math.sin( angle ); - var t = 1 - c; - var x = axis.x, y = axis.y, z = axis.z; - var tx = t * x, ty = t * y; - - this.set( - - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 - - ); - - return this; - - }, - - makeScale: function ( x, y, z ) { - - this.set( - - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 - - ); - - return this; - - }, - - compose: function ( position, quaternion, scale ) { - - this.makeRotationFromQuaternion( quaternion ); - this.scale( scale ); - this.setPosition( position ); - - return this; - - }, - - decompose: function () { - - var vector = new THREE.Vector3(); - var matrix = new THREE.Matrix4(); - - return function ( position, quaternion, scale ) { - - var te = this.elements; - - var sx = vector.set( te[0], te[1], te[2] ).length(); - var sy = vector.set( te[4], te[5], te[6] ).length(); - var sz = vector.set( te[8], te[9], te[10] ).length(); - - // if determine is negative, we need to invert one scale - var det = this.determinant(); - if( det < 0 ) { - sx = -sx; - } - - position.x = te[12]; - position.y = te[13]; - position.z = te[14]; - - // scale the rotation part - - matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() - - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; - - matrix.elements[0] *= invSX; - matrix.elements[1] *= invSX; - matrix.elements[2] *= invSX; - - matrix.elements[4] *= invSY; - matrix.elements[5] *= invSY; - matrix.elements[6] *= invSY; - - matrix.elements[8] *= invSZ; - matrix.elements[9] *= invSZ; - matrix.elements[10] *= invSZ; - - quaternion.setFromRotationMatrix( matrix ); - - scale.x = sx; - scale.y = sy; - scale.z = sz; - - return this; - - }; - - }(), - - makeFrustum: function ( left, right, bottom, top, near, far ) { - - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); - - var a = ( right + left ) / ( right - left ); - var b = ( top + bottom ) / ( top - bottom ); - var c = - ( far + near ) / ( far - near ); - var d = - 2 * far * near / ( far - near ); - - te[0] = x; te[4] = 0; te[8] = a; te[12] = 0; - te[1] = 0; te[5] = y; te[9] = b; te[13] = 0; - te[2] = 0; te[6] = 0; te[10] = c; te[14] = d; - te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0; - - return this; - - }, - - makePerspective: function ( fov, aspect, near, far ) { - - var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) ); - var ymin = - ymax; - var xmin = ymin * aspect; - var xmax = ymax * aspect; - - return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); - - }, - - makeOrthographic: function ( left, right, top, bottom, near, far ) { - - var te = this.elements; - var w = right - left; - var h = top - bottom; - var p = far - near; - - var x = ( right + left ) / w; - var y = ( top + bottom ) / h; - var z = ( far + near ) / p; - - te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x; - te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y; - te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z; - te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1; - - return this; - - }, - - fromArray: function ( array ) { - - this.elements.set( array ); - - return this; - - }, - - toArray: function () { - - var te = this.elements; - - return [ - te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ], - te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ], - te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ], - te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ] - ]; - - }, - - clone: function () { - - var te = this.elements; - - return new THREE.Matrix4( - - te[0], te[4], te[8], te[12], - te[1], te[5], te[9], te[13], - te[2], te[6], te[10], te[14], - te[3], te[7], te[11], te[15] - - ); - - } - -}; -/** - * @author bhouston / http://exocortex.com - */ - -THREE.Ray = function ( origin, direction ) { - - this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); - this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); - -}; - -THREE.Ray.prototype = { - - constructor: THREE.Ray, - - set: function ( origin, direction ) { - - this.origin.copy( origin ); - this.direction.copy( direction ); - - return this; - - }, - - copy: function ( ray ) { - - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); - - return this; - - }, - - at: function ( t, optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - - return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - - }, - - recast: function () { - - var v1 = new THREE.Vector3(); - - return function ( t ) { - - this.origin.copy( this.at( t, v1 ) ); - - return this; - - }; - - }(), - - closestPointToPoint: function ( point, optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - result.subVectors( point, this.origin ); - var directionDistance = result.dot( this.direction ); - - if ( directionDistance < 0 ) { - - return result.copy( this.origin ); - - } - - return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - - }, - - distanceToPoint: function () { - - var v1 = new THREE.Vector3(); - - return function ( point ) { - - var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); - - // point behind the ray - - if ( directionDistance < 0 ) { - - return this.origin.distanceTo( point ); - - } - - v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - - return v1.distanceTo( point ); - - }; - - }(), - - distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - - // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment - - var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 ); - var segDir = v1.clone().sub( v0 ).normalize(); - var segExtent = v0.distanceTo( v1 ) * 0.5; - var diff = this.origin.clone().sub( segCenter ); - var a01 = - this.direction.dot( segDir ); - var b0 = diff.dot( this.direction ); - var b1 = - diff.dot( segDir ); - var c = diff.lengthSq(); - var det = Math.abs( 1 - a01 * a01 ); - var s0, s1, sqrDist, extDet; - - if ( det >= 0 ) { - - // The ray and segment are not parallel. - - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; - - if ( s0 >= 0 ) { - - if ( s1 >= - extDet ) { - - if ( s1 <= extDet ) { - - // region 0 - // Minimum at interior points of ray and segment. - - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - - } else { - - // region 1 - - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } else { - - // region 5 - - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } else { - - if ( s1 <= - extDet) { - - // region 4 - - s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } else if ( s1 <= extDet ) { - - // region 3 - - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; - - } else { - - // region 2 - - s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - } - - } else { - - // Ray and segment are parallel. - - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - - } - - if ( optionalPointOnRay ) { - - optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) ); - - } - - if ( optionalPointOnSegment ) { - - optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) ); - - } - - return sqrDist; - - }, - - isIntersectionSphere: function ( sphere ) { - - return this.distanceToPoint( sphere.center ) <= sphere.radius; - - }, - - isIntersectionPlane: function ( plane ) { - - // check if the ray lies on the plane first - - var distToPoint = plane.distanceToPoint( this.origin ); - - if ( distToPoint === 0 ) { - - return true; - - } - - var denominator = plane.normal.dot( this.direction ); - - if ( denominator * distToPoint < 0 ) { - - return true - - } - - // ray origin is behind the plane (and is pointing behind it) - - return false; - - }, - - distanceToPlane: function ( plane ) { - - var denominator = plane.normal.dot( this.direction ); - if ( denominator == 0 ) { - - // line is coplanar, return origin - if( plane.distanceToPoint( this.origin ) == 0 ) { - - return 0; - - } - - // Null is preferable to undefined since undefined means.... it is undefined - - return null; - - } - - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - - // Return if the ray never intersects the plane - - return t >= 0 ? t : null; - - }, - - intersectPlane: function ( plane, optionalTarget ) { - - var t = this.distanceToPlane( plane ); - - if ( t === null ) { - - return null; - } - - return this.at( t, optionalTarget ); - - }, - - isIntersectionBox: function () { - - var v = new THREE.Vector3(); - - return function ( box ) { - - return this.intersectBox( box, v ) !== null; - - } - - }(), - - intersectBox: function ( box , optionalTarget ) { - - // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/ - - var tmin,tmax,tymin,tymax,tzmin,tzmax; - - var invdirx = 1/this.direction.x, - invdiry = 1/this.direction.y, - invdirz = 1/this.direction.z; - - var origin = this.origin; - - if (invdirx >= 0) { - - tmin = (box.min.x - origin.x) * invdirx; - tmax = (box.max.x - origin.x) * invdirx; - - } else { - - tmin = (box.max.x - origin.x) * invdirx; - tmax = (box.min.x - origin.x) * invdirx; - } - - if (invdiry >= 0) { - - tymin = (box.min.y - origin.y) * invdiry; - tymax = (box.max.y - origin.y) * invdiry; - - } else { - - tymin = (box.max.y - origin.y) * invdiry; - tymax = (box.min.y - origin.y) * invdiry; - } - - if ((tmin > tymax) || (tymin > tmax)) return null; - - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN - - if (tymin > tmin || tmin !== tmin ) tmin = tymin; - - if (tymax < tmax || tmax !== tmax ) tmax = tymax; - - if (invdirz >= 0) { - - tzmin = (box.min.z - origin.z) * invdirz; - tzmax = (box.max.z - origin.z) * invdirz; - - } else { - - tzmin = (box.max.z - origin.z) * invdirz; - tzmax = (box.min.z - origin.z) * invdirz; - } - - if ((tmin > tzmax) || (tzmin > tmax)) return null; - - if (tzmin > tmin || tmin !== tmin ) tmin = tzmin; - - if (tzmax < tmax || tmax !== tmax ) tmax = tzmax; - - //return point closest to the ray (positive side) - - if ( tmax < 0 ) return null; - - return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); - - }, - - intersectTriangle: function() { - - // Compute the offset origin, edges, and normal. - var diff = new THREE.Vector3(); - var edge1 = new THREE.Vector3(); - var edge2 = new THREE.Vector3(); - var normal = new THREE.Vector3(); - - return function ( a, b, c, backfaceCulling, optionalTarget ) { - - // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp - - edge1.subVectors( b, a ); - edge2.subVectors( c, a ); - normal.crossVectors( edge1, edge2 ); - - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - var DdN = this.direction.dot( normal ); - var sign; - - if ( DdN > 0 ) { - - if ( backfaceCulling ) return null; - sign = 1; - - } else if ( DdN < 0 ) { - - sign = - 1; - DdN = - DdN; - - } else { - - return null; - - } - - diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { - - return null; - - } - - var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); - - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { - - return null; - - } - - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { - - return null; - - } - - // Line intersects triangle, check if ray does. - var QdN = - sign * diff.dot( normal ); - - // t < 0, no intersection - if ( QdN < 0 ) { - - return null; - - } - - // Ray intersects triangle. - return this.at( QdN / DdN, optionalTarget ); - - } - - }(), - - applyMatrix4: function ( matrix4 ) { - - this.direction.add( this.origin ).applyMatrix4( matrix4 ); - this.origin.applyMatrix4( matrix4 ); - this.direction.sub( this.origin ); - this.direction.normalize(); - - return this; - }, - - equals: function ( ray ) { - - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - - }, - - clone: function () { - - return new THREE.Ray().copy( this ); - - } - -}; -/** - * @author bhouston / http://exocortex.com - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Sphere = function ( center, radius ) { - - this.center = ( center !== undefined ) ? center : new THREE.Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; - -}; - -THREE.Sphere.prototype = { - - constructor: THREE.Sphere, - - set: function ( center, radius ) { - - this.center.copy( center ); - this.radius = radius; - - return this; - }, - - - setFromPoints: function () { - - var box = new THREE.Box3(); - - return function ( points, optionalCenter ) { - - var center = this.center; - - if ( optionalCenter !== undefined ) { - - center.copy( optionalCenter ); - - } else { - - box.setFromPoints( points ).center( center ); - - } - - var maxRadiusSq = 0; - - for ( var i = 0, il = points.length; i < il; i ++ ) { - - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - - } - - this.radius = Math.sqrt( maxRadiusSq ); - - return this; - - }; - - }(), - - copy: function ( sphere ) { - - this.center.copy( sphere.center ); - this.radius = sphere.radius; - - return this; - - }, - - empty: function () { - - return ( this.radius <= 0 ); - - }, - - containsPoint: function ( point ) { - - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - - }, - - distanceToPoint: function ( point ) { - - return ( point.distanceTo( this.center ) - this.radius ); - - }, - - intersectsSphere: function ( sphere ) { - - var radiusSum = this.radius + sphere.radius; - - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - - }, - - clampPoint: function ( point, optionalTarget ) { - - var deltaLengthSq = this.center.distanceToSquared( point ); - - var result = optionalTarget || new THREE.Vector3(); - result.copy( point ); - - if ( deltaLengthSq > ( this.radius * this.radius ) ) { - - result.sub( this.center ).normalize(); - result.multiplyScalar( this.radius ).add( this.center ); - - } - - return result; - - }, - - getBoundingBox: function ( optionalTarget ) { - - var box = optionalTarget || new THREE.Box3(); - - box.set( this.center, this.center ); - box.expandByScalar( this.radius ); - - return box; - - }, - - applyMatrix4: function ( matrix ) { - - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); - - return this; - - }, - - translate: function ( offset ) { - - this.center.add( offset ); - - return this; - - }, - - equals: function ( sphere ) { - - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - - }, - - clone: function () { - - return new THREE.Sphere().copy( this ); - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://exocortex.com - */ - -THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) { - - this.planes = [ - - ( p0 !== undefined ) ? p0 : new THREE.Plane(), - ( p1 !== undefined ) ? p1 : new THREE.Plane(), - ( p2 !== undefined ) ? p2 : new THREE.Plane(), - ( p3 !== undefined ) ? p3 : new THREE.Plane(), - ( p4 !== undefined ) ? p4 : new THREE.Plane(), - ( p5 !== undefined ) ? p5 : new THREE.Plane() - - ]; - -}; - -THREE.Frustum.prototype = { - - constructor: THREE.Frustum, - - set: function ( p0, p1, p2, p3, p4, p5 ) { - - var planes = this.planes; - - planes[0].copy( p0 ); - planes[1].copy( p1 ); - planes[2].copy( p2 ); - planes[3].copy( p3 ); - planes[4].copy( p4 ); - planes[5].copy( p5 ); - - return this; - - }, - - copy: function ( frustum ) { - - var planes = this.planes; - - for( var i = 0; i < 6; i ++ ) { - - planes[i].copy( frustum.planes[i] ); - - } - - return this; - - }, - - setFromMatrix: function ( m ) { - - var planes = this.planes; - var me = m.elements; - var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; - var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; - var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; - var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; - - planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); - planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); - planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); - planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); - planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - - return this; - - }, - - intersectsObject: function () { - - var sphere = new THREE.Sphere(); - - return function ( object ) { - - var geometry = object.geometry; - - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( object.matrixWorld ); - - return this.intersectsSphere( sphere ); - - }; - - }(), - - intersectsSphere: function ( sphere ) { - - var planes = this.planes; - var center = sphere.center; - var negRadius = -sphere.radius; - - for ( var i = 0; i < 6; i ++ ) { - - var distance = planes[ i ].distanceToPoint( center ); - - if ( distance < negRadius ) { - - return false; - - } - - } - - return true; - - }, - - intersectsBox : function() { - - var p1 = new THREE.Vector3(), - p2 = new THREE.Vector3(); - - return function( box ) { - - var planes = this.planes; - - for ( var i = 0; i < 6 ; i ++ ) { - - var plane = planes[i]; - - p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; - p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; - p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; - p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; - p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; - p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; - - var d1 = plane.distanceToPoint( p1 ); - var d2 = plane.distanceToPoint( p2 ); - - // if both outside plane, no intersection - - if ( d1 < 0 && d2 < 0 ) { - - return false; - - } - } - - return true; - }; - - }(), - - - containsPoint: function ( point ) { - - var planes = this.planes; - - for ( var i = 0; i < 6; i ++ ) { - - if ( planes[ i ].distanceToPoint( point ) < 0 ) { - - return false; - - } - - } - - return true; - - }, - - clone: function () { - - return new THREE.Frustum().copy( this ); - - } - -}; -/** - * @author bhouston / http://exocortex.com - */ - -THREE.Plane = function ( normal, constant ) { - - this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; - -}; - -THREE.Plane.prototype = { - - constructor: THREE.Plane, - - set: function ( normal, constant ) { - - this.normal.copy( normal ); - this.constant = constant; - - return this; - - }, - - setComponents: function ( x, y, z, w ) { - - this.normal.set( x, y, z ); - this.constant = w; - - return this; - - }, - - setFromNormalAndCoplanarPoint: function ( normal, point ) { - - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized - - return this; - - }, - - setFromCoplanarPoints: function() { - - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - - return function ( a, b, c ) { - - var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); - - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - - this.setFromNormalAndCoplanarPoint( normal, a ); - - return this; - - }; - - }(), - - - copy: function ( plane ) { - - this.normal.copy( plane.normal ); - this.constant = plane.constant; - - return this; - - }, - - normalize: function () { - - // Note: will lead to a divide by zero if the plane is invalid. - - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; - - return this; - - }, - - negate: function () { - - this.constant *= -1; - this.normal.negate(); - - return this; - - }, - - distanceToPoint: function ( point ) { - - return this.normal.dot( point ) + this.constant; - - }, - - distanceToSphere: function ( sphere ) { - - return this.distanceToPoint( sphere.center ) - sphere.radius; - - }, - - projectPoint: function ( point, optionalTarget ) { - - return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); - - }, - - orthoPoint: function ( point, optionalTarget ) { - - var perpendicularMagnitude = this.distanceToPoint( point ); - - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); - - }, - - isIntersectionLine: function ( line ) { - - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); - - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - - }, - - intersectLine: function() { - - var v1 = new THREE.Vector3(); - - return function ( line, optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - - var direction = line.delta( v1 ); - - var denominator = this.normal.dot( direction ); - - if ( denominator == 0 ) { - - // line is coplanar, return origin - if( this.distanceToPoint( line.start ) == 0 ) { - - return result.copy( line.start ); - - } - - // Unsure if this is the correct method to handle this case. - return undefined; - - } - - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - - if( t < 0 || t > 1 ) { - - return undefined; - - } - - return result.copy( direction ).multiplyScalar( t ).add( line.start ); - - }; - - }(), - - - coplanarPoint: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( - this.constant ); - - }, - - applyMatrix4: function() { - - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var m1 = new THREE.Matrix3(); - - return function ( matrix, optionalNormalMatrix ) { - - // compute new normal based on theory here: - // http://www.songho.ca/opengl/gl_normaltransform.html - var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); - var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix ); - - var newCoplanarPoint = this.coplanarPoint( v2 ); - newCoplanarPoint.applyMatrix4( matrix ); - - this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint ); - - return this; - - }; - - }(), - - translate: function ( offset ) { - - this.constant = this.constant - offset.dot( this.normal ); - - return this; - - }, - - equals: function ( plane ) { - - return plane.normal.equals( this.normal ) && ( plane.constant == this.constant ); - - }, - - clone: function () { - - return new THREE.Plane().copy( this ); - - } - -}; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Math = { - - PI2: Math.PI * 2, - - generateUUID: function () { - - // http://www.broofa.com/Tools/Math.uuid.htm - - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); - var uuid = new Array(36); - var rnd = 0, r; - - return function () { - - for ( var i = 0; i < 36; i ++ ) { - - if ( i == 8 || i == 13 || i == 18 || i == 23 ) { - - uuid[ i ] = '-'; - - } else if ( i == 14 ) { - - uuid[ i ] = '4'; - - } else { - - if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; - r = rnd & 0xf; - rnd = rnd >> 4; - uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; - - } - } - - return uuid.join(''); - - }; - - }(), - - // Clamp value to range - - clamp: function ( x, a, b ) { - - return ( x < a ) ? a : ( ( x > b ) ? b : x ); - - }, - - // Clamp value to range to range - - mapLinear: function ( x, a1, a2, b1, b2 ) { - - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - - }, - - // http://en.wikipedia.org/wiki/Smoothstep - - smoothstep: function ( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min )/( max - min ); - - return x*x*(3 - 2*x); - - }, - - smootherstep: function ( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min )/( max - min ); - - return x*x*x*(x*(x*6 - 15) + 10); - - }, - - // Random float from <0, 1> with 16 bits of randomness - // (standard Math.random() creates repetitive patterns when applied over larger space) - - random16: function () { - - return ( 65280 * Math.random() + 255 * Math.random() ) / 65535; - - }, - - // Random integer from interval - - randInt: function ( low, high ) { - - return low + Math.floor( Math.random() * ( high - low + 1 ) ); - - }, - - // Random float from interval - - randFloat: function ( low, high ) { - - return low + Math.random() * ( high - low ); - - }, - - // Random float from <-range/2, range/2> interval - - randFloatSpread: function ( range ) { - - return range * ( 0.5 - Math.random() ); - - }, - - sign: function ( x ) { - - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0; - - }, - - degToRad: function() { - - var degreeToRadiansFactor = Math.PI / 180; - - return function ( degrees ) { - - return degrees * degreeToRadiansFactor; - - }; - - }(), - - radToDeg: function() { - - var radianToDegreesFactor = 180 / Math.PI; - - return function ( radians ) { - - return radians * radianToDegreesFactor; - - }; - - }(), - - isPowerOfTwo: function ( value ) { - return ( value & ( value - 1 ) ) === 0 && value !== 0; - } - -}; -/** - * Spline from Tween.js, slightly optimized (and trashed) - * http://sole.github.com/tween.js/examples/05_spline.html - * - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Spline = function ( points ) { - - this.points = points; - - var c = [], v3 = { x: 0, y: 0, z: 0 }, - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; - - this.initFromArray = function( a ) { - - this.points = []; - - for ( var i = 0; i < a.length; i++ ) { - - this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; - - } - - }; - - this.getPoint = function ( k ) { - - point = ( this.points.length - 1 ) * k; - intPoint = Math.floor( point ); - weight = point - intPoint; - - c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1; - c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2; - - pa = this.points[ c[ 0 ] ]; - pb = this.points[ c[ 1 ] ]; - pc = this.points[ c[ 2 ] ]; - pd = this.points[ c[ 3 ] ]; - - w2 = weight * weight; - w3 = weight * w2; - - v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 ); - v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 ); - v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 ); - - return v3; - - }; - - this.getControlPointsArray = function () { - - var i, p, l = this.points.length, - coords = []; - - for ( i = 0; i < l; i ++ ) { - - p = this.points[ i ]; - coords[ i ] = [ p.x, p.y, p.z ]; - - } - - return coords; - - }; - - // approximate length by summing linear segments - - this.getLength = function ( nSubDivisions ) { - - var i, index, nSamples, position, - point = 0, intPoint = 0, oldIntPoint = 0, - oldPosition = new THREE.Vector3(), - tmpVec = new THREE.Vector3(), - chunkLengths = [], - totalLength = 0; - - // first point has 0 length - - chunkLengths[ 0 ] = 0; - - if ( !nSubDivisions ) nSubDivisions = 100; - - nSamples = this.points.length * nSubDivisions; - - oldPosition.copy( this.points[ 0 ] ); - - for ( i = 1; i < nSamples; i ++ ) { - - index = i / nSamples; - - position = this.getPoint( index ); - tmpVec.copy( position ); - - totalLength += tmpVec.distanceTo( oldPosition ); - - oldPosition.copy( position ); - - point = ( this.points.length - 1 ) * index; - intPoint = Math.floor( point ); - - if ( intPoint != oldIntPoint ) { - - chunkLengths[ intPoint ] = totalLength; - oldIntPoint = intPoint; - - } - - } - - // last point ends with total length - - chunkLengths[ chunkLengths.length ] = totalLength; - - return { chunks: chunkLengths, total: totalLength }; - - }; - - this.reparametrizeByArcLength = function ( samplingCoef ) { - - var i, j, - index, indexCurrent, indexNext, - linearDistance, realDistance, - sampling, position, - newpoints = [], - tmpVec = new THREE.Vector3(), - sl = this.getLength(); - - newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); - - for ( i = 1; i < this.points.length; i++ ) { - - //tmpVec.copy( this.points[ i - 1 ] ); - //linearDistance = tmpVec.distanceTo( this.points[ i ] ); - - realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; - - sampling = Math.ceil( samplingCoef * realDistance / sl.total ); - - indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); - indexNext = i / ( this.points.length - 1 ); - - for ( j = 1; j < sampling - 1; j++ ) { - - index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); - - position = this.getPoint( index ); - newpoints.push( tmpVec.copy( position ).clone() ); - - } - - newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); - - } - - this.points = newpoints; - - }; - - // Catmull-Rom - - function interpolate( p0, p1, p2, p3, t, t2, t3 ) { - - var v0 = ( p2 - p0 ) * 0.5, - v1 = ( p3 - p1 ) * 0.5; - - return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; - - }; - -}; -/** - * @author bhouston / http://exocortex.com - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Triangle = function ( a, b, c ) { - - this.a = ( a !== undefined ) ? a : new THREE.Vector3(); - this.b = ( b !== undefined ) ? b : new THREE.Vector3(); - this.c = ( c !== undefined ) ? c : new THREE.Vector3(); - -}; - -THREE.Triangle.normal = function() { - - var v0 = new THREE.Vector3(); - - return function ( a, b, c, optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - - result.subVectors( c, b ); - v0.subVectors( a, b ); - result.cross( v0 ); - - var resultLengthSq = result.lengthSq(); - if( resultLengthSq > 0 ) { - - return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); - - } - - return result.set( 0, 0, 0 ); - - }; - -}(); - -// static/instance method to calculate barycoordinates -// based on: http://www.blackpawn.com/texts/pointinpoly/default.html -THREE.Triangle.barycoordFromPoint = function() { - - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - - return function ( point, a, b, c, optionalTarget ) { - - v0.subVectors( c, a ); - v1.subVectors( b, a ); - v2.subVectors( point, a ); - - var dot00 = v0.dot( v0 ); - var dot01 = v0.dot( v1 ); - var dot02 = v0.dot( v2 ); - var dot11 = v1.dot( v1 ); - var dot12 = v1.dot( v2 ); - - var denom = ( dot00 * dot11 - dot01 * dot01 ); - - var result = optionalTarget || new THREE.Vector3(); - - // colinear or singular triangle - if( denom == 0 ) { - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return result.set( -2, -1, -1 ); - } - - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - - // barycoordinates must always sum to 1 - return result.set( 1 - u - v, v, u ); - - }; - -}(); - -THREE.Triangle.containsPoint = function() { - - var v1 = new THREE.Vector3(); - - return function ( point, a, b, c ) { - - var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); - - return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); - - }; - -}(); - -THREE.Triangle.prototype = { - - constructor: THREE.Triangle, - - set: function ( a, b, c ) { - - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); - - return this; - - }, - - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { - - this.a.copy( points[i0] ); - this.b.copy( points[i1] ); - this.c.copy( points[i2] ); - - return this; - - }, - - copy: function ( triangle ) { - - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); - - return this; - - }, - - area: function() { - - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); - - return function () { - - v0.subVectors( this.c, this.b ); - v1.subVectors( this.a, this.b ); - - return v0.cross( v1 ).length() * 0.5; - - }; - - }(), - - midpoint: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - - }, - - normal: function ( optionalTarget ) { - - return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); - - }, - - plane: function ( optionalTarget ) { - - var result = optionalTarget || new THREE.Plane(); - - return result.setFromCoplanarPoints( this.a, this.b, this.c ); - - }, - - barycoordFromPoint: function ( point, optionalTarget ) { - - return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); - - }, - - containsPoint: function ( point ) { - - return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); - - }, - - equals: function ( triangle ) { - - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - - }, - - clone: function () { - - return new THREE.Triangle().copy( this ); - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Vertex = function ( v ) { - - console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.') - return v; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.UV = function ( u, v ) { - - console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.') - return new THREE.Vector2( u, v ); - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Clock = function ( autoStart ) { - - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; - - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; - - this.running = false; - -}; - -THREE.Clock.prototype = { - - constructor: THREE.Clock, - - start: function () { - - this.startTime = self.performance !== undefined && self.performance.now !== undefined - ? self.performance.now() - : Date.now(); - - this.oldTime = this.startTime; - this.running = true; - }, - - stop: function () { - - this.getElapsedTime(); - this.running = false; - - }, - - getElapsedTime: function () { - - this.getDelta(); - return this.elapsedTime; - - }, - - getDelta: function () { - - var diff = 0; - - if ( this.autoStart && ! this.running ) { - - this.start(); - - } - - if ( this.running ) { - - var newTime = self.performance !== undefined && self.performance.now !== undefined - ? self.performance.now() - : Date.now(); - - diff = 0.001 * ( newTime - this.oldTime ); - this.oldTime = newTime; - - this.elapsedTime += diff; - - } - - return diff; - - } - -}; -/** - * https://github.com/mrdoob/eventdispatcher.js/ - */ - -THREE.EventDispatcher = function () {} - -THREE.EventDispatcher.prototype = { - - constructor: THREE.EventDispatcher, - - apply: function ( object ) { - - object.addEventListener = THREE.EventDispatcher.prototype.addEventListener; - object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener; - object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener; - object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent; - - }, - - addEventListener: function ( type, listener ) { - - if ( this._listeners === undefined ) this._listeners = {}; - - var listeners = this._listeners; - - if ( listeners[ type ] === undefined ) { - - listeners[ type ] = []; - - } - - if ( listeners[ type ].indexOf( listener ) === - 1 ) { - - listeners[ type ].push( listener ); - - } - - }, - - hasEventListener: function ( type, listener ) { - - if ( this._listeners === undefined ) return false; - - var listeners = this._listeners; - - if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { - - return true; - - } - - return false; - - }, - - removeEventListener: function ( type, listener ) { - - if ( this._listeners === undefined ) return; - - var listeners = this._listeners; - var listenerArray = listeners[ type ]; - - if ( listenerArray !== undefined ) { - - var index = listenerArray.indexOf( listener ); - - if ( index !== - 1 ) { - - listenerArray.splice( index, 1 ); - - } - - } - - }, - - dispatchEvent: function () { - - var array = []; - - return function ( event ) { - - if ( this._listeners === undefined ) return; - - var listeners = this._listeners; - var listenerArray = listeners[ event.type ]; - - if ( listenerArray !== undefined ) { - - event.target = this; - - var length = listenerArray.length; - - for ( var i = 0; i < length; i ++ ) { - - array[ i ] = listenerArray[ i ]; - - } - - for ( var i = 0; i < length; i ++ ) { - - array[ i ].call( this, event ); - - } - - } - - }; - - }() - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author bhouston / http://exocortex.com/ - * @author stephomi / http://stephaneginier.com/ - */ - -( function ( THREE ) { - - THREE.Raycaster = function ( origin, direction, near, far ) { - - this.ray = new THREE.Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) - - this.near = near || 0; - this.far = far || Infinity; - - }; - - var sphere = new THREE.Sphere(); - var localRay = new THREE.Ray(); - var facePlane = new THREE.Plane(); - var intersectPoint = new THREE.Vector3(); - var matrixPosition = new THREE.Vector3(); - - var inverseMatrix = new THREE.Matrix4(); - - var descSort = function ( a, b ) { - - return a.distance - b.distance; - - }; - - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); - - var intersectObject = function ( object, raycaster, intersects ) { - - if ( object instanceof THREE.Sprite ) { - - matrixPosition.setFromMatrixPosition( object.matrixWorld ); - - var distance = raycaster.ray.distanceToPoint( matrixPosition ); - - if ( distance > object.scale.x ) { - - return intersects; - - } - - intersects.push( { - - distance: distance, - point: object.position, - face: null, - object: object - - } ); - - } else if ( object instanceof THREE.LOD ) { - - matrixPosition.setFromMatrixPosition( object.matrixWorld ); - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); - - intersectObject( object.getObjectForDistance( distance ), raycaster, intersects ); - - } else if ( object instanceof THREE.Mesh ) { - - var geometry = object.geometry; - - // Checking boundingSphere distance to ray - - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( object.matrixWorld ); - - if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { - - return intersects; - - } - - // Check boundingBox before continuing - - inverseMatrix.getInverse( object.matrixWorld ); - localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - - if ( geometry.boundingBox !== null ) { - - if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) { - - return intersects; - - } - - } - - if ( geometry instanceof THREE.BufferGeometry ) { - - var material = object.material; - - if ( material === undefined ) return intersects; - - var attributes = geometry.attributes; - - var a, b, c; - var precision = raycaster.precision; - - if ( attributes.index !== undefined ) { - - var offsets = geometry.offsets; - var indices = attributes.index.array; - var positions = attributes.position.array; - - for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) { - - var start = offsets[ oi ].start; - var count = offsets[ oi ].count; - var index = offsets[ oi ].index; - - for ( var i = start, il = start + count; i < il; i += 3 ) { - - a = index + indices[ i ]; - b = index + indices[ i + 1 ]; - c = index + indices[ i + 2 ]; - - vA.set( - positions[ a * 3 ], - positions[ a * 3 + 1 ], - positions[ a * 3 + 2 ] - ); - vB.set( - positions[ b * 3 ], - positions[ b * 3 + 1 ], - positions[ b * 3 + 2 ] - ); - vC.set( - positions[ c * 3 ], - positions[ c * 3 + 1 ], - positions[ c * 3 + 2 ] - ); - - - if ( material.side === THREE.BackSide ) { - - var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true ); - - } else { - - var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); - - } - - if ( intersectionPoint === null ) continue; - - intersectionPoint.applyMatrix4( object.matrixWorld ); - - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - - intersects.push( { - - distance: distance, - point: intersectionPoint, - indices: [a, b, c], - face: null, - faceIndex: null, - object: object - - } ); - - } - - } - - } else { - - var offsets = geometry.offsets; - var positions = attributes.position.array; - - for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) { - - a = i; - b = i + 1; - c = i + 2; - - vA.set( - positions[ a * 3 ], - positions[ a * 3 + 1 ], - positions[ a * 3 + 2 ] - ); - vB.set( - positions[ b * 3 ], - positions[ b * 3 + 1 ], - positions[ b * 3 + 2 ] - ); - vC.set( - positions[ c * 3 ], - positions[ c * 3 + 1 ], - positions[ c * 3 + 2 ] - ); - - - if ( material.side === THREE.BackSide ) { - - var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true ); - - } else { - - var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); - - } - - if ( intersectionPoint === null ) continue; - - intersectionPoint.applyMatrix4( object.matrixWorld ); - - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - - intersects.push( { - - distance: distance, - point: intersectionPoint, - indices: [a, b, c], - face: null, - faceIndex: null, - object: object - - } ); - - } - - } - - } else if ( geometry instanceof THREE.Geometry ) { - - var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; - var objectMaterials = isFaceMaterial === true ? object.material.materials : null; - - var a, b, c, d; - var precision = raycaster.precision; - - var vertices = geometry.vertices; - - for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { - - var face = geometry.faces[ f ]; - - var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material; - - if ( material === undefined ) continue; - - a = vertices[ face.a ]; - b = vertices[ face.b ]; - c = vertices[ face.c ]; - - if ( material.morphTargets === true ) { - - var morphTargets = geometry.morphTargets; - var morphInfluences = object.morphTargetInfluences; - - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); - - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - - var influence = morphInfluences[ t ]; - - if ( influence === 0 ) continue; - - var targets = morphTargets[ t ].vertices; - - vA.x += ( targets[ face.a ].x - a.x ) * influence; - vA.y += ( targets[ face.a ].y - a.y ) * influence; - vA.z += ( targets[ face.a ].z - a.z ) * influence; - - vB.x += ( targets[ face.b ].x - b.x ) * influence; - vB.y += ( targets[ face.b ].y - b.y ) * influence; - vB.z += ( targets[ face.b ].z - b.z ) * influence; - - vC.x += ( targets[ face.c ].x - c.x ) * influence; - vC.y += ( targets[ face.c ].y - c.y ) * influence; - vC.z += ( targets[ face.c ].z - c.z ) * influence; - - } - - vA.add( a ); - vB.add( b ); - vC.add( c ); - - a = vA; - b = vB; - c = vC; - - } - - if ( material.side === THREE.BackSide ) { - - var intersectionPoint = localRay.intersectTriangle( c, b, a, true ); - - } else { - - var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide ); - - } - - if ( intersectionPoint === null ) continue; - - intersectionPoint.applyMatrix4( object.matrixWorld ); - - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - - intersects.push( { - - distance: distance, - point: intersectionPoint, - face: face, - faceIndex: f, - object: object - - } ); - - } - - } - - } else if ( object instanceof THREE.Line ) { - - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; - - var geometry = object.geometry; - - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - - // Checking boundingSphere distance to ray - - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( object.matrixWorld ); - - if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { - - return intersects; - - } - - inverseMatrix.getInverse( object.matrixWorld ); - localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - - /* if ( geometry instanceof THREE.BufferGeometry ) { - - } else */ if ( geometry instanceof THREE.Geometry ) { - - var vertices = geometry.vertices; - var nbVertices = vertices.length; - var interSegment = new THREE.Vector3(); - var interRay = new THREE.Vector3(); - var step = object.type === THREE.LineStrip ? 1 : 2; - - for ( var i = 0; i < nbVertices - 1; i = i + step ) { - - var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); - - if ( distSq > precisionSq ) continue; - - var distance = localRay.origin.distanceTo( interRay ); - - if ( distance < raycaster.near || distance > raycaster.far ) continue; - - intersects.push( { - - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( object.matrixWorld ), - face: null, - faceIndex: null, - object: object - - } ); - - } - - } - - } - - }; - - var intersectDescendants = function ( object, raycaster, intersects ) { - - var descendants = object.getDescendants(); - - for ( var i = 0, l = descendants.length; i < l; i ++ ) { - - intersectObject( descendants[ i ], raycaster, intersects ); - - } - }; - - // - - THREE.Raycaster.prototype.precision = 0.0001; - THREE.Raycaster.prototype.linePrecision = 1; - - THREE.Raycaster.prototype.set = function ( origin, direction ) { - - this.ray.set( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) - - }; - - THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) { - - var intersects = []; - - if ( recursive === true ) { - - intersectDescendants( object, this, intersects ); - - } - - intersectObject( object, this, intersects ); - - intersects.sort( descSort ); - - return intersects; - - }; - - THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) { - - var intersects = []; - - for ( var i = 0, l = objects.length; i < l; i ++ ) { - - intersectObject( objects[ i ], this, intersects ); - - if ( recursive === true ) { - - intersectDescendants( objects[ i ], this, intersects ); - - } - - } - - intersects.sort( descSort ); - - return intersects; - - }; - -}( THREE ) ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - */ - -THREE.Object3D = function () { - - this.id = THREE.Object3DIdCount ++; - this.uuid = THREE.Math.generateUUID(); - - this.name = ''; - - this.parent = undefined; - this.children = []; - - this.up = new THREE.Vector3( 0, 1, 0 ); - - this.position = new THREE.Vector3(); - this._rotation = new THREE.Euler(); - this._quaternion = new THREE.Quaternion(); - this.scale = new THREE.Vector3( 1, 1, 1 ); - - // keep rotation and quaternion in sync - - this._rotation._quaternion = this.quaternion; - this._quaternion._euler = this.rotation; - - this.renderDepth = null; - - this.rotationAutoUpdate = true; - - this.matrix = new THREE.Matrix4(); - this.matrixWorld = new THREE.Matrix4(); - - this.matrixAutoUpdate = true; - this.matrixWorldNeedsUpdate = true; - - this.visible = true; - - this.castShadow = false; - this.receiveShadow = false; - - this.frustumCulled = true; - - this.userData = {}; - -}; - - -THREE.Object3D.prototype = { - - constructor: THREE.Object3D, - - get rotation () { - return this._rotation; - }, - - set rotation ( value ) { - - this._rotation = value; - this._rotation._quaternion = this._quaternion; - this._quaternion._euler = this._rotation; - this._rotation._updateQuaternion(); - - }, - - get quaternion () { - return this._quaternion; - }, - - set quaternion ( value ) { - - this._quaternion = value; - this._quaternion._euler = this._rotation; - this._rotation._quaternion = this._quaternion; - this._quaternion._updateEuler(); - - }, - - get eulerOrder () { - - console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' ); - - return this.rotation.order; - - }, - - set eulerOrder ( value ) { - - console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' ); - - this.rotation.order = value; - - }, - - get useQuaternion () { - - console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' ); - - }, - - set useQuaternion ( value ) { - - console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' ); - - }, - - applyMatrix: function ( matrix ) { - - this.matrix.multiplyMatrices( matrix, this.matrix ); - - this.matrix.decompose( this.position, this.quaternion, this.scale ); - - }, - - setRotationFromAxisAngle: function ( axis, angle ) { - - // assumes axis is normalized - - this.quaternion.setFromAxisAngle( axis, angle ); - - }, - - setRotationFromEuler: function ( euler ) { - - this.quaternion.setFromEuler( euler, true ); - - }, - - setRotationFromMatrix: function ( m ) { - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - this.quaternion.setFromRotationMatrix( m ); - - }, - - setRotationFromQuaternion: function ( q ) { - - // assumes q is normalized - - this.quaternion.copy( q ); - - }, - - rotateOnAxis: function() { - - // rotate object on axis in object space - // axis is assumed to be normalized - - var q1 = new THREE.Quaternion(); - - return function ( axis, angle ) { - - q1.setFromAxisAngle( axis, angle ); - - this.quaternion.multiply( q1 ); - - return this; - - } - - }(), - - rotateX: function () { - - var v1 = new THREE.Vector3( 1, 0, 0 ); - - return function ( angle ) { - - return this.rotateOnAxis( v1, angle ); - - }; - - }(), - - rotateY: function () { - - var v1 = new THREE.Vector3( 0, 1, 0 ); - - return function ( angle ) { - - return this.rotateOnAxis( v1, angle ); - - }; - - }(), - - rotateZ: function () { - - var v1 = new THREE.Vector3( 0, 0, 1 ); - - return function ( angle ) { - - return this.rotateOnAxis( v1, angle ); - - }; - - }(), - - translateOnAxis: function () { - - // translate object by distance along axis in object space - // axis is assumed to be normalized - - var v1 = new THREE.Vector3(); - - return function ( axis, distance ) { - - v1.copy( axis ); - - v1.applyQuaternion( this.quaternion ); - - this.position.add( v1.multiplyScalar( distance ) ); - - return this; - - } - - }(), - - translate: function ( distance, axis ) { - - console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' ); - return this.translateOnAxis( axis, distance ); - - }, - - translateX: function () { - - var v1 = new THREE.Vector3( 1, 0, 0 ); - - return function ( distance ) { - - return this.translateOnAxis( v1, distance ); - - }; - - }(), - - translateY: function () { - - var v1 = new THREE.Vector3( 0, 1, 0 ); - - return function ( distance ) { - - return this.translateOnAxis( v1, distance ); - - }; - - }(), - - translateZ: function () { - - var v1 = new THREE.Vector3( 0, 0, 1 ); - - return function ( distance ) { - - return this.translateOnAxis( v1, distance ); - - }; - - }(), - - localToWorld: function ( vector ) { - - return vector.applyMatrix4( this.matrixWorld ); - - }, - - worldToLocal: function () { - - var m1 = new THREE.Matrix4(); - - return function ( vector ) { - - return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); - - }; - - }(), - - lookAt: function () { - - // This routine does not support objects with rotated and/or translated parent(s) - - var m1 = new THREE.Matrix4(); - - return function ( vector ) { - - m1.lookAt( vector, this.position, this.up ); - - this.quaternion.setFromRotationMatrix( m1 ); - - }; - - }(), - - add: function ( object ) { - - if ( object === this ) { - - console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' ); - return; - - } - - if ( object instanceof THREE.Object3D ) { - - if ( object.parent !== undefined ) { - - object.parent.remove( object ); - - } - - object.parent = this; - object.dispatchEvent( { type: 'added' } ); - - this.children.push( object ); - - // add to scene - - var scene = this; - - while ( scene.parent !== undefined ) { - - scene = scene.parent; - - } - - if ( scene !== undefined && scene instanceof THREE.Scene ) { - - scene.__addObject( object ); - - } - - } - - }, - - remove: function ( object ) { - - var index = this.children.indexOf( object ); - - if ( index !== - 1 ) { - - object.parent = undefined; - object.dispatchEvent( { type: 'removed' } ); - - this.children.splice( index, 1 ); - - // remove from scene - - var scene = this; - - while ( scene.parent !== undefined ) { - - scene = scene.parent; - - } - - if ( scene !== undefined && scene instanceof THREE.Scene ) { - - scene.__removeObject( object ); - - } - - } - - }, - - traverse: function ( callback ) { - - callback( this ); - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - this.children[ i ].traverse( callback ); - - } - - }, - - getObjectById: function ( id, recursive ) { - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - var child = this.children[ i ]; - - if ( child.id === id ) { - - return child; - - } - - if ( recursive === true ) { - - child = child.getObjectById( id, recursive ); - - if ( child !== undefined ) { - - return child; - - } - - } - - } - - return undefined; - - }, - - getObjectByName: function ( name, recursive ) { - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - var child = this.children[ i ]; - - if ( child.name === name ) { - - return child; - - } - - if ( recursive === true ) { - - child = child.getObjectByName( name, recursive ); - - if ( child !== undefined ) { - - return child; - - } - - } - - } - - return undefined; - - }, - - getChildByName: function ( name, recursive ) { - - console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name, recursive ); - - }, - - getDescendants: function ( array ) { - - if ( array === undefined ) array = []; - - Array.prototype.push.apply( array, this.children ); - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - this.children[ i ].getDescendants( array ); - - } - - return array; - - }, - - updateMatrix: function () { - - this.matrix.compose( this.position, this.quaternion, this.scale ); - - this.matrixWorldNeedsUpdate = true; - - }, - - updateMatrixWorld: function ( force ) { - - if ( this.matrixAutoUpdate === true ) this.updateMatrix(); - - if ( this.matrixWorldNeedsUpdate === true || force === true ) { - - if ( this.parent === undefined ) { - - this.matrixWorld.copy( this.matrix ); - - } else { - - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - - } - - this.matrixWorldNeedsUpdate = false; - - force = true; - - } - - // update children - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - this.children[ i ].updateMatrixWorld( force ); - - } - - }, - - clone: function ( object, recursive ) { - - if ( object === undefined ) object = new THREE.Object3D(); - if ( recursive === undefined ) recursive = true; - - object.name = this.name; - - object.up.copy( this.up ); - - object.position.copy( this.position ); - object.quaternion.copy( this.quaternion ); - object.scale.copy( this.scale ); - - object.renderDepth = this.renderDepth; - - object.rotationAutoUpdate = this.rotationAutoUpdate; - - object.matrix.copy( this.matrix ); - object.matrixWorld.copy( this.matrixWorld ); - - object.matrixAutoUpdate = this.matrixAutoUpdate; - object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate; - - object.visible = this.visible; - - object.castShadow = this.castShadow; - object.receiveShadow = this.receiveShadow; - - object.frustumCulled = this.frustumCulled; - - object.userData = JSON.parse( JSON.stringify( this.userData ) ); - - if ( recursive === true ) { - - for ( var i = 0; i < this.children.length; i ++ ) { - - var child = this.children[ i ]; - object.add( child.clone() ); - - } - - } - - return object; - - } - -}; - -THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype ); - -THREE.Object3DIdCount = 0; -/** - * @author mrdoob / http://mrdoob.com/ - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author julianwa / https://github.com/julianwa - */ - -THREE.Projector = function () { - - var _object, _objectCount, _objectPool = [], _objectPoolLength = 0, - _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0, - _face, _faceCount, _facePool = [], _facePoolLength = 0, - _line, _lineCount, _linePool = [], _linePoolLength = 0, - _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0, - - _renderData = { objects: [], lights: [], elements: [] }, - - _vA = new THREE.Vector3(), - _vB = new THREE.Vector3(), - _vC = new THREE.Vector3(), - - _vector3 = new THREE.Vector3(), - _vector4 = new THREE.Vector4(), - - _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ), - _boundingBox = new THREE.Box3(), - _points3 = new Array( 3 ), - _points4 = new Array( 4 ), - - _viewMatrix = new THREE.Matrix4(), - _viewProjectionMatrix = new THREE.Matrix4(), - - _modelMatrix, - _modelViewProjectionMatrix = new THREE.Matrix4(), - - _normalMatrix = new THREE.Matrix3(), - - _frustum = new THREE.Frustum(), - - _clippedVertex1PositionScreen = new THREE.Vector4(), - _clippedVertex2PositionScreen = new THREE.Vector4(); - - this.projectVector = function ( vector, camera ) { - - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - - _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - - return vector.applyProjection( _viewProjectionMatrix ); - - }; - - this.unprojectVector = function () { - - var projectionMatrixInverse = new THREE.Matrix4(); - - return function ( vector, camera ) { - - projectionMatrixInverse.getInverse( camera.projectionMatrix ); - _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse ); - - return vector.applyProjection( _viewProjectionMatrix ); - - }; - - }(); - - this.pickingRay = function ( vector, camera ) { - - // set two vectors with opposing z values - vector.z = -1.0; - var end = new THREE.Vector3( vector.x, vector.y, 1.0 ); - - this.unprojectVector( vector, camera ); - this.unprojectVector( end, camera ); - - // find direction from vector to end - end.sub( vector ).normalize(); - - return new THREE.Raycaster( vector, end ); - - }; - - var projectObject = function ( object ) { - - if ( object.visible === false ) return; - - if ( object instanceof THREE.Light ) { - - _renderData.lights.push( object ); - - } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) { - - if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) { - - _object = getNextObjectInPool(); - _object.id = object.id; - _object.object = object; - - if ( object.renderDepth !== null ) { - - _object.z = object.renderDepth; - - } else { - - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _viewProjectionMatrix ); - _object.z = _vector3.z; - - } - - _renderData.objects.push( _object ); - - } - - } - - for ( var i = 0, l = object.children.length; i < l; i ++ ) { - - projectObject( object.children[ i ] ); - - } - - }; - - var projectGraph = function ( root, sortObjects ) { - - _objectCount = 0; - - _renderData.objects.length = 0; - _renderData.lights.length = 0; - - projectObject( root ); - - if ( sortObjects === true ) { - - _renderData.objects.sort( painterSort ); - - } - - }; - - var RenderList = function () { - - var normals = []; - - var object = null; - var normalMatrix = new THREE.Matrix3(); - - var setObject = function ( value ) { - - object = value; - normalMatrix.getNormalMatrix( object.matrixWorld ); - - normals.length = 0; - - }; - - var projectVertex = function ( vertex ) { - - var position = vertex.position; - var positionWorld = vertex.positionWorld; - var positionScreen = vertex.positionScreen; - - positionWorld.copy( position ).applyMatrix4( _modelMatrix ); - positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix ); - - var invW = 1 / positionScreen.w; - - positionScreen.x *= invW; - positionScreen.y *= invW; - positionScreen.z *= invW; - - vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 && - positionScreen.y >= -1 && positionScreen.y <= 1 && - positionScreen.z >= -1 && positionScreen.z <= 1; - - }; - - var pushVertex = function ( x, y, z ) { - - _vertex = getNextVertexInPool(); - _vertex.position.set( x, y, z ); - - projectVertex( _vertex ); - - }; - - var pushNormal = function ( x, y, z ) { - - normals.push( x, y, z ); - - }; - - var checkTriangleVisibility = function ( v1, v2, v3 ) { - - _points3[ 0 ] = v1.positionScreen; - _points3[ 1 ] = v2.positionScreen; - _points3[ 2 ] = v3.positionScreen; - - if ( v1.visible === true || v2.visible === true || v3.visible === true || - _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) { - - return ( ( v3.positionScreen.x - v1.positionScreen.x ) * - ( v2.positionScreen.y - v1.positionScreen.y ) - - ( v3.positionScreen.y - v1.positionScreen.y ) * - ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0; - - } - - return false; - - }; - - var pushLine = function ( a, b ) { - - var v1 = _vertexPool[ a ]; - var v2 = _vertexPool[ b ]; - - _line = getNextLineInPool(); - - _line.id = object.id; - _line.v1.copy( v1 ); - _line.v2.copy( v2 ); - _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2; - - _line.material = object.material; - - _renderData.elements.push( _line ); - - }; - - var pushTriangle = function ( a, b, c ) { - - var v1 = _vertexPool[ a ]; - var v2 = _vertexPool[ b ]; - var v3 = _vertexPool[ c ]; - - if ( checkTriangleVisibility( v1, v2, v3 ) === true ) { - - _face = getNextFaceInPool(); - - _face.id = object.id; - _face.v1.copy( v1 ); - _face.v2.copy( v2 ); - _face.v3.copy( v3 ); - _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3; - - for ( var i = 0; i < 3; i ++ ) { - - var offset = arguments[ i ] * 3; - var normal = _face.vertexNormalsModel[ i ]; - - normal.set( normals[ offset + 0 ], normals[ offset + 1 ], normals[ offset + 2 ] ); - normal.applyMatrix3( normalMatrix ).normalize(); - - } - - _face.vertexNormalsLength = 3; - - _face.material = object.material; - - _renderData.elements.push( _face ); - - } - - }; - - return { - setObject: setObject, - projectVertex: projectVertex, - checkTriangleVisibility: checkTriangleVisibility, - pushVertex: pushVertex, - pushNormal: pushNormal, - pushLine: pushLine, - pushTriangle: pushTriangle - } - - }; - - var renderList = new RenderList(); - - this.projectScene = function ( scene, camera, sortObjects, sortElements ) { - - var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs, - isFaceMaterial, objectMaterials; - - _faceCount = 0; - _lineCount = 0; - _spriteCount = 0; - - _renderData.elements.length = 0; - - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - if ( camera.parent === undefined ) camera.updateMatrixWorld(); - - _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) ); - _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix ); - - _frustum.setFromMatrix( _viewProjectionMatrix ); - - projectGraph( scene, sortObjects ); - - for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) { - - object = _renderData.objects[ o ].object; - geometry = object.geometry; - - renderList.setObject( object ); - - _modelMatrix = object.matrixWorld; - - _vertexCount = 0; - - if ( object instanceof THREE.Mesh ) { - - if ( geometry instanceof THREE.BufferGeometry ) { - - var attributes = geometry.attributes; - var offsets = geometry.offsets; - - if ( attributes.position === undefined ) continue; - - var positions = attributes.position.array; - - for ( var i = 0, l = positions.length; i < l; i += 3 ) { - - renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - - } - - var normals = attributes.normal.array; - - for ( var i = 0, l = normals.length; i < l; i += 3 ) { - - renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ); - - } - - if ( attributes.index !== undefined ) { - - var indices = attributes.index.array; - - if ( offsets.length > 0 ) { - - for ( var o = 0; o < offsets.length; o ++ ) { - - var offset = offsets[ o ]; - var index = offset.index; - - for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) { - - renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index ); - - } - - } - - } else { - - for ( var i = 0, l = indices.length; i < l; i += 3 ) { - - renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - - } - - } - - } else { - - for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) { - - renderList.pushTriangle( i, i + 1, i + 2 ); - - } - - } - - } else if ( geometry instanceof THREE.Geometry ) { - - vertices = geometry.vertices; - faces = geometry.faces; - faceVertexUvs = geometry.faceVertexUvs; - - _normalMatrix.getNormalMatrix( _modelMatrix ); - - isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; - objectMaterials = isFaceMaterial === true ? object.material : null; - - for ( var v = 0, vl = vertices.length; v < vl; v ++ ) { - - var vertex = vertices[ v ]; - renderList.pushVertex( vertex.x, vertex.y, vertex.z ); - - } - - for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - - face = faces[ f ]; - - var material = isFaceMaterial === true - ? objectMaterials.materials[ face.materialIndex ] - : object.material; - - if ( material === undefined ) continue; - - var side = material.side; - - var v1 = _vertexPool[ face.a ]; - var v2 = _vertexPool[ face.b ]; - var v3 = _vertexPool[ face.c ]; - - if ( material.morphTargets === true ) { - - var morphTargets = geometry.morphTargets; - var morphInfluences = object.morphTargetInfluences; - - var v1p = v1.position; - var v2p = v2.position; - var v3p = v3.position; - - _vA.set( 0, 0, 0 ); - _vB.set( 0, 0, 0 ); - _vC.set( 0, 0, 0 ); - - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - - var influence = morphInfluences[ t ]; - - if ( influence === 0 ) continue; - - var targets = morphTargets[ t ].vertices; - - _vA.x += ( targets[ face.a ].x - v1p.x ) * influence; - _vA.y += ( targets[ face.a ].y - v1p.y ) * influence; - _vA.z += ( targets[ face.a ].z - v1p.z ) * influence; - - _vB.x += ( targets[ face.b ].x - v2p.x ) * influence; - _vB.y += ( targets[ face.b ].y - v2p.y ) * influence; - _vB.z += ( targets[ face.b ].z - v2p.z ) * influence; - - _vC.x += ( targets[ face.c ].x - v3p.x ) * influence; - _vC.y += ( targets[ face.c ].y - v3p.y ) * influence; - _vC.z += ( targets[ face.c ].z - v3p.z ) * influence; - - } - - v1.position.add( _vA ); - v2.position.add( _vB ); - v3.position.add( _vC ); - - renderList.projectVertex( v1 ); - renderList.projectVertex( v2 ); - renderList.projectVertex( v3 ); - - } - - var visible = renderList.checkTriangleVisibility( v1, v2, v3 ); - - if ( ( visible === false && side === THREE.FrontSide ) || - ( visible === true && side === THREE.BackSide ) ) continue; - - _face = getNextFaceInPool(); - - _face.id = object.id; - _face.v1.copy( v1 ); - _face.v2.copy( v2 ); - _face.v3.copy( v3 ); - - _face.normalModel.copy( face.normal ); - - if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) { - - _face.normalModel.negate(); - - } - - _face.normalModel.applyMatrix3( _normalMatrix ).normalize(); - - _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix ); - - faceVertexNormals = face.vertexNormals; - - for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) { - - var normalModel = _face.vertexNormalsModel[ n ]; - normalModel.copy( faceVertexNormals[ n ] ); - - if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) { - - normalModel.negate(); - - } - - normalModel.applyMatrix3( _normalMatrix ).normalize(); - - } - - _face.vertexNormalsLength = faceVertexNormals.length; - - for ( var c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) { - - uvs = faceVertexUvs[ c ][ f ]; - - if ( uvs === undefined ) continue; - - for ( var u = 0, ul = uvs.length; u < ul; u ++ ) { - - _face.uvs[ c ][ u ] = uvs[ u ]; - - } - - } - - _face.color = face.color; - _face.material = material; - - _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3; - - _renderData.elements.push( _face ); - - } - - } - - } else if ( object instanceof THREE.Line ) { - - if ( geometry instanceof THREE.BufferGeometry ) { - - var attributes = geometry.attributes; - - if ( attributes.position !== undefined ) { - - var positions = attributes.position.array; - - for ( var i = 0, l = positions.length; i < l; i += 3 ) { - - renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - - } - - if ( attributes.index !== undefined ) { - - var indices = attributes.index.array; - - for ( var i = 0, l = indices.length; i < l; i += 2 ) { - - renderList.pushLine( indices[ i ], indices[ i + 1 ] ); - - } - - } else { - - for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) { - - renderList.pushLine( i, i + 1 ); - - } - - } - - } - - } else if ( geometry instanceof THREE.Geometry ) { - - _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix ); - - vertices = object.geometry.vertices; - - if ( vertices.length === 0 ) continue; - - v1 = getNextVertexInPool(); - v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix ); - - // Handle LineStrip and LinePieces - var step = object.type === THREE.LinePieces ? 2 : 1; - - for ( var v = 1, vl = vertices.length; v < vl; v ++ ) { - - v1 = getNextVertexInPool(); - v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix ); - - if ( ( v + 1 ) % step > 0 ) continue; - - v2 = _vertexPool[ _vertexCount - 2 ]; - - _clippedVertex1PositionScreen.copy( v1.positionScreen ); - _clippedVertex2PositionScreen.copy( v2.positionScreen ); - - if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) { - - // Perform the perspective divide - _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w ); - _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w ); - - _line = getNextLineInPool(); - - _line.id = object.id; - _line.v1.positionScreen.copy( _clippedVertex1PositionScreen ); - _line.v2.positionScreen.copy( _clippedVertex2PositionScreen ); - - _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z ); - - _line.material = object.material; - - if ( object.material.vertexColors === THREE.VertexColors ) { - - _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] ); - _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] ); - - } - - _renderData.elements.push( _line ); - - } - - } - - } - - } else if ( object instanceof THREE.Sprite ) { - - _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 ); - _vector4.applyMatrix4( _viewProjectionMatrix ); - - var invW = 1 / _vector4.w; - - _vector4.z *= invW; - - if ( _vector4.z >= -1 && _vector4.z <= 1 ) { - - _sprite = getNextSpriteInPool(); - _sprite.id = object.id; - _sprite.x = _vector4.x * invW; - _sprite.y = _vector4.y * invW; - _sprite.z = _vector4.z; - _sprite.object = object; - - _sprite.rotation = object.rotation; - - _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) ); - _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) ); - - _sprite.material = object.material; - - _renderData.elements.push( _sprite ); - - } - - } - - } - - if ( sortElements === true ) _renderData.elements.sort( painterSort ); - - return _renderData; - - }; - - // Pools - - function getNextObjectInPool() { - - if ( _objectCount === _objectPoolLength ) { - - var object = new THREE.RenderableObject(); - _objectPool.push( object ); - _objectPoolLength ++; - _objectCount ++; - return object; - - } - - return _objectPool[ _objectCount ++ ]; - - } - - function getNextVertexInPool() { - - if ( _vertexCount === _vertexPoolLength ) { - - var vertex = new THREE.RenderableVertex(); - _vertexPool.push( vertex ); - _vertexPoolLength ++; - _vertexCount ++; - return vertex; - - } - - return _vertexPool[ _vertexCount ++ ]; - - } - - function getNextFaceInPool() { - - if ( _faceCount === _facePoolLength ) { - - var face = new THREE.RenderableFace(); - _facePool.push( face ); - _facePoolLength ++; - _faceCount ++; - return face; - - } - - return _facePool[ _faceCount ++ ]; - - - } - - function getNextLineInPool() { - - if ( _lineCount === _linePoolLength ) { - - var line = new THREE.RenderableLine(); - _linePool.push( line ); - _linePoolLength ++; - _lineCount ++ - return line; - - } - - return _linePool[ _lineCount ++ ]; - - } - - function getNextSpriteInPool() { - - if ( _spriteCount === _spritePoolLength ) { - - var sprite = new THREE.RenderableSprite(); - _spritePool.push( sprite ); - _spritePoolLength ++; - _spriteCount ++ - return sprite; - - } - - return _spritePool[ _spriteCount ++ ]; - - } - - // - - function painterSort( a, b ) { - - if ( a.z !== b.z ) { - - return b.z - a.z; - - } else if ( a.id !== b.id ) { - - return a.id - b.id; - - } else { - - return 0; - - } - - } - - function clipLine( s1, s2 ) { - - var alpha1 = 0, alpha2 = 1, - - // Calculate the boundary coordinate of each vertex for the near and far clip planes, - // Z = -1 and Z = +1, respectively. - bc1near = s1.z + s1.w, - bc2near = s2.z + s2.w, - bc1far = - s1.z + s1.w, - bc2far = - s2.z + s2.w; - - if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) { - - // Both vertices lie entirely within all clip planes. - return true; - - } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) { - - // Both vertices lie entirely outside one of the clip planes. - return false; - - } else { - - // The line segment spans at least one clip plane. - - if ( bc1near < 0 ) { - - // v1 lies outside the near plane, v2 inside - alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) ); - - } else if ( bc2near < 0 ) { - - // v2 lies outside the near plane, v1 inside - alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) ); - - } - - if ( bc1far < 0 ) { - - // v1 lies outside the far plane, v2 inside - alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) ); - - } else if ( bc2far < 0 ) { - - // v2 lies outside the far plane, v2 inside - alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) ); - - } - - if ( alpha2 < alpha1 ) { - - // The line segment spans two boundaries, but is outside both of them. - // (This can't happen when we're only clipping against just near/far but good - // to leave the check here for future usage if other clip planes are added.) - return false; - - } else { - - // Update the s1 and s2 vertices to match the clipped line segment. - s1.lerp( s2, alpha1 ); - s2.lerp( s1, 1 - alpha2 ); - - return true; - - } - - } - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { - - this.a = a; - this.b = b; - this.c = c; - - this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); - this.vertexNormals = normal instanceof Array ? normal : [ ]; - - this.color = color instanceof THREE.Color ? color : new THREE.Color(); - this.vertexColors = color instanceof Array ? color : []; - - this.vertexTangents = []; - - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - - this.centroid = new THREE.Vector3(); - -}; - -THREE.Face3.prototype = { - - constructor: THREE.Face3, - - clone: function () { - - var face = new THREE.Face3( this.a, this.b, this.c ); - - face.normal.copy( this.normal ); - face.color.copy( this.color ); - face.centroid.copy( this.centroid ); - - face.materialIndex = this.materialIndex; - - var i, il; - for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone(); - for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone(); - for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone(); - - return face; - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) { - - console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.') - - return new THREE.Face3( a, b, c, normal, color, materialIndex ); - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.BufferGeometry = function () { - - this.id = THREE.GeometryIdCount ++; - this.uuid = THREE.Math.generateUUID(); - - this.name = ''; - - // attributes - - this.attributes = {}; - - // offsets for chunks when using indexed elements - - this.offsets = []; - - // boundings - - this.boundingBox = null; - this.boundingSphere = null; - -}; - -THREE.BufferGeometry.prototype = { - - constructor: THREE.BufferGeometry, - - addAttribute: function ( name, type, numItems, itemSize ) { - - this.attributes[ name ] = { - - array: new type( numItems * itemSize ), - itemSize: itemSize - - }; - - return this.attributes[ name ]; - - }, - - applyMatrix: function ( matrix ) { - - var position = this.attributes.position; - - if ( position !== undefined ) { - - matrix.multiplyVector3Array( position.array ); - position.needsUpdate = true; - - } - - var normal = this.attributes.normal; - - if ( normal !== undefined ) { - - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); - - normalMatrix.multiplyVector3Array( normal.array ); - normal.needsUpdate = true; - - } - - }, - - computeBoundingBox: function () { - - if ( this.boundingBox === null ) { - - this.boundingBox = new THREE.Box3(); - - } - - var positions = this.attributes[ "position" ].array; - - if ( positions ) { - - var bb = this.boundingBox; - - if( positions.length >= 3 ) { - bb.min.x = bb.max.x = positions[ 0 ]; - bb.min.y = bb.max.y = positions[ 1 ]; - bb.min.z = bb.max.z = positions[ 2 ]; - } - - for ( var i = 3, il = positions.length; i < il; i += 3 ) { - - var x = positions[ i ]; - var y = positions[ i + 1 ]; - var z = positions[ i + 2 ]; - - // bounding box - - if ( x < bb.min.x ) { - - bb.min.x = x; - - } else if ( x > bb.max.x ) { - - bb.max.x = x; - - } - - if ( y < bb.min.y ) { - - bb.min.y = y; - - } else if ( y > bb.max.y ) { - - bb.max.y = y; - - } - - if ( z < bb.min.z ) { - - bb.min.z = z; - - } else if ( z > bb.max.z ) { - - bb.max.z = z; - - } - - } - - } - - if ( positions === undefined || positions.length === 0 ) { - - this.boundingBox.min.set( 0, 0, 0 ); - this.boundingBox.max.set( 0, 0, 0 ); - - } - - }, - - computeBoundingSphere: function () { - - var box = new THREE.Box3(); - var vector = new THREE.Vector3(); - - return function () { - - if ( this.boundingSphere === null ) { - - this.boundingSphere = new THREE.Sphere(); - - } - - var positions = this.attributes[ "position" ].array; - - if ( positions ) { - - box.makeEmpty(); - - var center = this.boundingSphere.center; - - for ( var i = 0, il = positions.length; i < il; i += 3 ) { - - vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - box.addPoint( vector ); - - } - - box.center( center ); - - var maxRadiusSq = 0; - - for ( var i = 0, il = positions.length; i < il; i += 3 ) { - - vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); - - } - - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - - } - - } - - }(), - - computeVertexNormals: function () { - - if ( this.attributes[ "position" ] ) { - - var i, il; - var j, jl; - - var nVertexElements = this.attributes[ "position" ].array.length; - - if ( this.attributes[ "normal" ] === undefined ) { - - this.attributes[ "normal" ] = { - - itemSize: 3, - array: new Float32Array( nVertexElements ) - - }; - - } else { - - // reset existing normals to zero - - for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) { - - this.attributes[ "normal" ].array[ i ] = 0; - - } - - } - - var positions = this.attributes[ "position" ].array; - var normals = this.attributes[ "normal" ].array; - - var vA, vB, vC, x, y, z, - - pA = new THREE.Vector3(), - pB = new THREE.Vector3(), - pC = new THREE.Vector3(), - - cb = new THREE.Vector3(), - ab = new THREE.Vector3(); - - // indexed elements - - if ( this.attributes[ "index" ] ) { - - var indices = this.attributes[ "index" ].array; - - var offsets = this.offsets; - - for ( j = 0, jl = offsets.length; j < jl; ++ j ) { - - var start = offsets[ j ].start; - var count = offsets[ j ].count; - var index = offsets[ j ].index; - - for ( i = start, il = start + count; i < il; i += 3 ) { - - vA = index + indices[ i ]; - vB = index + indices[ i + 1 ]; - vC = index + indices[ i + 2 ]; - - x = positions[ vA * 3 ]; - y = positions[ vA * 3 + 1 ]; - z = positions[ vA * 3 + 2 ]; - pA.set( x, y, z ); - - x = positions[ vB * 3 ]; - y = positions[ vB * 3 + 1 ]; - z = positions[ vB * 3 + 2 ]; - pB.set( x, y, z ); - - x = positions[ vC * 3 ]; - y = positions[ vC * 3 + 1 ]; - z = positions[ vC * 3 + 2 ]; - pC.set( x, y, z ); - - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); - - normals[ vA * 3 ] += cb.x; - normals[ vA * 3 + 1 ] += cb.y; - normals[ vA * 3 + 2 ] += cb.z; - - normals[ vB * 3 ] += cb.x; - normals[ vB * 3 + 1 ] += cb.y; - normals[ vB * 3 + 2 ] += cb.z; - - normals[ vC * 3 ] += cb.x; - normals[ vC * 3 + 1 ] += cb.y; - normals[ vC * 3 + 2 ] += cb.z; - - } - - } - - // non-indexed elements (unconnected triangle soup) - - } else { - - for ( i = 0, il = positions.length; i < il; i += 9 ) { - - x = positions[ i ]; - y = positions[ i + 1 ]; - z = positions[ i + 2 ]; - pA.set( x, y, z ); - - x = positions[ i + 3 ]; - y = positions[ i + 4 ]; - z = positions[ i + 5 ]; - pB.set( x, y, z ); - - x = positions[ i + 6 ]; - y = positions[ i + 7 ]; - z = positions[ i + 8 ]; - pC.set( x, y, z ); - - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); - - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; - - normals[ i + 3 ] = cb.x; - normals[ i + 4 ] = cb.y; - normals[ i + 5 ] = cb.z; - - normals[ i + 6 ] = cb.x; - normals[ i + 7 ] = cb.y; - normals[ i + 8 ] = cb.z; - - } - - } - - this.normalizeNormals(); - - this.normalsNeedUpdate = true; - - } - - }, - - normalizeNormals: function () { - - var normals = this.attributes[ "normal" ].array; - - var x, y, z, n; - - for ( var i = 0, il = normals.length; i < il; i += 3 ) { - - x = normals[ i ]; - y = normals[ i + 1 ]; - z = normals[ i + 2 ]; - - n = 1.0 / Math.sqrt( x * x + y * y + z * z ); - - normals[ i ] *= n; - normals[ i + 1 ] *= n; - normals[ i + 2 ] *= n; - - } - - }, - - computeTangents: function () { - - // based on http://www.terathon.com/code/tangent.html - // (per vertex tangents) - - if ( this.attributes[ "index" ] === undefined || - this.attributes[ "position" ] === undefined || - this.attributes[ "normal" ] === undefined || - this.attributes[ "uv" ] === undefined ) { - - console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" ); - return; - - } - - var indices = this.attributes[ "index" ].array; - var positions = this.attributes[ "position" ].array; - var normals = this.attributes[ "normal" ].array; - var uvs = this.attributes[ "uv" ].array; - - var nVertices = positions.length / 3; - - if ( this.attributes[ "tangent" ] === undefined ) { - - var nTangentElements = 4 * nVertices; - - this.attributes[ "tangent" ] = { - - itemSize: 4, - array: new Float32Array( nTangentElements ) - - }; - - } - - var tangents = this.attributes[ "tangent" ].array; - - var tan1 = [], tan2 = []; - - for ( var k = 0; k < nVertices; k ++ ) { - - tan1[ k ] = new THREE.Vector3(); - tan2[ k ] = new THREE.Vector3(); - - } - - var xA, yA, zA, - xB, yB, zB, - xC, yC, zC, - - uA, vA, - uB, vB, - uC, vC, - - x1, x2, y1, y2, z1, z2, - s1, s2, t1, t2, r; - - var sdir = new THREE.Vector3(), tdir = new THREE.Vector3(); - - function handleTriangle( a, b, c ) { - - xA = positions[ a * 3 ]; - yA = positions[ a * 3 + 1 ]; - zA = positions[ a * 3 + 2 ]; - - xB = positions[ b * 3 ]; - yB = positions[ b * 3 + 1 ]; - zB = positions[ b * 3 + 2 ]; - - xC = positions[ c * 3 ]; - yC = positions[ c * 3 + 1 ]; - zC = positions[ c * 3 + 2 ]; - - uA = uvs[ a * 2 ]; - vA = uvs[ a * 2 + 1 ]; - - uB = uvs[ b * 2 ]; - vB = uvs[ b * 2 + 1 ]; - - uC = uvs[ c * 2 ]; - vC = uvs[ c * 2 + 1 ]; - - x1 = xB - xA; - x2 = xC - xA; - - y1 = yB - yA; - y2 = yC - yA; - - z1 = zB - zA; - z2 = zC - zA; - - s1 = uB - uA; - s2 = uC - uA; - - t1 = vB - vA; - t2 = vC - vA; - - r = 1.0 / ( s1 * t2 - s2 * t1 ); - - sdir.set( - ( t2 * x1 - t1 * x2 ) * r, - ( t2 * y1 - t1 * y2 ) * r, - ( t2 * z1 - t1 * z2 ) * r - ); - - tdir.set( - ( s1 * x2 - s2 * x1 ) * r, - ( s1 * y2 - s2 * y1 ) * r, - ( s1 * z2 - s2 * z1 ) * r - ); - - tan1[ a ].add( sdir ); - tan1[ b ].add( sdir ); - tan1[ c ].add( sdir ); - - tan2[ a ].add( tdir ); - tan2[ b ].add( tdir ); - tan2[ c ].add( tdir ); - - } - - var i, il; - var j, jl; - var iA, iB, iC; - - var offsets = this.offsets; - - for ( j = 0, jl = offsets.length; j < jl; ++ j ) { - - var start = offsets[ j ].start; - var count = offsets[ j ].count; - var index = offsets[ j ].index; - - for ( i = start, il = start + count; i < il; i += 3 ) { - - iA = index + indices[ i ]; - iB = index + indices[ i + 1 ]; - iC = index + indices[ i + 2 ]; - - handleTriangle( iA, iB, iC ); - - } - - } - - var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(); - var n = new THREE.Vector3(), n2 = new THREE.Vector3(); - var w, t, test; - - function handleVertex( v ) { - - n.x = normals[ v * 3 ]; - n.y = normals[ v * 3 + 1 ]; - n.z = normals[ v * 3 + 2 ]; - - n2.copy( n ); - - t = tan1[ v ]; - - // Gram-Schmidt orthogonalize - - tmp.copy( t ); - tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); - - // Calculate handedness - - tmp2.crossVectors( n2, t ); - test = tmp2.dot( tan2[ v ] ); - w = ( test < 0.0 ) ? -1.0 : 1.0; - - tangents[ v * 4 ] = tmp.x; - tangents[ v * 4 + 1 ] = tmp.y; - tangents[ v * 4 + 2 ] = tmp.z; - tangents[ v * 4 + 3 ] = w; - - } - - for ( j = 0, jl = offsets.length; j < jl; ++ j ) { - - var start = offsets[ j ].start; - var count = offsets[ j ].count; - var index = offsets[ j ].index; - - for ( i = start, il = start + count; i < il; i += 3 ) { - - iA = index + indices[ i ]; - iB = index + indices[ i + 1 ]; - iC = index + indices[ i + 2 ]; - - handleVertex( iA ); - handleVertex( iB ); - handleVertex( iC ); - - } - - } - - }, - - /* - computeOffsets - Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices. - This method will effectively rewrite the index buffer and remap all attributes to match the new indices. - WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets. - indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks. - */ - computeOffsets: function(indexBufferSize) { - - var size = indexBufferSize; - if(indexBufferSize === undefined) - size = 65535; //WebGL limits type of index buffer values to 16-bit. - - var s = Date.now(); - - var indices = this.attributes['index'].array; - var vertices = this.attributes['position'].array; - - var verticesCount = (vertices.length/3); - var facesCount = (indices.length/3); - - /* - console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length); - console.log("Faces to process: "+(indices.length/3)); - console.log("Reordering "+verticesCount+" vertices."); - */ - - var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers - var indexPtr = 0; - var vertexPtr = 0; - - var offsets = [ { start:0, count:0, index:0 } ]; - var offset = offsets[0]; - - var duplicatedVertices = 0; - var newVerticeMaps = 0; - var faceVertices = new Int32Array(6); - var vertexMap = new Int32Array( vertices.length ); - var revVertexMap = new Int32Array( vertices.length ); - for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; } - - /* - Traverse every face and reorder vertices in the proper offsets of 65k. - We can have more than 65k entries in the index buffer per offset, but only reference 65k values. - */ - for(var findex = 0; findex < facesCount; findex++) { - newVerticeMaps = 0; - - for(var vo = 0; vo < 3; vo++) { - var vid = indices[ findex*3 + vo ]; - if(vertexMap[vid] == -1) { - //Unmapped vertice - faceVertices[vo*2] = vid; - faceVertices[vo*2+1] = -1; - newVerticeMaps++; - } else if(vertexMap[vid] < offset.index) { - //Reused vertices from previous block (duplicate) - faceVertices[vo*2] = vid; - faceVertices[vo*2+1] = -1; - duplicatedVertices++; - } else { - //Reused vertice in the current block - faceVertices[vo*2] = vid; - faceVertices[vo*2+1] = vertexMap[vid]; - } - } - - var faceMax = vertexPtr + newVerticeMaps; - if(faceMax > (offset.index + size)) { - var new_offset = { start:indexPtr, count:0, index:vertexPtr }; - offsets.push(new_offset); - offset = new_offset; - - //Re-evaluate reused vertices in light of new offset. - for(var v = 0; v < 6; v+=2) { - var new_vid = faceVertices[v+1]; - if(new_vid > -1 && new_vid < offset.index) - faceVertices[v+1] = -1; - } - } - - //Reindex the face. - for(var v = 0; v < 6; v+=2) { - var vid = faceVertices[v]; - var new_vid = faceVertices[v+1]; - - if(new_vid === -1) - new_vid = vertexPtr++; - - vertexMap[vid] = new_vid; - revVertexMap[new_vid] = vid; - sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit - offset.count++; - } - } - - /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */ - this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr); - this.offsets = offsets; - - /* - var orderTime = Date.now(); - console.log("Reorder time: "+(orderTime-s)+"ms"); - console.log("Duplicated "+duplicatedVertices+" vertices."); - console.log("Compute Buffers time: "+(Date.now()-s)+"ms"); - console.log("Draw offsets: "+offsets.length); - */ - - return offsets; - }, - - /* - reoderBuffers: - Reorder attributes based on a new indexBuffer and indexMap. - indexBuffer - Uint16Array of the new ordered indices. - indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex. - vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack). - */ - reorderBuffers: function(indexBuffer, indexMap, vertexCount) { - - /* Create a copy of all attributes for reordering. */ - var sortedAttributes = {}; - var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ]; - for( var attr in this.attributes ) { - if(attr == 'index') - continue; - var sourceArray = this.attributes[attr].array; - for ( var i = 0, il = types.length; i < il; i++ ) { - var type = types[i]; - if (sourceArray instanceof type) { - sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount ); - break; - } - } - } - - /* Move attribute positions based on the new index map */ - for(var new_vid = 0; new_vid < vertexCount; new_vid++) { - var vid = indexMap[new_vid]; - for ( var attr in this.attributes ) { - if(attr == 'index') - continue; - var attrArray = this.attributes[attr].array; - var attrSize = this.attributes[attr].itemSize; - var sortedAttr = sortedAttributes[attr]; - for(var k = 0; k < attrSize; k++) - sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ]; - } - } - - /* Carry the new sorted buffers locally */ - this.attributes['index'].array = indexBuffer; - for ( var attr in this.attributes ) { - if(attr == 'index') - continue; - this.attributes[attr].array = sortedAttributes[attr]; - this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount; - } - }, - - clone: function () { - - var geometry = new THREE.BufferGeometry(); - - var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ]; - - for ( var attr in this.attributes ) { - - var sourceAttr = this.attributes[ attr ]; - var sourceArray = sourceAttr.array; - - var attribute = { - - itemSize: sourceAttr.itemSize, - array: null - - }; - - for ( var i = 0, il = types.length; i < il; i ++ ) { - - var type = types[ i ]; - - if ( sourceArray instanceof type ) { - - attribute.array = new type( sourceArray ); - break; - - } - - } - - geometry.attributes[ attr ] = attribute; - - } - - for ( var i = 0, il = this.offsets.length; i < il; i ++ ) { - - var offset = this.offsets[ i ]; - - geometry.offsets.push( { - - start: offset.start, - index: offset.index, - count: offset.count - - } ); - - } - - return geometry; - - }, - - dispose: function () { - - this.dispatchEvent( { type: 'dispose' } ); - - } - -}; - -THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author kile / http://kile.stravaganza.org/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author bhouston / http://exocortex.com - */ - -THREE.Geometry = function () { - - this.id = THREE.GeometryIdCount ++; - this.uuid = THREE.Math.generateUUID(); - - this.name = ''; - - this.vertices = []; - this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line - - this.faces = []; - - this.faceVertexUvs = [[]]; - - this.morphTargets = []; - this.morphColors = []; - this.morphNormals = []; - - this.skinWeights = []; - this.skinIndices = []; - - this.lineDistances = []; - - this.boundingBox = null; - this.boundingSphere = null; - - this.hasTangents = false; - - this.dynamic = true; // the intermediate typed arrays will be deleted when set to false - - // update flags - - this.verticesNeedUpdate = false; - this.elementsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.tangentsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - - this.buffersNeedUpdate = false; - -}; - -THREE.Geometry.prototype = { - - constructor: THREE.Geometry, - - applyMatrix: function ( matrix ) { - - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); - - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { - - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); - - } - - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); - - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - - } - - face.centroid.applyMatrix4( matrix ); - - } - - if ( this.boundingBox instanceof THREE.Box3 ) { - - this.computeBoundingBox(); - - } - - if ( this.boundingSphere instanceof THREE.Sphere ) { - - this.computeBoundingSphere(); - - } - - }, - - computeCentroids: function () { - - var f, fl, face; - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - face.centroid.set( 0, 0, 0 ); - - face.centroid.add( this.vertices[ face.a ] ); - face.centroid.add( this.vertices[ face.b ] ); - face.centroid.add( this.vertices[ face.c ] ); - face.centroid.divideScalar( 3 ); - - } - - }, - - computeFaceNormals: function () { - - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); - - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - - var face = this.faces[ f ]; - - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; - - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); - - cb.normalize(); - - face.normal.copy( cb ); - - } - - }, - - computeVertexNormals: function ( areaWeighted ) { - - var v, vl, f, fl, face, vertices; - - vertices = new Array( this.vertices.length ); - - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - - vertices[ v ] = new THREE.Vector3(); - - } - - if ( areaWeighted ) { - - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm - - var vA, vB, vC, vD; - var cb = new THREE.Vector3(), ab = new THREE.Vector3(), - db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3(); - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; - - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); - - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); - - } - - } else { - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); - - } - - } - - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - - vertices[ v ].normalize(); - - } - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - - face.vertexNormals[ 0 ] = vertices[ face.a ].clone(); - face.vertexNormals[ 1 ] = vertices[ face.b ].clone(); - face.vertexNormals[ 2 ] = vertices[ face.c ].clone(); - - } - - }, - - computeMorphNormals: function () { - - var i, il, f, fl, face; - - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - - if ( ! face.__originalFaceNormal ) { - - face.__originalFaceNormal = face.normal.clone(); - - } else { - - face.__originalFaceNormal.copy( face.normal ); - - } - - if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; - - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { - - if ( ! face.__originalVertexNormals[ i ] ) { - - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); - - } else { - - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); - - } - - } - - } - - // use temp geometry to compute face and vertex normals for each morph - - var tmpGeo = new THREE.Geometry(); - tmpGeo.faces = this.faces; - - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { - - // create on first access - - if ( ! this.morphNormals[ i ] ) { - - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; - - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - - var faceNormal, vertexNormals; - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - - faceNormal = new THREE.Vector3(); - vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() }; - - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); - - } - - } - - var morphNormals = this.morphNormals[ i ]; - - // set vertices to morph target - - tmpGeo.vertices = this.morphTargets[ i ].vertices; - - // compute morph normals - - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); - - // store morph normals - - var faceNormal, vertexNormals; - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; - - faceNormal.copy( face.normal ); - - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); - - } - - } - - // restore original normals - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; - - } - - }, - - computeTangents: function () { - - // based on http://www.terathon.com/code/tangent.html - // tangents go to vertices - - var f, fl, v, vl, i, il, vertexIndex, - face, uv, vA, vB, vC, uvA, uvB, uvC, - x1, x2, y1, y2, z1, z2, - s1, s2, t1, t2, r, t, test, - tan1 = [], tan2 = [], - sdir = new THREE.Vector3(), tdir = new THREE.Vector3(), - tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(), - n = new THREE.Vector3(), w; - - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - - tan1[ v ] = new THREE.Vector3(); - tan2[ v ] = new THREE.Vector3(); - - } - - function handleTriangle( context, a, b, c, ua, ub, uc ) { - - vA = context.vertices[ a ]; - vB = context.vertices[ b ]; - vC = context.vertices[ c ]; - - uvA = uv[ ua ]; - uvB = uv[ ub ]; - uvC = uv[ uc ]; - - x1 = vB.x - vA.x; - x2 = vC.x - vA.x; - y1 = vB.y - vA.y; - y2 = vC.y - vA.y; - z1 = vB.z - vA.z; - z2 = vC.z - vA.z; - - s1 = uvB.x - uvA.x; - s2 = uvC.x - uvA.x; - t1 = uvB.y - uvA.y; - t2 = uvC.y - uvA.y; - - r = 1.0 / ( s1 * t2 - s2 * t1 ); - sdir.set( ( t2 * x1 - t1 * x2 ) * r, - ( t2 * y1 - t1 * y2 ) * r, - ( t2 * z1 - t1 * z2 ) * r ); - tdir.set( ( s1 * x2 - s2 * x1 ) * r, - ( s1 * y2 - s2 * y1 ) * r, - ( s1 * z2 - s2 * z1 ) * r ); - - tan1[ a ].add( sdir ); - tan1[ b ].add( sdir ); - tan1[ c ].add( sdir ); - - tan2[ a ].add( tdir ); - tan2[ b ].add( tdir ); - tan2[ c ].add( tdir ); - - } - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents - - handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 ); - - } - - var faceIndex = [ 'a', 'b', 'c', 'd' ]; - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - - for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) { - - n.copy( face.vertexNormals[ i ] ); - - vertexIndex = face[ faceIndex[ i ] ]; - - t = tan1[ vertexIndex ]; - - // Gram-Schmidt orthogonalize - - tmp.copy( t ); - tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); - - // Calculate handedness - - tmp2.crossVectors( face.vertexNormals[ i ], t ); - test = tmp2.dot( tan2[ vertexIndex ] ); - w = (test < 0.0) ? -1.0 : 1.0; - - face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w ); - - } - - } - - this.hasTangents = true; - - }, - - computeLineDistances: function ( ) { - - var d = 0; - var vertices = this.vertices; - - for ( var i = 0, il = vertices.length; i < il; i ++ ) { - - if ( i > 0 ) { - - d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); - - } - - this.lineDistances[ i ] = d; - - } - - }, - - computeBoundingBox: function () { - - if ( this.boundingBox === null ) { - - this.boundingBox = new THREE.Box3(); - - } - - this.boundingBox.setFromPoints( this.vertices ); - - }, - - computeBoundingSphere: function () { - - if ( this.boundingSphere === null ) { - - this.boundingSphere = new THREE.Sphere(); - - } - - this.boundingSphere.setFromPoints( this.vertices ); - - }, - - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ - - mergeVertices: function () { - - var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique) - var unique = [], changes = []; - - var v, key; - var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001 - var precision = Math.pow( 10, precisionPoints ); - var i,il, face; - var indices, k, j, jl, u; - - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { - - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); - - if ( verticesMap[ key ] === undefined ) { - - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; - - } else { - - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; - - } - - }; - - - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; - - for( i = 0, il = this.faces.length; i < il; i ++ ) { - - face = this.faces[ i ]; - - face.a = changes[ face.a ]; - face.b = changes[ face.b ]; - face.c = changes[ face.c ]; - - indices = [ face.a, face.b, face.c ]; - - var dupIndex = -1; - - // if any duplicate vertices are found in a Face3 - // we have to remove the face as nothing can be saved - for ( var n = 0; n < 3; n ++ ) { - if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) { - - dupIndex = n; - faceIndicesToRemove.push( i ); - break; - - } - } - - } - - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - var idx = faceIndicesToRemove[ i ]; - - this.faces.splice( idx, 1 ); - - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { - - this.faceVertexUvs[ j ].splice( idx, 1 ); - - } - - } - - // Use unique set of vertices - - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; - - }, - - // Geometry splitting - - makeGroups: ( function () { - - var geometryGroupCounter = 0; - - return function ( usesFaceMaterial ) { - - var f, fl, face, materialIndex, - groupHash, hash_map = {}; - - var numMorphTargets = this.morphTargets.length; - var numMorphNormals = this.morphNormals.length; - - this.geometryGroups = {}; - - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - - face = this.faces[ f ]; - materialIndex = usesFaceMaterial ? face.materialIndex : 0; - - if ( ! ( materialIndex in hash_map ) ) { - - hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 }; - - } - - groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter; - - if ( ! ( groupHash in this.geometryGroups ) ) { - - this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals }; - - } - - if ( this.geometryGroups[ groupHash ].vertices + 3 > 65535 ) { - - hash_map[ materialIndex ].counter += 1; - groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter; - - if ( ! ( groupHash in this.geometryGroups ) ) { - - this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals }; - - } - - } - - this.geometryGroups[ groupHash ].faces3.push( f ); - this.geometryGroups[ groupHash ].vertices += 3; - - } - - this.geometryGroupsList = []; - - for ( var g in this.geometryGroups ) { - - this.geometryGroups[ g ].id = geometryGroupCounter ++; - - this.geometryGroupsList.push( this.geometryGroups[ g ] ); - - } - - }; - - } )(), - - clone: function () { - - var geometry = new THREE.Geometry(); - - var vertices = this.vertices; - - for ( var i = 0, il = vertices.length; i < il; i ++ ) { - - geometry.vertices.push( vertices[ i ].clone() ); - - } - - var faces = this.faces; - - for ( var i = 0, il = faces.length; i < il; i ++ ) { - - geometry.faces.push( faces[ i ].clone() ); - - } - - var uvs = this.faceVertexUvs[ 0 ]; - - for ( var i = 0, il = uvs.length; i < il; i ++ ) { - - var uv = uvs[ i ], uvCopy = []; - - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - - uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) ); - - } - - geometry.faceVertexUvs[ 0 ].push( uvCopy ); - - } - - return geometry; - - }, - - dispose: function () { - - this.dispatchEvent( { type: 'dispose' } ); - - } - -}; - -THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype ); - -THREE.GeometryIdCount = 0; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Geometry2 = function ( size ) { - - THREE.BufferGeometry.call( this ); - - this.vertices = this.addAttribute( 'position', Float32Array, size, 3 ).array; - this.normals = this.addAttribute( 'normal', Float32Array, size, 3 ).array; - this.uvs = this.addAttribute( 'uv', Float32Array, size, 2 ).array; - - this.boundingBox = null; - this.boundingSphere = null; - -}; - -THREE.Geometry2.prototype = Object.create( THREE.BufferGeometry.prototype );/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author WestLangley / http://github.com/WestLangley -*/ - -THREE.Camera = function () { - - THREE.Object3D.call( this ); - - this.matrixWorldInverse = new THREE.Matrix4(); - this.projectionMatrix = new THREE.Matrix4(); - -}; - -THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.Camera.prototype.lookAt = function () { - - // This routine does not support cameras with rotated and/or translated parent(s) - - var m1 = new THREE.Matrix4(); - - return function ( vector ) { - - m1.lookAt( this.position, vector, this.up ); - - this.quaternion.setFromRotationMatrix( m1 ); - - }; - -}(); - -THREE.Camera.prototype.clone = function (camera) { - - if ( camera === undefined ) camera = new THREE.Camera(); - - THREE.Object3D.prototype.clone.call( this, camera ); - - camera.matrixWorldInverse.copy( this.matrixWorldInverse ); - camera.projectionMatrix.copy( this.projectionMatrix ); - - return camera; -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { - - THREE.Camera.call( this ); - - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; - - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; - - this.updateProjectionMatrix(); - -}; - -THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype ); - -THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () { - - this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far ); - -}; - -THREE.OrthographicCamera.prototype.clone = function () { - - var camera = new THREE.OrthographicCamera(); - - THREE.Camera.prototype.clone.call( this, camera ); - - camera.left = this.left; - camera.right = this.right; - camera.top = this.top; - camera.bottom = this.bottom; - - camera.near = this.near; - camera.far = this.far; - - return camera; -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ - -THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { - - THREE.Camera.call( this ); - - this.fov = fov !== undefined ? fov : 50; - this.aspect = aspect !== undefined ? aspect : 1; - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; - - this.updateProjectionMatrix(); - -}; - -THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype ); - - -/** - * Uses Focal Length (in mm) to estimate and set FOV - * 35mm (fullframe) camera is used if frame size is not specified; - * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html - */ - -THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) { - - if ( frameHeight === undefined ) frameHeight = 24; - - this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) ); - this.updateProjectionMatrix(); - -} - - -/** - * Sets an offset in a larger frustum. This is useful for multi-window or - * multi-monitor/multi-machine setups. - * - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and - * the monitors are in grid like this - * - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - * - * then for each monitor you would call it like this - * - * var w = 1920; - * var h = 1080; - * var fullWidth = w * 3; - * var fullHeight = h * 2; - * - * --A-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * --B-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * --C-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * --D-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * --E-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * --F-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); - * - * Note there is no reason monitors have to be the same size or in a grid. - */ - -THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) { - - this.fullWidth = fullWidth; - this.fullHeight = fullHeight; - this.x = x; - this.y = y; - this.width = width; - this.height = height; - - this.updateProjectionMatrix(); - -}; - - -THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () { - - if ( this.fullWidth ) { - - var aspect = this.fullWidth / this.fullHeight; - var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near; - var bottom = -top; - var left = aspect * bottom; - var right = aspect * top; - var width = Math.abs( right - left ); - var height = Math.abs( top - bottom ); - - this.projectionMatrix.makeFrustum( - left + this.x * width / this.fullWidth, - left + ( this.x + this.width ) * width / this.fullWidth, - top - ( this.y + this.height ) * height / this.fullHeight, - top - this.y * height / this.fullHeight, - this.near, - this.far - ); - - } else { - - this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far ); - - } - -}; - -THREE.PerspectiveCamera.prototype.clone = function () { - - var camera = new THREE.PerspectiveCamera(); - - THREE.Camera.prototype.clone.call( this, camera ); - - camera.fov = this.fov; - camera.aspect = this.aspect; - camera.near = this.near; - camera.far = this.far; - - return camera; -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Light = function ( color ) { - - THREE.Object3D.call( this ); - - this.color = new THREE.Color( color ); - -}; - -THREE.Light.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.Light.prototype.clone = function ( light ) { - - if ( light === undefined ) light = new THREE.Light(); - - THREE.Object3D.prototype.clone.call( this, light ); - - light.color.copy( this.color ); - - return light; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.AmbientLight = function ( color ) { - - THREE.Light.call( this, color ); - -}; - -THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype ); - -THREE.AmbientLight.prototype.clone = function () { - - var light = new THREE.AmbientLight(); - - THREE.Light.prototype.clone.call( this, light ); - - return light; - -}; -/** - * @author MPanknin / http://www.redplant.de/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.AreaLight = function ( color, intensity ) { - - THREE.Light.call( this, color ); - - this.normal = new THREE.Vector3( 0, -1, 0 ); - this.right = new THREE.Vector3( 1, 0, 0 ); - - this.intensity = ( intensity !== undefined ) ? intensity : 1; - - this.width = 1.0; - this.height = 1.0; - - this.constantAttenuation = 1.5; - this.linearAttenuation = 0.5; - this.quadraticAttenuation = 0.1; - -}; - -THREE.AreaLight.prototype = Object.create( THREE.Light.prototype ); - -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.DirectionalLight = function ( color, intensity ) { - - THREE.Light.call( this, color ); - - this.position.set( 0, 1, 0 ); - this.target = new THREE.Object3D(); - - this.intensity = ( intensity !== undefined ) ? intensity : 1; - - this.castShadow = false; - this.onlyShadow = false; - - // - - this.shadowCameraNear = 50; - this.shadowCameraFar = 5000; - - this.shadowCameraLeft = -500; - this.shadowCameraRight = 500; - this.shadowCameraTop = 500; - this.shadowCameraBottom = -500; - - this.shadowCameraVisible = false; - - this.shadowBias = 0; - this.shadowDarkness = 0.5; - - this.shadowMapWidth = 512; - this.shadowMapHeight = 512; - - // - - this.shadowCascade = false; - - this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 ); - this.shadowCascadeCount = 2; - - this.shadowCascadeBias = [ 0, 0, 0 ]; - this.shadowCascadeWidth = [ 512, 512, 512 ]; - this.shadowCascadeHeight = [ 512, 512, 512 ]; - - this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ]; - this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ]; - - this.shadowCascadeArray = []; - - // - - this.shadowMap = null; - this.shadowMapSize = null; - this.shadowCamera = null; - this.shadowMatrix = null; - -}; - -THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype ); - -THREE.DirectionalLight.prototype.clone = function () { - - var light = new THREE.DirectionalLight(); - - THREE.Light.prototype.clone.call( this, light ); - - light.target = this.target.clone(); - - light.intensity = this.intensity; - - light.castShadow = this.castShadow; - light.onlyShadow = this.onlyShadow; - - return light; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { - - THREE.Light.call( this, skyColor ); - - this.position.set( 0, 100, 0 ); - - this.groundColor = new THREE.Color( groundColor ); - this.intensity = ( intensity !== undefined ) ? intensity : 1; - -}; - -THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype ); - -THREE.HemisphereLight.prototype.clone = function () { - - var light = new THREE.HemisphereLight(); - - THREE.Light.prototype.clone.call( this, light ); - - light.groundColor.copy( this.groundColor ); - light.intensity = this.intensity; - - return light; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.PointLight = function ( color, intensity, distance ) { - - THREE.Light.call( this, color ); - - this.intensity = ( intensity !== undefined ) ? intensity : 1; - this.distance = ( distance !== undefined ) ? distance : 0; - -}; - -THREE.PointLight.prototype = Object.create( THREE.Light.prototype ); - -THREE.PointLight.prototype.clone = function () { - - var light = new THREE.PointLight(); - - THREE.Light.prototype.clone.call( this, light ); - - light.intensity = this.intensity; - light.distance = this.distance; - - return light; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) { - - THREE.Light.call( this, color ); - - this.position.set( 0, 1, 0 ); - this.target = new THREE.Object3D(); - - this.intensity = ( intensity !== undefined ) ? intensity : 1; - this.distance = ( distance !== undefined ) ? distance : 0; - this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; - this.exponent = ( exponent !== undefined ) ? exponent : 10; - - this.castShadow = false; - this.onlyShadow = false; - - // - - this.shadowCameraNear = 50; - this.shadowCameraFar = 5000; - this.shadowCameraFov = 50; - - this.shadowCameraVisible = false; - - this.shadowBias = 0; - this.shadowDarkness = 0.5; - - this.shadowMapWidth = 512; - this.shadowMapHeight = 512; - - // - - this.shadowMap = null; - this.shadowMapSize = null; - this.shadowCamera = null; - this.shadowMatrix = null; - -}; - -THREE.SpotLight.prototype = Object.create( THREE.Light.prototype ); - -THREE.SpotLight.prototype.clone = function () { - - var light = new THREE.SpotLight(); - - THREE.Light.prototype.clone.call( this, light ); - - light.target = this.target.clone(); - - light.intensity = this.intensity; - light.distance = this.distance; - light.angle = this.angle; - light.exponent = this.exponent; - - light.castShadow = this.castShadow; - light.onlyShadow = this.onlyShadow; - - return light; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Loader = function ( showStatus ) { - - this.showStatus = showStatus; - this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null; - - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; - -}; - -THREE.Loader.prototype = { - - constructor: THREE.Loader, - - crossOrigin: undefined, - - addStatusElement: function () { - - var e = document.createElement( "div" ); - - e.style.position = "absolute"; - e.style.right = "0px"; - e.style.top = "0px"; - e.style.fontSize = "0.8em"; - e.style.textAlign = "left"; - e.style.background = "rgba(0,0,0,0.25)"; - e.style.color = "#fff"; - e.style.width = "120px"; - e.style.padding = "0.5em 0.5em 0.5em 0.5em"; - e.style.zIndex = 1000; - - e.innerHTML = "Loading ..."; - - return e; - - }, - - updateProgress: function ( progress ) { - - var message = "Loaded "; - - if ( progress.total ) { - - message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%"; - - - } else { - - message += ( progress.loaded / 1000 ).toFixed(2) + " KB"; - - } - - this.statusDomElement.innerHTML = message; - - }, - - extractUrlBase: function ( url ) { - - var parts = url.split( '/' ); - - if ( parts.length === 1 ) return './'; - - parts.pop(); - - return parts.join( '/' ) + '/'; - - }, - - initMaterials: function ( materials, texturePath ) { - - var array = []; - - for ( var i = 0; i < materials.length; ++ i ) { - - array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath ); - - } - - return array; - - }, - - needsTangents: function ( materials ) { - - for( var i = 0, il = materials.length; i < il; i ++ ) { - - var m = materials[ i ]; - - if ( m instanceof THREE.ShaderMaterial ) return true; - - } - - return false; - - }, - - createMaterial: function ( m, texturePath ) { - - var _this = this; - - function is_pow2( n ) { - - var l = Math.log( n ) / Math.LN2; - return Math.floor( l ) == l; - - } - - function nearest_pow2( n ) { - - var l = Math.log( n ) / Math.LN2; - return Math.pow( 2, Math.round( l ) ); - - } - - function load_image( where, url ) { - - var image = new Image(); - - image.onload = function () { - - if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) { - - var width = nearest_pow2( this.width ); - var height = nearest_pow2( this.height ); - - where.image.width = width; - where.image.height = height; - where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height ); - - } else { - - where.image = this; - - } - - where.needsUpdate = true; - - }; - - if ( _this.crossOrigin !== undefined ) image.crossOrigin = _this.crossOrigin; - image.src = url; - - } - - function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) { - - var isCompressed = /\.dds$/i.test( sourceFile ); - - var fullPath = texturePath + sourceFile; - - if ( isCompressed ) { - - var texture = THREE.ImageUtils.loadCompressedTexture( fullPath ); - - where[ name ] = texture; - - } else { - - var texture = document.createElement( 'canvas' ); - - where[ name ] = new THREE.Texture( texture ); - - } - - where[ name ].sourceFile = sourceFile; - - if( repeat ) { - - where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] ); - - if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping; - - } - - if ( offset ) { - - where[ name ].offset.set( offset[ 0 ], offset[ 1 ] ); - - } - - if ( wrap ) { - - var wrapMap = { - "repeat": THREE.RepeatWrapping, - "mirror": THREE.MirroredRepeatWrapping - } - - if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ]; - if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ]; - - } - - if ( anisotropy ) { - - where[ name ].anisotropy = anisotropy; - - } - - if ( ! isCompressed ) { - - load_image( where[ name ], fullPath ); - - } - - } - - function rgb2hex( rgb ) { - - return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255; - - } - - // defaults - - var mtype = "MeshLambertMaterial"; - var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false }; - - // parameters from model file - - if ( m.shading ) { - - var shading = m.shading.toLowerCase(); - - if ( shading === "phong" ) mtype = "MeshPhongMaterial"; - else if ( shading === "basic" ) mtype = "MeshBasicMaterial"; - - } - - if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) { - - mpars.blending = THREE[ m.blending ]; - - } - - if ( m.transparent !== undefined || m.opacity < 1.0 ) { - - mpars.transparent = m.transparent; - - } - - if ( m.depthTest !== undefined ) { - - mpars.depthTest = m.depthTest; - - } - - if ( m.depthWrite !== undefined ) { - - mpars.depthWrite = m.depthWrite; - - } - - if ( m.visible !== undefined ) { - - mpars.visible = m.visible; - - } - - if ( m.flipSided !== undefined ) { - - mpars.side = THREE.BackSide; - - } - - if ( m.doubleSided !== undefined ) { - - mpars.side = THREE.DoubleSide; - - } - - if ( m.wireframe !== undefined ) { - - mpars.wireframe = m.wireframe; - - } - - if ( m.vertexColors !== undefined ) { - - if ( m.vertexColors === "face" ) { - - mpars.vertexColors = THREE.FaceColors; - - } else if ( m.vertexColors ) { - - mpars.vertexColors = THREE.VertexColors; - - } - - } - - // colors - - if ( m.colorDiffuse ) { - - mpars.color = rgb2hex( m.colorDiffuse ); - - } else if ( m.DbgColor ) { - - mpars.color = m.DbgColor; - - } - - if ( m.colorSpecular ) { - - mpars.specular = rgb2hex( m.colorSpecular ); - - } - - if ( m.colorAmbient ) { - - mpars.ambient = rgb2hex( m.colorAmbient ); - - } - - // modifiers - - if ( m.transparency ) { - - mpars.opacity = m.transparency; - - } - - if ( m.specularCoef ) { - - mpars.shininess = m.specularCoef; - - } - - // textures - - if ( m.mapDiffuse && texturePath ) { - - create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); - - } - - if ( m.mapLight && texturePath ) { - - create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); - - } - - if ( m.mapBump && texturePath ) { - - create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); - - } - - if ( m.mapNormal && texturePath ) { - - create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); - - } - - if ( m.mapSpecular && texturePath ) { - - create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); - - } - - // - - if ( m.mapBumpScale ) { - - mpars.bumpScale = m.mapBumpScale; - - } - - // special case for normal mapped material - - if ( m.mapNormal ) { - - var shader = THREE.ShaderLib[ "normalmap" ]; - var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); - - uniforms[ "tNormal" ].value = mpars.normalMap; - - if ( m.mapNormalFactor ) { - - uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor ); - - } - - if ( mpars.map ) { - - uniforms[ "tDiffuse" ].value = mpars.map; - uniforms[ "enableDiffuse" ].value = true; - - } - - if ( mpars.specularMap ) { - - uniforms[ "tSpecular" ].value = mpars.specularMap; - uniforms[ "enableSpecular" ].value = true; - - } - - if ( mpars.lightMap ) { - - uniforms[ "tAO" ].value = mpars.lightMap; - uniforms[ "enableAO" ].value = true; - - } - - // for the moment don't handle displacement texture - - uniforms[ "diffuse" ].value.setHex( mpars.color ); - uniforms[ "specular" ].value.setHex( mpars.specular ); - uniforms[ "ambient" ].value.setHex( mpars.ambient ); - - uniforms[ "shininess" ].value = mpars.shininess; - - if ( mpars.opacity !== undefined ) { - - uniforms[ "opacity" ].value = mpars.opacity; - - } - - var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true }; - var material = new THREE.ShaderMaterial( parameters ); - - if ( mpars.transparent ) { - - material.transparent = true; - - } - - } else { - - var material = new THREE[ mtype ]( mpars ); - - } - - if ( m.DbgName !== undefined ) material.name = m.DbgName; - - return material; - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.XHRLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.XHRLoader.prototype = { - - constructor: THREE.XHRLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - var request = new XMLHttpRequest(); - - if ( onLoad !== undefined ) { - - request.addEventListener( 'load', function ( event ) { - - onLoad( event.target.responseText ); - scope.manager.itemEnd( url ); - - }, false ); - - } - - if ( onProgress !== undefined ) { - - request.addEventListener( 'progress', function ( event ) { - - onProgress( event ); - - }, false ); - - } - - if ( onError !== undefined ) { - - request.addEventListener( 'error', function ( event ) { - - onError( event ); - - }, false ); - - } - - if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin; - - request.open( 'GET', url, true ); - request.send( null ); - - scope.manager.itemStart( url ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.ImageLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.ImageLoader.prototype = { - - constructor: THREE.ImageLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - var image = document.createElement( 'img' ); - - if ( onLoad !== undefined ) { - - image.addEventListener( 'load', function ( event ) { - - scope.manager.itemEnd( url ); - onLoad( this ); - - }, false ); - - } - - if ( onProgress !== undefined ) { - - image.addEventListener( 'progress', function ( event ) { - - onProgress( event ); - - }, false ); - - } - - if ( onError !== undefined ) { - - image.addEventListener( 'error', function ( event ) { - - onError( event ); - - }, false ); - - } - - if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; - - image.src = url; - - scope.manager.itemStart( url ); - - return image; - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - } - -} -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.JSONLoader = function ( showStatus ) { - - THREE.Loader.call( this, showStatus ); - - this.withCredentials = false; - -}; - -THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype ); - -THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) { - - var scope = this; - - // todo: unify load API to for easier SceneLoader use - - texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url ); - - this.onLoadStart(); - this.loadAjaxJSON( this, url, callback, texturePath ); - -}; - -THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) { - - var xhr = new XMLHttpRequest(); - - var length = 0; - - xhr.onreadystatechange = function () { - - if ( xhr.readyState === xhr.DONE ) { - - if ( xhr.status === 200 || xhr.status === 0 ) { - - if ( xhr.responseText ) { - - var json = JSON.parse( xhr.responseText ); - - if ( json.metadata.type === 'scene' ) { - - console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' ); - return; - - } - - var result = context.parse( json, texturePath ); - callback( result.geometry, result.materials ); - - } else { - - console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' ); - - } - - // in context of more complex asset initialization - // do not block on single failed file - // maybe should go even one more level up - - context.onLoadComplete(); - - } else { - - console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' ); - - } - - } else if ( xhr.readyState === xhr.LOADING ) { - - if ( callbackProgress ) { - - if ( length === 0 ) { - - length = xhr.getResponseHeader( 'Content-Length' ); - - } - - callbackProgress( { total: length, loaded: xhr.responseText.length } ); - - } - - } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) { - - if ( callbackProgress !== undefined ) { - - length = xhr.getResponseHeader( "Content-Length" ); - - } - - } - - }; - - xhr.open( "GET", url, true ); - xhr.withCredentials = this.withCredentials; - xhr.send( null ); - -}; - -THREE.JSONLoader.prototype.parse = function ( json, texturePath ) { - - var scope = this, - geometry = new THREE.Geometry(), - scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; - - parseModel( scale ); - - parseSkin(); - parseMorphing( scale ); - - geometry.computeCentroids(); - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); - - function parseModel( scale ) { - - function isBitSet( value, position ) { - - return value & ( 1 << position ); - - } - - var i, j, fi, - - offset, zLength, - - colorIndex, normalIndex, uvIndex, materialIndex, - - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, - - vertex, face, faceA, faceB, color, hex, normal, - - uvLayer, uv, u, v, - - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, - - nUvLayers = 0; - - if ( json.uvs !== undefined ) { - - // disregard empty arrays - - for ( i = 0; i < json.uvs.length; i++ ) { - - if ( json.uvs[ i ].length ) nUvLayers ++; - - } - - for ( i = 0; i < nUvLayers; i++ ) { - - geometry.faceVertexUvs[ i ] = []; - - } - - } - - offset = 0; - zLength = vertices.length; - - while ( offset < zLength ) { - - vertex = new THREE.Vector3(); - - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; - - geometry.vertices.push( vertex ); - - } - - offset = 0; - zLength = faces.length; - - while ( offset < zLength ) { - - type = faces[ offset ++ ]; - - - isQuad = isBitSet( type, 0 ); - hasMaterial = isBitSet( type, 1 ); - hasFaceVertexUv = isBitSet( type, 3 ); - hasFaceNormal = isBitSet( type, 4 ); - hasFaceVertexNormal = isBitSet( type, 5 ); - hasFaceColor = isBitSet( type, 6 ); - hasFaceVertexColor = isBitSet( type, 7 ); - - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - - if ( isQuad ) { - - faceA = new THREE.Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; - - faceB = new THREE.Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; - - offset += 4; - - if ( hasMaterial ) { - - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; - - } - - // to get face <=> uv index correspondence - - fi = geometry.faces.length; - - if ( hasFaceVertexUv ) { - - for ( i = 0; i < nUvLayers; i++ ) { - - uvLayer = json.uvs[ i ]; - - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = [] - - for ( j = 0; j < 4; j ++ ) { - - uvIndex = faces[ offset ++ ]; - - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; - - uv = new THREE.Vector2( u, v ); - - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); - - } - - } - - } - - if ( hasFaceNormal ) { - - normalIndex = faces[ offset ++ ] * 3; - - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); - - faceB.normal.copy( faceA.normal ); - - } - - if ( hasFaceVertexNormal ) { - - for ( i = 0; i < 4; i++ ) { - - normalIndex = faces[ offset ++ ] * 3; - - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); - - - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); - - } - - } - - - if ( hasFaceColor ) { - - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; - - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); - - } - - - if ( hasFaceVertexColor ) { - - for ( i = 0; i < 4; i++ ) { - - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; - - if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); - - } - - } - - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); - - } else { - - face = new THREE.Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; - - if ( hasMaterial ) { - - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; - - } - - // to get face <=> uv index correspondence - - fi = geometry.faces.length; - - if ( hasFaceVertexUv ) { - - for ( i = 0; i < nUvLayers; i++ ) { - - uvLayer = json.uvs[ i ]; - - geometry.faceVertexUvs[ i ][ fi ] = []; - - for ( j = 0; j < 3; j ++ ) { - - uvIndex = faces[ offset ++ ]; - - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; - - uv = new THREE.Vector2( u, v ); - - geometry.faceVertexUvs[ i ][ fi ].push( uv ); - - } - - } - - } - - if ( hasFaceNormal ) { - - normalIndex = faces[ offset ++ ] * 3; - - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); - - } - - if ( hasFaceVertexNormal ) { - - for ( i = 0; i < 3; i++ ) { - - normalIndex = faces[ offset ++ ] * 3; - - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); - - face.vertexNormals.push( normal ); - - } - - } - - - if ( hasFaceColor ) { - - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); - - } - - - if ( hasFaceVertexColor ) { - - for ( i = 0; i < 3; i++ ) { - - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); - - } - - } - - geometry.faces.push( face ); - - } - - } - - }; - - function parseSkin() { - - if ( json.skinWeights ) { - - for ( var i = 0, l = json.skinWeights.length; i < l; i += 2 ) { - - var x = json.skinWeights[ i ]; - var y = json.skinWeights[ i + 1 ]; - var z = 0; - var w = 0; - - geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); - - } - - } - - if ( json.skinIndices ) { - - for ( var i = 0, l = json.skinIndices.length; i < l; i += 2 ) { - - var a = json.skinIndices[ i ]; - var b = json.skinIndices[ i + 1 ]; - var c = 0; - var d = 0; - - geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); - - } - - } - - geometry.bones = json.bones; - - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - - console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); - - } - - - // could change this to json.animations[0] or remove completely - - geometry.animation = json.animation; - geometry.animations = json.animations; - - }; - - function parseMorphing( scale ) { - - if ( json.morphTargets !== undefined ) { - - var i, l, v, vl, dstVertices, srcVertices; - - for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) { - - geometry.morphTargets[ i ] = {}; - geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; - geometry.morphTargets[ i ].vertices = []; - - dstVertices = geometry.morphTargets[ i ].vertices; - srcVertices = json.morphTargets [ i ].vertices; - - for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - - var vertex = new THREE.Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; - - dstVertices.push( vertex ); - - } - - } - - } - - if ( json.morphColors !== undefined ) { - - var i, l, c, cl, dstColors, srcColors, color; - - for ( i = 0, l = json.morphColors.length; i < l; i++ ) { - - geometry.morphColors[ i ] = {}; - geometry.morphColors[ i ].name = json.morphColors[ i ].name; - geometry.morphColors[ i ].colors = []; - - dstColors = geometry.morphColors[ i ].colors; - srcColors = json.morphColors [ i ].colors; - - for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) { - - color = new THREE.Color( 0xffaa00 ); - color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] ); - dstColors.push( color ); - - } - - } - - } - - }; - - if ( json.materials === undefined ) { - - return { geometry: geometry }; - - } else { - - var materials = this.initMaterials( json.materials, texturePath ); - - if ( this.needsTangents( materials ) ) { - - geometry.computeTangents(); - - } - - return { geometry: geometry, materials: materials }; - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.LoadingManager = function ( onLoad, onProgress, onError ) { - - var scope = this; - - var loaded = 0, total = 0; - - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; - - this.itemStart = function ( url ) { - - total ++; - - }; - - this.itemEnd = function ( url ) { - - loaded ++; - - if ( scope.onProgress !== undefined ) { - - scope.onProgress( url, loaded, total ); - - } - - if ( loaded === total && scope.onLoad !== undefined ) { - - scope.onLoad(); - - } - - }; - -}; - -THREE.DefaultLoadingManager = new THREE.LoadingManager(); -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.BufferGeometryLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.BufferGeometryLoader.prototype = { - - constructor: THREE.BufferGeometryLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new THREE.XHRLoader(); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { - - onLoad( scope.parse( JSON.parse( text ) ) ); - - } ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - }, - - parse: function ( json ) { - - var geometry = new THREE.BufferGeometry(); - - var attributes = json.attributes; - var offsets = json.offsets; - var boundingSphere = json.boundingSphere; - - for ( var key in attributes ) { - - var attribute = attributes[ key ]; - - geometry.attributes[ key ] = { - itemSize: attribute.itemSize, - array: new self[ attribute.type ]( attribute.array ) - } - - } - - if ( offsets !== undefined ) { - - geometry.offsets = JSON.parse( JSON.stringify( offsets ) ); - - } - - if ( boundingSphere !== undefined ) { - - geometry.boundingSphere = new THREE.Sphere( - new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ), - boundingSphere.radius - ); - - } - - return geometry; - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Geometry2Loader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.Geometry2Loader.prototype = { - - constructor: THREE.Geometry2Loader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new THREE.XHRLoader(); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { - - onLoad( scope.parse( JSON.parse( text ) ) ); - - } ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - }, - - parse: function ( json ) { - - var geometry = new THREE.Geometry2( json.vertices.length / 3 ); - - var attributes = [ 'vertices', 'normals', 'uvs' ]; - var boundingSphere = json.boundingSphere; - - for ( var key in attributes ) { - - var attribute = attributes[ key ]; - geometry[ attribute ].set( json[ attribute ] ); - - } - - if ( boundingSphere !== undefined ) { - - geometry.boundingSphere = new THREE.Sphere( - new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ), - boundingSphere.radius - ); - - } - - return geometry; - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.MaterialLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.MaterialLoader.prototype = { - - constructor: THREE.MaterialLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new THREE.XHRLoader(); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { - - onLoad( scope.parse( JSON.parse( text ) ) ); - - } ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - }, - - parse: function ( json ) { - - var material = new THREE[ json.type ]; - - if ( json.color !== undefined ) material.color.setHex( json.color ); - if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient ); - if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); - if ( json.specular !== undefined ) material.specular.setHex( json.specular ); - if ( json.shininess !== undefined ) material.shininess = json.shininess; - if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; - if ( json.blending !== undefined ) material.blending = json.blending; - if ( json.side !== undefined ) material.side = json.side; - if ( json.opacity !== undefined ) material.opacity = json.opacity; - if ( json.transparent !== undefined ) material.transparent = json.transparent; - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - - if ( json.materials !== undefined ) { - - for ( var i = 0, l = json.materials.length; i < l; i ++ ) { - - material.materials.push( this.parse( json.materials[ i ] ) ); - - } - - } - - return material; - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.ObjectLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.ObjectLoader.prototype = { - - constructor: THREE.ObjectLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { - - onLoad( scope.parse( JSON.parse( text ) ) ); - - } ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - }, - - parse: function ( json ) { - - var geometries = this.parseGeometries( json.geometries ); - var materials = this.parseMaterials( json.materials ); - var object = this.parseObject( json.object, geometries, materials ); - - return object; - - }, - - parseGeometries: function ( json ) { - - var geometries = {}; - - if ( json !== undefined ) { - - var geometryLoader = new THREE.JSONLoader(); - var geometry2Loader = new THREE.Geometry2Loader(); - var bufferGeometryLoader = new THREE.BufferGeometryLoader(); - - for ( var i = 0, l = json.length; i < l; i ++ ) { - - var geometry; - var data = json[ i ]; - - switch ( data.type ) { - - case 'PlaneGeometry': - - geometry = new THREE.PlaneGeometry( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); - - break; - - case 'BoxGeometry': - case 'CubeGeometry': // DEPRECATED - - geometry = new THREE.BoxGeometry( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); - - break; - - case 'CircleGeometry': - - geometry = new THREE.CircleGeometry( - data.radius, - data.segments - ); - - break; - - case 'CylinderGeometry': - - geometry = new THREE.CylinderGeometry( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded - ); - - break; - - case 'SphereGeometry': - - geometry = new THREE.SphereGeometry( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); - - break; - - case 'IcosahedronGeometry': - - geometry = new THREE.IcosahedronGeometry( - data.radius, - data.detail - ); - - break; - - case 'TorusGeometry': - - geometry = new THREE.TorusGeometry( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); - - break; - - case 'TorusKnotGeometry': - - geometry = new THREE.TorusKnotGeometry( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.p, - data.q, - data.heightScale - ); - - break; - - case 'BufferGeometry': - - geometry = bufferGeometryLoader.parse( data.data ); - - break; - - case 'Geometry2': - - geometry = geometry2Loader.parse( data.data ); - - break; - - case 'Geometry': - - geometry = geometryLoader.parse( data.data ).geometry; - - break; - - } - - geometry.uuid = data.uuid; - - if ( data.name !== undefined ) geometry.name = data.name; - - geometries[ data.uuid ] = geometry; - - } - - } - - return geometries; - - }, - - parseMaterials: function ( json ) { - - var materials = {}; - - if ( json !== undefined ) { - - var loader = new THREE.MaterialLoader(); - - for ( var i = 0, l = json.length; i < l; i ++ ) { - - var data = json[ i ]; - var material = loader.parse( data ); - - material.uuid = data.uuid; - - if ( data.name !== undefined ) material.name = data.name; - - materials[ data.uuid ] = material; - - } - - } - - return materials; - - }, - - parseObject: function () { - - var matrix = new THREE.Matrix4(); - - return function ( data, geometries, materials ) { - - var object; - - switch ( data.type ) { - - case 'Scene': - - object = new THREE.Scene(); - - break; - - case 'PerspectiveCamera': - - object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - - break; - - case 'OrthographicCamera': - - object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - - break; - - case 'AmbientLight': - - object = new THREE.AmbientLight( data.color ); - - break; - - case 'DirectionalLight': - - object = new THREE.DirectionalLight( data.color, data.intensity ); - - break; - - case 'PointLight': - - object = new THREE.PointLight( data.color, data.intensity, data.distance ); - - break; - - case 'SpotLight': - - object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent ); - - break; - - case 'HemisphereLight': - - object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); - - break; - - case 'Mesh': - - var geometry = geometries[ data.geometry ]; - var material = materials[ data.material ]; - - if ( geometry === undefined ) { - - console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry ); - - } - - if ( material === undefined ) { - - console.error( 'THREE.ObjectLoader: Undefined material ' + data.material ); - - } - - object = new THREE.Mesh( geometry, material ); - - break; - - case 'Sprite': - - var material = materials[ data.material ]; - - if ( material === undefined ) { - - console.error( 'THREE.ObjectLoader: Undefined material ' + data.material ); - - } - - object = new THREE.Sprite( material ); - - break; - - default: - - object = new THREE.Object3D(); - - } - - object.uuid = data.uuid; - - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { - - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); - - } else { - - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - - } - - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; - - if ( data.children !== undefined ) { - - for ( var child in data.children ) { - - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); - - } - - } - - return object; - - } - - }() - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.SceneLoader = function () { - - this.onLoadStart = function () {}; - this.onLoadProgress = function() {}; - this.onLoadComplete = function () {}; - - this.callbackSync = function () {}; - this.callbackProgress = function () {}; - - this.geometryHandlers = {}; - this.hierarchyHandlers = {}; - - this.addGeometryHandler( "ascii", THREE.JSONLoader ); - -}; - -THREE.SceneLoader.prototype = { - - constructor: THREE.SceneLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { - - scope.parse( JSON.parse( text ), onLoad, url ); - - } ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - }, - - addGeometryHandler: function ( typeID, loaderClass ) { - - this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass }; - - }, - - addHierarchyHandler: function ( typeID, loaderClass ) { - - this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass }; - - }, - - parse: function ( json, callbackFinished, url ) { - - var scope = this; - - var urlBase = THREE.Loader.prototype.extractUrlBase( url ); - - var geometry, material, camera, fog, - texture, images, color, - light, hex, intensity, - counter_models, counter_textures, - total_models, total_textures, - result; - - var target_array = []; - - var data = json; - - // async geometry loaders - - for ( var typeID in this.geometryHandlers ) { - - var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ]; - this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass(); - - } - - // async hierachy loaders - - for ( var typeID in this.hierarchyHandlers ) { - - var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ]; - this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass(); - - } - - counter_models = 0; - counter_textures = 0; - - result = { - - scene: new THREE.Scene(), - geometries: {}, - face_materials: {}, - materials: {}, - textures: {}, - objects: {}, - cameras: {}, - lights: {}, - fogs: {}, - empties: {}, - groups: {} - - }; - - if ( data.transform ) { - - var position = data.transform.position, - rotation = data.transform.rotation, - scale = data.transform.scale; - - if ( position ) { - - result.scene.position.fromArray( position ); - - } - - if ( rotation ) { - - result.scene.rotation.fromArray( rotation ); - - } - - if ( scale ) { - - result.scene.scale.fromArray( scale ); - - } - - if ( position || rotation || scale ) { - - result.scene.updateMatrix(); - result.scene.updateMatrixWorld(); - - } - - } - - function get_url( source_url, url_type ) { - - if ( url_type == "relativeToHTML" ) { - - return source_url; - - } else { - - return urlBase + source_url; - - } - - }; - - // toplevel loader function, delegates to handle_children - - function handle_objects() { - - handle_children( result.scene, data.objects ); - - } - - // handle all the children from the loaded json and attach them to given parent - - function handle_children( parent, children ) { - - var mat, dst, pos, rot, scl, quat; - - for ( var objID in children ) { - - // check by id if child has already been handled, - // if not, create new object - - var object = result.objects[ objID ]; - var objJSON = children[ objID ]; - - if ( object === undefined ) { - - // meshes - - if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) { - - if ( objJSON.loading === undefined ) { - - var reservedTypes = { - "type": 1, "url": 1, "material": 1, - "position": 1, "rotation": 1, "scale" : 1, - "visible": 1, "children": 1, "userData": 1, - "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 - }; - - var loaderParameters = {}; - - for ( var parType in objJSON ) { - - if ( ! ( parType in reservedTypes ) ) { - - loaderParameters[ parType ] = objJSON[ parType ]; - - } - - } - - material = result.materials[ objJSON.material ]; - - objJSON.loading = true; - - var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ]; - - // ColladaLoader - - if ( loader.options ) { - - loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) ); - - // UTF8Loader - // OBJLoader - - } else { - - loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters ); - - } - - } - - } else if ( objJSON.geometry !== undefined ) { - - geometry = result.geometries[ objJSON.geometry ]; - - // geometry already loaded - - if ( geometry ) { - - var needsTangents = false; - - material = result.materials[ objJSON.material ]; - needsTangents = material instanceof THREE.ShaderMaterial; - - pos = objJSON.position; - rot = objJSON.rotation; - scl = objJSON.scale; - mat = objJSON.matrix; - quat = objJSON.quaternion; - - // use materials from the model file - // if there is no material specified in the object - - if ( ! objJSON.material ) { - - material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] ); - - } - - // use materials from the model file - // if there is just empty face material - // (must create new material as each model has its own face material) - - if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) { - - material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] ); - - } - - if ( material instanceof THREE.MeshFaceMaterial ) { - - for ( var i = 0; i < material.materials.length; i ++ ) { - - needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial ); - - } - - } - - if ( needsTangents ) { - - geometry.computeTangents(); - - } - - if ( objJSON.skin ) { - - object = new THREE.SkinnedMesh( geometry, material ); - - } else if ( objJSON.morph ) { - - object = new THREE.MorphAnimMesh( geometry, material ); - - if ( objJSON.duration !== undefined ) { - - object.duration = objJSON.duration; - - } - - if ( objJSON.time !== undefined ) { - - object.time = objJSON.time; - - } - - if ( objJSON.mirroredLoop !== undefined ) { - - object.mirroredLoop = objJSON.mirroredLoop; - - } - - if ( material.morphNormals ) { - - geometry.computeMorphNormals(); - - } - - } else { - - object = new THREE.Mesh( geometry, material ); - - } - - object.name = objID; - - if ( mat ) { - - object.matrixAutoUpdate = false; - object.matrix.set( - mat[0], mat[1], mat[2], mat[3], - mat[4], mat[5], mat[6], mat[7], - mat[8], mat[9], mat[10], mat[11], - mat[12], mat[13], mat[14], mat[15] - ); - - } else { - - object.position.fromArray( pos ); - - if ( quat ) { - - object.quaternion.fromArray( quat ); - - } else { - - object.rotation.fromArray( rot ); - - } - - object.scale.fromArray( scl ); - - } - - object.visible = objJSON.visible; - object.castShadow = objJSON.castShadow; - object.receiveShadow = objJSON.receiveShadow; - - parent.add( object ); - - result.objects[ objID ] = object; - - } - - // lights - - } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" || - objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" || - objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) { - - var color = objJSON.color; - var intensity = objJSON.intensity; - var distance = objJSON.distance; - var position = objJSON.position; - var rotation = objJSON.rotation; - - switch ( objJSON.type ) { - - case 'AmbientLight': - light = new THREE.AmbientLight( color ); - break; - - case 'PointLight': - light = new THREE.PointLight( color, intensity, distance ); - light.position.fromArray( position ); - break; - - case 'DirectionalLight': - light = new THREE.DirectionalLight( color, intensity ); - light.position.fromArray( objJSON.direction ); - break; - - case 'SpotLight': - light = new THREE.SpotLight( color, intensity, distance, 1 ); - light.angle = objJSON.angle; - light.position.fromArray( position ); - light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] ); - light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) ); - break; - - case 'HemisphereLight': - light = new THREE.DirectionalLight( color, intensity, distance ); - light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] ); - light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) ); - break; - - case 'AreaLight': - light = new THREE.AreaLight(color, intensity); - light.position.fromArray( position ); - light.width = objJSON.size; - light.height = objJSON.size_y; - break; - - } - - parent.add( light ); - - light.name = objID; - result.lights[ objID ] = light; - result.objects[ objID ] = light; - - // cameras - - } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) { - - pos = objJSON.position; - rot = objJSON.rotation; - quat = objJSON.quaternion; - - if ( objJSON.type === "PerspectiveCamera" ) { - - camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far ); - - } else if ( objJSON.type === "OrthographicCamera" ) { - - camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far ); - - } - - camera.name = objID; - camera.position.fromArray( pos ); - - if ( quat !== undefined ) { - - camera.quaternion.fromArray( quat ); - - } else if ( rot !== undefined ) { - - camera.rotation.fromArray( rot ); - - } - - parent.add( camera ); - - result.cameras[ objID ] = camera; - result.objects[ objID ] = camera; - - // pure Object3D - - } else { - - pos = objJSON.position; - rot = objJSON.rotation; - scl = objJSON.scale; - quat = objJSON.quaternion; - - object = new THREE.Object3D(); - object.name = objID; - object.position.fromArray( pos ); - - if ( quat ) { - - object.quaternion.fromArray( quat ); - - } else { - - object.rotation.fromArray( rot ); - - } - - object.scale.fromArray( scl ); - object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false; - - parent.add( object ); - - result.objects[ objID ] = object; - result.empties[ objID ] = object; - - } - - if ( object ) { - - if ( objJSON.userData !== undefined ) { - - for ( var key in objJSON.userData ) { - - var value = objJSON.userData[ key ]; - object.userData[ key ] = value; - - } - - } - - if ( objJSON.groups !== undefined ) { - - for ( var i = 0; i < objJSON.groups.length; i ++ ) { - - var groupID = objJSON.groups[ i ]; - - if ( result.groups[ groupID ] === undefined ) { - - result.groups[ groupID ] = []; - - } - - result.groups[ groupID ].push( objID ); - - } - - } - - } - - } - - if ( object !== undefined && objJSON.children !== undefined ) { - - handle_children( object, objJSON.children ); - - } - - } - - }; - - function handle_mesh( geo, mat, id ) { - - result.geometries[ id ] = geo; - result.face_materials[ id ] = mat; - handle_objects(); - - }; - - function handle_hierarchy( node, id, parent, material, obj ) { - - var p = obj.position; - var r = obj.rotation; - var q = obj.quaternion; - var s = obj.scale; - - node.position.fromArray( p ); - - if ( q ) { - - node.quaternion.fromArray( q ); - - } else { - - node.rotation.fromArray( r ); - - } - - node.scale.fromArray( s ); - - // override children materials - // if object material was specified in JSON explicitly - - if ( material ) { - - node.traverse( function ( child ) { - - child.material = material; - - } ); - - } - - // override children visibility - // with root node visibility as specified in JSON - - var visible = ( obj.visible !== undefined ) ? obj.visible : true; - - node.traverse( function ( child ) { - - child.visible = visible; - - } ); - - parent.add( node ); - - node.name = id; - - result.objects[ id ] = node; - handle_objects(); - - }; - - function create_callback_geometry( id ) { - - return function ( geo, mat ) { - - geo.name = id; - - handle_mesh( geo, mat, id ); - - counter_models -= 1; - - scope.onLoadComplete(); - - async_callback_gate(); - - } - - }; - - function create_callback_hierachy( id, parent, material, obj ) { - - return function ( event ) { - - var result; - - // loaders which use EventDispatcher - - if ( event.content ) { - - result = event.content; - - // ColladaLoader - - } else if ( event.dae ) { - - result = event.scene; - - - // UTF8Loader - - } else { - - result = event; - - } - - handle_hierarchy( result, id, parent, material, obj ); - - counter_models -= 1; - - scope.onLoadComplete(); - - async_callback_gate(); - - } - - }; - - function create_callback_embed( id ) { - - return function ( geo, mat ) { - - geo.name = id; - - result.geometries[ id ] = geo; - result.face_materials[ id ] = mat; - - } - - }; - - function async_callback_gate() { - - var progress = { - - totalModels : total_models, - totalTextures : total_textures, - loadedModels : total_models - counter_models, - loadedTextures : total_textures - counter_textures - - }; - - scope.callbackProgress( progress, result ); - - scope.onLoadProgress(); - - if ( counter_models === 0 && counter_textures === 0 ) { - - finalize(); - callbackFinished( result ); - - } - - }; - - function finalize() { - - // take care of targets which could be asynchronously loaded objects - - for ( var i = 0; i < target_array.length; i ++ ) { - - var ta = target_array[ i ]; - - var target = result.objects[ ta.targetName ]; - - if ( target ) { - - ta.object.target = target; - - } else { - - // if there was error and target of specified name doesn't exist in the scene file - // create instead dummy target - // (target must be added to scene explicitly as parent is already added) - - ta.object.target = new THREE.Object3D(); - result.scene.add( ta.object.target ); - - } - - ta.object.target.userData.targetInverse = ta.object; - - } - - }; - - var callbackTexture = function ( count ) { - - counter_textures -= count; - async_callback_gate(); - - scope.onLoadComplete(); - - }; - - // must use this instead of just directly calling callbackTexture - // because of closure in the calling context loop - - var generateTextureCallback = function ( count ) { - - return function () { - - callbackTexture( count ); - - }; - - }; - - function traverse_json_hierarchy( objJSON, callback ) { - - callback( objJSON ); - - if ( objJSON.children !== undefined ) { - - for ( var objChildID in objJSON.children ) { - - traverse_json_hierarchy( objJSON.children[ objChildID ], callback ); - - } - - } - - }; - - // first go synchronous elements - - // fogs - - var fogID, fogJSON; - - for ( fogID in data.fogs ) { - - fogJSON = data.fogs[ fogID ]; - - if ( fogJSON.type === "linear" ) { - - fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far ); - - } else if ( fogJSON.type === "exp2" ) { - - fog = new THREE.FogExp2( 0x000000, fogJSON.density ); - - } - - color = fogJSON.color; - fog.color.setRGB( color[0], color[1], color[2] ); - - result.fogs[ fogID ] = fog; - - } - - // now come potentially asynchronous elements - - // geometries - - // count how many geometries will be loaded asynchronously - - var geoID, geoJSON; - - for ( geoID in data.geometries ) { - - geoJSON = data.geometries[ geoID ]; - - if ( geoJSON.type in this.geometryHandlers ) { - - counter_models += 1; - - scope.onLoadStart(); - - } - - } - - // count how many hierarchies will be loaded asynchronously - - for ( var objID in data.objects ) { - - traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) { - - if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) { - - counter_models += 1; - - scope.onLoadStart(); - - } - - }); - - } - - total_models = counter_models; - - for ( geoID in data.geometries ) { - - geoJSON = data.geometries[ geoID ]; - - if ( geoJSON.type === "cube" ) { - - geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; - - } else if ( geoJSON.type === "plane" ) { - - geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; - - } else if ( geoJSON.type === "sphere" ) { - - geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; - - } else if ( geoJSON.type === "cylinder" ) { - - geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; - - } else if ( geoJSON.type === "torus" ) { - - geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; - - } else if ( geoJSON.type === "icosahedron" ) { - - geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions ); - geometry.name = geoID; - result.geometries[ geoID ] = geometry; - - } else if ( geoJSON.type in this.geometryHandlers ) { - - var loaderParameters = {}; - - for ( var parType in geoJSON ) { - - if ( parType !== "type" && parType !== "url" ) { - - loaderParameters[ parType ] = geoJSON[ parType ]; - - } - - } - - var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ]; - loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters ); - - } else if ( geoJSON.type === "embedded" ) { - - var modelJson = data.embeds[ geoJSON.id ], - texture_path = ""; - - // pass metadata along to jsonLoader so it knows the format version - - modelJson.metadata = data.metadata; - - if ( modelJson ) { - - var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ]; - var model = jsonLoader.parse( modelJson, texture_path ); - create_callback_embed( geoID )( model.geometry, model.materials ); - - } - - } - - } - - // textures - - // count how many textures will be loaded asynchronously - - var textureID, textureJSON; - - for ( textureID in data.textures ) { - - textureJSON = data.textures[ textureID ]; - - if ( textureJSON.url instanceof Array ) { - - counter_textures += textureJSON.url.length; - - for( var n = 0; n < textureJSON.url.length; n ++ ) { - - scope.onLoadStart(); - - } - - } else { - - counter_textures += 1; - - scope.onLoadStart(); - - } - - } - - total_textures = counter_textures; - - for ( textureID in data.textures ) { - - textureJSON = data.textures[ textureID ]; - - if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) { - - textureJSON.mapping = new THREE[ textureJSON.mapping ](); - - } - - if ( textureJSON.url instanceof Array ) { - - var count = textureJSON.url.length; - var url_array = []; - - for( var i = 0; i < count; i ++ ) { - - url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType ); - - } - - var isCompressed = /\.dds$/i.test( url_array[ 0 ] ); - - if ( isCompressed ) { - - texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) ); - - } else { - - texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) ); - - } - - } else { - - var isCompressed = /\.dds$/i.test( textureJSON.url ); - var fullUrl = get_url( textureJSON.url, data.urlBaseType ); - var textureCallback = generateTextureCallback( 1 ); - - if ( isCompressed ) { - - texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback ); - - } else { - - texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback ); - - } - - if ( THREE[ textureJSON.minFilter ] !== undefined ) - texture.minFilter = THREE[ textureJSON.minFilter ]; - - if ( THREE[ textureJSON.magFilter ] !== undefined ) - texture.magFilter = THREE[ textureJSON.magFilter ]; - - if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy; - - if ( textureJSON.repeat ) { - - texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] ); - - if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; - if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; - - } - - if ( textureJSON.offset ) { - - texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] ); - - } - - // handle wrap after repeat so that default repeat can be overriden - - if ( textureJSON.wrap ) { - - var wrapMap = { - "repeat": THREE.RepeatWrapping, - "mirror": THREE.MirroredRepeatWrapping - } - - if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ]; - if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ]; - - } - - } - - result.textures[ textureID ] = texture; - - } - - // materials - - var matID, matJSON; - var parID; - - for ( matID in data.materials ) { - - matJSON = data.materials[ matID ]; - - for ( parID in matJSON.parameters ) { - - if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) { - - matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ]; - - } else if ( parID === "shading" ) { - - matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading; - - } else if ( parID === "side" ) { - - if ( matJSON.parameters[ parID ] == "double" ) { - - matJSON.parameters[ parID ] = THREE.DoubleSide; - - } else if ( matJSON.parameters[ parID ] == "back" ) { - - matJSON.parameters[ parID ] = THREE.BackSide; - - } else { - - matJSON.parameters[ parID ] = THREE.FrontSide; - - } - - } else if ( parID === "blending" ) { - - matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending; - - } else if ( parID === "combine" ) { - - matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation; - - } else if ( parID === "vertexColors" ) { - - if ( matJSON.parameters[ parID ] == "face" ) { - - matJSON.parameters[ parID ] = THREE.FaceColors; - - // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false - - } else if ( matJSON.parameters[ parID ] ) { - - matJSON.parameters[ parID ] = THREE.VertexColors; - - } - - } else if ( parID === "wrapRGB" ) { - - var v3 = matJSON.parameters[ parID ]; - matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] ); - - } - - } - - if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) { - - matJSON.parameters.transparent = true; - - } - - if ( matJSON.parameters.normalMap ) { - - var shader = THREE.ShaderLib[ "normalmap" ]; - var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); - - var diffuse = matJSON.parameters.color; - var specular = matJSON.parameters.specular; - var ambient = matJSON.parameters.ambient; - var shininess = matJSON.parameters.shininess; - - uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ]; - - if ( matJSON.parameters.normalScale ) { - - uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] ); - - } - - if ( matJSON.parameters.map ) { - - uniforms[ "tDiffuse" ].value = matJSON.parameters.map; - uniforms[ "enableDiffuse" ].value = true; - - } - - if ( matJSON.parameters.envMap ) { - - uniforms[ "tCube" ].value = matJSON.parameters.envMap; - uniforms[ "enableReflection" ].value = true; - uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity; - - } - - if ( matJSON.parameters.lightMap ) { - - uniforms[ "tAO" ].value = matJSON.parameters.lightMap; - uniforms[ "enableAO" ].value = true; - - } - - if ( matJSON.parameters.specularMap ) { - - uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ]; - uniforms[ "enableSpecular" ].value = true; - - } - - if ( matJSON.parameters.displacementMap ) { - - uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ]; - uniforms[ "enableDisplacement" ].value = true; - - uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias; - uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale; - - } - - uniforms[ "diffuse" ].value.setHex( diffuse ); - uniforms[ "specular" ].value.setHex( specular ); - uniforms[ "ambient" ].value.setHex( ambient ); - - uniforms[ "shininess" ].value = shininess; - - if ( matJSON.parameters.opacity ) { - - uniforms[ "opacity" ].value = matJSON.parameters.opacity; - - } - - var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true }; - - material = new THREE.ShaderMaterial( parameters ); - - } else { - - material = new THREE[ matJSON.type ]( matJSON.parameters ); - - } - - material.name = matID; - - result.materials[ matID ] = material; - - } - - // second pass through all materials to initialize MeshFaceMaterials - // that could be referring to other materials out of order - - for ( matID in data.materials ) { - - matJSON = data.materials[ matID ]; - - if ( matJSON.parameters.materials ) { - - var materialArray = []; - - for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) { - - var label = matJSON.parameters.materials[ i ]; - materialArray.push( result.materials[ label ] ); - - } - - result.materials[ matID ].materials = materialArray; - - } - - } - - // objects ( synchronous init of procedural primitives ) - - handle_objects(); - - // defaults - - if ( result.cameras && data.defaults.camera ) { - - result.currentCamera = result.cameras[ data.defaults.camera ]; - - } - - if ( result.fogs && data.defaults.fog ) { - - result.scene.fog = result.fogs[ data.defaults.fog ]; - - } - - // synchronous callback - - scope.callbackSync( result ); - - // just in case there are no async elements - - async_callback_gate(); - - } - -} -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.TextureLoader = function ( manager ) { - - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - -}; - -THREE.TextureLoader.prototype = { - - constructor: THREE.TextureLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - var scope = this; - - var loader = new THREE.ImageLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( image ) { - - var texture = new THREE.Texture( image ); - texture.needsUpdate = true; - - if ( onLoad !== undefined ) { - - onLoad( texture ); - - } - - } ); - - }, - - setCrossOrigin: function ( value ) { - - this.crossOrigin = value; - - } - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Material = function () { - - this.id = THREE.MaterialIdCount ++; - this.uuid = THREE.Math.generateUUID(); - - this.name = ''; - - this.side = THREE.FrontSide; - - this.opacity = 1; - this.transparent = false; - - this.blending = THREE.NormalBlending; - - this.blendSrc = THREE.SrcAlphaFactor; - this.blendDst = THREE.OneMinusSrcAlphaFactor; - this.blendEquation = THREE.AddEquation; - - this.depthTest = true; - this.depthWrite = true; - - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; - - this.alphaTest = 0; - - this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer - - this.visible = true; - - this.needsUpdate = true; - -}; - -THREE.Material.prototype = { - - constructor: THREE.Material, - - setValues: function ( values ) { - - if ( values === undefined ) return; - - for ( var key in values ) { - - var newValue = values[ key ]; - - if ( newValue === undefined ) { - - console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); - continue; - - } - - if ( key in this ) { - - var currentValue = this[ key ]; - - if ( currentValue instanceof THREE.Color ) { - - currentValue.set( newValue ); - - } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { - - currentValue.copy( newValue ); - - } else if ( key == 'overdraw') { - - // ensure overdraw is backwards-compatable with legacy boolean type - this[ key ] = Number(newValue); - - } else { - - this[ key ] = newValue; - - } - - } - - } - - }, - - clone: function ( material ) { - - if ( material === undefined ) material = new THREE.Material(); - - material.name = this.name; - - material.side = this.side; - - material.opacity = this.opacity; - material.transparent = this.transparent; - - material.blending = this.blending; - - material.blendSrc = this.blendSrc; - material.blendDst = this.blendDst; - material.blendEquation = this.blendEquation; - - material.depthTest = this.depthTest; - material.depthWrite = this.depthWrite; - - material.polygonOffset = this.polygonOffset; - material.polygonOffsetFactor = this.polygonOffsetFactor; - material.polygonOffsetUnits = this.polygonOffsetUnits; - - material.alphaTest = this.alphaTest; - - material.overdraw = this.overdraw; - - material.visible = this.visible; - - return material; - - }, - - dispose: function () { - - this.dispatchEvent( { type: 'dispose' } ); - - } - -}; - -THREE.EventDispatcher.prototype.apply( THREE.Material.prototype ); - -THREE.MaterialIdCount = 0; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round", - * - * vertexColors: - * - * fog: - * } - */ - -THREE.LineBasicMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.color = new THREE.Color( 0xffffff ); - - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; - - this.vertexColors = false; - - this.fog = true; - - this.setValues( parameters ); - -}; - -THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.LineBasicMaterial.prototype.clone = function () { - - var material = new THREE.LineBasicMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.color.copy( this.color ); - - material.linewidth = this.linewidth; - material.linecap = this.linecap; - material.linejoin = this.linejoin; - - material.vertexColors = this.vertexColors; - - material.fog = this.fog; - - return material; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: , - * - * vertexColors: - * - * fog: - * } - */ - -THREE.LineDashedMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.color = new THREE.Color( 0xffffff ); - - this.linewidth = 1; - - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; - - this.vertexColors = false; - - this.fog = true; - - this.setValues( parameters ); - -}; - -THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.LineDashedMaterial.prototype.clone = function () { - - var material = new THREE.LineDashedMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.color.copy( this.color ); - - material.linewidth = this.linewidth; - - material.scale = this.scale; - material.dashSize = this.dashSize; - material.gapSize = this.gapSize; - - material.vertexColors = this.vertexColors; - - material.fog = this.fog; - - return material; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * - * specularMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: , - * morphTargets: , - * - * fog: - * } - */ - -THREE.MeshBasicMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.color = new THREE.Color( 0xffffff ); // emissive - - this.map = null; - - this.lightMap = null; - - this.specularMap = null; - - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; - - this.fog = true; - - this.shading = THREE.SmoothShading; - - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; - - this.vertexColors = THREE.NoColors; - - this.skinning = false; - this.morphTargets = false; - - this.setValues( parameters ); - -}; - -THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.MeshBasicMaterial.prototype.clone = function () { - - var material = new THREE.MeshBasicMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.color.copy( this.color ); - - material.map = this.map; - - material.lightMap = this.lightMap; - - material.specularMap = this.specularMap; - - material.envMap = this.envMap; - material.combine = this.combine; - material.reflectivity = this.reflectivity; - material.refractionRatio = this.refractionRatio; - - material.fog = this.fog; - - material.shading = this.shading; - - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - material.wireframeLinecap = this.wireframeLinecap; - material.wireframeLinejoin = this.wireframeLinejoin; - - material.vertexColors = this.vertexColors; - - material.skinning = this.skinning; - material.morphTargets = this.morphTargets; - - return material; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * ambient: , - * emissive: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * - * specularMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * fog: - * } - */ - -THREE.MeshLambertMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.color = new THREE.Color( 0xffffff ); // diffuse - this.ambient = new THREE.Color( 0xffffff ); - this.emissive = new THREE.Color( 0x000000 ); - - this.wrapAround = false; - this.wrapRGB = new THREE.Vector3( 1, 1, 1 ); - - this.map = null; - - this.lightMap = null; - - this.specularMap = null; - - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; - - this.fog = true; - - this.shading = THREE.SmoothShading; - - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; - - this.vertexColors = THREE.NoColors; - - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; - - this.setValues( parameters ); - -}; - -THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.MeshLambertMaterial.prototype.clone = function () { - - var material = new THREE.MeshLambertMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.color.copy( this.color ); - material.ambient.copy( this.ambient ); - material.emissive.copy( this.emissive ); - - material.wrapAround = this.wrapAround; - material.wrapRGB.copy( this.wrapRGB ); - - material.map = this.map; - - material.lightMap = this.lightMap; - - material.specularMap = this.specularMap; - - material.envMap = this.envMap; - material.combine = this.combine; - material.reflectivity = this.reflectivity; - material.refractionRatio = this.refractionRatio; - - material.fog = this.fog; - - material.shading = this.shading; - - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - material.wireframeLinecap = this.wireframeLinecap; - material.wireframeLinejoin = this.wireframeLinejoin; - - material.vertexColors = this.vertexColors; - - material.skinning = this.skinning; - material.morphTargets = this.morphTargets; - material.morphNormals = this.morphNormals; - - return material; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * ambient: , - * emissive: , - * specular: , - * shininess: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * specularMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * fog: - * } - */ - -THREE.MeshPhongMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.color = new THREE.Color( 0xffffff ); // diffuse - this.ambient = new THREE.Color( 0xffffff ); - this.emissive = new THREE.Color( 0x000000 ); - this.specular = new THREE.Color( 0x111111 ); - this.shininess = 30; - - this.metal = false; - - this.wrapAround = false; - this.wrapRGB = new THREE.Vector3( 1, 1, 1 ); - - this.map = null; - - this.lightMap = null; - - this.bumpMap = null; - this.bumpScale = 1; - - this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); - - this.specularMap = null; - - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; - - this.fog = true; - - this.shading = THREE.SmoothShading; - - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; - - this.vertexColors = THREE.NoColors; - - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; - - this.setValues( parameters ); - -}; - -THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.MeshPhongMaterial.prototype.clone = function () { - - var material = new THREE.MeshPhongMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.color.copy( this.color ); - material.ambient.copy( this.ambient ); - material.emissive.copy( this.emissive ); - material.specular.copy( this.specular ); - material.shininess = this.shininess; - - material.metal = this.metal; - - material.wrapAround = this.wrapAround; - material.wrapRGB.copy( this.wrapRGB ); - - material.map = this.map; - - material.lightMap = this.lightMap; - - material.bumpMap = this.bumpMap; - material.bumpScale = this.bumpScale; - - material.normalMap = this.normalMap; - material.normalScale.copy( this.normalScale ); - - material.specularMap = this.specularMap; - - material.envMap = this.envMap; - material.combine = this.combine; - material.reflectivity = this.reflectivity; - material.refractionRatio = this.refractionRatio; - - material.fog = this.fog; - - material.shading = this.shading; - - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - material.wireframeLinecap = this.wireframeLinecap; - material.wireframeLinejoin = this.wireframeLinejoin; - - material.vertexColors = this.vertexColors; - - material.skinning = this.skinning; - material.morphTargets = this.morphTargets; - material.morphNormals = this.morphNormals; - - return material; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * opacity: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ - -THREE.MeshDepthMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.wireframe = false; - this.wireframeLinewidth = 1; - - this.setValues( parameters ); - -}; - -THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.MeshDepthMaterial.prototype.clone = function () { - - var material = new THREE.MeshDepthMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - - return material; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * opacity: , - * - * shading: THREE.FlatShading, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ - -THREE.MeshNormalMaterial = function ( parameters ) { - - THREE.Material.call( this, parameters ); - - this.shading = THREE.FlatShading; - - this.wireframe = false; - this.wireframeLinewidth = 1; - - this.morphTargets = false; - - this.setValues( parameters ); - -}; - -THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.MeshNormalMaterial.prototype.clone = function () { - - var material = new THREE.MeshNormalMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.shading = this.shading; - - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - - return material; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.MeshFaceMaterial = function ( materials ) { - - this.materials = materials instanceof Array ? materials : []; - -}; - -THREE.MeshFaceMaterial.prototype.clone = function () { - - var material = new THREE.MeshFaceMaterial(); - - for ( var i = 0; i < this.materials.length; i ++ ) { - - material.materials.push( this.materials[ i ].clone() ); - - } - - return material; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * size: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * vertexColors: , - * - * fog: - * } - */ - -THREE.ParticleSystemMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.color = new THREE.Color( 0xffffff ); - - this.map = null; - - this.size = 1; - this.sizeAttenuation = true; - - this.vertexColors = false; - - this.fog = true; - - this.setValues( parameters ); - -}; - -THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.ParticleSystemMaterial.prototype.clone = function () { - - var material = new THREE.ParticleSystemMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.color.copy( this.color ); - - material.map = this.map; - - material.size = this.size; - material.sizeAttenuation = this.sizeAttenuation; - - material.vertexColors = this.vertexColors; - - material.fog = this.fog; - - return material; - -}; - -// backwards compatibility - -THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial; -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * fragmentShader: , - * vertexShader: , - * - * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } }, - * - * defines: { "label" : "value" }, - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * fog: - * } - */ - -THREE.ShaderMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.fragmentShader = "void main() {}"; - this.vertexShader = "void main() {}"; - this.uniforms = {}; - this.defines = {}; - this.attributes = null; - - this.shading = THREE.SmoothShading; - - this.linewidth = 1; - - this.wireframe = false; - this.wireframeLinewidth = 1; - - this.fog = false; // set to use scene fog - - this.lights = false; // set to use scene lights - - this.vertexColors = THREE.NoColors; // set to use "color" attribute stream - - this.skinning = false; // set to use skinning attribute streams - - this.morphTargets = false; // set to use morph targets - this.morphNormals = false; // set to use morph normals - - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - "color" : [ 1, 1, 1], - "uv" : [ 0, 0 ], - "uv2" : [ 0, 0 ] - }; - - // By default, bind position to attribute index 0. In WebGL, attribute 0 - // should always be used to avoid potentially expensive emulation. - this.index0AttributeName = "position"; - - this.setValues( parameters ); - -}; - -THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.ShaderMaterial.prototype.clone = function () { - - var material = new THREE.ShaderMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.fragmentShader = this.fragmentShader; - material.vertexShader = this.vertexShader; - - material.uniforms = THREE.UniformsUtils.clone( this.uniforms ); - - material.attributes = this.attributes; - material.defines = this.defines; - - material.shading = this.shading; - - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - - material.fog = this.fog; - - material.lights = this.lights; - - material.vertexColors = this.vertexColors; - - material.skinning = this.skinning; - - material.morphTargets = this.morphTargets; - material.morphNormals = this.morphNormals; - - return material; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * uvOffset: new THREE.Vector2(), - * uvScale: new THREE.Vector2(), - * - * fog: - * } - */ - -THREE.SpriteMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - // defaults - - this.color = new THREE.Color( 0xffffff ); - this.map = null; - - this.rotation = 0; - - this.fog = false; - - // set parameters - - this.setValues( parameters ); - -}; - -THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.SpriteMaterial.prototype.clone = function () { - - var material = new THREE.SpriteMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.color.copy( this.color ); - material.map = this.map; - - material.rotation = this.rotation; - - material.fog = this.fog; - - return material; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * color: , - * program: , - * opacity: , - * blending: THREE.NormalBlending - * } - */ - -THREE.SpriteCanvasMaterial = function ( parameters ) { - - THREE.Material.call( this ); - - this.color = new THREE.Color( 0xffffff ); - this.program = function ( context, color ) {}; - - this.setValues( parameters ); - -}; - -THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype ); - -THREE.SpriteCanvasMaterial.prototype.clone = function () { - - var material = new THREE.SpriteCanvasMaterial(); - - THREE.Material.prototype.clone.call( this, material ); - - material.color.copy( this.color ); - material.program = this.program; - - return material; - -}; - -// backwards compatibility - -THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ - -THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - - this.id = THREE.TextureIdCount ++; - this.uuid = THREE.Math.generateUUID(); - - this.name = ''; - - this.image = image; - this.mipmaps = []; - - this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping(); - - this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; - - this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter; - - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - - this.format = format !== undefined ? format : THREE.RGBAFormat; - this.type = type !== undefined ? type : THREE.UnsignedByteType; - - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); - - this.generateMipmaps = true; - this.premultiplyAlpha = false; - this.flipY = true; - this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - - this._needsUpdate = false; - this.onUpdate = null; - -}; - -THREE.Texture.prototype = { - - constructor: THREE.Texture, - - get needsUpdate () { - - return this._needsUpdate; - - }, - - set needsUpdate ( value ) { - - if ( value === true ) this.update(); - - this._needsUpdate = value; - - }, - - clone: function ( texture ) { - - if ( texture === undefined ) texture = new THREE.Texture(); - - texture.image = this.image; - texture.mipmaps = this.mipmaps.slice(0); - - texture.mapping = this.mapping; - - texture.wrapS = this.wrapS; - texture.wrapT = this.wrapT; - - texture.magFilter = this.magFilter; - texture.minFilter = this.minFilter; - - texture.anisotropy = this.anisotropy; - - texture.format = this.format; - texture.type = this.type; - - texture.offset.copy( this.offset ); - texture.repeat.copy( this.repeat ); - - texture.generateMipmaps = this.generateMipmaps; - texture.premultiplyAlpha = this.premultiplyAlpha; - texture.flipY = this.flipY; - texture.unpackAlignment = this.unpackAlignment; - - return texture; - - }, - - update: function () { - - this.dispatchEvent( { type: 'update' } ); - - }, - - dispose: function () { - - this.dispatchEvent( { type: 'dispose' } ); - - } - -}; - -THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype ); - -THREE.TextureIdCount = 0; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { - - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; - - this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file - -}; - -THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); - -THREE.CompressedTexture.prototype.clone = function () { - - var texture = new THREE.CompressedTexture(); - - THREE.Texture.prototype.clone.call( this, texture ); - - return texture; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { - - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - - this.image = { data: data, width: width, height: height }; - -}; - -THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); - -THREE.DataTexture.prototype.clone = function () { - - var texture = new THREE.DataTexture(); - - THREE.Texture.prototype.clone.call( this, texture ); - - return texture; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.ParticleSystem = function ( geometry, material ) { - - THREE.Object3D.call( this ); - - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } ); - - this.sortParticles = false; - this.frustumCulled = false; - -}; - -THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.ParticleSystem.prototype.clone = function ( object ) { - - if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material ); - - object.sortParticles = this.sortParticles; - - THREE.Object3D.prototype.clone.call( this, object ); - - return object; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Line = function ( geometry, material, type ) { - - THREE.Object3D.call( this ); - - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); - - this.type = ( type !== undefined ) ? type : THREE.LineStrip; - -}; - -THREE.LineStrip = 0; -THREE.LinePieces = 1; - -THREE.Line.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.Line.prototype.clone = function ( object ) { - - if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type ); - - THREE.Object3D.prototype.clone.call( this, object ); - - return object; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ - */ - -THREE.Mesh = function ( geometry, material ) { - - THREE.Object3D.call( this ); - - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - - this.updateMorphTargets(); - -}; - -THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.Mesh.prototype.updateMorphTargets = function () { - - if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { - - this.morphTargetBase = -1; - this.morphTargetForcedOrder = []; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; - - for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { - - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; - - } - - } - -}; - -THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) { - - if ( this.morphTargetDictionary[ name ] !== undefined ) { - - return this.morphTargetDictionary[ name ]; - - } - - console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." ); - - return 0; - -}; - -THREE.Mesh.prototype.clone = function ( object ) { - - if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material ); - - THREE.Object3D.prototype.clone.call( this, object ); - - return object; - -}; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Bone = function( belongsToSkin ) { - - THREE.Object3D.call( this ); - - this.skin = belongsToSkin; - this.skinMatrix = new THREE.Matrix4(); - -}; - -THREE.Bone.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) { - - // update local - - if ( this.matrixAutoUpdate ) { - - forceUpdate |= this.updateMatrix(); - - } - - // update skin matrix - - if ( forceUpdate || this.matrixWorldNeedsUpdate ) { - - if( parentSkinMatrix ) { - - this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix ); - - } else { - - this.skinMatrix.copy( this.matrix ); - - } - - this.matrixWorldNeedsUpdate = false; - forceUpdate = true; - - } - - // update children - - var child, i, l = this.children.length; - - for ( i = 0; i < l; i ++ ) { - - this.children[ i ].update( this.skinMatrix, forceUpdate ); - - } - -}; - -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { - - THREE.Mesh.call( this, geometry, material ); - - // - - this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - - // init bones - - this.identityMatrix = new THREE.Matrix4(); - - this.bones = []; - this.boneMatrices = []; - - var b, bone, gbone, p, q, s; - - if ( this.geometry && this.geometry.bones !== undefined ) { - - for ( b = 0; b < this.geometry.bones.length; b ++ ) { - - gbone = this.geometry.bones[ b ]; - - p = gbone.pos; - q = gbone.rotq; - s = gbone.scl; - - bone = this.addBone(); - - bone.name = gbone.name; - bone.position.set( p[0], p[1], p[2] ); - bone.quaternion.set( q[0], q[1], q[2], q[3] ); - - if ( s !== undefined ) { - - bone.scale.set( s[0], s[1], s[2] ); - - } else { - - bone.scale.set( 1, 1, 1 ); - - } - - } - - for ( b = 0; b < this.bones.length; b ++ ) { - - gbone = this.geometry.bones[ b ]; - bone = this.bones[ b ]; - - if ( gbone.parent === -1 ) { - - this.add( bone ); - - } else { - - this.bones[ gbone.parent ].add( bone ); - - } - - } - - // - - var nBones = this.bones.length; - - if ( this.useVertexTexture ) { - - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones (8 * 8 / 4) - // 16x16 pixel texture max 64 bones (16 * 16 / 4) - // 32x32 pixel texture max 256 bones (32 * 32 / 4) - // 64x64 pixel texture max 1024 bones (64 * 64 / 4) - - var size; - - if ( nBones > 256 ) - size = 64; - else if ( nBones > 64 ) - size = 32; - else if ( nBones > 16 ) - size = 16; - else - size = 8; - - this.boneTextureWidth = size; - this.boneTextureHeight = size; - - this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel - this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); - this.boneTexture.minFilter = THREE.NearestFilter; - this.boneTexture.magFilter = THREE.NearestFilter; - this.boneTexture.generateMipmaps = false; - this.boneTexture.flipY = false; - - } else { - - this.boneMatrices = new Float32Array( 16 * nBones ); - - } - - this.pose(); - - } - -}; - -THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype ); - -THREE.SkinnedMesh.prototype.addBone = function( bone ) { - - if ( bone === undefined ) { - - bone = new THREE.Bone( this ); - - } - - this.bones.push( bone ); - - return bone; - -}; - -THREE.SkinnedMesh.prototype.updateMatrixWorld = function () { - - var offsetMatrix = new THREE.Matrix4(); - - return function ( force ) { - - this.matrixAutoUpdate && this.updateMatrix(); - - // update matrixWorld - - if ( this.matrixWorldNeedsUpdate || force ) { - - if ( this.parent ) { - - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - - } else { - - this.matrixWorld.copy( this.matrix ); - - } - - this.matrixWorldNeedsUpdate = false; - - force = true; - - } - - // update children - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - var child = this.children[ i ]; - - if ( child instanceof THREE.Bone ) { - - child.update( this.identityMatrix, false ); - - } else { - - child.updateMatrixWorld( true ); - - } - - } - - // make a snapshot of the bones' rest position - - if ( this.boneInverses == undefined ) { - - this.boneInverses = []; - - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - - var inverse = new THREE.Matrix4(); - - inverse.getInverse( this.bones[ b ].skinMatrix ); - - this.boneInverses.push( inverse ); - - } - - } - - // flatten bone matrices to array - - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - - // compute the offset between the current and the original transform; - - // TODO: we could get rid of this multiplication step if the skinMatrix - // was already representing the offset; however, this requires some - // major changes to the animation system - - offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] ); - offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 ); - - } - - if ( this.useVertexTexture ) { - - this.boneTexture.needsUpdate = true; - - } - - }; - -}(); - -THREE.SkinnedMesh.prototype.pose = function () { - - this.updateMatrixWorld( true ); - - this.normalizeSkinWeights(); - -}; - -THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () { - - if ( this.geometry instanceof THREE.Geometry ) { - - for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) { - - var sw = this.geometry.skinWeights[ i ]; - - var scale = 1.0 / sw.lengthManhattan(); - - if ( scale !== Infinity ) { - - sw.multiplyScalar( scale ); - - } else { - - sw.set( 1 ); // this will be normalized by the shader anyway - - } - - } - - } else { - - // skinning weights assumed to be normalized for THREE.BufferGeometry - - } - -}; - -THREE.SkinnedMesh.prototype.clone = function ( object ) { - - if ( object === undefined ) { - - object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture ); - - } - - THREE.Mesh.prototype.clone.call( this, object ); - - return object; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.MorphAnimMesh = function ( geometry, material ) { - - THREE.Mesh.call( this, geometry, material ); - - // API - - this.duration = 1000; // milliseconds - this.mirroredLoop = false; - this.time = 0; - - // internals - - this.lastKeyframe = 0; - this.currentKeyframe = 0; - - this.direction = 1; - this.directionBackwards = false; - - this.setFrameRange( 0, this.geometry.morphTargets.length - 1 ); - -}; - -THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype ); - -THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) { - - this.startKeyframe = start; - this.endKeyframe = end; - - this.length = this.endKeyframe - this.startKeyframe + 1; - -}; - -THREE.MorphAnimMesh.prototype.setDirectionForward = function () { - - this.direction = 1; - this.directionBackwards = false; - -}; - -THREE.MorphAnimMesh.prototype.setDirectionBackward = function () { - - this.direction = -1; - this.directionBackwards = true; - -}; - -THREE.MorphAnimMesh.prototype.parseAnimations = function () { - - var geometry = this.geometry; - - if ( ! geometry.animations ) geometry.animations = {}; - - var firstAnimation, animations = geometry.animations; - - var pattern = /([a-z]+)(\d+)/; - - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { - - var morph = geometry.morphTargets[ i ]; - var parts = morph.name.match( pattern ); - - if ( parts && parts.length > 1 ) { - - var label = parts[ 1 ]; - var num = parts[ 2 ]; - - if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity }; - - var animation = animations[ label ]; - - if ( i < animation.start ) animation.start = i; - if ( i > animation.end ) animation.end = i; - - if ( ! firstAnimation ) firstAnimation = label; - - } - - } - - geometry.firstAnimation = firstAnimation; - -}; - -THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) { - - if ( ! this.geometry.animations ) this.geometry.animations = {}; - - this.geometry.animations[ label ] = { start: start, end: end }; - -}; - -THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) { - - var animation = this.geometry.animations[ label ]; - - if ( animation ) { - - this.setFrameRange( animation.start, animation.end ); - this.duration = 1000 * ( ( animation.end - animation.start ) / fps ); - this.time = 0; - - } else { - - console.warn( "animation[" + label + "] undefined" ); - - } - -}; - -THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) { - - var frameTime = this.duration / this.length; - - this.time += this.direction * delta; - - if ( this.mirroredLoop ) { - - if ( this.time > this.duration || this.time < 0 ) { - - this.direction *= -1; - - if ( this.time > this.duration ) { - - this.time = this.duration; - this.directionBackwards = true; - - } - - if ( this.time < 0 ) { - - this.time = 0; - this.directionBackwards = false; - - } - - } - - } else { - - this.time = this.time % this.duration; - - if ( this.time < 0 ) this.time += this.duration; - - } - - var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 ); - - if ( keyframe !== this.currentKeyframe ) { - - this.morphTargetInfluences[ this.lastKeyframe ] = 0; - this.morphTargetInfluences[ this.currentKeyframe ] = 1; - - this.morphTargetInfluences[ keyframe ] = 0; - - this.lastKeyframe = this.currentKeyframe; - this.currentKeyframe = keyframe; - - } - - var mix = ( this.time % frameTime ) / frameTime; - - if ( this.directionBackwards ) { - - mix = 1 - mix; - - } - - this.morphTargetInfluences[ this.currentKeyframe ] = mix; - this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix; - -}; - -THREE.MorphAnimMesh.prototype.clone = function ( object ) { - - if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material ); - - object.duration = this.duration; - object.mirroredLoop = this.mirroredLoop; - object.time = this.time; - - object.lastKeyframe = this.lastKeyframe; - object.currentKeyframe = this.currentKeyframe; - - object.direction = this.direction; - object.directionBackwards = this.directionBackwards; - - THREE.Mesh.prototype.clone.call( this, object ); - - return object; - -}; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.LOD = function () { - - THREE.Object3D.call( this ); - - this.objects = []; - -}; - - -THREE.LOD.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.LOD.prototype.addLevel = function ( object, distance ) { - - if ( distance === undefined ) distance = 0; - - distance = Math.abs( distance ); - - for ( var l = 0; l < this.objects.length; l ++ ) { - - if ( distance < this.objects[ l ].distance ) { - - break; - - } - - } - - this.objects.splice( l, 0, { distance: distance, object: object } ); - this.add( object ); - -}; - -THREE.LOD.prototype.getObjectForDistance = function ( distance ) { - - for ( var i = 1, l = this.objects.length; i < l; i ++ ) { - - if ( distance < this.objects[ i ].distance ) { - - break; - - } - - } - - return this.objects[ i - 1 ].object; - -}; - -THREE.LOD.prototype.update = function () { - - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - - return function ( camera ) { - - if ( this.objects.length > 1 ) { - - v1.setFromMatrixPosition( camera.matrixWorld ); - v2.setFromMatrixPosition( this.matrixWorld ); - - var distance = v1.distanceTo( v2 ); - - this.objects[ 0 ].object.visible = true; - - for ( var i = 1, l = this.objects.length; i < l; i ++ ) { - - if ( distance >= this.objects[ i ].distance ) { - - this.objects[ i - 1 ].object.visible = false; - this.objects[ i ].object.visible = true; - - } else { - - break; - - } - - } - - for( ; i < l; i ++ ) { - - this.objects[ i ].object.visible = false; - - } - - } - - }; - -}(); - -THREE.LOD.prototype.clone = function ( object ) { - - if ( object === undefined ) object = new THREE.LOD(); - - THREE.Object3D.prototype.clone.call( this, object ); - - for ( var i = 0, l = this.objects.length; i < l; i ++ ) { - var x = this.objects[i].object.clone(); - x.visible = i === 0; - object.addLevel( x, this.objects[i].distance ); - } - - return object; - -}; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Sprite = ( function () { - - var geometry = new THREE.Geometry2( 3 ); - geometry.vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] ); - - return function ( material ) { - - THREE.Object3D.call( this ); - - this.geometry = geometry; - this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial(); - - }; - -} )(); - -THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype ); - -/* - * Custom update matrix - */ - -THREE.Sprite.prototype.updateMatrix = function () { - - this.matrix.compose( this.position, this.quaternion, this.scale ); - - this.matrixWorldNeedsUpdate = true; - -}; - -THREE.Sprite.prototype.clone = function ( object ) { - - if ( object === undefined ) object = new THREE.Sprite( this.material ); - - THREE.Object3D.prototype.clone.call( this, object ); - - return object; - -}; - -// Backwards compatibility - -THREE.Particle = THREE.Sprite;/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.Scene = function () { - - THREE.Object3D.call( this ); - - this.fog = null; - this.overrideMaterial = null; - - this.autoUpdate = true; // checked by the renderer - this.matrixAutoUpdate = false; - - this.__lights = []; - - this.__objectsAdded = []; - this.__objectsRemoved = []; - -}; - -THREE.Scene.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.Scene.prototype.__addObject = function ( object ) { - - if ( object instanceof THREE.Light ) { - - if ( this.__lights.indexOf( object ) === - 1 ) { - - this.__lights.push( object ); - - } - - if ( object.target && object.target.parent === undefined ) { - - this.add( object.target ); - - } - - } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) { - - this.__objectsAdded.push( object ); - - // check if previously removed - - var i = this.__objectsRemoved.indexOf( object ); - - if ( i !== -1 ) { - - this.__objectsRemoved.splice( i, 1 ); - - } - - } - - this.dispatchEvent( { type: 'objectAdded', object: object } ); - object.dispatchEvent( { type: 'addedToScene', scene: this } ); - - for ( var c = 0; c < object.children.length; c ++ ) { - - this.__addObject( object.children[ c ] ); - - } - -}; - -THREE.Scene.prototype.__removeObject = function ( object ) { - - if ( object instanceof THREE.Light ) { - - var i = this.__lights.indexOf( object ); - - if ( i !== -1 ) { - - this.__lights.splice( i, 1 ); - - } - - if ( object.shadowCascadeArray ) { - - for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) { - - this.__removeObject( object.shadowCascadeArray[ x ] ); - - } - - } - - } else if ( !( object instanceof THREE.Camera ) ) { - - this.__objectsRemoved.push( object ); - - // check if previously added - - var i = this.__objectsAdded.indexOf( object ); - - if ( i !== -1 ) { - - this.__objectsAdded.splice( i, 1 ); - - } - - } - - this.dispatchEvent( { type: 'objectRemoved', object: object } ); - object.dispatchEvent( { type: 'removedFromScene', scene: this } ); - - for ( var c = 0; c < object.children.length; c ++ ) { - - this.__removeObject( object.children[ c ] ); - - } - -}; - -THREE.Scene.prototype.clone = function ( object ) { - - if ( object === undefined ) object = new THREE.Scene(); - - THREE.Object3D.prototype.clone.call(this, object); - - if ( this.fog !== null ) object.fog = this.fog.clone(); - if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone(); - - object.autoUpdate = this.autoUpdate; - object.matrixAutoUpdate = this.matrixAutoUpdate; - - return object; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Fog = function ( color, near, far ) { - - this.name = ''; - - this.color = new THREE.Color( color ); - - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; - -}; - -THREE.Fog.prototype.clone = function () { - - return new THREE.Fog( this.color.getHex(), this.near, this.far ); - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.FogExp2 = function ( color, density ) { - - this.name = ''; - - this.color = new THREE.Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; - -}; - -THREE.FogExp2.prototype.clone = function () { - - return new THREE.FogExp2( this.color.getHex(), this.density ); - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.CanvasRenderer = function ( parameters ) { - - console.log( 'THREE.CanvasRenderer', THREE.REVISION ); - - var smoothstep = THREE.Math.smoothstep; - - parameters = parameters || {}; - - var _this = this, - _renderData, _elements, _lights, - _projector = new THREE.Projector(), - - _canvas = parameters.canvas !== undefined - ? parameters.canvas - : document.createElement( 'canvas' ), - - _canvasWidth = _canvas.width, - _canvasHeight = _canvas.height, - _canvasWidthHalf = Math.floor( _canvasWidth / 2 ), - _canvasHeightHalf = Math.floor( _canvasHeight / 2 ), - - _context = _canvas.getContext( '2d', { - alpha: parameters.alpha === true - } ), - - _clearColor = new THREE.Color( 0x000000 ), - _clearAlpha = 0, - - _contextGlobalAlpha = 1, - _contextGlobalCompositeOperation = 0, - _contextStrokeStyle = null, - _contextFillStyle = null, - _contextLineWidth = null, - _contextLineCap = null, - _contextLineJoin = null, - _contextDashSize = null, - _contextGapSize = 0, - - _camera, - - _v1, _v2, _v3, _v4, - _v5 = new THREE.RenderableVertex(), - _v6 = new THREE.RenderableVertex(), - - _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, - _v4x, _v4y, _v5x, _v5y, _v6x, _v6y, - - _color = new THREE.Color(), - _color1 = new THREE.Color(), - _color2 = new THREE.Color(), - _color3 = new THREE.Color(), - _color4 = new THREE.Color(), - - _diffuseColor = new THREE.Color(), - _emissiveColor = new THREE.Color(), - - _lightColor = new THREE.Color(), - - _patterns = {}, - - _near, _far, - - _image, _uvs, - _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, - - _clipBox = new THREE.Box2(), - _clearBox = new THREE.Box2(), - _elemBox = new THREE.Box2(), - - _ambientLight = new THREE.Color(), - _directionalLights = new THREE.Color(), - _pointLights = new THREE.Color(), - - _vector3 = new THREE.Vector3(), // Needed for PointLight - _normal = new THREE.Vector3(), - _normalViewMatrix = new THREE.Matrix3(), - - _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData, - _gradientMap, _gradientMapContext, _gradientMapQuality = 16; - - _pixelMap = document.createElement( 'canvas' ); - _pixelMap.width = _pixelMap.height = 2; - - _pixelMapContext = _pixelMap.getContext( '2d' ); - _pixelMapContext.fillStyle = 'rgba(0,0,0,1)'; - _pixelMapContext.fillRect( 0, 0, 2, 2 ); - - _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 ); - _pixelMapData = _pixelMapImage.data; - - _gradientMap = document.createElement( 'canvas' ); - _gradientMap.width = _gradientMap.height = _gradientMapQuality; - - _gradientMapContext = _gradientMap.getContext( '2d' ); - _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 ); - _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality ); - - _gradientMapQuality --; // Fix UVs - - // dash+gap fallbacks for Firefox and everything else - - if ( _context.setLineDash === undefined ) { - - if ( _context.mozDash !== undefined ) { - - _context.setLineDash = function ( values ) { - - _context.mozDash = values[ 0 ] !== null ? values : null; - - } - - } else { - - _context.setLineDash = function () {} - - } - - } - - this.domElement = _canvas; - - this.devicePixelRatio = parameters.devicePixelRatio !== undefined - ? parameters.devicePixelRatio - : self.devicePixelRatio !== undefined - ? self.devicePixelRatio - : 1; - - this.autoClear = true; - this.sortObjects = true; - this.sortElements = true; - - this.info = { - - render: { - - vertices: 0, - faces: 0 - - } - - } - - // WebGLRenderer compatibility - - this.supportsVertexTextures = function () {}; - this.setFaceCulling = function () {}; - - this.setSize = function ( width, height, updateStyle ) { - - _canvasWidth = width * this.devicePixelRatio; - _canvasHeight = height * this.devicePixelRatio; - - _canvasWidthHalf = Math.floor( _canvasWidth / 2 ); - _canvasHeightHalf = Math.floor( _canvasHeight / 2 ); - - _canvas.width = _canvasWidth; - _canvas.height = _canvasHeight; - - if ( this.devicePixelRatio !== 1 && updateStyle !== false ) { - - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; - - } - - _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ), - _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf ); - - _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ); - _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf ); - - _contextGlobalAlpha = 1; - _contextGlobalCompositeOperation = 0; - _contextStrokeStyle = null; - _contextFillStyle = null; - _contextLineWidth = null; - _contextLineCap = null; - _contextLineJoin = null; - - }; - - this.setClearColor = function ( color, alpha ) { - - _clearColor.set( color ); - _clearAlpha = alpha !== undefined ? alpha : 1; - - _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ); - _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf ); - - }; - - this.setClearColorHex = function ( hex, alpha ) { - - console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' ); - this.setClearColor( hex, alpha ); - - }; - - this.getMaxAnisotropy = function () { - - return 0; - - }; - - this.clear = function () { - - _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf ); - - if ( _clearBox.empty() === false ) { - - _clearBox.intersect( _clipBox ); - _clearBox.expandByScalar( 2 ); - - if ( _clearAlpha < 1 ) { - - _context.clearRect( - _clearBox.min.x | 0, - _clearBox.min.y | 0, - ( _clearBox.max.x - _clearBox.min.x ) | 0, - ( _clearBox.max.y - _clearBox.min.y ) | 0 - ); - - } - - if ( _clearAlpha > 0 ) { - - setBlending( THREE.NormalBlending ); - setOpacity( 1 ); - - setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' ); - - _context.fillRect( - _clearBox.min.x | 0, - _clearBox.min.y | 0, - ( _clearBox.max.x - _clearBox.min.x ) | 0, - ( _clearBox.max.y - _clearBox.min.y ) | 0 - ); - - } - - _clearBox.makeEmpty(); - - } - - }; - - // compatibility - - this.clearColor = function () {}; - this.clearDepth = function () {}; - this.clearStencil = function () {}; - - this.render = function ( scene, camera ) { - - if ( camera instanceof THREE.Camera === false ) { - - console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' ); - return; - - } - - if ( this.autoClear === true ) this.clear(); - - _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf ); - - _this.info.render.vertices = 0; - _this.info.render.faces = 0; - - _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements ); - _elements = _renderData.elements; - _lights = _renderData.lights; - _camera = camera; - - _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse ); - - /* DEBUG - setFillStyle( 'rgba( 0, 255, 255, 0.5 )' ); - _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y ); - */ - - calculateLights(); - - for ( var e = 0, el = _elements.length; e < el; e ++ ) { - - var element = _elements[ e ]; - - var material = element.material; - - if ( material === undefined || material.visible === false ) continue; - - _elemBox.makeEmpty(); - - if ( element instanceof THREE.RenderableSprite ) { - - _v1 = element; - _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf; - - renderSprite( _v1, element, material ); - - } else if ( element instanceof THREE.RenderableLine ) { - - _v1 = element.v1; _v2 = element.v2; - - _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf; - _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf; - - _elemBox.setFromPoints( [ - _v1.positionScreen, - _v2.positionScreen - ] ); - - if ( _clipBox.isIntersectionBox( _elemBox ) === true ) { - - renderLine( _v1, _v2, element, material ); - - } - - } else if ( element instanceof THREE.RenderableFace ) { - - _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; - - if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue; - if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue; - if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue; - - _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf; - _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf; - _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf; - - if ( material.overdraw > 0 ) { - - expand( _v1.positionScreen, _v2.positionScreen, material.overdraw ); - expand( _v2.positionScreen, _v3.positionScreen, material.overdraw ); - expand( _v3.positionScreen, _v1.positionScreen, material.overdraw ); - - } - - _elemBox.setFromPoints( [ - _v1.positionScreen, - _v2.positionScreen, - _v3.positionScreen - ] ); - - if ( _clipBox.isIntersectionBox( _elemBox ) === true ) { - - renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material ); - - } - - } - - /* DEBUG - setLineWidth( 1 ); - setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' ); - _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y ); - */ - - _clearBox.union( _elemBox ); - - } - - /* DEBUG - setLineWidth( 1 ); - setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' ); - _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y ); - */ - - _context.setTransform( 1, 0, 0, 1, 0, 0 ); - - }; - - // - - function calculateLights() { - - _ambientLight.setRGB( 0, 0, 0 ); - _directionalLights.setRGB( 0, 0, 0 ); - _pointLights.setRGB( 0, 0, 0 ); - - for ( var l = 0, ll = _lights.length; l < ll; l ++ ) { - - var light = _lights[ l ]; - var lightColor = light.color; - - if ( light instanceof THREE.AmbientLight ) { - - _ambientLight.add( lightColor ); - - } else if ( light instanceof THREE.DirectionalLight ) { - - // for sprites - - _directionalLights.add( lightColor ); - - } else if ( light instanceof THREE.PointLight ) { - - // for sprites - - _pointLights.add( lightColor ); - - } - - } - - } - - function calculateLight( position, normal, color ) { - - for ( var l = 0, ll = _lights.length; l < ll; l ++ ) { - - var light = _lights[ l ]; - - _lightColor.copy( light.color ); - - if ( light instanceof THREE.DirectionalLight ) { - - var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize(); - - var amount = normal.dot( lightPosition ); - - if ( amount <= 0 ) continue; - - amount *= light.intensity; - - color.add( _lightColor.multiplyScalar( amount ) ); - - } else if ( light instanceof THREE.PointLight ) { - - var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ); - - var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() ); - - if ( amount <= 0 ) continue; - - amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 ); - - if ( amount == 0 ) continue; - - amount *= light.intensity; - - color.add( _lightColor.multiplyScalar( amount ) ); - - } - - } - - } - - function renderSprite( v1, element, material ) { - - setOpacity( material.opacity ); - setBlending( material.blending ); - - var scaleX = element.scale.x * _canvasWidthHalf; - var scaleY = element.scale.y * _canvasHeightHalf; - - var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite - _elemBox.min.set( v1.x - dist, v1.y - dist ); - _elemBox.max.set( v1.x + dist, v1.y + dist ); - - if ( material instanceof THREE.SpriteMaterial || - material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility - - var texture = material.map; - - if ( texture !== null ) { - - if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) { - - if ( texture.image !== undefined && texture.image.width > 0 ) { - - textureToPattern( texture ); - - } - - texture.addEventListener( 'update', onTextureUpdate ); - - } - - var pattern = _patterns[ texture.id ]; - - if ( pattern !== undefined ) { - - setFillStyle( pattern ); - - } else { - - setFillStyle( 'rgba( 0, 0, 0, 1 )' ); - - } - - // - - var bitmap = texture.image; - - var ox = bitmap.width * texture.offset.x; - var oy = bitmap.height * texture.offset.y; - - var sx = bitmap.width * texture.repeat.x; - var sy = bitmap.height * texture.repeat.y; - - var cx = scaleX / sx; - var cy = scaleY / sy; - - _context.save(); - _context.translate( v1.x, v1.y ); - if ( material.rotation !== 0 ) _context.rotate( material.rotation ); - _context.translate( - scaleX / 2, - scaleY / 2 ); - _context.scale( cx, cy ); - _context.translate( - ox, - oy ); - _context.fillRect( ox, oy, sx, sy ); - _context.restore(); - - } else { // no texture - - setFillStyle( material.color.getStyle() ); - - _context.save(); - _context.translate( v1.x, v1.y ); - if ( material.rotation !== 0 ) _context.rotate( material.rotation ); - _context.scale( scaleX, - scaleY ); - _context.fillRect( - 0.5, - 0.5, 1, 1 ); - _context.restore(); - - } - - } else if ( material instanceof THREE.SpriteCanvasMaterial ) { - - setStrokeStyle( material.color.getStyle() ); - setFillStyle( material.color.getStyle() ); - - _context.save(); - _context.translate( v1.x, v1.y ); - if ( material.rotation !== 0 ) _context.rotate( material.rotation ); - _context.scale( scaleX, scaleY ); - - material.program( _context ); - - _context.restore(); - - } - - /* DEBUG - setStrokeStyle( 'rgb(255,255,0)' ); - _context.beginPath(); - _context.moveTo( v1.x - 10, v1.y ); - _context.lineTo( v1.x + 10, v1.y ); - _context.moveTo( v1.x, v1.y - 10 ); - _context.lineTo( v1.x, v1.y + 10 ); - _context.stroke(); - */ - - } - - function renderLine( v1, v2, element, material ) { - - setOpacity( material.opacity ); - setBlending( material.blending ); - - _context.beginPath(); - _context.moveTo( v1.positionScreen.x, v1.positionScreen.y ); - _context.lineTo( v2.positionScreen.x, v2.positionScreen.y ); - - if ( material instanceof THREE.LineBasicMaterial ) { - - setLineWidth( material.linewidth ); - setLineCap( material.linecap ); - setLineJoin( material.linejoin ); - - if ( material.vertexColors !== THREE.VertexColors ) { - - setStrokeStyle( material.color.getStyle() ); - - } else { - - var colorStyle1 = element.vertexColors[0].getStyle(); - var colorStyle2 = element.vertexColors[1].getStyle(); - - if ( colorStyle1 === colorStyle2 ) { - - setStrokeStyle( colorStyle1 ); - - } else { - - try { - - var grad = _context.createLinearGradient( - v1.positionScreen.x, - v1.positionScreen.y, - v2.positionScreen.x, - v2.positionScreen.y - ); - grad.addColorStop( 0, colorStyle1 ); - grad.addColorStop( 1, colorStyle2 ); - - } catch ( exception ) { - - grad = colorStyle1; - - } - - setStrokeStyle( grad ); - - } - - } - - _context.stroke(); - _elemBox.expandByScalar( material.linewidth * 2 ); - - } else if ( material instanceof THREE.LineDashedMaterial ) { - - setLineWidth( material.linewidth ); - setLineCap( material.linecap ); - setLineJoin( material.linejoin ); - setStrokeStyle( material.color.getStyle() ); - setDashAndGap( material.dashSize, material.gapSize ); - - _context.stroke(); - - _elemBox.expandByScalar( material.linewidth * 2 ); - - setDashAndGap( null, null ); - - } - - } - - function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) { - - _this.info.render.vertices += 3; - _this.info.render.faces ++; - - setOpacity( material.opacity ); - setBlending( material.blending ); - - _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y; - _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y; - _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y; - - drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y ); - - if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) { - - _diffuseColor.copy( material.color ); - _emissiveColor.copy( material.emissive ); - - if ( material.vertexColors === THREE.FaceColors ) { - - _diffuseColor.multiply( element.color ); - - } - - if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) { - - _color1.copy( _ambientLight ); - _color2.copy( _ambientLight ); - _color3.copy( _ambientLight ); - - calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 ); - calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 ); - calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 ); - - _color1.multiply( _diffuseColor ).add( _emissiveColor ); - _color2.multiply( _diffuseColor ).add( _emissiveColor ); - _color3.multiply( _diffuseColor ).add( _emissiveColor ); - _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 ); - - _image = getGradientTexture( _color1, _color2, _color3, _color4 ); - - clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image ); - - } else { - - _color.copy( _ambientLight ); - - calculateLight( element.centroidModel, element.normalModel, _color ); - - _color.multiply( _diffuseColor ).add( _emissiveColor ); - - material.wireframe === true - ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) - : fillPath( _color ); - - } - - } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) { - - if ( material.map !== null ) { - - if ( material.map.mapping instanceof THREE.UVMapping ) { - - _uvs = element.uvs[ 0 ]; - patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map ); - - } - - - } else if ( material.envMap !== null ) { - - if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) { - - _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix ); - _uv1x = 0.5 * _normal.x + 0.5; - _uv1y = 0.5 * _normal.y + 0.5; - - _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix ); - _uv2x = 0.5 * _normal.x + 0.5; - _uv2y = 0.5 * _normal.y + 0.5; - - _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix ); - _uv3x = 0.5 * _normal.x + 0.5; - _uv3y = 0.5 * _normal.y + 0.5; - - patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap ); - - }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) { - - - - }*/ - - - } else { - - _color.copy( material.color ); - - if ( material.vertexColors === THREE.FaceColors ) { - - _color.multiply( element.color ); - - } - - material.wireframe === true - ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) - : fillPath( _color ); - - } - - } else if ( material instanceof THREE.MeshDepthMaterial ) { - - _near = _camera.near; - _far = _camera.far; - - _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far ); - _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far ); - _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far ); - _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 ); - - _image = getGradientTexture( _color1, _color2, _color3, _color4 ); - - clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image ); - - } else if ( material instanceof THREE.MeshNormalMaterial ) { - - if ( material.shading === THREE.FlatShading ) { - - _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix ); - - _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 ); - - material.wireframe === true - ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) - : fillPath( _color ); - - } else if ( material.shading === THREE.SmoothShading ) { - - _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix ); - _color1.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 ); - - _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix ); - _color2.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 ); - - _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix ); - _color3.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 ); - - _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 ); - - _image = getGradientTexture( _color1, _color2, _color3, _color4 ); - - clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image ); - - } - - } - - } - - // - - function drawTriangle( x0, y0, x1, y1, x2, y2 ) { - - _context.beginPath(); - _context.moveTo( x0, y0 ); - _context.lineTo( x1, y1 ); - _context.lineTo( x2, y2 ); - _context.closePath(); - - } - - function strokePath( color, linewidth, linecap, linejoin ) { - - setLineWidth( linewidth ); - setLineCap( linecap ); - setLineJoin( linejoin ); - setStrokeStyle( color.getStyle() ); - - _context.stroke(); - - _elemBox.expandByScalar( linewidth * 2 ); - - } - - function fillPath( color ) { - - setFillStyle( color.getStyle() ); - _context.fill(); - - } - - function onTextureUpdate ( event ) { - - textureToPattern( event.target ); - - } - - function textureToPattern( texture ) { - - var repeatX = texture.wrapS === THREE.RepeatWrapping; - var repeatY = texture.wrapT === THREE.RepeatWrapping; - - var image = texture.image; - - var canvas = document.createElement( 'canvas' ); - canvas.width = image.width; - canvas.height = image.height; - - var context = canvas.getContext( '2d' ); - context.setTransform( 1, 0, 0, - 1, 0, image.height ); - context.drawImage( image, 0, 0 ); - - _patterns[ texture.id ] = _context.createPattern( - canvas, repeatX === true && repeatY === true - ? 'repeat' - : repeatX === true && repeatY === false - ? 'repeat-x' - : repeatX === false && repeatY === true - ? 'repeat-y' - : 'no-repeat' - ); - - } - - function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) { - - if ( texture instanceof THREE.DataTexture ) return; - - if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) { - - if ( texture.image !== undefined && texture.image.width > 0 ) { - - textureToPattern( texture ); - - } - - texture.addEventListener( 'update', onTextureUpdate ); - - } - - var pattern = _patterns[ texture.id ]; - - if ( pattern !== undefined ) { - - setFillStyle( pattern ); - - } else { - - setFillStyle( 'rgba(0,0,0,1)' ); - _context.fill(); - - return; - - } - - // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120 - - var a, b, c, d, e, f, det, idet, - offsetX = texture.offset.x / texture.repeat.x, - offsetY = texture.offset.y / texture.repeat.y, - width = texture.image.width * texture.repeat.x, - height = texture.image.height * texture.repeat.y; - - u0 = ( u0 + offsetX ) * width; - v0 = ( v0 + offsetY ) * height; - - u1 = ( u1 + offsetX ) * width; - v1 = ( v1 + offsetY ) * height; - - u2 = ( u2 + offsetX ) * width; - v2 = ( v2 + offsetY ) * height; - - x1 -= x0; y1 -= y0; - x2 -= x0; y2 -= y0; - - u1 -= u0; v1 -= v0; - u2 -= u0; v2 -= v0; - - det = u1 * v2 - u2 * v1; - - if ( det === 0 ) return; - - idet = 1 / det; - - a = ( v2 * x1 - v1 * x2 ) * idet; - b = ( v2 * y1 - v1 * y2 ) * idet; - c = ( u1 * x2 - u2 * x1 ) * idet; - d = ( u1 * y2 - u2 * y1 ) * idet; - - e = x0 - a * u0 - c * v0; - f = y0 - b * u0 - d * v0; - - _context.save(); - _context.transform( a, b, c, d, e, f ); - _context.fill(); - _context.restore(); - - } - - function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) { - - // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120 - - var a, b, c, d, e, f, det, idet, - width = image.width - 1, - height = image.height - 1; - - u0 *= width; v0 *= height; - u1 *= width; v1 *= height; - u2 *= width; v2 *= height; - - x1 -= x0; y1 -= y0; - x2 -= x0; y2 -= y0; - - u1 -= u0; v1 -= v0; - u2 -= u0; v2 -= v0; - - det = u1 * v2 - u2 * v1; - - idet = 1 / det; - - a = ( v2 * x1 - v1 * x2 ) * idet; - b = ( v2 * y1 - v1 * y2 ) * idet; - c = ( u1 * x2 - u2 * x1 ) * idet; - d = ( u1 * y2 - u2 * y1 ) * idet; - - e = x0 - a * u0 - c * v0; - f = y0 - b * u0 - d * v0; - - _context.save(); - _context.transform( a, b, c, d, e, f ); - _context.clip(); - _context.drawImage( image, 0, 0 ); - _context.restore(); - - } - - function getGradientTexture( color1, color2, color3, color4 ) { - - // http://mrdoob.com/blog/post/710 - - _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0; - _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0; - _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0; - - _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0; - _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0; - _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0; - - _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0; - _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0; - _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0; - - _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0; - _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0; - _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0; - - _pixelMapContext.putImageData( _pixelMapImage, 0, 0 ); - _gradientMapContext.drawImage( _pixelMap, 0, 0 ); - - return _gradientMap; - - } - - // Hide anti-alias gaps - - function expand( v1, v2, pixels ) { - - var x = v2.x - v1.x, y = v2.y - v1.y, - det = x * x + y * y, idet; - - if ( det === 0 ) return; - - idet = pixels / Math.sqrt( det ); - - x *= idet; y *= idet; - - v2.x += x; v2.y += y; - v1.x -= x; v1.y -= y; - - } - - // Context cached methods. - - function setOpacity( value ) { - - if ( _contextGlobalAlpha !== value ) { - - _context.globalAlpha = value; - _contextGlobalAlpha = value; - - } - - } - - function setBlending( value ) { - - if ( _contextGlobalCompositeOperation !== value ) { - - if ( value === THREE.NormalBlending ) { - - _context.globalCompositeOperation = 'source-over'; - - } else if ( value === THREE.AdditiveBlending ) { - - _context.globalCompositeOperation = 'lighter'; - - } else if ( value === THREE.SubtractiveBlending ) { - - _context.globalCompositeOperation = 'darker'; - - } - - _contextGlobalCompositeOperation = value; - - } - - } - - function setLineWidth( value ) { - - if ( _contextLineWidth !== value ) { - - _context.lineWidth = value; - _contextLineWidth = value; - - } - - } - - function setLineCap( value ) { - - // "butt", "round", "square" - - if ( _contextLineCap !== value ) { - - _context.lineCap = value; - _contextLineCap = value; - - } - - } - - function setLineJoin( value ) { - - // "round", "bevel", "miter" - - if ( _contextLineJoin !== value ) { - - _context.lineJoin = value; - _contextLineJoin = value; - - } - - } - - function setStrokeStyle( value ) { - - if ( _contextStrokeStyle !== value ) { - - _context.strokeStyle = value; - _contextStrokeStyle = value; - - } - - } - - function setFillStyle( value ) { - - if ( _contextFillStyle !== value ) { - - _context.fillStyle = value; - _contextFillStyle = value; - - } - - } - - function setDashAndGap( dashSizeValue, gapSizeValue ) { - - if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) { - - _context.setLineDash( [ dashSizeValue, gapSizeValue ] ); - _contextDashSize = dashSizeValue; - _contextGapSize = gapSizeValue; - - } - - } - -}; -/** - * Shader chunks for WebLG Shader library - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ - -THREE.ShaderChunk = { - - // FOG - - fog_pars_fragment: [ - - "#ifdef USE_FOG", - - "uniform vec3 fogColor;", - - "#ifdef FOG_EXP2", - - "uniform float fogDensity;", - - "#else", - - "uniform float fogNear;", - "uniform float fogFar;", - - "#endif", - - "#endif" - - ].join("\n"), - - fog_fragment: [ - - "#ifdef USE_FOG", - - "float depth = gl_FragCoord.z / gl_FragCoord.w;", - - "#ifdef FOG_EXP2", - - "const float LOG2 = 1.442695;", - "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );", - "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );", - - "#else", - - "float fogFactor = smoothstep( fogNear, fogFar, depth );", - - "#endif", - - "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );", - - "#endif" - - ].join("\n"), - - // ENVIRONMENT MAP - - envmap_pars_fragment: [ - - "#ifdef USE_ENVMAP", - - "uniform float reflectivity;", - "uniform samplerCube envMap;", - "uniform float flipEnvMap;", - "uniform int combine;", - - "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )", - - "uniform bool useRefract;", - "uniform float refractionRatio;", - - "#else", - - "varying vec3 vReflect;", - - "#endif", - - "#endif" - - ].join("\n"), - - envmap_fragment: [ - - "#ifdef USE_ENVMAP", - - "vec3 reflectVec;", - - "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )", - - "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );", - - "if ( useRefract ) {", - - "reflectVec = refract( cameraToVertex, normal, refractionRatio );", - - "} else { ", - - "reflectVec = reflect( cameraToVertex, normal );", - - "}", - - "#else", - - "reflectVec = vReflect;", - - "#endif", - - "#ifdef DOUBLE_SIDED", - - "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );", - "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );", - - "#else", - - "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );", - - "#endif", - - "#ifdef GAMMA_INPUT", - - "cubeColor.xyz *= cubeColor.xyz;", - - "#endif", - - "if ( combine == 1 ) {", - - "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );", - - "} else if ( combine == 2 ) {", - - "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;", - - "} else {", - - "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );", - - "}", - - "#endif" - - ].join("\n"), - - envmap_pars_vertex: [ - - "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )", - - "varying vec3 vReflect;", - - "uniform float refractionRatio;", - "uniform bool useRefract;", - - "#endif" - - ].join("\n"), - - worldpos_vertex : [ - - "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )", - - "#ifdef USE_SKINNING", - - "vec4 worldPosition = modelMatrix * skinned;", - - "#endif", - - "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )", - - "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );", - - "#endif", - - "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )", - - "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", - - "#endif", - - "#endif" - - ].join("\n"), - - envmap_vertex : [ - - "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )", - - "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;", - "worldNormal = normalize( worldNormal );", - - "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );", - - "if ( useRefract ) {", - - "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );", - - "} else {", - - "vReflect = reflect( cameraToVertex, worldNormal );", - - "}", - - "#endif" - - ].join("\n"), - - // COLOR MAP (particles) - - map_particle_pars_fragment: [ - - "#ifdef USE_MAP", - - "uniform sampler2D map;", - - "#endif" - - ].join("\n"), - - - map_particle_fragment: [ - - "#ifdef USE_MAP", - - "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );", - - "#endif" - - ].join("\n"), - - // COLOR MAP (triangles) - - map_pars_vertex: [ - - "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )", - - "varying vec2 vUv;", - "uniform vec4 offsetRepeat;", - - "#endif" - - ].join("\n"), - - map_pars_fragment: [ - - "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )", - - "varying vec2 vUv;", - - "#endif", - - "#ifdef USE_MAP", - - "uniform sampler2D map;", - - "#endif" - - ].join("\n"), - - map_vertex: [ - - "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )", - - "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;", - - "#endif" - - ].join("\n"), - - map_fragment: [ - - "#ifdef USE_MAP", - - "vec4 texelColor = texture2D( map, vUv );", - - "#ifdef GAMMA_INPUT", - - "texelColor.xyz *= texelColor.xyz;", - - "#endif", - - "gl_FragColor = gl_FragColor * texelColor;", - - "#endif" - - ].join("\n"), - - // LIGHT MAP - - lightmap_pars_fragment: [ - - "#ifdef USE_LIGHTMAP", - - "varying vec2 vUv2;", - "uniform sampler2D lightMap;", - - "#endif" - - ].join("\n"), - - lightmap_pars_vertex: [ - - "#ifdef USE_LIGHTMAP", - - "varying vec2 vUv2;", - - "#endif" - - ].join("\n"), - - lightmap_fragment: [ - - "#ifdef USE_LIGHTMAP", - - "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );", - - "#endif" - - ].join("\n"), - - lightmap_vertex: [ - - "#ifdef USE_LIGHTMAP", - - "vUv2 = uv2;", - - "#endif" - - ].join("\n"), - - // BUMP MAP - - bumpmap_pars_fragment: [ - - "#ifdef USE_BUMPMAP", - - "uniform sampler2D bumpMap;", - "uniform float bumpScale;", - - // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen - // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html - - // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2) - - "vec2 dHdxy_fwd() {", - - "vec2 dSTdx = dFdx( vUv );", - "vec2 dSTdy = dFdy( vUv );", - - "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;", - "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;", - "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;", - - "return vec2( dBx, dBy );", - - "}", - - "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {", - - "vec3 vSigmaX = dFdx( surf_pos );", - "vec3 vSigmaY = dFdy( surf_pos );", - "vec3 vN = surf_norm;", // normalized - - "vec3 R1 = cross( vSigmaY, vN );", - "vec3 R2 = cross( vN, vSigmaX );", - - "float fDet = dot( vSigmaX, R1 );", - - "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );", - "return normalize( abs( fDet ) * surf_norm - vGrad );", - - "}", - - "#endif" - - ].join("\n"), - - // NORMAL MAP - - normalmap_pars_fragment: [ - - "#ifdef USE_NORMALMAP", - - "uniform sampler2D normalMap;", - "uniform vec2 normalScale;", - - // Per-Pixel Tangent Space Normal Mapping - // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html - - "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {", - - "vec3 q0 = dFdx( eye_pos.xyz );", - "vec3 q1 = dFdy( eye_pos.xyz );", - "vec2 st0 = dFdx( vUv.st );", - "vec2 st1 = dFdy( vUv.st );", - - "vec3 S = normalize( q0 * st1.t - q1 * st0.t );", - "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );", - "vec3 N = normalize( surf_norm );", - - "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;", - "mapN.xy = normalScale * mapN.xy;", - "mat3 tsn = mat3( S, T, N );", - "return normalize( tsn * mapN );", - - "}", - - "#endif" - - ].join("\n"), - - // SPECULAR MAP - - specularmap_pars_fragment: [ - - "#ifdef USE_SPECULARMAP", - - "uniform sampler2D specularMap;", - - "#endif" - - ].join("\n"), - - specularmap_fragment: [ - - "float specularStrength;", - - "#ifdef USE_SPECULARMAP", - - "vec4 texelSpecular = texture2D( specularMap, vUv );", - "specularStrength = texelSpecular.r;", - - "#else", - - "specularStrength = 1.0;", - - "#endif" - - ].join("\n"), - - // LIGHTS LAMBERT - - lights_lambert_pars_vertex: [ - - "uniform vec3 ambient;", - "uniform vec3 diffuse;", - "uniform vec3 emissive;", - - "uniform vec3 ambientLightColor;", - - "#if MAX_DIR_LIGHTS > 0", - - "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];", - "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];", - - "#endif", - - "#if MAX_HEMI_LIGHTS > 0", - - "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];", - "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];", - "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];", - - "#endif", - - "#if MAX_POINT_LIGHTS > 0", - - "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];", - "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];", - "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];", - - "#endif", - - "#if MAX_SPOT_LIGHTS > 0", - - "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];", - "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];", - "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];", - "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];", - "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];", - "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];", - - "#endif", - - "#ifdef WRAP_AROUND", - - "uniform vec3 wrapRGB;", - - "#endif" - - ].join("\n"), - - lights_lambert_vertex: [ - - "vLightFront = vec3( 0.0 );", - - "#ifdef DOUBLE_SIDED", - - "vLightBack = vec3( 0.0 );", - - "#endif", - - "transformedNormal = normalize( transformedNormal );", - - "#if MAX_DIR_LIGHTS > 0", - - "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {", - - "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );", - "vec3 dirVector = normalize( lDirection.xyz );", - - "float dotProduct = dot( transformedNormal, dirVector );", - "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );", - - "#ifdef DOUBLE_SIDED", - - "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );", - - "#ifdef WRAP_AROUND", - - "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );", - - "#endif", - - "#endif", - - "#ifdef WRAP_AROUND", - - "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );", - "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );", - - "#ifdef DOUBLE_SIDED", - - "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );", - - "#endif", - - "#endif", - - "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;", - - "#ifdef DOUBLE_SIDED", - - "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;", - - "#endif", - - "}", - - "#endif", - - "#if MAX_POINT_LIGHTS > 0", - - "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {", - - "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );", - "vec3 lVector = lPosition.xyz - mvPosition.xyz;", - - "float lDistance = 1.0;", - "if ( pointLightDistance[ i ] > 0.0 )", - "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );", - - "lVector = normalize( lVector );", - "float dotProduct = dot( transformedNormal, lVector );", - - "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );", - - "#ifdef DOUBLE_SIDED", - - "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );", - - "#ifdef WRAP_AROUND", - - "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );", - - "#endif", - - "#endif", - - "#ifdef WRAP_AROUND", - - "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );", - "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );", - - "#ifdef DOUBLE_SIDED", - - "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );", - - "#endif", - - "#endif", - - "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;", - - "#ifdef DOUBLE_SIDED", - - "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;", - - "#endif", - - "}", - - "#endif", - - "#if MAX_SPOT_LIGHTS > 0", - - "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {", - - "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );", - "vec3 lVector = lPosition.xyz - mvPosition.xyz;", - - "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );", - - "if ( spotEffect > spotLightAngleCos[ i ] ) {", - - "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );", - - "float lDistance = 1.0;", - "if ( spotLightDistance[ i ] > 0.0 )", - "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );", - - "lVector = normalize( lVector );", - - "float dotProduct = dot( transformedNormal, lVector );", - "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );", - - "#ifdef DOUBLE_SIDED", - - "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );", - - "#ifdef WRAP_AROUND", - - "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );", - - "#endif", - - "#endif", - - "#ifdef WRAP_AROUND", - - "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );", - "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );", - - "#ifdef DOUBLE_SIDED", - - "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );", - - "#endif", - - "#endif", - - "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;", - - "#ifdef DOUBLE_SIDED", - - "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;", - - "#endif", - - "}", - - "}", - - "#endif", - - "#if MAX_HEMI_LIGHTS > 0", - - "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {", - - "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );", - "vec3 lVector = normalize( lDirection.xyz );", - - "float dotProduct = dot( transformedNormal, lVector );", - - "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;", - "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;", - - "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", - - "#ifdef DOUBLE_SIDED", - - "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );", - - "#endif", - - "}", - - "#endif", - - "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;", - - "#ifdef DOUBLE_SIDED", - - "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;", - - "#endif" - - ].join("\n"), - - // LIGHTS PHONG - - lights_phong_pars_vertex: [ - - "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )", - - "varying vec3 vWorldPosition;", - - "#endif" - - ].join("\n"), - - - lights_phong_vertex: [ - - "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )", - - "vWorldPosition = worldPosition.xyz;", - - "#endif" - - ].join("\n"), - - lights_phong_pars_fragment: [ - - "uniform vec3 ambientLightColor;", - - "#if MAX_DIR_LIGHTS > 0", - - "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];", - "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];", - - "#endif", - - "#if MAX_HEMI_LIGHTS > 0", - - "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];", - "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];", - "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];", - - "#endif", - - "#if MAX_POINT_LIGHTS > 0", - - "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];", - - "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];", - "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];", - - "#endif", - - "#if MAX_SPOT_LIGHTS > 0", - - "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];", - "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];", - "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];", - "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];", - "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];", - - "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];", - - "#endif", - - "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )", - - "varying vec3 vWorldPosition;", - - "#endif", - - "#ifdef WRAP_AROUND", - - "uniform vec3 wrapRGB;", - - "#endif", - - "varying vec3 vViewPosition;", - "varying vec3 vNormal;" - - ].join("\n"), - - lights_phong_fragment: [ - - "vec3 normal = normalize( vNormal );", - "vec3 viewPosition = normalize( vViewPosition );", - - "#ifdef DOUBLE_SIDED", - - "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );", - - "#endif", - - "#ifdef USE_NORMALMAP", - - "normal = perturbNormal2Arb( -vViewPosition, normal );", - - "#elif defined( USE_BUMPMAP )", - - "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );", - - "#endif", - - "#if MAX_POINT_LIGHTS > 0", - - "vec3 pointDiffuse = vec3( 0.0 );", - "vec3 pointSpecular = vec3( 0.0 );", - - "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {", - - "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );", - "vec3 lVector = lPosition.xyz + vViewPosition.xyz;", - - "float lDistance = 1.0;", - "if ( pointLightDistance[ i ] > 0.0 )", - "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );", - - "lVector = normalize( lVector );", - - // diffuse - - "float dotProduct = dot( normal, lVector );", - - "#ifdef WRAP_AROUND", - - "float pointDiffuseWeightFull = max( dotProduct, 0.0 );", - "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );", - - "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );", - - "#else", - - "float pointDiffuseWeight = max( dotProduct, 0.0 );", - - "#endif", - - "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;", - - // specular - - "vec3 pointHalfVector = normalize( lVector + viewPosition );", - "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );", - "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );", - - // 2.0 => 2.0001 is hack to work around ANGLE bug - - "float specularNormalization = ( shininess + 2.0001 ) / 8.0;", - - "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );", - "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;", - - "}", - - "#endif", - - "#if MAX_SPOT_LIGHTS > 0", - - "vec3 spotDiffuse = vec3( 0.0 );", - "vec3 spotSpecular = vec3( 0.0 );", - - "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {", - - "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );", - "vec3 lVector = lPosition.xyz + vViewPosition.xyz;", - - "float lDistance = 1.0;", - "if ( spotLightDistance[ i ] > 0.0 )", - "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );", - - "lVector = normalize( lVector );", - - "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );", - - "if ( spotEffect > spotLightAngleCos[ i ] ) {", - - "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );", - - // diffuse - - "float dotProduct = dot( normal, lVector );", - - "#ifdef WRAP_AROUND", - - "float spotDiffuseWeightFull = max( dotProduct, 0.0 );", - "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );", - - "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );", - - "#else", - - "float spotDiffuseWeight = max( dotProduct, 0.0 );", - - "#endif", - - "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;", - - // specular - - "vec3 spotHalfVector = normalize( lVector + viewPosition );", - "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );", - "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );", - - // 2.0 => 2.0001 is hack to work around ANGLE bug - - "float specularNormalization = ( shininess + 2.0001 ) / 8.0;", - - "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );", - "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;", - - "}", - - "}", - - "#endif", - - "#if MAX_DIR_LIGHTS > 0", - - "vec3 dirDiffuse = vec3( 0.0 );", - "vec3 dirSpecular = vec3( 0.0 );" , - - "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {", - - "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );", - "vec3 dirVector = normalize( lDirection.xyz );", - - // diffuse - - "float dotProduct = dot( normal, dirVector );", - - "#ifdef WRAP_AROUND", - - "float dirDiffuseWeightFull = max( dotProduct, 0.0 );", - "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );", - - "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );", - - "#else", - - "float dirDiffuseWeight = max( dotProduct, 0.0 );", - - "#endif", - - "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;", - - // specular - - "vec3 dirHalfVector = normalize( dirVector + viewPosition );", - "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );", - "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );", - - /* - // fresnel term from skin shader - "const float F0 = 0.128;", - - "float base = 1.0 - dot( viewPosition, dirHalfVector );", - "float exponential = pow( base, 5.0 );", - - "float fresnel = exponential + F0 * ( 1.0 - exponential );", - */ - - /* - // fresnel term from fresnel shader - "const float mFresnelBias = 0.08;", - "const float mFresnelScale = 0.3;", - "const float mFresnelPower = 5.0;", - - "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );", - */ - - // 2.0 => 2.0001 is hack to work around ANGLE bug - - "float specularNormalization = ( shininess + 2.0001 ) / 8.0;", - - //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;", - - "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );", - "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;", - - - "}", - - "#endif", - - "#if MAX_HEMI_LIGHTS > 0", - - "vec3 hemiDiffuse = vec3( 0.0 );", - "vec3 hemiSpecular = vec3( 0.0 );" , - - "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {", - - "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );", - "vec3 lVector = normalize( lDirection.xyz );", - - // diffuse - - "float dotProduct = dot( normal, lVector );", - "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;", - - "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", - - "hemiDiffuse += diffuse * hemiColor;", - - // specular (sky light) - - "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );", - "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;", - "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );", - - // specular (ground light) - - "vec3 lVectorGround = -lVector;", - - "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );", - "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;", - "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );", - - "float dotProductGround = dot( normal, lVectorGround );", - - // 2.0 => 2.0001 is hack to work around ANGLE bug - - "float specularNormalization = ( shininess + 2.0001 ) / 8.0;", - - "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );", - "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );", - "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );", - - "}", - - "#endif", - - "vec3 totalDiffuse = vec3( 0.0 );", - "vec3 totalSpecular = vec3( 0.0 );", - - "#if MAX_DIR_LIGHTS > 0", - - "totalDiffuse += dirDiffuse;", - "totalSpecular += dirSpecular;", - - "#endif", - - "#if MAX_HEMI_LIGHTS > 0", - - "totalDiffuse += hemiDiffuse;", - "totalSpecular += hemiSpecular;", - - "#endif", - - "#if MAX_POINT_LIGHTS > 0", - - "totalDiffuse += pointDiffuse;", - "totalSpecular += pointSpecular;", - - "#endif", - - "#if MAX_SPOT_LIGHTS > 0", - - "totalDiffuse += spotDiffuse;", - "totalSpecular += spotSpecular;", - - "#endif", - - "#ifdef METAL", - - "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );", - - "#else", - - "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;", - - "#endif" - - ].join("\n"), - - // VERTEX COLORS - - color_pars_fragment: [ - - "#ifdef USE_COLOR", - - "varying vec3 vColor;", - - "#endif" - - ].join("\n"), - - - color_fragment: [ - - "#ifdef USE_COLOR", - - "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );", - - "#endif" - - ].join("\n"), - - color_pars_vertex: [ - - "#ifdef USE_COLOR", - - "varying vec3 vColor;", - - "#endif" - - ].join("\n"), - - - color_vertex: [ - - "#ifdef USE_COLOR", - - "#ifdef GAMMA_INPUT", - - "vColor = color * color;", - - "#else", - - "vColor = color;", - - "#endif", - - "#endif" - - ].join("\n"), - - // SKINNING - - skinning_pars_vertex: [ - - "#ifdef USE_SKINNING", - - "#ifdef BONE_TEXTURE", - - "uniform sampler2D boneTexture;", - "uniform int boneTextureWidth;", - "uniform int boneTextureHeight;", - - "mat4 getBoneMatrix( const in float i ) {", - - "float j = i * 4.0;", - "float x = mod( j, float( boneTextureWidth ) );", - "float y = floor( j / float( boneTextureWidth ) );", - - "float dx = 1.0 / float( boneTextureWidth );", - "float dy = 1.0 / float( boneTextureHeight );", - - "y = dy * ( y + 0.5 );", - - "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );", - "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );", - "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );", - "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );", - - "mat4 bone = mat4( v1, v2, v3, v4 );", - - "return bone;", - - "}", - - "#else", - - "uniform mat4 boneGlobalMatrices[ MAX_BONES ];", - - "mat4 getBoneMatrix( const in float i ) {", - - "mat4 bone = boneGlobalMatrices[ int(i) ];", - "return bone;", - - "}", - - "#endif", - - "#endif" - - ].join("\n"), - - skinbase_vertex: [ - - "#ifdef USE_SKINNING", - - "mat4 boneMatX = getBoneMatrix( skinIndex.x );", - "mat4 boneMatY = getBoneMatrix( skinIndex.y );", - "mat4 boneMatZ = getBoneMatrix( skinIndex.z );", - "mat4 boneMatW = getBoneMatrix( skinIndex.w );", - - "#endif" - - ].join("\n"), - - skinning_vertex: [ - - "#ifdef USE_SKINNING", - - "#ifdef USE_MORPHTARGETS", - - "vec4 skinVertex = vec4( morphed, 1.0 );", - - "#else", - - "vec4 skinVertex = vec4( position, 1.0 );", - - "#endif", - - "vec4 skinned = boneMatX * skinVertex * skinWeight.x;", - "skinned += boneMatY * skinVertex * skinWeight.y;", - "skinned += boneMatZ * skinVertex * skinWeight.z;", - "skinned += boneMatW * skinVertex * skinWeight.w;", - - "#endif" - - ].join("\n"), - - // MORPHING - - morphtarget_pars_vertex: [ - - "#ifdef USE_MORPHTARGETS", - - "#ifndef USE_MORPHNORMALS", - - "uniform float morphTargetInfluences[ 8 ];", - - "#else", - - "uniform float morphTargetInfluences[ 4 ];", - - "#endif", - - "#endif" - - ].join("\n"), - - morphtarget_vertex: [ - - "#ifdef USE_MORPHTARGETS", - - "vec3 morphed = vec3( 0.0 );", - "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];", - "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];", - "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];", - "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];", - - "#ifndef USE_MORPHNORMALS", - - "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];", - "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];", - "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];", - "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];", - - "#endif", - - "morphed += position;", - - "#endif" - - ].join("\n"), - - default_vertex : [ - - "vec4 mvPosition;", - - "#ifdef USE_SKINNING", - - "mvPosition = modelViewMatrix * skinned;", - - "#endif", - - "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )", - - "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );", - - "#endif", - - "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )", - - "mvPosition = modelViewMatrix * vec4( position, 1.0 );", - - "#endif", - - "gl_Position = projectionMatrix * mvPosition;" - - ].join("\n"), - - morphnormal_vertex: [ - - "#ifdef USE_MORPHNORMALS", - - "vec3 morphedNormal = vec3( 0.0 );", - - "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];", - "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];", - "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];", - "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];", - - "morphedNormal += normal;", - - "#endif" - - ].join("\n"), - - skinnormal_vertex: [ - - "#ifdef USE_SKINNING", - - "mat4 skinMatrix = skinWeight.x * boneMatX;", - "skinMatrix += skinWeight.y * boneMatY;", - - "#ifdef USE_MORPHNORMALS", - - "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );", - - "#else", - - "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );", - - "#endif", - - "#endif" - - ].join("\n"), - - defaultnormal_vertex: [ - - "vec3 objectNormal;", - - "#ifdef USE_SKINNING", - - "objectNormal = skinnedNormal.xyz;", - - "#endif", - - "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )", - - "objectNormal = morphedNormal;", - - "#endif", - - "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )", - - "objectNormal = normal;", - - "#endif", - - "#ifdef FLIP_SIDED", - - "objectNormal = -objectNormal;", - - "#endif", - - "vec3 transformedNormal = normalMatrix * objectNormal;" - - ].join("\n"), - - // SHADOW MAP - - // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples - // http://spidergl.org/example.php?id=6 - // http://fabiensanglard.net/shadowmapping - - shadowmap_pars_fragment: [ - - "#ifdef USE_SHADOWMAP", - - "uniform sampler2D shadowMap[ MAX_SHADOWS ];", - "uniform vec2 shadowMapSize[ MAX_SHADOWS ];", - - "uniform float shadowDarkness[ MAX_SHADOWS ];", - "uniform float shadowBias[ MAX_SHADOWS ];", - - "varying vec4 vShadowCoord[ MAX_SHADOWS ];", - - "float unpackDepth( const in vec4 rgba_depth ) {", - - "const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );", - "float depth = dot( rgba_depth, bit_shift );", - "return depth;", - - "}", - - "#endif" - - ].join("\n"), - - shadowmap_fragment: [ - - "#ifdef USE_SHADOWMAP", - - "#ifdef SHADOWMAP_DEBUG", - - "vec3 frustumColors[3];", - "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );", - "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );", - "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );", - - "#endif", - - "#ifdef SHADOWMAP_CASCADE", - - "int inFrustumCount = 0;", - - "#endif", - - "float fDepth;", - "vec3 shadowColor = vec3( 1.0 );", - - "for( int i = 0; i < MAX_SHADOWS; i ++ ) {", - - "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;", - - // "if ( something && something )" breaks ATI OpenGL shader compiler - // "if ( all( something, something ) )" using this instead - - "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );", - "bool inFrustum = all( inFrustumVec );", - - // don't shadow pixels outside of light frustum - // use just first frustum (for cascades) - // don't shadow pixels behind far plane of light frustum - - "#ifdef SHADOWMAP_CASCADE", - - "inFrustumCount += int( inFrustum );", - "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );", - - "#else", - - "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );", - - "#endif", - - "bool frustumTest = all( frustumTestVec );", - - "if ( frustumTest ) {", - - "shadowCoord.z += shadowBias[ i ];", - - "#if defined( SHADOWMAP_TYPE_PCF )", - - // Percentage-close filtering - // (9 pixel kernel) - // http://fabiensanglard.net/shadowmappingPCF/ - - "float shadow = 0.0;", - - /* - // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL - // must enroll loop manually - - "for ( float y = -1.25; y <= 1.25; y += 1.25 )", - "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {", - - "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );", - - // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup - //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );", - - "float fDepth = unpackDepth( rgbaDepth );", - - "if ( fDepth < shadowCoord.z )", - "shadow += 1.0;", - - "}", - - "shadow /= 9.0;", - - */ - - "const float shadowDelta = 1.0 / 9.0;", - - "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;", - "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;", - - "float dx0 = -1.25 * xPixelOffset;", - "float dy0 = -1.25 * yPixelOffset;", - "float dx1 = 1.25 * xPixelOffset;", - "float dy1 = 1.25 * yPixelOffset;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );", - "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;", - - "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );", - - "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )", - - // Percentage-close filtering - // (9 pixel kernel) - // http://fabiensanglard.net/shadowmappingPCF/ - - "float shadow = 0.0;", - - "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;", - "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;", - - "float dx0 = -1.0 * xPixelOffset;", - "float dy0 = -1.0 * yPixelOffset;", - "float dx1 = 1.0 * xPixelOffset;", - "float dy1 = 1.0 * yPixelOffset;", - - "mat3 shadowKernel;", - "mat3 depthKernel;", - - "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );", - "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );", - "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );", - "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );", - "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );", - "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );", - "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );", - "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );", - "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );", - - "vec3 shadowZ = vec3( shadowCoord.z );", - "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));", - "shadowKernel[0] *= vec3(0.25);", - - "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));", - "shadowKernel[1] *= vec3(0.25);", - - "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));", - "shadowKernel[2] *= vec3(0.25);", - - "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );", - - "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );", - "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );", - - "vec4 shadowValues;", - "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );", - "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );", - "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );", - "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );", - - "shadow = dot( shadowValues, vec4( 1.0 ) );", - - "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );", - - "#else", - - "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );", - "float fDepth = unpackDepth( rgbaDepth );", - - "if ( fDepth < shadowCoord.z )", - - // spot with multiple shadows is darker - - "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );", - - // spot with multiple shadows has the same color as single shadow spot - - //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );", - - "#endif", - - "}", - - - "#ifdef SHADOWMAP_DEBUG", - - "#ifdef SHADOWMAP_CASCADE", - - "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];", - - "#else", - - "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];", - - "#endif", - - "#endif", - - "}", - - "#ifdef GAMMA_OUTPUT", - - "shadowColor *= shadowColor;", - - "#endif", - - "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;", - - "#endif" - - ].join("\n"), - - shadowmap_pars_vertex: [ - - "#ifdef USE_SHADOWMAP", - - "varying vec4 vShadowCoord[ MAX_SHADOWS ];", - "uniform mat4 shadowMatrix[ MAX_SHADOWS ];", - - "#endif" - - ].join("\n"), - - shadowmap_vertex: [ - - "#ifdef USE_SHADOWMAP", - - "for( int i = 0; i < MAX_SHADOWS; i ++ ) {", - - "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;", - - "}", - - "#endif" - - ].join("\n"), - - // ALPHATEST - - alphatest_fragment: [ - - "#ifdef ALPHATEST", - - "if ( gl_FragColor.a < ALPHATEST ) discard;", - - "#endif" - - ].join("\n"), - - // LINEAR SPACE - - linear_to_gamma_fragment: [ - - "#ifdef GAMMA_OUTPUT", - - "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );", - - "#endif" - - ].join("\n") - - -};/** - * Uniform Utilities - */ - -THREE.UniformsUtils = { - - merge: function ( uniforms ) { - - var u, p, tmp, merged = {}; - - for ( u = 0; u < uniforms.length; u ++ ) { - - tmp = this.clone( uniforms[ u ] ); - - for ( p in tmp ) { - - merged[ p ] = tmp[ p ]; - - } - - } - - return merged; - - }, - - clone: function ( uniforms_src ) { - - var u, p, parameter, parameter_src, uniforms_dst = {}; - - for ( u in uniforms_src ) { - - uniforms_dst[ u ] = {}; - - for ( p in uniforms_src[ u ] ) { - - parameter_src = uniforms_src[ u ][ p ]; - - if ( parameter_src instanceof THREE.Color || - parameter_src instanceof THREE.Vector2 || - parameter_src instanceof THREE.Vector3 || - parameter_src instanceof THREE.Vector4 || - parameter_src instanceof THREE.Matrix4 || - parameter_src instanceof THREE.Texture ) { - - uniforms_dst[ u ][ p ] = parameter_src.clone(); - - } else if ( parameter_src instanceof Array ) { - - uniforms_dst[ u ][ p ] = parameter_src.slice(); - - } else { - - uniforms_dst[ u ][ p ] = parameter_src; - - } - - } - - } - - return uniforms_dst; - - } - -};/** - * Uniforms library for shared webgl shaders - */ - -THREE.UniformsLib = { - - common: { - - "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, - "opacity" : { type: "f", value: 1.0 }, - - "map" : { type: "t", value: null }, - "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, - - "lightMap" : { type: "t", value: null }, - "specularMap" : { type: "t", value: null }, - - "envMap" : { type: "t", value: null }, - "flipEnvMap" : { type: "f", value: -1 }, - "useRefract" : { type: "i", value: 0 }, - "reflectivity" : { type: "f", value: 1.0 }, - "refractionRatio" : { type: "f", value: 0.98 }, - "combine" : { type: "i", value: 0 }, - - "morphTargetInfluences" : { type: "f", value: 0 } - - }, - - bump: { - - "bumpMap" : { type: "t", value: null }, - "bumpScale" : { type: "f", value: 1 } - - }, - - normalmap: { - - "normalMap" : { type: "t", value: null }, - "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) } - }, - - fog : { - - "fogDensity" : { type: "f", value: 0.00025 }, - "fogNear" : { type: "f", value: 1 }, - "fogFar" : { type: "f", value: 2000 }, - "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } - - }, - - lights: { - - "ambientLightColor" : { type: "fv", value: [] }, - - "directionalLightDirection" : { type: "fv", value: [] }, - "directionalLightColor" : { type: "fv", value: [] }, - - "hemisphereLightDirection" : { type: "fv", value: [] }, - "hemisphereLightSkyColor" : { type: "fv", value: [] }, - "hemisphereLightGroundColor" : { type: "fv", value: [] }, - - "pointLightColor" : { type: "fv", value: [] }, - "pointLightPosition" : { type: "fv", value: [] }, - "pointLightDistance" : { type: "fv1", value: [] }, - - "spotLightColor" : { type: "fv", value: [] }, - "spotLightPosition" : { type: "fv", value: [] }, - "spotLightDirection" : { type: "fv", value: [] }, - "spotLightDistance" : { type: "fv1", value: [] }, - "spotLightAngleCos" : { type: "fv1", value: [] }, - "spotLightExponent" : { type: "fv1", value: [] } - - }, - - particle: { - - "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, - "opacity" : { type: "f", value: 1.0 }, - "size" : { type: "f", value: 1.0 }, - "scale" : { type: "f", value: 1.0 }, - "map" : { type: "t", value: null }, - - "fogDensity" : { type: "f", value: 0.00025 }, - "fogNear" : { type: "f", value: 1 }, - "fogFar" : { type: "f", value: 2000 }, - "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } - - }, - - shadowmap: { - - "shadowMap": { type: "tv", value: [] }, - "shadowMapSize": { type: "v2v", value: [] }, - - "shadowBias" : { type: "fv1", value: [] }, - "shadowDarkness": { type: "fv1", value: [] }, - - "shadowMatrix" : { type: "m4v", value: [] } - - } - -};/** - * Webgl Shader Library for three.js - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ - - -THREE.ShaderLib = { - - 'basic': { - - uniforms: THREE.UniformsUtils.merge( [ - - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "shadowmap" ] - - ] ), - - vertexShader: [ - - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - - "void main() {", - - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - - "#ifdef USE_ENVMAP", - - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], - - "#endif", - - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], - - "}" - - ].join("\n"), - - fragmentShader: [ - - "uniform vec3 diffuse;", - "uniform float opacity;", - - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - - "void main() {", - - "gl_FragColor = vec4( diffuse, opacity );", - - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], - - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - - THREE.ShaderChunk[ "fog_fragment" ], - - "}" - - ].join("\n") - - }, - - 'lambert': { - - uniforms: THREE.UniformsUtils.merge( [ - - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], - - { - "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) }, - "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, - "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } - } - - ] ), - - vertexShader: [ - - "#define LAMBERT", - - "varying vec3 vLightFront;", - - "#ifdef DOUBLE_SIDED", - - "varying vec3 vLightBack;", - - "#endif", - - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "lights_lambert_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - - "void main() {", - - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], - - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], - - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "lights_lambert_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], - - "}" - - ].join("\n"), - - fragmentShader: [ - - "uniform float opacity;", - - "varying vec3 vLightFront;", - - "#ifdef DOUBLE_SIDED", - - "varying vec3 vLightBack;", - - "#endif", - - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - - "void main() {", - - "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );", - - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], - - "#ifdef DOUBLE_SIDED", - - //"float isFront = float( gl_FrontFacing );", - //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;", - - "if ( gl_FrontFacing )", - "gl_FragColor.xyz *= vLightFront;", - "else", - "gl_FragColor.xyz *= vLightBack;", - - "#else", - - "gl_FragColor.xyz *= vLightFront;", - - "#endif", - - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], - - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - - THREE.ShaderChunk[ "fog_fragment" ], - - "}" - - ].join("\n") - - }, - - 'phong': { - - uniforms: THREE.UniformsUtils.merge( [ - - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "bump" ], - THREE.UniformsLib[ "normalmap" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], - - { - "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) }, - "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, - "specular" : { type: "c", value: new THREE.Color( 0x111111 ) }, - "shininess": { type: "f", value: 30 }, - "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } - } - - ] ), - - vertexShader: [ - - "#define PHONG", - - "varying vec3 vViewPosition;", - "varying vec3 vNormal;", - - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "lights_phong_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - - "void main() {", - - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], - - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], - - "vNormal = normalize( transformedNormal );", - - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - - "vViewPosition = -mvPosition.xyz;", - - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "lights_phong_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], - - "}" - - ].join("\n"), - - fragmentShader: [ - - "uniform vec3 diffuse;", - "uniform float opacity;", - - "uniform vec3 ambient;", - "uniform vec3 emissive;", - "uniform vec3 specular;", - "uniform float shininess;", - - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "lights_phong_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "bumpmap_pars_fragment" ], - THREE.ShaderChunk[ "normalmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - - "void main() {", - - "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );", - - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], - - THREE.ShaderChunk[ "lights_phong_fragment" ], - - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], - - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - - THREE.ShaderChunk[ "fog_fragment" ], - - "}" - - ].join("\n") - - }, - - 'particle_basic': { - - uniforms: THREE.UniformsUtils.merge( [ - - THREE.UniformsLib[ "particle" ], - THREE.UniformsLib[ "shadowmap" ] - - ] ), - - vertexShader: [ - - "uniform float size;", - "uniform float scale;", - - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - - "void main() {", - - THREE.ShaderChunk[ "color_vertex" ], - - "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", - - "#ifdef USE_SIZEATTENUATION", - "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );", - "#else", - "gl_PointSize = size;", - "#endif", - - "gl_Position = projectionMatrix * mvPosition;", - - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], - - "}" - - ].join("\n"), - - fragmentShader: [ - - "uniform vec3 psColor;", - "uniform float opacity;", - - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_particle_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - - "void main() {", - - "gl_FragColor = vec4( psColor, opacity );", - - THREE.ShaderChunk[ "map_particle_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], - THREE.ShaderChunk[ "fog_fragment" ], - - "}" - - ].join("\n") - - }, - - 'dashed': { - - uniforms: THREE.UniformsUtils.merge( [ - - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], - - { - "scale": { type: "f", value: 1 }, - "dashSize": { type: "f", value: 1 }, - "totalSize": { type: "f", value: 2 } - } - - ] ), - - vertexShader: [ - - "uniform float scale;", - "attribute float lineDistance;", - - "varying float vLineDistance;", - - THREE.ShaderChunk[ "color_pars_vertex" ], - - "void main() {", - - THREE.ShaderChunk[ "color_vertex" ], - - "vLineDistance = scale * lineDistance;", - - "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", - "gl_Position = projectionMatrix * mvPosition;", - - "}" - - ].join("\n"), - - fragmentShader: [ - - "uniform vec3 diffuse;", - "uniform float opacity;", - - "uniform float dashSize;", - "uniform float totalSize;", - - "varying float vLineDistance;", - - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - - "void main() {", - - "if ( mod( vLineDistance, totalSize ) > dashSize ) {", - - "discard;", - - "}", - - "gl_FragColor = vec4( diffuse, opacity );", - - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "fog_fragment" ], - - "}" - - ].join("\n") - - }, - - 'depth': { - - uniforms: { - - "mNear": { type: "f", value: 1.0 }, - "mFar" : { type: "f", value: 2000.0 }, - "opacity" : { type: "f", value: 1.0 } - - }, - - vertexShader: [ - - "void main() {", - - "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", - - "}" - - ].join("\n"), - - fragmentShader: [ - - "uniform float mNear;", - "uniform float mFar;", - "uniform float opacity;", - - "void main() {", - - "float depth = gl_FragCoord.z / gl_FragCoord.w;", - "float color = 1.0 - smoothstep( mNear, mFar, depth );", - "gl_FragColor = vec4( vec3( color ), opacity );", - - "}" - - ].join("\n") - - }, - - 'normal': { - - uniforms: { - - "opacity" : { type: "f", value: 1.0 } - - }, - - vertexShader: [ - - "varying vec3 vNormal;", - - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - - "void main() {", - - "vNormal = normalize( normalMatrix * normal );", - - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - - "}" - - ].join("\n"), - - fragmentShader: [ - - "uniform float opacity;", - "varying vec3 vNormal;", - - "void main() {", - - "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );", - - "}" - - ].join("\n") - - }, - - /* ------------------------------------------------------------------------- - // Normal map shader - // - Blinn-Phong - // - normal + diffuse + specular + AO + displacement + reflection + shadow maps - // - point and directional lights (use with "lights: true" material option) - ------------------------------------------------------------------------- */ - - 'normalmap' : { - - uniforms: THREE.UniformsUtils.merge( [ - - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], - - { - - "enableAO" : { type: "i", value: 0 }, - "enableDiffuse" : { type: "i", value: 0 }, - "enableSpecular" : { type: "i", value: 0 }, - "enableReflection": { type: "i", value: 0 }, - "enableDisplacement": { type: "i", value: 0 }, - - "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture - "tDiffuse" : { type: "t", value: null }, - "tCube" : { type: "t", value: null }, - "tNormal" : { type: "t", value: null }, - "tSpecular" : { type: "t", value: null }, - "tAO" : { type: "t", value: null }, - - "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) }, - - "uDisplacementBias": { type: "f", value: 0.0 }, - "uDisplacementScale": { type: "f", value: 1.0 }, - - "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) }, - "specular": { type: "c", value: new THREE.Color( 0x111111 ) }, - "ambient": { type: "c", value: new THREE.Color( 0xffffff ) }, - "shininess": { type: "f", value: 30 }, - "opacity": { type: "f", value: 1 }, - - "useRefract": { type: "i", value: 0 }, - "refractionRatio": { type: "f", value: 0.98 }, - "reflectivity": { type: "f", value: 0.5 }, - - "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) }, - "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }, - - "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } - - } - - ] ), - - fragmentShader: [ - - "uniform vec3 ambient;", - "uniform vec3 diffuse;", - "uniform vec3 specular;", - "uniform float shininess;", - "uniform float opacity;", - - "uniform bool enableDiffuse;", - "uniform bool enableSpecular;", - "uniform bool enableAO;", - "uniform bool enableReflection;", - - "uniform sampler2D tDiffuse;", - "uniform sampler2D tNormal;", - "uniform sampler2D tSpecular;", - "uniform sampler2D tAO;", - - "uniform samplerCube tCube;", - - "uniform vec2 uNormalScale;", - - "uniform bool useRefract;", - "uniform float refractionRatio;", - "uniform float reflectivity;", - - "varying vec3 vTangent;", - "varying vec3 vBinormal;", - "varying vec3 vNormal;", - "varying vec2 vUv;", - - "uniform vec3 ambientLightColor;", - - "#if MAX_DIR_LIGHTS > 0", - - "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];", - "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];", - - "#endif", - - "#if MAX_HEMI_LIGHTS > 0", - - "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];", - "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];", - "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];", - - "#endif", - - "#if MAX_POINT_LIGHTS > 0", - - "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];", - "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];", - "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];", - - "#endif", - - "#if MAX_SPOT_LIGHTS > 0", - - "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];", - "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];", - "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];", - "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];", - "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];", - "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];", - - "#endif", - - "#ifdef WRAP_AROUND", - - "uniform vec3 wrapRGB;", - - "#endif", - - "varying vec3 vWorldPosition;", - "varying vec3 vViewPosition;", - - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - - "void main() {", - - "gl_FragColor = vec4( vec3( 1.0 ), opacity );", - - "vec3 specularTex = vec3( 1.0 );", - - "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;", - "normalTex.xy *= uNormalScale;", - "normalTex = normalize( normalTex );", - - "if( enableDiffuse ) {", - - "#ifdef GAMMA_INPUT", - - "vec4 texelColor = texture2D( tDiffuse, vUv );", - "texelColor.xyz *= texelColor.xyz;", - - "gl_FragColor = gl_FragColor * texelColor;", - - "#else", - - "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );", - - "#endif", - - "}", - - "if( enableAO ) {", - - "#ifdef GAMMA_INPUT", - - "vec4 aoColor = texture2D( tAO, vUv );", - "aoColor.xyz *= aoColor.xyz;", - - "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;", - - "#else", - - "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;", - - "#endif", - - "}", - - "if( enableSpecular )", - "specularTex = texture2D( tSpecular, vUv ).xyz;", - - "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );", - "vec3 finalNormal = tsb * normalTex;", - - "#ifdef FLIP_SIDED", - - "finalNormal = -finalNormal;", - - "#endif", - - "vec3 normal = normalize( finalNormal );", - "vec3 viewPosition = normalize( vViewPosition );", - - // point lights - - "#if MAX_POINT_LIGHTS > 0", - - "vec3 pointDiffuse = vec3( 0.0 );", - "vec3 pointSpecular = vec3( 0.0 );", - - "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {", - - "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );", - "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;", - - "float pointDistance = 1.0;", - "if ( pointLightDistance[ i ] > 0.0 )", - "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );", - - "pointVector = normalize( pointVector );", - - // diffuse - - "#ifdef WRAP_AROUND", - - "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );", - "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );", - - "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );", - - "#else", - - "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );", - - "#endif", - - "pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;", - - // specular - - "vec3 pointHalfVector = normalize( pointVector + viewPosition );", - "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );", - "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );", - - // 2.0 => 2.0001 is hack to work around ANGLE bug - - "float specularNormalization = ( shininess + 2.0001 ) / 8.0;", - - "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );", - "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;", - - "}", - - "#endif", - - // spot lights - - "#if MAX_SPOT_LIGHTS > 0", - - "vec3 spotDiffuse = vec3( 0.0 );", - "vec3 spotSpecular = vec3( 0.0 );", - - "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {", - - "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );", - "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;", - - "float spotDistance = 1.0;", - "if ( spotLightDistance[ i ] > 0.0 )", - "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );", - - "spotVector = normalize( spotVector );", - - "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );", - - "if ( spotEffect > spotLightAngleCos[ i ] ) {", - - "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );", - - // diffuse - - "#ifdef WRAP_AROUND", - - "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );", - "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );", - - "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );", - - "#else", - - "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );", - - "#endif", - - "spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;", - - // specular - - "vec3 spotHalfVector = normalize( spotVector + viewPosition );", - "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );", - "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );", - - // 2.0 => 2.0001 is hack to work around ANGLE bug - - "float specularNormalization = ( shininess + 2.0001 ) / 8.0;", - - "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );", - "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;", - - "}", - - "}", - - "#endif", - - // directional lights - - "#if MAX_DIR_LIGHTS > 0", - - "vec3 dirDiffuse = vec3( 0.0 );", - "vec3 dirSpecular = vec3( 0.0 );", - - "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {", - - "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );", - "vec3 dirVector = normalize( lDirection.xyz );", - - // diffuse - - "#ifdef WRAP_AROUND", - - "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );", - "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );", - - "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );", - - "#else", - - "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );", - - "#endif", - - "dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;", - - // specular - - "vec3 dirHalfVector = normalize( dirVector + viewPosition );", - "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );", - "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );", - - // 2.0 => 2.0001 is hack to work around ANGLE bug - - "float specularNormalization = ( shininess + 2.0001 ) / 8.0;", - - "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );", - "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;", - - "}", - - "#endif", - - // hemisphere lights - - "#if MAX_HEMI_LIGHTS > 0", - - "vec3 hemiDiffuse = vec3( 0.0 );", - "vec3 hemiSpecular = vec3( 0.0 );" , - - "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {", - - "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );", - "vec3 lVector = normalize( lDirection.xyz );", - - // diffuse - - "float dotProduct = dot( normal, lVector );", - "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;", - - "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", - - "hemiDiffuse += diffuse * hemiColor;", - - // specular (sky light) - - - "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );", - "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;", - "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );", - - // specular (ground light) - - "vec3 lVectorGround = -lVector;", - - "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );", - "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;", - "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );", - - "float dotProductGround = dot( normal, lVectorGround );", - - // 2.0 => 2.0001 is hack to work around ANGLE bug - - "float specularNormalization = ( shininess + 2.0001 ) / 8.0;", - - "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );", - "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );", - "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );", - - "}", - - "#endif", - - // all lights contribution summation - - "vec3 totalDiffuse = vec3( 0.0 );", - "vec3 totalSpecular = vec3( 0.0 );", - - "#if MAX_DIR_LIGHTS > 0", - - "totalDiffuse += dirDiffuse;", - "totalSpecular += dirSpecular;", - - "#endif", - - "#if MAX_HEMI_LIGHTS > 0", - - "totalDiffuse += hemiDiffuse;", - "totalSpecular += hemiSpecular;", - - "#endif", - - "#if MAX_POINT_LIGHTS > 0", - - "totalDiffuse += pointDiffuse;", - "totalSpecular += pointSpecular;", - - "#endif", - - "#if MAX_SPOT_LIGHTS > 0", - - "totalDiffuse += spotDiffuse;", - "totalSpecular += spotSpecular;", - - "#endif", - - "#ifdef METAL", - - "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );", - - "#else", - - "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;", - - "#endif", - - "if ( enableReflection ) {", - - "vec3 vReflect;", - "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );", - - "if ( useRefract ) {", - - "vReflect = refract( cameraToVertex, normal, refractionRatio );", - - "} else {", - - "vReflect = reflect( cameraToVertex, normal );", - - "}", - - "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );", - - "#ifdef GAMMA_INPUT", - - "cubeColor.xyz *= cubeColor.xyz;", - - "#endif", - - "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );", - - "}", - - THREE.ShaderChunk[ "shadowmap_fragment" ], - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - THREE.ShaderChunk[ "fog_fragment" ], - - "}" - - ].join("\n"), - - vertexShader: [ - - "attribute vec4 tangent;", - - "uniform vec2 uOffset;", - "uniform vec2 uRepeat;", - - "uniform bool enableDisplacement;", - - "#ifdef VERTEX_TEXTURES", - - "uniform sampler2D tDisplacement;", - "uniform float uDisplacementScale;", - "uniform float uDisplacementBias;", - - "#endif", - - "varying vec3 vTangent;", - "varying vec3 vBinormal;", - "varying vec3 vNormal;", - "varying vec2 vUv;", - - "varying vec3 vWorldPosition;", - "varying vec3 vViewPosition;", - - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - - "void main() {", - - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - - // normal, tangent and binormal vectors - - "#ifdef USE_SKINNING", - - "vNormal = normalize( normalMatrix * skinnedNormal.xyz );", - - "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );", - "vTangent = normalize( normalMatrix * skinnedTangent.xyz );", - - "#else", - - "vNormal = normalize( normalMatrix * normal );", - "vTangent = normalize( normalMatrix * tangent.xyz );", - - "#endif", - - "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );", - - "vUv = uv * uRepeat + uOffset;", - - // displacement mapping - - "vec3 displacedPosition;", - - "#ifdef VERTEX_TEXTURES", - - "if ( enableDisplacement ) {", - - "vec3 dv = texture2D( tDisplacement, uv ).xyz;", - "float df = uDisplacementScale * dv.x + uDisplacementBias;", - "displacedPosition = position + normalize( normal ) * df;", - - "} else {", - - "#ifdef USE_SKINNING", - - "vec4 skinVertex = vec4( position, 1.0 );", - - "vec4 skinned = boneMatX * skinVertex * skinWeight.x;", - "skinned += boneMatY * skinVertex * skinWeight.y;", - - "displacedPosition = skinned.xyz;", - - "#else", - - "displacedPosition = position;", - - "#endif", - - "}", - - "#else", - - "#ifdef USE_SKINNING", - - "vec4 skinVertex = vec4( position, 1.0 );", - - "vec4 skinned = boneMatX * skinVertex * skinWeight.x;", - "skinned += boneMatY * skinVertex * skinWeight.y;", - - "displacedPosition = skinned.xyz;", - - "#else", - - "displacedPosition = position;", - - "#endif", - - "#endif", - - // - - "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );", - "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );", - - "gl_Position = projectionMatrix * mvPosition;", - - // - - "vWorldPosition = worldPosition.xyz;", - "vViewPosition = -mvPosition.xyz;", - - // shadows - - "#ifdef USE_SHADOWMAP", - - "for( int i = 0; i < MAX_SHADOWS; i ++ ) {", - - "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;", - - "}", - - "#endif", - - "}" - - ].join("\n") - - }, - - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ - - 'cube': { - - uniforms: { "tCube": { type: "t", value: null }, - "tFlip": { type: "f", value: -1 } }, - - vertexShader: [ - - "varying vec3 vWorldPosition;", - - "void main() {", - - "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", - "vWorldPosition = worldPosition.xyz;", - - "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", - - "}" - - ].join("\n"), - - fragmentShader: [ - - "uniform samplerCube tCube;", - "uniform float tFlip;", - - "varying vec3 vWorldPosition;", - - "void main() {", - - "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", - - "}" - - ].join("\n") - - }, - - // Depth encoding into RGBA texture - // based on SpiderGL shadow map example - // http://spidergl.org/example.php?id=6 - // originally from - // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD - // see also here: - // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/ - - 'depthRGBA': { - - uniforms: {}, - - vertexShader: [ - - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - - "void main() {", - - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - - "}" - - ].join("\n"), - - fragmentShader: [ - - "vec4 pack_depth( const in float depth ) {", - - "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );", - "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );", - "vec4 res = fract( depth * bit_shift );", - "res -= res.xxyz * bit_mask;", - "return res;", - - "}", - - "void main() {", - - "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );", - - //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );", - //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );", - //"gl_FragData[ 0 ] = pack_depth( z );", - //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );", - - "}" - - ].join("\n") - - } - -}; -/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ - -THREE.WebGLRenderer = function ( parameters ) { - - console.log( 'THREE.WebGLRenderer', THREE.REVISION ); - - parameters = parameters || {}; - - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, - - _precision = parameters.precision !== undefined ? parameters.precision : 'highp', - - _buffers = {}, - - _alpha = parameters.alpha !== undefined ? parameters.alpha : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, - - _clearColor = new THREE.Color( 0x000000 ), - _clearAlpha = 0; - - // public properties - - this.domElement = _canvas; - this.context = null; - this.devicePixelRatio = parameters.devicePixelRatio !== undefined - ? parameters.devicePixelRatio - : self.devicePixelRatio !== undefined - ? self.devicePixelRatio - : 1; - - // clearing - - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; - - // scene graph - - this.sortObjects = true; - this.autoUpdateObjects = true; - - // physically based shading - - this.gammaInput = false; - this.gammaOutput = false; - - // shadow map - - this.shadowMapEnabled = false; - this.shadowMapAutoUpdate = true; - this.shadowMapType = THREE.PCFShadowMap; - this.shadowMapCullFace = THREE.CullFaceFront; - this.shadowMapDebug = false; - this.shadowMapCascade = false; - - // morphs - - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; - - // flags - - this.autoScaleCubemaps = true; - - // custom render plugins - - this.renderPluginsPre = []; - this.renderPluginsPost = []; - - // info - - this.info = { - - memory: { - - programs: 0, - geometries: 0, - textures: 0 - - }, - - render: { - - calls: 0, - vertices: 0, - faces: 0, - points: 0 - - } - - }; - - // internal properties - - var _this = this, - - _programs = [], - _programs_counter = 0, - - // internal state cache - - _currentProgram = null, - _currentFramebuffer = null, - _currentMaterialId = -1, - _currentGeometryGroupHash = null, - _currentCamera = null, - - _usedTextureUnits = 0, - - // GL state cache - - _oldDoubleSided = -1, - _oldFlipSided = -1, - - _oldBlending = -1, - - _oldBlendEquation = -1, - _oldBlendSrc = -1, - _oldBlendDst = -1, - - _oldDepthTest = -1, - _oldDepthWrite = -1, - - _oldPolygonOffset = null, - _oldPolygonOffsetFactor = null, - _oldPolygonOffsetUnits = null, - - _oldLineWidth = null, - - _viewportX = 0, - _viewportY = 0, - _viewportWidth = _canvas.width, - _viewportHeight = _canvas.height, - _currentWidth = 0, - _currentHeight = 0, - - _enabledAttributes = new Uint8Array( 16 ), - - // frustum - - _frustum = new THREE.Frustum(), - - // camera matrices cache - - _projScreenMatrix = new THREE.Matrix4(), - _projScreenMatrixPS = new THREE.Matrix4(), - - _vector3 = new THREE.Vector3(), - - // light arrays cache - - _direction = new THREE.Vector3(), - - _lightsNeedUpdate = true, - - _lights = { - - ambient: [ 0, 0, 0 ], - directional: { length: 0, colors: new Array(), positions: new Array() }, - point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }, - spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() }, - hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() } - - }; - - // initialize - - var _gl; - - var _glExtensionTextureFloat; - var _glExtensionTextureFloatLinear; - var _glExtensionStandardDerivatives; - var _glExtensionTextureFilterAnisotropic; - var _glExtensionCompressedTextureS3TC; - - initGL(); - - setDefaultGLState(); - - this.context = _gl; - - // GPU capabilities - - var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ); - var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); - var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ); - var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE ); - - var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0; - - var _supportsVertexTextures = ( _maxVertexTextures > 0 ); - var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat; - - var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : []; - - // - - var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT ); - var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT ); - var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT ); - - var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT ); - var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT ); - var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT ); - - var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT ); - var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT ); - var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT ); - - var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT ); - var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT ); - var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT ); - - // clamp precision to maximum available - - var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0; - var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0; - - if ( _precision === "highp" && ! highpAvailable ) { - - if ( mediumpAvailable ) { - - _precision = "mediump"; - console.warn( "WebGLRenderer: highp not supported, using mediump" ); - - } else { - - _precision = "lowp"; - console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" ); - - } - - } - - if ( _precision === "mediump" && ! mediumpAvailable ) { - - _precision = "lowp"; - console.warn( "WebGLRenderer: mediump not supported, using lowp" ); - - } - - // API - - this.getContext = function () { - - return _gl; - - }; - - this.supportsVertexTextures = function () { - - return _supportsVertexTextures; - - }; - - this.supportsFloatTextures = function () { - - return _glExtensionTextureFloat; - - }; - - this.supportsStandardDerivatives = function () { - - return _glExtensionStandardDerivatives; - - }; - - this.supportsCompressedTextureS3TC = function () { - - return _glExtensionCompressedTextureS3TC; - - }; - - this.getMaxAnisotropy = function () { - - return _maxAnisotropy; - - }; - - this.getPrecision = function () { - - return _precision; - - }; - - this.setSize = function ( width, height, updateStyle ) { - - _canvas.width = width * this.devicePixelRatio; - _canvas.height = height * this.devicePixelRatio; - - if ( this.devicePixelRatio !== 1 && updateStyle !== false ) { - - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; - - } - - this.setViewport( 0, 0, width, height ); - - }; - - this.setViewport = function ( x, y, width, height ) { - - _viewportX = x * this.devicePixelRatio; - _viewportY = y * this.devicePixelRatio; - - _viewportWidth = width * this.devicePixelRatio; - _viewportHeight = height * this.devicePixelRatio; - - _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); - - }; - - this.setScissor = function ( x, y, width, height ) { - - _gl.scissor( - x * this.devicePixelRatio, - y * this.devicePixelRatio, - width * this.devicePixelRatio, - height * this.devicePixelRatio - ); - - }; - - this.enableScissorTest = function ( enable ) { - - enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST ); - - }; - - // Clearing - - this.setClearColor = function ( color, alpha ) { - - _clearColor.set( color ); - _clearAlpha = alpha !== undefined ? alpha : 1; - - _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - - }; - - this.setClearColorHex = function ( hex, alpha ) { - - console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' ); - this.setClearColor( hex, alpha ); - - }; - - this.getClearColor = function () { - - return _clearColor; - - }; - - this.getClearAlpha = function () { - - return _clearAlpha; - - }; - - this.clear = function ( color, depth, stencil ) { - - var bits = 0; - - if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; - if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; - if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; - - _gl.clear( bits ); - - }; - - this.clearColor = function () { - - _gl.clear( _gl.COLOR_BUFFER_BIT ); - - }; - - this.clearDepth = function () { - - _gl.clear( _gl.DEPTH_BUFFER_BIT ); - - }; - - this.clearStencil = function () { - - _gl.clear( _gl.STENCIL_BUFFER_BIT ); - - }; - - this.clearTarget = function ( renderTarget, color, depth, stencil ) { - - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); - - }; - - // Plugins - - this.addPostPlugin = function ( plugin ) { - - plugin.init( this ); - this.renderPluginsPost.push( plugin ); - - }; - - this.addPrePlugin = function ( plugin ) { - - plugin.init( this ); - this.renderPluginsPre.push( plugin ); - - }; - - // Rendering - - this.updateShadowMap = function ( scene, camera ) { - - _currentProgram = null; - _oldBlending = -1; - _oldDepthTest = -1; - _oldDepthWrite = -1; - _currentGeometryGroupHash = -1; - _currentMaterialId = -1; - _lightsNeedUpdate = true; - _oldDoubleSided = -1; - _oldFlipSided = -1; - - this.shadowMapPlugin.update( scene, camera ); - - }; - - // Internal functions - - // Buffer allocation - - function createParticleBuffers ( geometry ) { - - geometry.__webglVertexBuffer = _gl.createBuffer(); - geometry.__webglColorBuffer = _gl.createBuffer(); - - _this.info.memory.geometries ++; - - }; - - function createLineBuffers ( geometry ) { - - geometry.__webglVertexBuffer = _gl.createBuffer(); - geometry.__webglColorBuffer = _gl.createBuffer(); - geometry.__webglLineDistanceBuffer = _gl.createBuffer(); - - _this.info.memory.geometries ++; - - }; - - function createMeshBuffers ( geometryGroup ) { - - geometryGroup.__webglVertexBuffer = _gl.createBuffer(); - geometryGroup.__webglNormalBuffer = _gl.createBuffer(); - geometryGroup.__webglTangentBuffer = _gl.createBuffer(); - geometryGroup.__webglColorBuffer = _gl.createBuffer(); - geometryGroup.__webglUVBuffer = _gl.createBuffer(); - geometryGroup.__webglUV2Buffer = _gl.createBuffer(); - - geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer(); - geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer(); - - geometryGroup.__webglFaceBuffer = _gl.createBuffer(); - geometryGroup.__webglLineBuffer = _gl.createBuffer(); - - var m, ml; - - if ( geometryGroup.numMorphTargets ) { - - geometryGroup.__webglMorphTargetsBuffers = []; - - for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { - - geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() ); - - } - - } - - if ( geometryGroup.numMorphNormals ) { - - geometryGroup.__webglMorphNormalsBuffers = []; - - for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { - - geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() ); - - } - - } - - _this.info.memory.geometries ++; - - }; - - // Events - - var onGeometryDispose = function ( event ) { - - var geometry = event.target; - - geometry.removeEventListener( 'dispose', onGeometryDispose ); - - deallocateGeometry( geometry ); - - }; - - var onTextureDispose = function ( event ) { - - var texture = event.target; - - texture.removeEventListener( 'dispose', onTextureDispose ); - - deallocateTexture( texture ); - - _this.info.memory.textures --; - - - }; - - var onRenderTargetDispose = function ( event ) { - - var renderTarget = event.target; - - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - - deallocateRenderTarget( renderTarget ); - - _this.info.memory.textures --; - - }; - - var onMaterialDispose = function ( event ) { - - var material = event.target; - - material.removeEventListener( 'dispose', onMaterialDispose ); - - deallocateMaterial( material ); - - }; - - // Buffer deallocation - - var deleteBuffers = function ( geometry ) { - - if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer ); - if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer ); - if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer ); - if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer ); - if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer ); - if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer ); - - if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer ); - if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer ); - - if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer ); - if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer ); - - if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer ); - // custom attributes - - if ( geometry.__webglCustomAttributesList !== undefined ) { - - for ( var id in geometry.__webglCustomAttributesList ) { - - _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer ); - - } - - } - - _this.info.memory.geometries --; - - }; - - var deallocateGeometry = function ( geometry ) { - - geometry.__webglInit = undefined; - - if ( geometry instanceof THREE.BufferGeometry ) { - - var attributes = geometry.attributes; - - for ( var key in attributes ) { - - if ( attributes[ key ].buffer !== undefined ) { - - _gl.deleteBuffer( attributes[ key ].buffer ); - - } - - } - - _this.info.memory.geometries --; - - } else { - - if ( geometry.geometryGroups !== undefined ) { - - for ( var g in geometry.geometryGroups ) { - - var geometryGroup = geometry.geometryGroups[ g ]; - - if ( geometryGroup.numMorphTargets !== undefined ) { - - for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { - - _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] ); - - } - - } - - if ( geometryGroup.numMorphNormals !== undefined ) { - - for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { - - _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] ); - - } - - } - - deleteBuffers( geometryGroup ); - - } - - } else { - - deleteBuffers( geometry ); - - } - - } - - }; - - var deallocateTexture = function ( texture ) { - - if ( texture.image && texture.image.__webglTextureCube ) { - - // cube texture - - _gl.deleteTexture( texture.image.__webglTextureCube ); - - } else { - - // 2D texture - - if ( ! texture.__webglInit ) return; - - texture.__webglInit = false; - _gl.deleteTexture( texture.__webglTexture ); - - } - - }; - - var deallocateRenderTarget = function ( renderTarget ) { - - if ( !renderTarget || ! renderTarget.__webglTexture ) return; - - _gl.deleteTexture( renderTarget.__webglTexture ); - - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { - - for ( var i = 0; i < 6; i ++ ) { - - _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] ); - _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] ); - - } - - } else { - - _gl.deleteFramebuffer( renderTarget.__webglFramebuffer ); - _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer ); - - } - - }; - - var deallocateMaterial = function ( material ) { - - var program = material.program; - - if ( program === undefined ) return; - - material.program = undefined; - - // only deallocate GL program if this was the last use of shared program - // assumed there is only single copy of any program in the _programs list - // (that's how it's constructed) - - var i, il, programInfo; - var deleteProgram = false; - - for ( i = 0, il = _programs.length; i < il; i ++ ) { - - programInfo = _programs[ i ]; - - if ( programInfo.program === program ) { - - programInfo.usedTimes --; - - if ( programInfo.usedTimes === 0 ) { - - deleteProgram = true; - - } - - break; - - } - - } - - if ( deleteProgram === true ) { - - // avoid using array.splice, this is costlier than creating new array from scratch - - var newPrograms = []; - - for ( i = 0, il = _programs.length; i < il; i ++ ) { - - programInfo = _programs[ i ]; - - if ( programInfo.program !== program ) { - - newPrograms.push( programInfo ); - - } - - } - - _programs = newPrograms; - - _gl.deleteProgram( program ); - - _this.info.memory.programs --; - - } - - }; - - // Buffer initialization - - function initCustomAttributes ( geometry, object ) { - - var nvertices = geometry.vertices.length; - - var material = object.material; - - if ( material.attributes ) { - - if ( geometry.__webglCustomAttributesList === undefined ) { - - geometry.__webglCustomAttributesList = []; - - } - - for ( var a in material.attributes ) { - - var attribute = material.attributes[ a ]; - - if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { - - attribute.__webglInitialized = true; - - var size = 1; // "f" and "i" - - if ( attribute.type === "v2" ) size = 2; - else if ( attribute.type === "v3" ) size = 3; - else if ( attribute.type === "v4" ) size = 4; - else if ( attribute.type === "c" ) size = 3; - - attribute.size = size; - - attribute.array = new Float32Array( nvertices * size ); - - attribute.buffer = _gl.createBuffer(); - attribute.buffer.belongsToAttribute = a; - - attribute.needsUpdate = true; - - } - - geometry.__webglCustomAttributesList.push( attribute ); - - } - - } - - }; - - function initParticleBuffers ( geometry, object ) { - - var nvertices = geometry.vertices.length; - - geometry.__vertexArray = new Float32Array( nvertices * 3 ); - geometry.__colorArray = new Float32Array( nvertices * 3 ); - - geometry.__sortArray = []; - - geometry.__webglParticleCount = nvertices; - - initCustomAttributes ( geometry, object ); - - }; - - function initLineBuffers ( geometry, object ) { - - var nvertices = geometry.vertices.length; - - geometry.__vertexArray = new Float32Array( nvertices * 3 ); - geometry.__colorArray = new Float32Array( nvertices * 3 ); - geometry.__lineDistanceArray = new Float32Array( nvertices * 1 ); - - geometry.__webglLineCount = nvertices; - - initCustomAttributes ( geometry, object ); - - }; - - function initMeshBuffers ( geometryGroup, object ) { - - var geometry = object.geometry, - faces3 = geometryGroup.faces3, - - nvertices = faces3.length * 3, - ntris = faces3.length * 1, - nlines = faces3.length * 3, - - material = getBufferMaterial( object, geometryGroup ), - - uvType = bufferGuessUVType( material ), - normalType = bufferGuessNormalType( material ), - vertexColorType = bufferGuessVertexColorType( material ); - - // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material ); - - geometryGroup.__vertexArray = new Float32Array( nvertices * 3 ); - - if ( normalType ) { - - geometryGroup.__normalArray = new Float32Array( nvertices * 3 ); - - } - - if ( geometry.hasTangents ) { - - geometryGroup.__tangentArray = new Float32Array( nvertices * 4 ); - - } - - if ( vertexColorType ) { - - geometryGroup.__colorArray = new Float32Array( nvertices * 3 ); - - } - - if ( uvType ) { - - if ( geometry.faceVertexUvs.length > 0 ) { - - geometryGroup.__uvArray = new Float32Array( nvertices * 2 ); - - } - - if ( geometry.faceVertexUvs.length > 1 ) { - - geometryGroup.__uv2Array = new Float32Array( nvertices * 2 ); - - } - - } - - if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) { - - geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 ); - geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 ); - - } - - geometryGroup.__faceArray = new Uint16Array( ntris * 3 ); - geometryGroup.__lineArray = new Uint16Array( nlines * 2 ); - - var m, ml; - - if ( geometryGroup.numMorphTargets ) { - - geometryGroup.__morphTargetsArrays = []; - - for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { - - geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) ); - - } - - } - - if ( geometryGroup.numMorphNormals ) { - - geometryGroup.__morphNormalsArrays = []; - - for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { - - geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) ); - - } - - } - - geometryGroup.__webglFaceCount = ntris * 3; - geometryGroup.__webglLineCount = nlines * 2; - - - // custom attributes - - if ( material.attributes ) { - - if ( geometryGroup.__webglCustomAttributesList === undefined ) { - - geometryGroup.__webglCustomAttributesList = []; - - } - - for ( var a in material.attributes ) { - - // Do a shallow copy of the attribute object so different geometryGroup chunks use different - // attribute buffers which are correctly indexed in the setMeshBuffers function - - var originalAttribute = material.attributes[ a ]; - - var attribute = {}; - - for ( var property in originalAttribute ) { - - attribute[ property ] = originalAttribute[ property ]; - - } - - if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { - - attribute.__webglInitialized = true; - - var size = 1; // "f" and "i" - - if( attribute.type === "v2" ) size = 2; - else if( attribute.type === "v3" ) size = 3; - else if( attribute.type === "v4" ) size = 4; - else if( attribute.type === "c" ) size = 3; - - attribute.size = size; - - attribute.array = new Float32Array( nvertices * size ); - - attribute.buffer = _gl.createBuffer(); - attribute.buffer.belongsToAttribute = a; - - originalAttribute.needsUpdate = true; - attribute.__original = originalAttribute; - - } - - geometryGroup.__webglCustomAttributesList.push( attribute ); - - } - - } - - geometryGroup.__inittedArrays = true; - - }; - - function getBufferMaterial( object, geometryGroup ) { - - return object.material instanceof THREE.MeshFaceMaterial - ? object.material.materials[ geometryGroup.materialIndex ] - : object.material; - - }; - - function materialNeedsSmoothNormals ( material ) { - - return material && material.shading !== undefined && material.shading === THREE.SmoothShading; - - }; - - function bufferGuessNormalType ( material ) { - - // only MeshBasicMaterial and MeshDepthMaterial don't need normals - - if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) { - - return false; - - } - - if ( materialNeedsSmoothNormals( material ) ) { - - return THREE.SmoothShading; - - } else { - - return THREE.FlatShading; - - } - - }; - - function bufferGuessVertexColorType( material ) { - - if ( material.vertexColors ) { - - return material.vertexColors; - - } - - return false; - - }; - - function bufferGuessUVType( material ) { - - // material must use some texture to require uvs - - if ( material.map || - material.lightMap || - material.bumpMap || - material.normalMap || - material.specularMap || - material instanceof THREE.ShaderMaterial ) { - - return true; - - } - - return false; - - }; - - // - - function initDirectBuffers( geometry ) { - - var a, attribute, type; - - for ( a in geometry.attributes ) { - - if ( a === "index" ) { - - type = _gl.ELEMENT_ARRAY_BUFFER; - - } else { - - type = _gl.ARRAY_BUFFER; - - } - - attribute = geometry.attributes[ a ]; - - attribute.buffer = _gl.createBuffer(); - - _gl.bindBuffer( type, attribute.buffer ); - _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW ); - - } - - }; - - // Buffer setting - - function setParticleBuffers ( geometry, hint, object ) { - - var v, c, vertex, offset, index, color, - - vertices = geometry.vertices, - vl = vertices.length, - - colors = geometry.colors, - cl = colors.length, - - vertexArray = geometry.__vertexArray, - colorArray = geometry.__colorArray, - - sortArray = geometry.__sortArray, - - dirtyVertices = geometry.verticesNeedUpdate, - dirtyElements = geometry.elementsNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, - - customAttributes = geometry.__webglCustomAttributesList, - i, il, - a, ca, cal, value, - customAttribute; - - if ( object.sortParticles ) { - - _projScreenMatrixPS.copy( _projScreenMatrix ); - _projScreenMatrixPS.multiply( object.matrixWorld ); - - for ( v = 0; v < vl; v ++ ) { - - vertex = vertices[ v ]; - - _vector3.copy( vertex ); - _vector3.applyProjection( _projScreenMatrixPS ); - - sortArray[ v ] = [ _vector3.z, v ]; - - } - - sortArray.sort( numericalSort ); - - for ( v = 0; v < vl; v ++ ) { - - vertex = vertices[ sortArray[v][1] ]; - - offset = v * 3; - - vertexArray[ offset ] = vertex.x; - vertexArray[ offset + 1 ] = vertex.y; - vertexArray[ offset + 2 ] = vertex.z; - - } - - for ( c = 0; c < cl; c ++ ) { - - offset = c * 3; - - color = colors[ sortArray[c][1] ]; - - colorArray[ offset ] = color.r; - colorArray[ offset + 1 ] = color.g; - colorArray[ offset + 2 ] = color.b; - - } - - if ( customAttributes ) { - - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - - customAttribute = customAttributes[ i ]; - - if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue; - - offset = 0; - - cal = customAttribute.value.length; - - if ( customAttribute.size === 1 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - index = sortArray[ ca ][ 1 ]; - - customAttribute.array[ ca ] = customAttribute.value[ index ]; - - } - - } else if ( customAttribute.size === 2 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - index = sortArray[ ca ][ 1 ]; - - value = customAttribute.value[ index ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - - offset += 2; - - } - - } else if ( customAttribute.size === 3 ) { - - if ( customAttribute.type === "c" ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - index = sortArray[ ca ][ 1 ]; - - value = customAttribute.value[ index ]; - - customAttribute.array[ offset ] = value.r; - customAttribute.array[ offset + 1 ] = value.g; - customAttribute.array[ offset + 2 ] = value.b; - - offset += 3; - - } - - } else { - - for ( ca = 0; ca < cal; ca ++ ) { - - index = sortArray[ ca ][ 1 ]; - - value = customAttribute.value[ index ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - - offset += 3; - - } - - } - - } else if ( customAttribute.size === 4 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - index = sortArray[ ca ][ 1 ]; - - value = customAttribute.value[ index ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - customAttribute.array[ offset + 3 ] = value.w; - - offset += 4; - - } - - } - - } - - } - - } else { - - if ( dirtyVertices ) { - - for ( v = 0; v < vl; v ++ ) { - - vertex = vertices[ v ]; - - offset = v * 3; - - vertexArray[ offset ] = vertex.x; - vertexArray[ offset + 1 ] = vertex.y; - vertexArray[ offset + 2 ] = vertex.z; - - } - - } - - if ( dirtyColors ) { - - for ( c = 0; c < cl; c ++ ) { - - color = colors[ c ]; - - offset = c * 3; - - colorArray[ offset ] = color.r; - colorArray[ offset + 1 ] = color.g; - colorArray[ offset + 2 ] = color.b; - - } - - } - - if ( customAttributes ) { - - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - - customAttribute = customAttributes[ i ]; - - if ( customAttribute.needsUpdate && - ( customAttribute.boundTo === undefined || - customAttribute.boundTo === "vertices") ) { - - cal = customAttribute.value.length; - - offset = 0; - - if ( customAttribute.size === 1 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - customAttribute.array[ ca ] = customAttribute.value[ ca ]; - - } - - } else if ( customAttribute.size === 2 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - - offset += 2; - - } - - } else if ( customAttribute.size === 3 ) { - - if ( customAttribute.type === "c" ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.r; - customAttribute.array[ offset + 1 ] = value.g; - customAttribute.array[ offset + 2 ] = value.b; - - offset += 3; - - } - - } else { - - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - - offset += 3; - - } - - } - - } else if ( customAttribute.size === 4 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - customAttribute.array[ offset + 3 ] = value.w; - - offset += 4; - - } - - } - - } - - } - - } - - } - - if ( dirtyVertices || object.sortParticles ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); - - } - - if ( dirtyColors || object.sortParticles ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - - } - - if ( customAttributes ) { - - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - - customAttribute = customAttributes[ i ]; - - if ( customAttribute.needsUpdate || object.sortParticles ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); - - } - - } - - } - - - }; - - function setLineBuffers ( geometry, hint ) { - - var v, c, d, vertex, offset, color, - - vertices = geometry.vertices, - colors = geometry.colors, - lineDistances = geometry.lineDistances, - - vl = vertices.length, - cl = colors.length, - dl = lineDistances.length, - - vertexArray = geometry.__vertexArray, - colorArray = geometry.__colorArray, - lineDistanceArray = geometry.__lineDistanceArray, - - dirtyVertices = geometry.verticesNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, - dirtyLineDistances = geometry.lineDistancesNeedUpdate, - - customAttributes = geometry.__webglCustomAttributesList, - - i, il, - a, ca, cal, value, - customAttribute; - - if ( dirtyVertices ) { - - for ( v = 0; v < vl; v ++ ) { - - vertex = vertices[ v ]; - - offset = v * 3; - - vertexArray[ offset ] = vertex.x; - vertexArray[ offset + 1 ] = vertex.y; - vertexArray[ offset + 2 ] = vertex.z; - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); - - } - - if ( dirtyColors ) { - - for ( c = 0; c < cl; c ++ ) { - - color = colors[ c ]; - - offset = c * 3; - - colorArray[ offset ] = color.r; - colorArray[ offset + 1 ] = color.g; - colorArray[ offset + 2 ] = color.b; - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - - } - - if ( dirtyLineDistances ) { - - for ( d = 0; d < dl; d ++ ) { - - lineDistanceArray[ d ] = lineDistances[ d ]; - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint ); - - } - - if ( customAttributes ) { - - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - - customAttribute = customAttributes[ i ]; - - if ( customAttribute.needsUpdate && - ( customAttribute.boundTo === undefined || - customAttribute.boundTo === "vertices" ) ) { - - offset = 0; - - cal = customAttribute.value.length; - - if ( customAttribute.size === 1 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - customAttribute.array[ ca ] = customAttribute.value[ ca ]; - - } - - } else if ( customAttribute.size === 2 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - - offset += 2; - - } - - } else if ( customAttribute.size === 3 ) { - - if ( customAttribute.type === "c" ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.r; - customAttribute.array[ offset + 1 ] = value.g; - customAttribute.array[ offset + 2 ] = value.b; - - offset += 3; - - } - - } else { - - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - - offset += 3; - - } - - } - - } else if ( customAttribute.size === 4 ) { - - for ( ca = 0; ca < cal; ca ++ ) { - - value = customAttribute.value[ ca ]; - - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - customAttribute.array[ offset + 3 ] = value.w; - - offset += 4; - - } - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); - - } - - } - - } - - }; - - function setMeshBuffers( geometryGroup, object, hint, dispose, material ) { - - if ( ! geometryGroup.__inittedArrays ) { - - return; - - } - - var normalType = bufferGuessNormalType( material ), - vertexColorType = bufferGuessVertexColorType( material ), - uvType = bufferGuessUVType( material ), - - needsSmoothNormals = ( normalType === THREE.SmoothShading ); - - var f, fl, fi, face, - vertexNormals, faceNormal, normal, - vertexColors, faceColor, - vertexTangents, - uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4, - c1, c2, c3, c4, - sw1, sw2, sw3, sw4, - si1, si2, si3, si4, - sa1, sa2, sa3, sa4, - sb1, sb2, sb3, sb4, - m, ml, i, il, - vn, uvi, uv2i, - vk, vkl, vka, - nka, chf, faceVertexNormals, - a, - - vertexIndex = 0, - - offset = 0, - offset_uv = 0, - offset_uv2 = 0, - offset_face = 0, - offset_normal = 0, - offset_tangent = 0, - offset_line = 0, - offset_color = 0, - offset_skin = 0, - offset_morphTarget = 0, - offset_custom = 0, - offset_customSrc = 0, - - value, - - vertexArray = geometryGroup.__vertexArray, - uvArray = geometryGroup.__uvArray, - uv2Array = geometryGroup.__uv2Array, - normalArray = geometryGroup.__normalArray, - tangentArray = geometryGroup.__tangentArray, - colorArray = geometryGroup.__colorArray, - - skinIndexArray = geometryGroup.__skinIndexArray, - skinWeightArray = geometryGroup.__skinWeightArray, - - morphTargetsArrays = geometryGroup.__morphTargetsArrays, - morphNormalsArrays = geometryGroup.__morphNormalsArrays, - - customAttributes = geometryGroup.__webglCustomAttributesList, - customAttribute, - - faceArray = geometryGroup.__faceArray, - lineArray = geometryGroup.__lineArray, - - geometry = object.geometry, // this is shared for all chunks - - dirtyVertices = geometry.verticesNeedUpdate, - dirtyElements = geometry.elementsNeedUpdate, - dirtyUvs = geometry.uvsNeedUpdate, - dirtyNormals = geometry.normalsNeedUpdate, - dirtyTangents = geometry.tangentsNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, - dirtyMorphTargets = geometry.morphTargetsNeedUpdate, - - vertices = geometry.vertices, - chunk_faces3 = geometryGroup.faces3, - obj_faces = geometry.faces, - - obj_uvs = geometry.faceVertexUvs[ 0 ], - obj_uvs2 = geometry.faceVertexUvs[ 1 ], - - obj_colors = geometry.colors, - - obj_skinIndices = geometry.skinIndices, - obj_skinWeights = geometry.skinWeights, - - morphTargets = geometry.morphTargets, - morphNormals = geometry.morphNormals; - - if ( dirtyVertices ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - v1 = vertices[ face.a ]; - v2 = vertices[ face.b ]; - v3 = vertices[ face.c ]; - - vertexArray[ offset ] = v1.x; - vertexArray[ offset + 1 ] = v1.y; - vertexArray[ offset + 2 ] = v1.z; - - vertexArray[ offset + 3 ] = v2.x; - vertexArray[ offset + 4 ] = v2.y; - vertexArray[ offset + 5 ] = v2.z; - - vertexArray[ offset + 6 ] = v3.x; - vertexArray[ offset + 7 ] = v3.y; - vertexArray[ offset + 8 ] = v3.z; - - offset += 9; - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); - - } - - if ( dirtyMorphTargets ) { - - for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) { - - offset_morphTarget = 0; - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - chf = chunk_faces3[ f ]; - face = obj_faces[ chf ]; - - // morph positions - - v1 = morphTargets[ vk ].vertices[ face.a ]; - v2 = morphTargets[ vk ].vertices[ face.b ]; - v3 = morphTargets[ vk ].vertices[ face.c ]; - - vka = morphTargetsArrays[ vk ]; - - vka[ offset_morphTarget ] = v1.x; - vka[ offset_morphTarget + 1 ] = v1.y; - vka[ offset_morphTarget + 2 ] = v1.z; - - vka[ offset_morphTarget + 3 ] = v2.x; - vka[ offset_morphTarget + 4 ] = v2.y; - vka[ offset_morphTarget + 5 ] = v2.z; - - vka[ offset_morphTarget + 6 ] = v3.x; - vka[ offset_morphTarget + 7 ] = v3.y; - vka[ offset_morphTarget + 8 ] = v3.z; - - // morph normals - - if ( material.morphNormals ) { - - if ( needsSmoothNormals ) { - - faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; - - n1 = faceVertexNormals.a; - n2 = faceVertexNormals.b; - n3 = faceVertexNormals.c; - - } else { - - n1 = morphNormals[ vk ].faceNormals[ chf ]; - n2 = n1; - n3 = n1; - - } - - nka = morphNormalsArrays[ vk ]; - - nka[ offset_morphTarget ] = n1.x; - nka[ offset_morphTarget + 1 ] = n1.y; - nka[ offset_morphTarget + 2 ] = n1.z; - - nka[ offset_morphTarget + 3 ] = n2.x; - nka[ offset_morphTarget + 4 ] = n2.y; - nka[ offset_morphTarget + 5 ] = n2.z; - - nka[ offset_morphTarget + 6 ] = n3.x; - nka[ offset_morphTarget + 7 ] = n3.y; - nka[ offset_morphTarget + 8 ] = n3.z; - - } - - // - - offset_morphTarget += 9; - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] ); - _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint ); - - if ( material.morphNormals ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] ); - _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint ); - - } - - } - - } - - if ( obj_skinWeights.length ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - // weights - - sw1 = obj_skinWeights[ face.a ]; - sw2 = obj_skinWeights[ face.b ]; - sw3 = obj_skinWeights[ face.c ]; - - skinWeightArray[ offset_skin ] = sw1.x; - skinWeightArray[ offset_skin + 1 ] = sw1.y; - skinWeightArray[ offset_skin + 2 ] = sw1.z; - skinWeightArray[ offset_skin + 3 ] = sw1.w; - - skinWeightArray[ offset_skin + 4 ] = sw2.x; - skinWeightArray[ offset_skin + 5 ] = sw2.y; - skinWeightArray[ offset_skin + 6 ] = sw2.z; - skinWeightArray[ offset_skin + 7 ] = sw2.w; - - skinWeightArray[ offset_skin + 8 ] = sw3.x; - skinWeightArray[ offset_skin + 9 ] = sw3.y; - skinWeightArray[ offset_skin + 10 ] = sw3.z; - skinWeightArray[ offset_skin + 11 ] = sw3.w; - - // indices - - si1 = obj_skinIndices[ face.a ]; - si2 = obj_skinIndices[ face.b ]; - si3 = obj_skinIndices[ face.c ]; - - skinIndexArray[ offset_skin ] = si1.x; - skinIndexArray[ offset_skin + 1 ] = si1.y; - skinIndexArray[ offset_skin + 2 ] = si1.z; - skinIndexArray[ offset_skin + 3 ] = si1.w; - - skinIndexArray[ offset_skin + 4 ] = si2.x; - skinIndexArray[ offset_skin + 5 ] = si2.y; - skinIndexArray[ offset_skin + 6 ] = si2.z; - skinIndexArray[ offset_skin + 7 ] = si2.w; - - skinIndexArray[ offset_skin + 8 ] = si3.x; - skinIndexArray[ offset_skin + 9 ] = si3.y; - skinIndexArray[ offset_skin + 10 ] = si3.z; - skinIndexArray[ offset_skin + 11 ] = si3.w; - - offset_skin += 12; - - } - - if ( offset_skin > 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint ); - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint ); - - } - - } - - if ( dirtyColors && vertexColorType ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - vertexColors = face.vertexColors; - faceColor = face.color; - - if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) { - - c1 = vertexColors[ 0 ]; - c2 = vertexColors[ 1 ]; - c3 = vertexColors[ 2 ]; - - } else { - - c1 = faceColor; - c2 = faceColor; - c3 = faceColor; - - } - - colorArray[ offset_color ] = c1.r; - colorArray[ offset_color + 1 ] = c1.g; - colorArray[ offset_color + 2 ] = c1.b; - - colorArray[ offset_color + 3 ] = c2.r; - colorArray[ offset_color + 4 ] = c2.g; - colorArray[ offset_color + 5 ] = c2.b; - - colorArray[ offset_color + 6 ] = c3.r; - colorArray[ offset_color + 7 ] = c3.g; - colorArray[ offset_color + 8 ] = c3.b; - - offset_color += 9; - - } - - if ( offset_color > 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - - } - - } - - if ( dirtyTangents && geometry.hasTangents ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - vertexTangents = face.vertexTangents; - - t1 = vertexTangents[ 0 ]; - t2 = vertexTangents[ 1 ]; - t3 = vertexTangents[ 2 ]; - - tangentArray[ offset_tangent ] = t1.x; - tangentArray[ offset_tangent + 1 ] = t1.y; - tangentArray[ offset_tangent + 2 ] = t1.z; - tangentArray[ offset_tangent + 3 ] = t1.w; - - tangentArray[ offset_tangent + 4 ] = t2.x; - tangentArray[ offset_tangent + 5 ] = t2.y; - tangentArray[ offset_tangent + 6 ] = t2.z; - tangentArray[ offset_tangent + 7 ] = t2.w; - - tangentArray[ offset_tangent + 8 ] = t3.x; - tangentArray[ offset_tangent + 9 ] = t3.y; - tangentArray[ offset_tangent + 10 ] = t3.z; - tangentArray[ offset_tangent + 11 ] = t3.w; - - offset_tangent += 12; - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint ); - - } - - if ( dirtyNormals && normalType ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - vertexNormals = face.vertexNormals; - faceNormal = face.normal; - - if ( vertexNormals.length === 3 && needsSmoothNormals ) { - - for ( i = 0; i < 3; i ++ ) { - - vn = vertexNormals[ i ]; - - normalArray[ offset_normal ] = vn.x; - normalArray[ offset_normal + 1 ] = vn.y; - normalArray[ offset_normal + 2 ] = vn.z; - - offset_normal += 3; - - } - - } else { - - for ( i = 0; i < 3; i ++ ) { - - normalArray[ offset_normal ] = faceNormal.x; - normalArray[ offset_normal + 1 ] = faceNormal.y; - normalArray[ offset_normal + 2 ] = faceNormal.z; - - offset_normal += 3; - - } - - } - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint ); - - } - - if ( dirtyUvs && obj_uvs && uvType ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - fi = chunk_faces3[ f ]; - - uv = obj_uvs[ fi ]; - - if ( uv === undefined ) continue; - - for ( i = 0; i < 3; i ++ ) { - - uvi = uv[ i ]; - - uvArray[ offset_uv ] = uvi.x; - uvArray[ offset_uv + 1 ] = uvi.y; - - offset_uv += 2; - - } - - } - - if ( offset_uv > 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint ); - - } - - } - - if ( dirtyUvs && obj_uvs2 && uvType ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - fi = chunk_faces3[ f ]; - - uv2 = obj_uvs2[ fi ]; - - if ( uv2 === undefined ) continue; - - for ( i = 0; i < 3; i ++ ) { - - uv2i = uv2[ i ]; - - uv2Array[ offset_uv2 ] = uv2i.x; - uv2Array[ offset_uv2 + 1 ] = uv2i.y; - - offset_uv2 += 2; - - } - - } - - if ( offset_uv2 > 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint ); - - } - - } - - if ( dirtyElements ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - faceArray[ offset_face ] = vertexIndex; - faceArray[ offset_face + 1 ] = vertexIndex + 1; - faceArray[ offset_face + 2 ] = vertexIndex + 2; - - offset_face += 3; - - lineArray[ offset_line ] = vertexIndex; - lineArray[ offset_line + 1 ] = vertexIndex + 1; - - lineArray[ offset_line + 2 ] = vertexIndex; - lineArray[ offset_line + 3 ] = vertexIndex + 2; - - lineArray[ offset_line + 4 ] = vertexIndex + 1; - lineArray[ offset_line + 5 ] = vertexIndex + 2; - - offset_line += 6; - - vertexIndex += 3; - - } - - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint ); - - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint ); - - } - - if ( customAttributes ) { - - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - - customAttribute = customAttributes[ i ]; - - if ( ! customAttribute.__original.needsUpdate ) continue; - - offset_custom = 0; - offset_customSrc = 0; - - if ( customAttribute.size === 1 ) { - - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; - customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; - customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; - - offset_custom += 3; - - } - - } else if ( customAttribute.boundTo === "faces" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - value = customAttribute.value[ chunk_faces3[ f ] ]; - - customAttribute.array[ offset_custom ] = value; - customAttribute.array[ offset_custom + 1 ] = value; - customAttribute.array[ offset_custom + 2 ] = value; - - offset_custom += 3; - - } - - } - - } else if ( customAttribute.size === 2 ) { - - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - v1 = customAttribute.value[ face.a ]; - v2 = customAttribute.value[ face.b ]; - v3 = customAttribute.value[ face.c ]; - - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; - - customAttribute.array[ offset_custom + 2 ] = v2.x; - customAttribute.array[ offset_custom + 3 ] = v2.y; - - customAttribute.array[ offset_custom + 4 ] = v3.x; - customAttribute.array[ offset_custom + 5 ] = v3.y; - - offset_custom += 6; - - } - - } else if ( customAttribute.boundTo === "faces" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - value = customAttribute.value[ chunk_faces3[ f ] ]; - - v1 = value; - v2 = value; - v3 = value; - - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; - - customAttribute.array[ offset_custom + 2 ] = v2.x; - customAttribute.array[ offset_custom + 3 ] = v2.y; - - customAttribute.array[ offset_custom + 4 ] = v3.x; - customAttribute.array[ offset_custom + 5 ] = v3.y; - - offset_custom += 6; - - } - - } - - } else if ( customAttribute.size === 3 ) { - - var pp; - - if ( customAttribute.type === "c" ) { - - pp = [ "r", "g", "b" ]; - - } else { - - pp = [ "x", "y", "z" ]; - - } - - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - v1 = customAttribute.value[ face.a ]; - v2 = customAttribute.value[ face.b ]; - v3 = customAttribute.value[ face.c ]; - - customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - - customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; - - customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; - - offset_custom += 9; - - } - - } else if ( customAttribute.boundTo === "faces" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - value = customAttribute.value[ chunk_faces3[ f ] ]; - - v1 = value; - v2 = value; - v3 = value; - - customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - - customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; - - customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; - - offset_custom += 9; - - } - - } else if ( customAttribute.boundTo === "faceVertices" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - value = customAttribute.value[ chunk_faces3[ f ] ]; - - v1 = value[ 0 ]; - v2 = value[ 1 ]; - v3 = value[ 2 ]; - - customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - - customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; - - customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; - - offset_custom += 9; - - } - - } - - } else if ( customAttribute.size === 4 ) { - - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - face = obj_faces[ chunk_faces3[ f ] ]; - - v1 = customAttribute.value[ face.a ]; - v2 = customAttribute.value[ face.b ]; - v3 = customAttribute.value[ face.c ]; - - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; - customAttribute.array[ offset_custom + 2 ] = v1.z; - customAttribute.array[ offset_custom + 3 ] = v1.w; - - customAttribute.array[ offset_custom + 4 ] = v2.x; - customAttribute.array[ offset_custom + 5 ] = v2.y; - customAttribute.array[ offset_custom + 6 ] = v2.z; - customAttribute.array[ offset_custom + 7 ] = v2.w; - - customAttribute.array[ offset_custom + 8 ] = v3.x; - customAttribute.array[ offset_custom + 9 ] = v3.y; - customAttribute.array[ offset_custom + 10 ] = v3.z; - customAttribute.array[ offset_custom + 11 ] = v3.w; - - offset_custom += 12; - - } - - } else if ( customAttribute.boundTo === "faces" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - value = customAttribute.value[ chunk_faces3[ f ] ]; - - v1 = value; - v2 = value; - v3 = value; - - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; - customAttribute.array[ offset_custom + 2 ] = v1.z; - customAttribute.array[ offset_custom + 3 ] = v1.w; - - customAttribute.array[ offset_custom + 4 ] = v2.x; - customAttribute.array[ offset_custom + 5 ] = v2.y; - customAttribute.array[ offset_custom + 6 ] = v2.z; - customAttribute.array[ offset_custom + 7 ] = v2.w; - - customAttribute.array[ offset_custom + 8 ] = v3.x; - customAttribute.array[ offset_custom + 9 ] = v3.y; - customAttribute.array[ offset_custom + 10 ] = v3.z; - customAttribute.array[ offset_custom + 11 ] = v3.w; - - offset_custom += 12; - - } - - } else if ( customAttribute.boundTo === "faceVertices" ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - - value = customAttribute.value[ chunk_faces3[ f ] ]; - - v1 = value[ 0 ]; - v2 = value[ 1 ]; - v3 = value[ 2 ]; - - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; - customAttribute.array[ offset_custom + 2 ] = v1.z; - customAttribute.array[ offset_custom + 3 ] = v1.w; - - customAttribute.array[ offset_custom + 4 ] = v2.x; - customAttribute.array[ offset_custom + 5 ] = v2.y; - customAttribute.array[ offset_custom + 6 ] = v2.z; - customAttribute.array[ offset_custom + 7 ] = v2.w; - - customAttribute.array[ offset_custom + 8 ] = v3.x; - customAttribute.array[ offset_custom + 9 ] = v3.y; - customAttribute.array[ offset_custom + 10 ] = v3.z; - customAttribute.array[ offset_custom + 11 ] = v3.w; - - offset_custom += 12; - - } - - } - - } - - _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); - - } - - } - - if ( dispose ) { - - delete geometryGroup.__inittedArrays; - delete geometryGroup.__colorArray; - delete geometryGroup.__normalArray; - delete geometryGroup.__tangentArray; - delete geometryGroup.__uvArray; - delete geometryGroup.__uv2Array; - delete geometryGroup.__faceArray; - delete geometryGroup.__vertexArray; - delete geometryGroup.__lineArray; - delete geometryGroup.__skinIndexArray; - delete geometryGroup.__skinWeightArray; - - } - - }; - - // used by renderBufferDirect for THREE.Line - function setupLinesVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) { - - var attributeItem, attributeName, attributePointer, attributeSize; - - for ( attributeName in programAttributes ) { - - attributePointer = programAttributes[ attributeName ]; - attributeItem = geometryAttributes[ attributeName ]; - - if ( attributePointer >= 0 ) { - - if ( attributeItem ) { - - attributeSize = attributeItem.itemSize; - _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); - enableAttribute( attributePointer ); - _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32 - - } else if ( material.defaultAttributeValues ) { - - if ( material.defaultAttributeValues[ attributeName ].length === 2 ) { - - _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - - } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) { - - _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - - } - - } - - } - - } - - } - - function setDirectBuffers( geometry, hint ) { - - var attributes = geometry.attributes; - - var attributeName, attributeItem; - - for ( attributeName in attributes ) { - - attributeItem = attributes[ attributeName ]; - - if ( attributeItem.needsUpdate ) { - - if ( attributeName === 'index' ) { - - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint ); - - } else { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint ); - - } - - attributeItem.needsUpdate = false; - - } - - } - - } - - // Buffer rendering - - this.renderBufferImmediate = function ( object, program, material ) { - - if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer(); - if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer(); - if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer(); - if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer(); - - if ( object.hasPositions ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); - _gl.enableVertexAttribArray( program.attributes.position ); - _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - - } - - if ( object.hasNormals ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer ); - - if ( material.shading === THREE.FlatShading ) { - - var nx, ny, nz, - nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz, - normalArray, - i, il = object.count * 3; - - for( i = 0; i < il; i += 9 ) { - - normalArray = object.normalArray; - - nax = normalArray[ i ]; - nay = normalArray[ i + 1 ]; - naz = normalArray[ i + 2 ]; - - nbx = normalArray[ i + 3 ]; - nby = normalArray[ i + 4 ]; - nbz = normalArray[ i + 5 ]; - - ncx = normalArray[ i + 6 ]; - ncy = normalArray[ i + 7 ]; - ncz = normalArray[ i + 8 ]; - - nx = ( nax + nbx + ncx ) / 3; - ny = ( nay + nby + ncy ) / 3; - nz = ( naz + nbz + ncz ) / 3; - - normalArray[ i ] = nx; - normalArray[ i + 1 ] = ny; - normalArray[ i + 2 ] = nz; - - normalArray[ i + 3 ] = nx; - normalArray[ i + 4 ] = ny; - normalArray[ i + 5 ] = nz; - - normalArray[ i + 6 ] = nx; - normalArray[ i + 7 ] = ny; - normalArray[ i + 8 ] = nz; - - } - - } - - _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); - _gl.enableVertexAttribArray( program.attributes.normal ); - _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - - } - - if ( object.hasUvs && material.map ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); - _gl.enableVertexAttribArray( program.attributes.uv ); - _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - - } - - if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); - _gl.enableVertexAttribArray( program.attributes.color ); - _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - - } - - _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - - object.count = 0; - - }; - - this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) { - - if ( material.visible === false ) return; - - var linewidth, a, attribute; - var attributeItem, attributeName, attributePointer, attributeSize; - - var program = setProgram( camera, lights, fog, material, object ); - - var programAttributes = program.attributes; - var geometryAttributes = geometry.attributes; - - var updateBuffers = false, - wireframeBit = material.wireframe ? 1 : 0, - geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; - - if ( geometryHash !== _currentGeometryGroupHash ) { - - _currentGeometryGroupHash = geometryHash; - updateBuffers = true; - - } - - if ( updateBuffers ) { - - disableAttributes(); - - } - - // render mesh - - if ( object instanceof THREE.Mesh ) { - - var index = geometryAttributes[ "index" ]; - - // indexed triangles - - if ( index ) { - - var offsets = geometry.offsets; - - // if there is more than 1 chunk - // must set attribute pointers to use new offsets for each chunk - // even if geometry and materials didn't change - - if ( offsets.length > 1 ) updateBuffers = true; - - for ( var i = 0, il = offsets.length; i < il; i ++ ) { - - var startIndex = offsets[ i ].index; - - if ( updateBuffers ) { - - for ( attributeName in programAttributes ) { - - attributePointer = programAttributes[ attributeName ]; - attributeItem = geometryAttributes[ attributeName ]; - - if ( attributePointer >= 0 ) { - - if ( attributeItem ) { - - attributeSize = attributeItem.itemSize; - _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); - enableAttribute( attributePointer ); - _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32 - - } else if ( material.defaultAttributeValues ) { - - if ( material.defaultAttributeValues[ attributeName ].length === 2 ) { - - _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - - } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) { - - _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - - } - - } - - } - - } - - // indices - - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - - } - - // render indexed triangles - - _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16 - - _this.info.render.calls ++; - _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared - _this.info.render.faces += offsets[ i ].count / 3; - - } - - // non-indexed triangles - - } else { - - if ( updateBuffers ) { - - for ( attributeName in programAttributes ) { - - if ( attributeName === 'index') continue; - - attributePointer = programAttributes[ attributeName ]; - attributeItem = geometryAttributes[ attributeName ]; - - if ( attributePointer >= 0 ) { - - if ( attributeItem ) { - - attributeSize = attributeItem.itemSize; - _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); - enableAttribute( attributePointer ); - _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 ); - - } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) { - - if ( material.defaultAttributeValues[ attributeName ].length === 2 ) { - - _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - - } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) { - - _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - - } - - } - - } - - } - - } - - var position = geometry.attributes[ "position" ]; - - // render non-indexed triangles - - _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 ); - - _this.info.render.calls ++; - _this.info.render.vertices += position.array.length / 3; - _this.info.render.faces += position.array.length / 3 / 3; - - } - - // render particles - - } else if ( object instanceof THREE.ParticleSystem ) { - - if ( updateBuffers ) { - - for ( attributeName in programAttributes ) { - - attributePointer = programAttributes[ attributeName ]; - attributeItem = geometryAttributes[ attributeName ]; - - if ( attributePointer >= 0 ) { - - if ( attributeItem ) { - - attributeSize = attributeItem.itemSize; - _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); - enableAttribute( attributePointer ); - _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 ); - - } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) { - - if ( material.defaultAttributeValues[ attributeName ].length === 2 ) { - - _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - - } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) { - - _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); - - } - - } - - } - - } - - } - - var position = geometryAttributes[ "position" ]; - - // render particles - - _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 ); - - _this.info.render.calls ++; - _this.info.render.points += position.array.length / 3; - - } else if ( object instanceof THREE.Line ) { - - var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; - - setLineWidth( material.linewidth ); - - var index = geometryAttributes[ "index" ]; - - // indexed lines - - if ( index ) { - - var offsets = geometry.offsets; - - // if there is more than 1 chunk - // must set attribute pointers to use new offsets for each chunk - // even if geometry and materials didn't change - - if ( offsets.length > 1 ) updateBuffers = true; - - for ( var i = 0, il = offsets.length; i < il; i ++ ) { - - var startIndex = offsets[ i ].index; - - if ( updateBuffers ) { - - setupLinesVertexAttributes(material, programAttributes, geometryAttributes, startIndex); - - // indices - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - - } - - // render indexed lines - - _gl.drawElements( _gl.LINES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16Array - - _this.info.render.calls ++; - _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared - - } - - } - - // non-indexed lines - - else { - - if ( updateBuffers ) { - - setupLinesVertexAttributes(material, programAttributes, geometryAttributes, 0); - } - - var position = geometryAttributes[ "position" ]; - - _gl.drawArrays( primitives, 0, position.array.length / 3 ); - _this.info.render.calls ++; - _this.info.render.points += position.array.length; - } - - - - } - - }; - - this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) { - - if ( material.visible === false ) return; - - var linewidth, a, attribute, i, il; - - var program = setProgram( camera, lights, fog, material, object ); - - var attributes = program.attributes; - - var updateBuffers = false, - wireframeBit = material.wireframe ? 1 : 0, - geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; - - if ( geometryGroupHash !== _currentGeometryGroupHash ) { - - _currentGeometryGroupHash = geometryGroupHash; - updateBuffers = true; - - } - - if ( updateBuffers ) { - - disableAttributes(); - - } - - // vertices - - if ( !material.morphTargets && attributes.position >= 0 ) { - - if ( updateBuffers ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - - } - - } else { - - if ( object.morphTargetBase ) { - - setupMorphTargets( material, geometryGroup, object ); - - } - - } - - - if ( updateBuffers ) { - - // custom attributes - - // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers - - if ( geometryGroup.__webglCustomAttributesList ) { - - for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) { - - attribute = geometryGroup.__webglCustomAttributesList[ i ]; - - if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer ); - enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] ); - _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 ); - - } - - } - - } - - - // colors - - if ( attributes.color >= 0 ) { - - if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); - enableAttribute( attributes.color ); - _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - - } else if ( material.defaultAttributeValues ) { - - - _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color ); - - } - - } - - // normals - - if ( attributes.normal >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); - enableAttribute( attributes.normal ); - _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - - } - - // tangents - - if ( attributes.tangent >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); - enableAttribute( attributes.tangent ); - _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 ); - - } - - // uvs - - if ( attributes.uv >= 0 ) { - - if ( object.geometry.faceVertexUvs[0] ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); - enableAttribute( attributes.uv ); - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - - } else if ( material.defaultAttributeValues ) { - - - _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv ); - - } - - } - - if ( attributes.uv2 >= 0 ) { - - if ( object.geometry.faceVertexUvs[1] ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); - enableAttribute( attributes.uv2 ); - _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 ); - - } else if ( material.defaultAttributeValues ) { - - - _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 ); - - } - - } - - if ( material.skinning && - attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); - enableAttribute( attributes.skinIndex ); - _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 ); - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); - enableAttribute( attributes.skinWeight ); - _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 ); - - } - - // line distances - - if ( attributes.lineDistance >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer ); - enableAttribute( attributes.lineDistance ); - _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 ); - - } - - } - - // render mesh - - if ( object instanceof THREE.Mesh ) { - - // wireframe - - if ( material.wireframe ) { - - setLineWidth( material.wireframeLinewidth ); - - if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); - _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 ); - - // triangles - - } else { - - if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); - _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 ); - - } - - _this.info.render.calls ++; - _this.info.render.vertices += geometryGroup.__webglFaceCount; - _this.info.render.faces += geometryGroup.__webglFaceCount / 3; - - // render lines - - } else if ( object instanceof THREE.Line ) { - - var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; - - setLineWidth( material.linewidth ); - - _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount ); - - _this.info.render.calls ++; - - // render particles - - } else if ( object instanceof THREE.ParticleSystem ) { - - _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount ); - - _this.info.render.calls ++; - _this.info.render.points += geometryGroup.__webglParticleCount; - - } - - }; - - function enableAttribute( attribute ) { - - if ( _enabledAttributes[ attribute ] === 0 ) { - - _gl.enableVertexAttribArray( attribute ); - _enabledAttributes[ attribute ] = 1; - - } - - }; - - function disableAttributes() { - - for ( var attribute in _enabledAttributes ) { - - if ( _enabledAttributes[ attribute ] === 1 ) { - - _gl.disableVertexAttribArray( attribute ); - _enabledAttributes[ attribute ] = 0; - - } - - } - - }; - - function setupMorphTargets ( material, geometryGroup, object ) { - - // set base - - var attributes = material.program.attributes; - - if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] ); - enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - - } else if ( attributes.position >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - - } - - if ( object.morphTargetForcedOrder.length ) { - - // set forced order - - var m = 0; - var order = object.morphTargetForcedOrder; - var influences = object.morphTargetInfluences; - - while ( m < material.numSupportedMorphTargets && m < order.length ) { - - if ( attributes[ "morphTarget" + m ] >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] ); - enableAttribute( attributes[ "morphTarget" + m ] ); - _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); - - } - - if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] ); - enableAttribute( attributes[ "morphNormal" + m ] ); - _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); - - } - - object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ]; - - m ++; - } - - } else { - - // find the most influencing - - var influence, activeInfluenceIndices = []; - var influences = object.morphTargetInfluences; - var i, il = influences.length; - - for ( i = 0; i < il; i ++ ) { - - influence = influences[ i ]; - - if ( influence > 0 ) { - - activeInfluenceIndices.push( [ influence, i ] ); - - } - - } - - if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) { - - activeInfluenceIndices.sort( numericalSort ); - activeInfluenceIndices.length = material.numSupportedMorphTargets; - - } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) { - - activeInfluenceIndices.sort( numericalSort ); - - } else if ( activeInfluenceIndices.length === 0 ) { - - activeInfluenceIndices.push( [ 0, 0 ] ); - - }; - - var influenceIndex, m = 0; - - while ( m < material.numSupportedMorphTargets ) { - - if ( activeInfluenceIndices[ m ] ) { - - influenceIndex = activeInfluenceIndices[ m ][ 1 ]; - - if ( attributes[ "morphTarget" + m ] >= 0 ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] ); - enableAttribute( attributes[ "morphTarget" + m ] ); - _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); - - } - - if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) { - - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] ); - enableAttribute( attributes[ "morphNormal" + m ] ); - _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); - - - } - - object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ]; - - } else { - - /* - _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); - - if ( material.morphNormals ) { - - _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); - - } - */ - - object.__webglMorphTargetInfluences[ m ] = 0; - - } - - m ++; - - } - - } - - // load updated influences uniform - - if ( material.program.uniforms.morphTargetInfluences !== null ) { - - _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences ); - - } - - }; - - // Sorting - - function painterSortStable ( a, b ) { - - if ( a.z !== b.z ) { - - return b.z - a.z; - - } else { - - return a.id - b.id; - - } - - }; - - function numericalSort ( a, b ) { - - return b[ 0 ] - a[ 0 ]; - - }; - - - // Rendering - - this.render = function ( scene, camera, renderTarget, forceClear ) { - - if ( camera instanceof THREE.Camera === false ) { - - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; - - } - - var i, il, - - webglObject, object, - renderList, - - lights = scene.__lights, - fog = scene.fog; - - // reset caching for this frame - - _currentMaterialId = -1; - _lightsNeedUpdate = true; - - // update scene graph - - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - - // update camera matrices and frustum - - if ( camera.parent === undefined ) camera.updateMatrixWorld(); - - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); - - // update WebGL objects - - if ( this.autoUpdateObjects ) this.initWebGLObjects( scene ); - - // custom render plugins (pre pass) - - renderPlugins( this.renderPluginsPre, scene, camera ); - - // - - _this.info.render.calls = 0; - _this.info.render.vertices = 0; - _this.info.render.faces = 0; - _this.info.render.points = 0; - - this.setRenderTarget( renderTarget ); - - if ( this.autoClear || forceClear ) { - - this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); - - } - - // set matrices for regular objects (frustum culled) - - renderList = scene.__webglObjects; - - for ( i = 0, il = renderList.length; i < il; i ++ ) { - - webglObject = renderList[ i ]; - object = webglObject.object; - - webglObject.id = i; - webglObject.render = false; - - if ( object.visible ) { - - if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) { - - setupMatrices( object, camera ); - - unrollBufferMaterial( webglObject ); - - webglObject.render = true; - - if ( this.sortObjects === true ) { - - if ( object.renderDepth !== null ) { - - webglObject.z = object.renderDepth; - - } else { - - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); - - webglObject.z = _vector3.z; - - } - - } - - } - - } - - } - - if ( this.sortObjects ) { - - renderList.sort( painterSortStable ); - - } - - // set matrices for immediate objects - - renderList = scene.__webglObjectsImmediate; - - for ( i = 0, il = renderList.length; i < il; i ++ ) { - - webglObject = renderList[ i ]; - object = webglObject.object; - - if ( object.visible ) { - - setupMatrices( object, camera ); - - unrollImmediateBufferMaterial( webglObject ); - - } - - } - - if ( scene.overrideMaterial ) { - - var material = scene.overrideMaterial; - - this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - this.setDepthTest( material.depthTest ); - this.setDepthWrite( material.depthWrite ); - setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - - renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material ); - renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material ); - - } else { - - var material = null; - - // opaque pass (front-to-back order) - - this.setBlending( THREE.NoBlending ); - - renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material ); - renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material ); - - // transparent pass (back-to-front order) - - renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material ); - renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material ); - - } - - // custom render plugins (post pass) - - renderPlugins( this.renderPluginsPost, scene, camera ); - - - // Generate mipmap if we're using any kind of mipmap filtering - - if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) { - - updateRenderTargetMipmap( renderTarget ); - - } - - // Ensure depth buffer writing is enabled so it can be cleared on next render - - this.setDepthTest( true ); - this.setDepthWrite( true ); - - // _gl.finish(); - - }; - - function renderPlugins( plugins, scene, camera ) { - - if ( ! plugins.length ) return; - - for ( var i = 0, il = plugins.length; i < il; i ++ ) { - - // reset state for plugin (to start from clean slate) - - _currentProgram = null; - _currentCamera = null; - - _oldBlending = -1; - _oldDepthTest = -1; - _oldDepthWrite = -1; - _oldDoubleSided = -1; - _oldFlipSided = -1; - _currentGeometryGroupHash = -1; - _currentMaterialId = -1; - - _lightsNeedUpdate = true; - - plugins[ i ].render( scene, camera, _currentWidth, _currentHeight ); - - // reset state after plugin (anything could have changed) - - _currentProgram = null; - _currentCamera = null; - - _oldBlending = -1; - _oldDepthTest = -1; - _oldDepthWrite = -1; - _oldDoubleSided = -1; - _oldFlipSided = -1; - _currentGeometryGroupHash = -1; - _currentMaterialId = -1; - - _lightsNeedUpdate = true; - - } - - }; - - function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) { - - var webglObject, object, buffer, material, start, end, delta; - - if ( reverse ) { - - start = renderList.length - 1; - end = -1; - delta = -1; - - } else { - - start = 0; - end = renderList.length; - delta = 1; - } - - for ( var i = start; i !== end; i += delta ) { - - webglObject = renderList[ i ]; - - if ( webglObject.render ) { - - object = webglObject.object; - buffer = webglObject.buffer; - - if ( overrideMaterial ) { - - material = overrideMaterial; - - } else { - - material = webglObject[ materialType ]; - - if ( ! material ) continue; - - if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - - _this.setDepthTest( material.depthTest ); - _this.setDepthWrite( material.depthWrite ); - setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - - } - - _this.setMaterialFaces( material ); - - if ( buffer instanceof THREE.BufferGeometry ) { - - _this.renderBufferDirect( camera, lights, fog, material, buffer, object ); - - } else { - - _this.renderBuffer( camera, lights, fog, material, buffer, object ); - - } - - } - - } - - }; - - function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) { - - var webglObject, object, material, program; - - for ( var i = 0, il = renderList.length; i < il; i ++ ) { - - webglObject = renderList[ i ]; - object = webglObject.object; - - if ( object.visible ) { - - if ( overrideMaterial ) { - - material = overrideMaterial; - - } else { - - material = webglObject[ materialType ]; - - if ( ! material ) continue; - - if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - - _this.setDepthTest( material.depthTest ); - _this.setDepthWrite( material.depthWrite ); - setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - - } - - _this.renderImmediateObject( camera, lights, fog, material, object ); - - } - - } - - }; - - this.renderImmediateObject = function ( camera, lights, fog, material, object ) { - - var program = setProgram( camera, lights, fog, material, object ); - - _currentGeometryGroupHash = -1; - - _this.setMaterialFaces( material ); - - if ( object.immediateRenderCallback ) { - - object.immediateRenderCallback( program, _gl, _frustum ); - - } else { - - object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } ); - - } - - }; - - function unrollImmediateBufferMaterial ( globject ) { - - var object = globject.object, - material = object.material; - - if ( material.transparent ) { - - globject.transparent = material; - globject.opaque = null; - - } else { - - globject.opaque = material; - globject.transparent = null; - - } - - }; - - function unrollBufferMaterial ( globject ) { - - var object = globject.object; - var buffer = globject.buffer; - - var geometry = object.geometry; - var material = object.material; - - if ( material instanceof THREE.MeshFaceMaterial ) { - - var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex; - - material = material.materials[ materialIndex ]; - - if ( material.transparent ) { - - globject.transparent = material; - globject.opaque = null; - - } else { - - globject.opaque = material; - globject.transparent = null; - - } - - } else { - - if ( material ) { - - if ( material.transparent ) { - - globject.transparent = material; - globject.opaque = null; - - } else { - - globject.opaque = material; - globject.transparent = null; - - } - - } - - } - - }; - - // Objects refresh - - this.initWebGLObjects = function ( scene ) { - - if ( !scene.__webglObjects ) { - - scene.__webglObjects = []; - scene.__webglObjectsImmediate = []; - scene.__webglSprites = []; - scene.__webglFlares = []; - - } - - while ( scene.__objectsAdded.length ) { - - addObject( scene.__objectsAdded[ 0 ], scene ); - scene.__objectsAdded.splice( 0, 1 ); - - } - - while ( scene.__objectsRemoved.length ) { - - removeObject( scene.__objectsRemoved[ 0 ], scene ); - scene.__objectsRemoved.splice( 0, 1 ); - - } - - // update must be called after objects adding / removal - - for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) { - - var object = scene.__webglObjects[ o ].object; - - // TODO: Remove this hack (WebGLRenderer refactoring) - - if ( object.__webglInit === undefined ) { - - if ( object.__webglActive !== undefined ) { - - removeObject( object, scene ); - - } - - addObject( object, scene ); - - } - - updateObject( object ); - - } - - }; - - // Objects adding - - function addObject( object, scene ) { - - var g, geometry, material, geometryGroup; - - if ( object.__webglInit === undefined ) { - - object.__webglInit = true; - - object._modelViewMatrix = new THREE.Matrix4(); - object._normalMatrix = new THREE.Matrix3(); - - if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) { - - object.geometry.__webglInit = true; - object.geometry.addEventListener( 'dispose', onGeometryDispose ); - - } - - geometry = object.geometry; - - if ( geometry === undefined ) { - - // fail silently for now - - } else if ( geometry instanceof THREE.BufferGeometry ) { - - initDirectBuffers( geometry ); - - } else if ( object instanceof THREE.Mesh ) { - - material = object.material; - - if ( geometry.geometryGroups === undefined ) { - - geometry.makeGroups( material instanceof THREE.MeshFaceMaterial ); - - } - - // create separate VBOs per geometry chunk - - for ( g in geometry.geometryGroups ) { - - geometryGroup = geometry.geometryGroups[ g ]; - - // initialise VBO on the first access - - if ( ! geometryGroup.__webglVertexBuffer ) { - - createMeshBuffers( geometryGroup ); - initMeshBuffers( geometryGroup, object ); - - geometry.verticesNeedUpdate = true; - geometry.morphTargetsNeedUpdate = true; - geometry.elementsNeedUpdate = true; - geometry.uvsNeedUpdate = true; - geometry.normalsNeedUpdate = true; - geometry.tangentsNeedUpdate = true; - geometry.colorsNeedUpdate = true; - - } - - } - - } else if ( object instanceof THREE.Line ) { - - if ( ! geometry.__webglVertexBuffer ) { - - createLineBuffers( geometry ); - initLineBuffers( geometry, object ); - - geometry.verticesNeedUpdate = true; - geometry.colorsNeedUpdate = true; - geometry.lineDistancesNeedUpdate = true; - - } - - } else if ( object instanceof THREE.ParticleSystem ) { - - if ( ! geometry.__webglVertexBuffer ) { - - createParticleBuffers( geometry ); - initParticleBuffers( geometry, object ); - - geometry.verticesNeedUpdate = true; - geometry.colorsNeedUpdate = true; - - } - - } - - } - - if ( object.__webglActive === undefined ) { - - if ( object instanceof THREE.Mesh ) { - - geometry = object.geometry; - - if ( geometry instanceof THREE.BufferGeometry ) { - - addBuffer( scene.__webglObjects, geometry, object ); - - } else if ( geometry instanceof THREE.Geometry ) { - - for ( g in geometry.geometryGroups ) { - - geometryGroup = geometry.geometryGroups[ g ]; - - addBuffer( scene.__webglObjects, geometryGroup, object ); - - } - - } - - } else if ( object instanceof THREE.Line || - object instanceof THREE.ParticleSystem ) { - - geometry = object.geometry; - addBuffer( scene.__webglObjects, geometry, object ); - - } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { - - addBufferImmediate( scene.__webglObjectsImmediate, object ); - - } else if ( object instanceof THREE.Sprite ) { - - scene.__webglSprites.push( object ); - - } else if ( object instanceof THREE.LensFlare ) { - - scene.__webglFlares.push( object ); - - } - - object.__webglActive = true; - - } - - }; - - function addBuffer( objlist, buffer, object ) { - - objlist.push( - { - id: null, - buffer: buffer, - object: object, - opaque: null, - transparent: null, - z: 0 - } - ); - - }; - - function addBufferImmediate( objlist, object ) { - - objlist.push( - { - id: null, - object: object, - opaque: null, - transparent: null, - z: 0 - } - ); - - }; - - // Objects updates - - function updateObject( object ) { - - var geometry = object.geometry, - geometryGroup, customAttributesDirty, material; - - if ( geometry instanceof THREE.BufferGeometry ) { - - setDirectBuffers( geometry, _gl.DYNAMIC_DRAW ); - - } else if ( object instanceof THREE.Mesh ) { - - // check all geometry groups - - for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) { - - geometryGroup = geometry.geometryGroupsList[ i ]; - - material = getBufferMaterial( object, geometryGroup ); - - if ( geometry.buffersNeedUpdate ) { - - initMeshBuffers( geometryGroup, object ); - - } - - customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); - - if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate || - geometry.uvsNeedUpdate || geometry.normalsNeedUpdate || - geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) { - - setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material ); - - } - - } - - geometry.verticesNeedUpdate = false; - geometry.morphTargetsNeedUpdate = false; - geometry.elementsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.tangentsNeedUpdate = false; - - geometry.buffersNeedUpdate = false; - - material.attributes && clearCustomAttributes( material ); - - } else if ( object instanceof THREE.Line ) { - - material = getBufferMaterial( object, geometry ); - - customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); - - if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) { - - setLineBuffers( geometry, _gl.DYNAMIC_DRAW ); - - } - - geometry.verticesNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.lineDistancesNeedUpdate = false; - - material.attributes && clearCustomAttributes( material ); - - - } else if ( object instanceof THREE.ParticleSystem ) { - - material = getBufferMaterial( object, geometry ); - - customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); - - if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) { - - setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object ); - - } - - geometry.verticesNeedUpdate = false; - geometry.colorsNeedUpdate = false; - - material.attributes && clearCustomAttributes( material ); - - } - - }; - - // Objects updates - custom attributes check - - function areCustomAttributesDirty( material ) { - - for ( var a in material.attributes ) { - - if ( material.attributes[ a ].needsUpdate ) return true; - - } - - return false; - - }; - - function clearCustomAttributes( material ) { - - for ( var a in material.attributes ) { - - material.attributes[ a ].needsUpdate = false; - - } - - }; - - // Objects removal - - function removeObject( object, scene ) { - - if ( object instanceof THREE.Mesh || - object instanceof THREE.ParticleSystem || - object instanceof THREE.Line ) { - - removeInstances( scene.__webglObjects, object ); - - } else if ( object instanceof THREE.Sprite ) { - - removeInstancesDirect( scene.__webglSprites, object ); - - } else if ( object instanceof THREE.LensFlare ) { - - removeInstancesDirect( scene.__webglFlares, object ); - - } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { - - removeInstances( scene.__webglObjectsImmediate, object ); - - } - - delete object.__webglActive; - - }; - - function removeInstances( objlist, object ) { - - for ( var o = objlist.length - 1; o >= 0; o -- ) { - - if ( objlist[ o ].object === object ) { - - objlist.splice( o, 1 ); - - } - - } - - }; - - function removeInstancesDirect( objlist, object ) { - - for ( var o = objlist.length - 1; o >= 0; o -- ) { - - if ( objlist[ o ] === object ) { - - objlist.splice( o, 1 ); - - } - - } - - }; - - // Materials - - this.initMaterial = function ( material, lights, fog, object ) { - - material.addEventListener( 'dispose', onMaterialDispose ); - - var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID; - - if ( material instanceof THREE.MeshDepthMaterial ) { - - shaderID = 'depth'; - - } else if ( material instanceof THREE.MeshNormalMaterial ) { - - shaderID = 'normal'; - - } else if ( material instanceof THREE.MeshBasicMaterial ) { - - shaderID = 'basic'; - - } else if ( material instanceof THREE.MeshLambertMaterial ) { - - shaderID = 'lambert'; - - } else if ( material instanceof THREE.MeshPhongMaterial ) { - - shaderID = 'phong'; - - } else if ( material instanceof THREE.LineBasicMaterial ) { - - shaderID = 'basic'; - - } else if ( material instanceof THREE.LineDashedMaterial ) { - - shaderID = 'dashed'; - - } else if ( material instanceof THREE.ParticleSystemMaterial ) { - - shaderID = 'particle_basic'; - - } - - if ( shaderID ) { - - setMaterialShaders( material, THREE.ShaderLib[ shaderID ] ); - - } - - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) - - maxLightCount = allocateLights( lights ); - - maxShadows = allocateShadows( lights ); - - maxBones = allocateBones( object ); - - parameters = { - - map: !!material.map, - envMap: !!material.envMap, - lightMap: !!material.lightMap, - bumpMap: !!material.bumpMap, - normalMap: !!material.normalMap, - specularMap: !!material.specularMap, - - vertexColors: material.vertexColors, - - fog: fog, - useFog: material.fog, - fogExp: fog instanceof THREE.FogExp2, - - sizeAttenuation: material.sizeAttenuation, - - skinning: material.skinning, - maxBones: maxBones, - useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture, - - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: this.maxMorphTargets, - maxMorphNormals: this.maxMorphNormals, - - maxDirLights: maxLightCount.directional, - maxPointLights: maxLightCount.point, - maxSpotLights: maxLightCount.spot, - maxHemiLights: maxLightCount.hemi, - - maxShadows: maxShadows, - shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0, - shadowMapType: this.shadowMapType, - shadowMapDebug: this.shadowMapDebug, - shadowMapCascade: this.shadowMapCascade, - - alphaTest: material.alphaTest, - metal: material.metal, - wrapAround: material.wrapAround, - doubleSided: material.side === THREE.DoubleSide, - flipSided: material.side === THREE.BackSide - - }; - - material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName ); - - var attributes = material.program.attributes; - - if ( material.morphTargets ) { - - material.numSupportedMorphTargets = 0; - - var id, base = "morphTarget"; - - for ( i = 0; i < this.maxMorphTargets; i ++ ) { - - id = base + i; - - if ( attributes[ id ] >= 0 ) { - - material.numSupportedMorphTargets ++; - - } - - } - - } - - if ( material.morphNormals ) { - - material.numSupportedMorphNormals = 0; - - var id, base = "morphNormal"; - - for ( i = 0; i < this.maxMorphNormals; i ++ ) { - - id = base + i; - - if ( attributes[ id ] >= 0 ) { - - material.numSupportedMorphNormals ++; - - } - - } - - } - - material.uniformsList = []; - - for ( u in material.uniforms ) { - - material.uniformsList.push( [ material.uniforms[ u ], u ] ); - - } - - }; - - function setMaterialShaders( material, shaders ) { - - material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms ); - material.vertexShader = shaders.vertexShader; - material.fragmentShader = shaders.fragmentShader; - - }; - - function setProgram( camera, lights, fog, material, object ) { - - _usedTextureUnits = 0; - - if ( material.needsUpdate ) { - - if ( material.program ) deallocateMaterial( material ); - - _this.initMaterial( material, lights, fog, object ); - material.needsUpdate = false; - - } - - if ( material.morphTargets ) { - - if ( ! object.__webglMorphTargetInfluences ) { - - object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets ); - - } - - } - - var refreshMaterial = false; - - var program = material.program, - p_uniforms = program.uniforms, - m_uniforms = material.uniforms; - - if ( program !== _currentProgram ) { - - _gl.useProgram( program ); - _currentProgram = program; - - refreshMaterial = true; - - } - - if ( material.id !== _currentMaterialId ) { - - _currentMaterialId = material.id; - refreshMaterial = true; - - } - - if ( refreshMaterial || camera !== _currentCamera ) { - - _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - - if ( camera !== _currentCamera ) _currentCamera = camera; - - } - - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // not sure why, but otherwise weird things happen - - if ( material.skinning ) { - - if ( _supportsBoneTextures && object.useVertexTexture ) { - - if ( p_uniforms.boneTexture !== null ) { - - var textureUnit = getTextureUnit(); - - _gl.uniform1i( p_uniforms.boneTexture, textureUnit ); - _this.setTexture( object.boneTexture, textureUnit ); - - } - - if ( p_uniforms.boneTextureWidth !== null ) { - - _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth ); - - } - - if ( p_uniforms.boneTextureHeight !== null ) { - - _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight ); - - } - - } else { - - if ( p_uniforms.boneGlobalMatrices !== null ) { - - _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices ); - - } - - } - - } - - if ( refreshMaterial ) { - - // refresh uniforms common to several materials - - if ( fog && material.fog ) { - - refreshUniformsFog( m_uniforms, fog ); - - } - - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material.lights ) { - - if ( _lightsNeedUpdate ) { - - setupLights( program, lights ); - _lightsNeedUpdate = false; - - } - - refreshUniformsLights( m_uniforms, _lights ); - - } - - if ( material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshPhongMaterial ) { - - refreshUniformsCommon( m_uniforms, material ); - - } - - // refresh single material specific uniforms - - if ( material instanceof THREE.LineBasicMaterial ) { - - refreshUniformsLine( m_uniforms, material ); - - } else if ( material instanceof THREE.LineDashedMaterial ) { - - refreshUniformsLine( m_uniforms, material ); - refreshUniformsDash( m_uniforms, material ); - - } else if ( material instanceof THREE.ParticleSystemMaterial ) { - - refreshUniformsParticle( m_uniforms, material ); - - } else if ( material instanceof THREE.MeshPhongMaterial ) { - - refreshUniformsPhong( m_uniforms, material ); - - } else if ( material instanceof THREE.MeshLambertMaterial ) { - - refreshUniformsLambert( m_uniforms, material ); - - } else if ( material instanceof THREE.MeshDepthMaterial ) { - - m_uniforms.mNear.value = camera.near; - m_uniforms.mFar.value = camera.far; - m_uniforms.opacity.value = material.opacity; - - } else if ( material instanceof THREE.MeshNormalMaterial ) { - - m_uniforms.opacity.value = material.opacity; - - } - - if ( object.receiveShadow && ! material._shadowPass ) { - - refreshUniformsShadow( m_uniforms, lights ); - - } - - // load common uniforms - - loadUniformsGeneric( program, material.uniformsList ); - - // load material specific uniforms - // (shader material also gets them for the sake of genericity) - - if ( material instanceof THREE.ShaderMaterial || - material instanceof THREE.MeshPhongMaterial || - material.envMap ) { - - if ( p_uniforms.cameraPosition !== null ) { - - _vector3.setFromMatrixPosition( camera.matrixWorld ); - _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z ); - - } - - } - - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.ShaderMaterial || - material.skinning ) { - - if ( p_uniforms.viewMatrix !== null ) { - - _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements ); - - } - - } - - } - - loadUniformsMatrices( p_uniforms, object ); - - if ( p_uniforms.modelMatrix !== null ) { - - _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements ); - - } - - return program; - - }; - - // Uniforms (refresh uniforms objects) - - function refreshUniformsCommon ( uniforms, material ) { - - uniforms.opacity.value = material.opacity; - - if ( _this.gammaInput ) { - - uniforms.diffuse.value.copyGammaToLinear( material.color ); - - } else { - - uniforms.diffuse.value = material.color; - - } - - uniforms.map.value = material.map; - uniforms.lightMap.value = material.lightMap; - uniforms.specularMap.value = material.specularMap; - - if ( material.bumpMap ) { - - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - - } - - if ( material.normalMap ) { - - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - - } - - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - - var uvScaleMap; - - if ( material.map ) { - - uvScaleMap = material.map; - - } else if ( material.specularMap ) { - - uvScaleMap = material.specularMap; - - } else if ( material.normalMap ) { - - uvScaleMap = material.normalMap; - - } else if ( material.bumpMap ) { - - uvScaleMap = material.bumpMap; - - } - - if ( uvScaleMap !== undefined ) { - - var offset = uvScaleMap.offset; - var repeat = uvScaleMap.repeat; - - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - - } - - uniforms.envMap.value = material.envMap; - uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1; - - if ( _this.gammaInput ) { - - //uniforms.reflectivity.value = material.reflectivity * material.reflectivity; - uniforms.reflectivity.value = material.reflectivity; - - } else { - - uniforms.reflectivity.value = material.reflectivity; - - } - - uniforms.refractionRatio.value = material.refractionRatio; - uniforms.combine.value = material.combine; - uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping; - - }; - - function refreshUniformsLine ( uniforms, material ) { - - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; - - }; - - function refreshUniformsDash ( uniforms, material ) { - - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; - - }; - - function refreshUniformsParticle ( uniforms, material ) { - - uniforms.psColor.value = material.color; - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size; - uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this. - - uniforms.map.value = material.map; - - }; - - function refreshUniformsFog ( uniforms, fog ) { - - uniforms.fogColor.value = fog.color; - - if ( fog instanceof THREE.Fog ) { - - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; - - } else if ( fog instanceof THREE.FogExp2 ) { - - uniforms.fogDensity.value = fog.density; - - } - - }; - - function refreshUniformsPhong ( uniforms, material ) { - - uniforms.shininess.value = material.shininess; - - if ( _this.gammaInput ) { - - uniforms.ambient.value.copyGammaToLinear( material.ambient ); - uniforms.emissive.value.copyGammaToLinear( material.emissive ); - uniforms.specular.value.copyGammaToLinear( material.specular ); - - } else { - - uniforms.ambient.value = material.ambient; - uniforms.emissive.value = material.emissive; - uniforms.specular.value = material.specular; - - } - - if ( material.wrapAround ) { - - uniforms.wrapRGB.value.copy( material.wrapRGB ); - - } - - }; - - function refreshUniformsLambert ( uniforms, material ) { - - if ( _this.gammaInput ) { - - uniforms.ambient.value.copyGammaToLinear( material.ambient ); - uniforms.emissive.value.copyGammaToLinear( material.emissive ); - - } else { - - uniforms.ambient.value = material.ambient; - uniforms.emissive.value = material.emissive; - - } - - if ( material.wrapAround ) { - - uniforms.wrapRGB.value.copy( material.wrapRGB ); - - } - - }; - - function refreshUniformsLights ( uniforms, lights ) { - - uniforms.ambientLightColor.value = lights.ambient; - - uniforms.directionalLightColor.value = lights.directional.colors; - uniforms.directionalLightDirection.value = lights.directional.positions; - - uniforms.pointLightColor.value = lights.point.colors; - uniforms.pointLightPosition.value = lights.point.positions; - uniforms.pointLightDistance.value = lights.point.distances; - - uniforms.spotLightColor.value = lights.spot.colors; - uniforms.spotLightPosition.value = lights.spot.positions; - uniforms.spotLightDistance.value = lights.spot.distances; - uniforms.spotLightDirection.value = lights.spot.directions; - uniforms.spotLightAngleCos.value = lights.spot.anglesCos; - uniforms.spotLightExponent.value = lights.spot.exponents; - - uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors; - uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors; - uniforms.hemisphereLightDirection.value = lights.hemi.positions; - - }; - - function refreshUniformsShadow ( uniforms, lights ) { - - if ( uniforms.shadowMatrix ) { - - var j = 0; - - for ( var i = 0, il = lights.length; i < il; i ++ ) { - - var light = lights[ i ]; - - if ( ! light.castShadow ) continue; - - if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) { - - uniforms.shadowMap.value[ j ] = light.shadowMap; - uniforms.shadowMapSize.value[ j ] = light.shadowMapSize; - - uniforms.shadowMatrix.value[ j ] = light.shadowMatrix; - - uniforms.shadowDarkness.value[ j ] = light.shadowDarkness; - uniforms.shadowBias.value[ j ] = light.shadowBias; - - j ++; - - } - - } - - } - - }; - - // Uniforms (load to GPU) - - function loadUniformsMatrices ( uniforms, object ) { - - _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements ); - - if ( uniforms.normalMatrix ) { - - _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements ); - - } - - }; - - function getTextureUnit() { - - var textureUnit = _usedTextureUnits; - - if ( textureUnit >= _maxTextures ) { - - console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures ); - - } - - _usedTextureUnits += 1; - - return textureUnit; - - }; - - function loadUniformsGeneric ( program, uniforms ) { - - var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset; - - for ( j = 0, jl = uniforms.length; j < jl; j ++ ) { - - location = program.uniforms[ uniforms[ j ][ 1 ] ]; - if ( !location ) continue; - - uniform = uniforms[ j ][ 0 ]; - - type = uniform.type; - value = uniform.value; - - if ( type === "i" ) { // single integer - - _gl.uniform1i( location, value ); - - } else if ( type === "f" ) { // single float - - _gl.uniform1f( location, value ); - - } else if ( type === "v2" ) { // single THREE.Vector2 - - _gl.uniform2f( location, value.x, value.y ); - - } else if ( type === "v3" ) { // single THREE.Vector3 - - _gl.uniform3f( location, value.x, value.y, value.z ); - - } else if ( type === "v4" ) { // single THREE.Vector4 - - _gl.uniform4f( location, value.x, value.y, value.z, value.w ); - - } else if ( type === "c" ) { // single THREE.Color - - _gl.uniform3f( location, value.r, value.g, value.b ); - - } else if ( type === "iv1" ) { // flat array of integers (JS or typed array) - - _gl.uniform1iv( location, value ); - - } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array) - - _gl.uniform3iv( location, value ); - - } else if ( type === "fv1" ) { // flat array of floats (JS or typed array) - - _gl.uniform1fv( location, value ); - - } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array) - - _gl.uniform3fv( location, value ); - - } else if ( type === "v2v" ) { // array of THREE.Vector2 - - if ( uniform._array === undefined ) { - - uniform._array = new Float32Array( 2 * value.length ); - - } - - for ( i = 0, il = value.length; i < il; i ++ ) { - - offset = i * 2; - - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; - - } - - _gl.uniform2fv( location, uniform._array ); - - } else if ( type === "v3v" ) { // array of THREE.Vector3 - - if ( uniform._array === undefined ) { - - uniform._array = new Float32Array( 3 * value.length ); - - } - - for ( i = 0, il = value.length; i < il; i ++ ) { - - offset = i * 3; - - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; - uniform._array[ offset + 2 ] = value[ i ].z; - - } - - _gl.uniform3fv( location, uniform._array ); - - } else if ( type === "v4v" ) { // array of THREE.Vector4 - - if ( uniform._array === undefined ) { - - uniform._array = new Float32Array( 4 * value.length ); - - } - - for ( i = 0, il = value.length; i < il; i ++ ) { - - offset = i * 4; - - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; - uniform._array[ offset + 2 ] = value[ i ].z; - uniform._array[ offset + 3 ] = value[ i ].w; - - } - - _gl.uniform4fv( location, uniform._array ); - - } else if ( type === "m4") { // single THREE.Matrix4 - - if ( uniform._array === undefined ) { - - uniform._array = new Float32Array( 16 ); - - } - - value.flattenToArray( uniform._array ); - _gl.uniformMatrix4fv( location, false, uniform._array ); - - } else if ( type === "m4v" ) { // array of THREE.Matrix4 - - if ( uniform._array === undefined ) { - - uniform._array = new Float32Array( 16 * value.length ); - - } - - for ( i = 0, il = value.length; i < il; i ++ ) { - - value[ i ].flattenToArrayOffset( uniform._array, i * 16 ); - - } - - _gl.uniformMatrix4fv( location, false, uniform._array ); - - } else if ( type === "t" ) { // single THREE.Texture (2d or cube) - - texture = value; - textureUnit = getTextureUnit(); - - _gl.uniform1i( location, textureUnit ); - - if ( !texture ) continue; - - if ( texture.image instanceof Array && texture.image.length === 6 ) { - - setCubeTexture( texture, textureUnit ); - - } else if ( texture instanceof THREE.WebGLRenderTargetCube ) { - - setCubeTextureDynamic( texture, textureUnit ); - - } else { - - _this.setTexture( texture, textureUnit ); - - } - - } else if ( type === "tv" ) { // array of THREE.Texture (2d) - - if ( uniform._array === undefined ) { - - uniform._array = []; - - } - - for( i = 0, il = uniform.value.length; i < il; i ++ ) { - - uniform._array[ i ] = getTextureUnit(); - - } - - _gl.uniform1iv( location, uniform._array ); - - for( i = 0, il = uniform.value.length; i < il; i ++ ) { - - texture = uniform.value[ i ]; - textureUnit = uniform._array[ i ]; - - if ( !texture ) continue; - - _this.setTexture( texture, textureUnit ); - - } - - } else { - - console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type ); - - } - - } - - }; - - function setupMatrices ( object, camera ) { - - object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object._normalMatrix.getNormalMatrix( object._modelViewMatrix ); - - }; - - // - - function setColorGamma( array, offset, color, intensitySq ) { - - array[ offset ] = color.r * color.r * intensitySq; - array[ offset + 1 ] = color.g * color.g * intensitySq; - array[ offset + 2 ] = color.b * color.b * intensitySq; - - }; - - function setColorLinear( array, offset, color, intensity ) { - - array[ offset ] = color.r * intensity; - array[ offset + 1 ] = color.g * intensity; - array[ offset + 2 ] = color.b * intensity; - - }; - - function setupLights ( program, lights ) { - - var l, ll, light, n, - r = 0, g = 0, b = 0, - color, skyColor, groundColor, - intensity, intensitySq, - position, - distance, - - zlights = _lights, - - dirColors = zlights.directional.colors, - dirPositions = zlights.directional.positions, - - pointColors = zlights.point.colors, - pointPositions = zlights.point.positions, - pointDistances = zlights.point.distances, - - spotColors = zlights.spot.colors, - spotPositions = zlights.spot.positions, - spotDistances = zlights.spot.distances, - spotDirections = zlights.spot.directions, - spotAnglesCos = zlights.spot.anglesCos, - spotExponents = zlights.spot.exponents, - - hemiSkyColors = zlights.hemi.skyColors, - hemiGroundColors = zlights.hemi.groundColors, - hemiPositions = zlights.hemi.positions, - - dirLength = 0, - pointLength = 0, - spotLength = 0, - hemiLength = 0, - - dirCount = 0, - pointCount = 0, - spotCount = 0, - hemiCount = 0, - - dirOffset = 0, - pointOffset = 0, - spotOffset = 0, - hemiOffset = 0; - - for ( l = 0, ll = lights.length; l < ll; l ++ ) { - - light = lights[ l ]; - - if ( light.onlyShadow ) continue; - - color = light.color; - intensity = light.intensity; - distance = light.distance; - - if ( light instanceof THREE.AmbientLight ) { - - if ( ! light.visible ) continue; - - if ( _this.gammaInput ) { - - r += color.r * color.r; - g += color.g * color.g; - b += color.b * color.b; - - } else { - - r += color.r; - g += color.g; - b += color.b; - - } - - } else if ( light instanceof THREE.DirectionalLight ) { - - dirCount += 1; - - if ( ! light.visible ) continue; - - _direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - _direction.sub( _vector3 ); - _direction.normalize(); - - // skip lights with undefined direction - // these create troubles in OpenGL (making pixel black) - - if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue; - - dirOffset = dirLength * 3; - - dirPositions[ dirOffset ] = _direction.x; - dirPositions[ dirOffset + 1 ] = _direction.y; - dirPositions[ dirOffset + 2 ] = _direction.z; - - if ( _this.gammaInput ) { - - setColorGamma( dirColors, dirOffset, color, intensity * intensity ); - - } else { - - setColorLinear( dirColors, dirOffset, color, intensity ); - - } - - dirLength += 1; - - } else if ( light instanceof THREE.PointLight ) { - - pointCount += 1; - - if ( ! light.visible ) continue; - - pointOffset = pointLength * 3; - - if ( _this.gammaInput ) { - - setColorGamma( pointColors, pointOffset, color, intensity * intensity ); - - } else { - - setColorLinear( pointColors, pointOffset, color, intensity ); - - } - - _vector3.setFromMatrixPosition( light.matrixWorld ); - - pointPositions[ pointOffset ] = _vector3.x; - pointPositions[ pointOffset + 1 ] = _vector3.y; - pointPositions[ pointOffset + 2 ] = _vector3.z; - - pointDistances[ pointLength ] = distance; - - pointLength += 1; - - } else if ( light instanceof THREE.SpotLight ) { - - spotCount += 1; - - if ( ! light.visible ) continue; - - spotOffset = spotLength * 3; - - if ( _this.gammaInput ) { - - setColorGamma( spotColors, spotOffset, color, intensity * intensity ); - - } else { - - setColorLinear( spotColors, spotOffset, color, intensity ); - - } - - _vector3.setFromMatrixPosition( light.matrixWorld ); - - spotPositions[ spotOffset ] = _vector3.x; - spotPositions[ spotOffset + 1 ] = _vector3.y; - spotPositions[ spotOffset + 2 ] = _vector3.z; - - spotDistances[ spotLength ] = distance; - - _direction.copy( _vector3 ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - _direction.sub( _vector3 ); - _direction.normalize(); - - spotDirections[ spotOffset ] = _direction.x; - spotDirections[ spotOffset + 1 ] = _direction.y; - spotDirections[ spotOffset + 2 ] = _direction.z; - - spotAnglesCos[ spotLength ] = Math.cos( light.angle ); - spotExponents[ spotLength ] = light.exponent; - - spotLength += 1; - - } else if ( light instanceof THREE.HemisphereLight ) { - - hemiCount += 1; - - if ( ! light.visible ) continue; - - _direction.setFromMatrixPosition( light.matrixWorld ); - _direction.normalize(); - - // skip lights with undefined direction - // these create troubles in OpenGL (making pixel black) - - if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue; - - hemiOffset = hemiLength * 3; - - hemiPositions[ hemiOffset ] = _direction.x; - hemiPositions[ hemiOffset + 1 ] = _direction.y; - hemiPositions[ hemiOffset + 2 ] = _direction.z; - - skyColor = light.color; - groundColor = light.groundColor; - - if ( _this.gammaInput ) { - - intensitySq = intensity * intensity; - - setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq ); - setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq ); - - } else { - - setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity ); - setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity ); - - } - - hemiLength += 1; - - } - - } - - // null eventual remains from removed lights - // (this is to avoid if in shader) - - for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0; - for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0; - for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0; - for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0; - for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0; - - zlights.directional.length = dirLength; - zlights.point.length = pointLength; - zlights.spot.length = spotLength; - zlights.hemi.length = hemiLength; - - zlights.ambient[ 0 ] = r; - zlights.ambient[ 1 ] = g; - zlights.ambient[ 2 ] = b; - - }; - - // GL state setting - - this.setFaceCulling = function ( cullFace, frontFaceDirection ) { - - if ( cullFace === THREE.CullFaceNone ) { - - _gl.disable( _gl.CULL_FACE ); - - } else { - - if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) { - - _gl.frontFace( _gl.CW ); - - } else { - - _gl.frontFace( _gl.CCW ); - - } - - if ( cullFace === THREE.CullFaceBack ) { - - _gl.cullFace( _gl.BACK ); - - } else if ( cullFace === THREE.CullFaceFront ) { - - _gl.cullFace( _gl.FRONT ); - - } else { - - _gl.cullFace( _gl.FRONT_AND_BACK ); - - } - - _gl.enable( _gl.CULL_FACE ); - - } - - }; - - this.setMaterialFaces = function ( material ) { - - var doubleSided = material.side === THREE.DoubleSide; - var flipSided = material.side === THREE.BackSide; - - if ( _oldDoubleSided !== doubleSided ) { - - if ( doubleSided ) { - - _gl.disable( _gl.CULL_FACE ); - - } else { - - _gl.enable( _gl.CULL_FACE ); - - } - - _oldDoubleSided = doubleSided; - - } - - if ( _oldFlipSided !== flipSided ) { - - if ( flipSided ) { - - _gl.frontFace( _gl.CW ); - - } else { - - _gl.frontFace( _gl.CCW ); - - } - - _oldFlipSided = flipSided; - - } - - }; - - this.setDepthTest = function ( depthTest ) { - - if ( _oldDepthTest !== depthTest ) { - - if ( depthTest ) { - - _gl.enable( _gl.DEPTH_TEST ); - - } else { - - _gl.disable( _gl.DEPTH_TEST ); - - } - - _oldDepthTest = depthTest; - - } - - }; - - this.setDepthWrite = function ( depthWrite ) { - - if ( _oldDepthWrite !== depthWrite ) { - - _gl.depthMask( depthWrite ); - _oldDepthWrite = depthWrite; - - } - - }; - - function setLineWidth ( width ) { - - if ( width !== _oldLineWidth ) { - - _gl.lineWidth( width ); - - _oldLineWidth = width; - - } - - }; - - function setPolygonOffset ( polygonoffset, factor, units ) { - - if ( _oldPolygonOffset !== polygonoffset ) { - - if ( polygonoffset ) { - - _gl.enable( _gl.POLYGON_OFFSET_FILL ); - - } else { - - _gl.disable( _gl.POLYGON_OFFSET_FILL ); - - } - - _oldPolygonOffset = polygonoffset; - - } - - if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) { - - _gl.polygonOffset( factor, units ); - - _oldPolygonOffsetFactor = factor; - _oldPolygonOffsetUnits = units; - - } - - }; - - this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) { - - if ( blending !== _oldBlending ) { - - if ( blending === THREE.NoBlending ) { - - _gl.disable( _gl.BLEND ); - - } else if ( blending === THREE.AdditiveBlending ) { - - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); - - } else if ( blending === THREE.SubtractiveBlending ) { - - // TODO: Find blendFuncSeparate() combination - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR ); - - } else if ( blending === THREE.MultiplyBlending ) { - - // TODO: Find blendFuncSeparate() combination - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR ); - - } else if ( blending === THREE.CustomBlending ) { - - _gl.enable( _gl.BLEND ); - - } else { - - _gl.enable( _gl.BLEND ); - _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD ); - _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA ); - - } - - _oldBlending = blending; - - } - - if ( blending === THREE.CustomBlending ) { - - if ( blendEquation !== _oldBlendEquation ) { - - _gl.blendEquation( paramThreeToGL( blendEquation ) ); - - _oldBlendEquation = blendEquation; - - } - - if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) { - - _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) ); - - _oldBlendSrc = blendSrc; - _oldBlendDst = blendDst; - - } - - } else { - - _oldBlendEquation = null; - _oldBlendSrc = null; - _oldBlendDst = null; - - } - - }; - - // Defines - - function generateDefines ( defines ) { - - var value, chunk, chunks = []; - - for ( var d in defines ) { - - value = defines[ d ]; - if ( value === false ) continue; - - chunk = "#define " + d + " " + value; - chunks.push( chunk ); - - } - - return chunks.join( "\n" ); - - }; - - // Shaders - - function buildProgram( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) { - - var p, pl, d, program, code; - var chunks = []; - - // Generate code - - if ( shaderID ) { - - chunks.push( shaderID ); - - } else { - - chunks.push( fragmentShader ); - chunks.push( vertexShader ); - - } - - for ( d in defines ) { - - chunks.push( d ); - chunks.push( defines[ d ] ); - - } - - for ( p in parameters ) { - - chunks.push( p ); - chunks.push( parameters[ p ] ); - - } - - code = chunks.join(); - - // Check if code has been already compiled - - for ( p = 0, pl = _programs.length; p < pl; p ++ ) { - - var programInfo = _programs[ p ]; - - if ( programInfo.code === code ) { - - // console.log( "Code already compiled." /*: \n\n" + code*/ ); - - programInfo.usedTimes ++; - - return programInfo.program; - - } - - } - - var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; - - if ( parameters.shadowMapType === THREE.PCFShadowMap ) { - - shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; - - } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { - - shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; - - } - - // console.log( "building new program " ); - - // - - var customDefines = generateDefines( defines ); - - // - - program = _gl.createProgram(); - - var prefix_vertex = [ - - "precision " + _precision + " float;", - "precision " + _precision + " int;", - - customDefines, - - _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "", - - _this.gammaInput ? "#define GAMMA_INPUT" : "", - _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", - - "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, - "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, - "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, - "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, - - "#define MAX_SHADOWS " + parameters.maxShadows, - - "#define MAX_BONES " + parameters.maxBones, - - parameters.map ? "#define USE_MAP" : "", - parameters.envMap ? "#define USE_ENVMAP" : "", - parameters.lightMap ? "#define USE_LIGHTMAP" : "", - parameters.bumpMap ? "#define USE_BUMPMAP" : "", - parameters.normalMap ? "#define USE_NORMALMAP" : "", - parameters.specularMap ? "#define USE_SPECULARMAP" : "", - parameters.vertexColors ? "#define USE_COLOR" : "", - - parameters.skinning ? "#define USE_SKINNING" : "", - parameters.useVertexTexture ? "#define BONE_TEXTURE" : "", - - parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", - parameters.morphNormals ? "#define USE_MORPHNORMALS" : "", - parameters.wrapAround ? "#define WRAP_AROUND" : "", - parameters.doubleSided ? "#define DOUBLE_SIDED" : "", - parameters.flipSided ? "#define FLIP_SIDED" : "", - - parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", - parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", - parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", - parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", - - parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", - - "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;", - "attribute vec2 uv2;", - - "#ifdef USE_COLOR", - - "attribute vec3 color;", - - "#endif", - - "#ifdef USE_MORPHTARGETS", - - "attribute vec3 morphTarget0;", - "attribute vec3 morphTarget1;", - "attribute vec3 morphTarget2;", - "attribute vec3 morphTarget3;", - - "#ifdef USE_MORPHNORMALS", - - "attribute vec3 morphNormal0;", - "attribute vec3 morphNormal1;", - "attribute vec3 morphNormal2;", - "attribute vec3 morphNormal3;", - - "#else", - - "attribute vec3 morphTarget4;", - "attribute vec3 morphTarget5;", - "attribute vec3 morphTarget6;", - "attribute vec3 morphTarget7;", - - "#endif", - - "#endif", - - "#ifdef USE_SKINNING", - - "attribute vec4 skinIndex;", - "attribute vec4 skinWeight;", - - "#endif", - - "" - - ].join("\n"); - - var prefix_fragment = [ - - "precision " + _precision + " float;", - "precision " + _precision + " int;", - - ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "", - - customDefines, - - "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, - "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, - "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, - "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, - - "#define MAX_SHADOWS " + parameters.maxShadows, - - parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "", - - _this.gammaInput ? "#define GAMMA_INPUT" : "", - _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", - - ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "", - ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "", - - parameters.map ? "#define USE_MAP" : "", - parameters.envMap ? "#define USE_ENVMAP" : "", - parameters.lightMap ? "#define USE_LIGHTMAP" : "", - parameters.bumpMap ? "#define USE_BUMPMAP" : "", - parameters.normalMap ? "#define USE_NORMALMAP" : "", - parameters.specularMap ? "#define USE_SPECULARMAP" : "", - parameters.vertexColors ? "#define USE_COLOR" : "", - - parameters.metal ? "#define METAL" : "", - parameters.wrapAround ? "#define WRAP_AROUND" : "", - parameters.doubleSided ? "#define DOUBLE_SIDED" : "", - parameters.flipSided ? "#define FLIP_SIDED" : "", - - parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", - parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", - parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", - parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", - - "uniform mat4 viewMatrix;", - "uniform vec3 cameraPosition;", - "" - - ].join("\n"); - - var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader ); - var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader ); - - _gl.attachShader( program, glVertexShader ); - _gl.attachShader( program, glFragmentShader ); - - // Force a particular attribute to index 0. - // because potentially expensive emulation is done by browser if attribute 0 is disabled. - // And, color, for example is often automatically bound to index 0 so disabling it - if ( index0AttributeName !== undefined ) { - - _gl.bindAttribLocation( program, 0, index0AttributeName ); - - } - - _gl.linkProgram( program ); - - if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) { - - console.error( 'Could not initialise shader' ); - console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) ); - console.error( 'gl.getError()', _gl.getError() ); - - } - - if ( _gl.getProgramInfoLog( program ) !== '' ) { - - console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) ); - - } - - // clean up - - _gl.deleteShader( glFragmentShader ); - _gl.deleteShader( glVertexShader ); - - // console.log( prefix_fragment + fragmentShader ); - // console.log( prefix_vertex + vertexShader ); - - program.uniforms = {}; - program.attributes = {}; - - var identifiers, u, a, i; - - // cache uniform locations - - identifiers = [ - - 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition', - 'morphTargetInfluences' - - ]; - - if ( parameters.useVertexTexture ) { - - identifiers.push( 'boneTexture' ); - identifiers.push( 'boneTextureWidth' ); - identifiers.push( 'boneTextureHeight' ); - - } else { - - identifiers.push( 'boneGlobalMatrices' ); - - } - - for ( u in uniforms ) { - - identifiers.push( u ); - - } - - cacheUniformLocations( program, identifiers ); - - // cache attributes locations - - identifiers = [ - - "position", "normal", "uv", "uv2", "tangent", "color", - "skinIndex", "skinWeight", "lineDistance" - - ]; - - for ( i = 0; i < parameters.maxMorphTargets; i ++ ) { - - identifiers.push( "morphTarget" + i ); - - } - - for ( i = 0; i < parameters.maxMorphNormals; i ++ ) { - - identifiers.push( "morphNormal" + i ); - - } - - for ( a in attributes ) { - - identifiers.push( a ); - - } - - cacheAttributeLocations( program, identifiers ); - - program.id = _programs_counter ++; - - _programs.push( { program: program, code: code, usedTimes: 1 } ); - - _this.info.memory.programs = _programs.length; - - return program; - - }; - - // Shader parameters cache - - function cacheUniformLocations ( program, identifiers ) { - - var i, l, id; - - for( i = 0, l = identifiers.length; i < l; i ++ ) { - - id = identifiers[ i ]; - program.uniforms[ id ] = _gl.getUniformLocation( program, id ); - - } - - }; - - function cacheAttributeLocations ( program, identifiers ) { - - var i, l, id; - - for( i = 0, l = identifiers.length; i < l; i ++ ) { - - id = identifiers[ i ]; - program.attributes[ id ] = _gl.getAttribLocation( program, id ); - - } - - }; - - function addLineNumbers ( string ) { - - var chunks = string.split( "\n" ); - - for ( var i = 0, il = chunks.length; i < il; i ++ ) { - - // Chrome reports shader errors on lines - // starting counting from 1 - - chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ]; - - } - - return chunks.join( "\n" ); - - }; - - function getShader ( type, string ) { - - var shader; - - if ( type === "fragment" ) { - - shader = _gl.createShader( _gl.FRAGMENT_SHADER ); - - } else if ( type === "vertex" ) { - - shader = _gl.createShader( _gl.VERTEX_SHADER ); - - } - - _gl.shaderSource( shader, string ); - _gl.compileShader( shader ); - - if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) { - - console.error( _gl.getShaderInfoLog( shader ) ); - console.error( addLineNumbers( string ) ); - return null; - - } - - return shader; - - }; - - // Textures - - function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) { - - if ( isImagePowerOfTwo ) { - - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); - - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - - } else { - - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - - } - - if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) { - - if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) { - - _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) ); - texture.__oldAnisotropy = texture.anisotropy; - - } - - } - - }; - - this.setTexture = function ( texture, slot ) { - - if ( texture.needsUpdate ) { - - if ( ! texture.__webglInit ) { - - texture.__webglInit = true; - - texture.addEventListener( 'dispose', onTextureDispose ); - - texture.__webglTexture = _gl.createTexture(); - - _this.info.memory.textures ++; - - } - - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); - - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); - _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); - - var image = texture.image, - isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); - - setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); - - var mipmap, mipmaps = texture.mipmaps; - - if ( texture instanceof THREE.DataTexture ) { - - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels - - if ( mipmaps.length > 0 && isImagePowerOfTwo ) { - - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - - mipmap = mipmaps[ i ]; - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - - } - - texture.generateMipmaps = false; - - } else { - - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); - - } - - } else if ( texture instanceof THREE.CompressedTexture ) { - - for( var i = 0, il = mipmaps.length; i < il; i ++ ) { - - mipmap = mipmaps[ i ]; - if ( texture.format!==THREE.RGBAFormat ) { - _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } else { - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } - - } - - } else { // regular Texture (image, video, canvas) - - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels - - if ( mipmaps.length > 0 && isImagePowerOfTwo ) { - - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - - mipmap = mipmaps[ i ]; - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - - } - - texture.generateMipmaps = false; - - } else { - - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image ); - - } - - } - - if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - - texture.needsUpdate = false; - - if ( texture.onUpdate ) texture.onUpdate(); - - } else { - - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); - - } - - }; - - function clampToMaxSize ( image, maxSize ) { - - if ( image.width <= maxSize && image.height <= maxSize ) { - - return image; - - } - - // Warning: Scaling through the canvas will only work with images that use - // premultiplied alpha. - - var maxDimension = Math.max( image.width, image.height ); - var newWidth = Math.floor( image.width * maxSize / maxDimension ); - var newHeight = Math.floor( image.height * maxSize / maxDimension ); - - var canvas = document.createElement( 'canvas' ); - canvas.width = newWidth; - canvas.height = newHeight; - - var ctx = canvas.getContext( "2d" ); - ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight ); - - return canvas; - - } - - function setCubeTexture ( texture, slot ) { - - if ( texture.image.length === 6 ) { - - if ( texture.needsUpdate ) { - - if ( ! texture.image.__webglTextureCube ) { - - texture.addEventListener( 'dispose', onTextureDispose ); - - texture.image.__webglTextureCube = _gl.createTexture(); - - _this.info.memory.textures ++; - - } - - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); - - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - - var isCompressed = texture instanceof THREE.CompressedTexture; - - var cubeImage = []; - - for ( var i = 0; i < 6; i ++ ) { - - if ( _this.autoScaleCubemaps && ! isCompressed ) { - - cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize ); - - } else { - - cubeImage[ i ] = texture.image[ i ]; - - } - - } - - var image = cubeImage[ 0 ], - isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); - - setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo ); - - for ( var i = 0; i < 6; i ++ ) { - - if( !isCompressed ) { - - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); - - } else { - - var mipmap, mipmaps = cubeImage[ i ].mipmaps; - - for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - - mipmap = mipmaps[ j ]; - if ( texture.format!==THREE.RGBAFormat ) { - - _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - - } else { - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } - - } - } - } - - if ( texture.generateMipmaps && isImagePowerOfTwo ) { - - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - - } - - texture.needsUpdate = false; - - if ( texture.onUpdate ) texture.onUpdate(); - - } else { - - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); - - } - - } - - }; - - function setCubeTextureDynamic ( texture, slot ) { - - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture ); - - }; - - // Render targets - - function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) { - - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 ); - - }; - - function setupRenderBuffer ( renderbuffer, renderTarget ) { - - _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - - /* For some reason this is not working. Defaulting to RGBA4. - } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - */ - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - - } else { - - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); - - } - - }; - - this.setRenderTarget = function ( renderTarget ) { - - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - - if ( renderTarget && ! renderTarget.__webglFramebuffer ) { - - if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true; - if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true; - - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - - renderTarget.__webglTexture = _gl.createTexture(); - - _this.info.memory.textures ++; - - // Setup texture, create render and frame buffers - - var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ), - glFormat = paramThreeToGL( renderTarget.format ), - glType = paramThreeToGL( renderTarget.type ); - - if ( isCube ) { - - renderTarget.__webglFramebuffer = []; - renderTarget.__webglRenderbuffer = []; - - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo ); - - for ( var i = 0; i < 6; i ++ ) { - - renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer(); - - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - - setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); - setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget ); - - } - - if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - - } else { - - renderTarget.__webglFramebuffer = _gl.createFramebuffer(); - - if ( renderTarget.shareDepthFrom ) { - - renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer; - - } else { - - renderTarget.__webglRenderbuffer = _gl.createRenderbuffer(); - - } - - _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); - setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo ); - - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - - setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D ); - - if ( renderTarget.shareDepthFrom ) { - - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); - - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); - - } - - } else { - - setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget ); - - } - - if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - - } - - // Release everything - - if ( isCube ) { - - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - - } else { - - _gl.bindTexture( _gl.TEXTURE_2D, null ); - - } - - _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - - } - - var framebuffer, width, height, vx, vy; - - if ( renderTarget ) { - - if ( isCube ) { - - framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ]; - - } else { - - framebuffer = renderTarget.__webglFramebuffer; - - } - - width = renderTarget.width; - height = renderTarget.height; - - vx = 0; - vy = 0; - - } else { - - framebuffer = null; - - width = _viewportWidth; - height = _viewportHeight; - - vx = _viewportX; - vy = _viewportY; - - } - - if ( framebuffer !== _currentFramebuffer ) { - - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.viewport( vx, vy, width, height ); - - _currentFramebuffer = framebuffer; - - } - - _currentWidth = width; - _currentHeight = height; - - }; - - function updateRenderTargetMipmap ( renderTarget ) { - - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { - - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - - } else { - - _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); - _gl.generateMipmap( _gl.TEXTURE_2D ); - _gl.bindTexture( _gl.TEXTURE_2D, null ); - - } - - }; - - // Fallback filters for non-power-of-2 textures - - function filterFallback ( f ) { - - if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { - - return _gl.NEAREST; - - } - - return _gl.LINEAR; - - }; - - // Map three.js constants to WebGL constants - - function paramThreeToGL ( p ) { - - if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; - if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; - if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; - - if ( p === THREE.NearestFilter ) return _gl.NEAREST; - if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; - if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; - - if ( p === THREE.LinearFilter ) return _gl.LINEAR; - if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; - - if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; - - if ( p === THREE.ByteType ) return _gl.BYTE; - if ( p === THREE.ShortType ) return _gl.SHORT; - if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === THREE.IntType ) return _gl.INT; - if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === THREE.FloatType ) return _gl.FLOAT; - - if ( p === THREE.AlphaFormat ) return _gl.ALPHA; - if ( p === THREE.RGBFormat ) return _gl.RGB; - if ( p === THREE.RGBAFormat ) return _gl.RGBA; - if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; - if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - - if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; - if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - - if ( p === THREE.ZeroFactor ) return _gl.ZERO; - if ( p === THREE.OneFactor ) return _gl.ONE; - if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; - if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; - if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; - if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; - if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; - if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; - - if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; - if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; - - if ( _glExtensionCompressedTextureS3TC !== undefined ) { - - if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT; - if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT; - - } - - return 0; - - }; - - // Allocations - - function allocateBones ( object ) { - - if ( _supportsBoneTextures && object && object.useVertexTexture ) { - - return 1024; - - } else { - - // default for when object is not specified - // ( for example when prebuilding shader - // to be used with multiple objects ) - // - // - leave some extra space for other uniforms - // - limit here is ANGLE's 254 max uniform vectors - // (up to 54 should be safe) - - var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ); - var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - - var maxBones = nVertexMatrices; - - if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { - - maxBones = Math.min( object.bones.length, maxBones ); - - if ( maxBones < object.bones.length ) { - - console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" ); - - } - - } - - return maxBones; - - } - - }; - - function allocateLights( lights ) { - - var dirLights = 0; - var pointLights = 0; - var spotLights = 0; - var hemiLights = 0; - - for ( var l = 0, ll = lights.length; l < ll; l ++ ) { - - var light = lights[ l ]; - - if ( light.onlyShadow || light.visible === false ) continue; - - if ( light instanceof THREE.DirectionalLight ) dirLights ++; - if ( light instanceof THREE.PointLight ) pointLights ++; - if ( light instanceof THREE.SpotLight ) spotLights ++; - if ( light instanceof THREE.HemisphereLight ) hemiLights ++; - - } - - return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights }; - - }; - - function allocateShadows( lights ) { - - var maxShadows = 0; - - for ( var l = 0, ll = lights.length; l < ll; l++ ) { - - var light = lights[ l ]; - - if ( ! light.castShadow ) continue; - - if ( light instanceof THREE.SpotLight ) maxShadows ++; - if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++; - - } - - return maxShadows; - - }; - - // Initialization - - function initGL() { - - try { - - var attributes = { - alpha: _alpha, - premultipliedAlpha: _premultipliedAlpha, - antialias: _antialias, - stencil: _stencil, - preserveDrawingBuffer: _preserveDrawingBuffer - }; - - _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); - - if ( _gl === null ) { - - throw 'Error creating WebGL context.'; - - } - - } catch ( error ) { - - console.error( error ); - - } - - _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' ); - _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' ); - _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' ); - - _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); - - _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); - - if ( ! _glExtensionTextureFloat ) { - - console.log( 'THREE.WebGLRenderer: Float textures not supported.' ); - - } - - if ( ! _glExtensionStandardDerivatives ) { - - console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' ); - - } - - if ( ! _glExtensionTextureFilterAnisotropic ) { - - console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' ); - - } - - if ( ! _glExtensionCompressedTextureS3TC ) { - - console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' ); - - } - - if ( _gl.getShaderPrecisionFormat === undefined ) { - - _gl.getShaderPrecisionFormat = function() { - - return { - "rangeMin" : 1, - "rangeMax" : 1, - "precision" : 1 - }; - - } - } - - }; - - function setDefaultGLState () { - - _gl.clearColor( 0, 0, 0, 1 ); - _gl.clearDepth( 1 ); - _gl.clearStencil( 0 ); - - _gl.enable( _gl.DEPTH_TEST ); - _gl.depthFunc( _gl.LEQUAL ); - - _gl.frontFace( _gl.CCW ); - _gl.cullFace( _gl.BACK ); - _gl.enable( _gl.CULL_FACE ); - - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA ); - - _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); - - _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - - }; - - // default plugins (order is important) - - this.shadowMapPlugin = new THREE.ShadowMapPlugin(); - this.addPrePlugin( this.shadowMapPlugin ); - - this.addPostPlugin( new THREE.SpritePlugin() ); - this.addPostPlugin( new THREE.LensFlarePlugin() ); - -}; -/** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.WebGLRenderTarget = function ( width, height, options ) { - - this.width = width; - this.height = height; - - options = options || {}; - - this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping; - - this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter; - this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter; - - this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1; - - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); - - this.format = options.format !== undefined ? options.format : THREE.RGBAFormat; - this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType; - - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; - - this.generateMipmaps = true; - - this.shareDepthFrom = null; - -}; - -THREE.WebGLRenderTarget.prototype = { - - constructor: THREE.WebGLRenderTarget, - - clone: function () { - - var tmp = new THREE.WebGLRenderTarget( this.width, this.height ); - - tmp.wrapS = this.wrapS; - tmp.wrapT = this.wrapT; - - tmp.magFilter = this.magFilter; - tmp.minFilter = this.minFilter; - - tmp.anisotropy = this.anisotropy; - - tmp.offset.copy( this.offset ); - tmp.repeat.copy( this.repeat ); - - tmp.format = this.format; - tmp.type = this.type; - - tmp.depthBuffer = this.depthBuffer; - tmp.stencilBuffer = this.stencilBuffer; - - tmp.generateMipmaps = this.generateMipmaps; - - tmp.shareDepthFrom = this.shareDepthFrom; - - return tmp; - - }, - - dispose: function () { - - this.dispatchEvent( { type: 'dispose' } ); - - } - -}; - -THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype ); -/** - * @author alteredq / http://alteredqualia.com - */ - -THREE.WebGLRenderTargetCube = function ( width, height, options ) { - - THREE.WebGLRenderTarget.call( this, width, height, options ); - - this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - -}; - -THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.RenderableVertex = function () { - - this.position = new THREE.Vector3(); - this.positionWorld = new THREE.Vector3(); - this.positionScreen = new THREE.Vector4(); - - this.visible = true; - -}; - -THREE.RenderableVertex.prototype.copy = function ( vertex ) { - - this.positionWorld.copy( vertex.positionWorld ); - this.positionScreen.copy( vertex.positionScreen ); - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.RenderableFace = function () { - - this.id = 0; - - this.v1 = new THREE.RenderableVertex(); - this.v2 = new THREE.RenderableVertex(); - this.v3 = new THREE.RenderableVertex(); - - this.centroidModel = new THREE.Vector3(); - - this.normalModel = new THREE.Vector3(); - - this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ]; - this.vertexNormalsLength = 0; - - this.color = null; - this.material = null; - this.uvs = [[]]; - - this.z = 0; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.RenderableObject = function () { - - this.id = 0; - - this.object = null; - this.z = 0; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.RenderableSprite = function () { - - this.id = 0; - - this.object = null; - - this.x = 0; - this.y = 0; - this.z = 0; - - this.rotation = 0; - this.scale = new THREE.Vector2(); - - this.material = null; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.RenderableLine = function () { - - this.id = 0; - - this.v1 = new THREE.RenderableVertex(); - this.v2 = new THREE.RenderableVertex(); - - this.vertexColors = [ new THREE.Color(), new THREE.Color() ]; - this.material = null; - - this.z = 0; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.GeometryUtils = { - - // Merge two geometries or geometry and geometry from object (using object's transform) - - merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) { - - var matrix, normalMatrix, - vertexOffset = geometry1.vertices.length, - uvPosition = geometry1.faceVertexUvs[ 0 ].length, - geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2, - vertices1 = geometry1.vertices, - vertices2 = geometry2.vertices, - faces1 = geometry1.faces, - faces2 = geometry2.faces, - uvs1 = geometry1.faceVertexUvs[ 0 ], - uvs2 = geometry2.faceVertexUvs[ 0 ]; - - if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - - if ( object2 instanceof THREE.Mesh ) { - - object2.matrixAutoUpdate && object2.updateMatrix(); - - matrix = object2.matrix; - - normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); - - } - - // vertices - - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - - var vertex = vertices2[ i ]; - - var vertexCopy = vertex.clone(); - - if ( matrix ) vertexCopy.applyMatrix4( matrix ); - - vertices1.push( vertexCopy ); - - } - - // faces - - for ( i = 0, il = faces2.length; i < il; i ++ ) { - - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; - - faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); - - if ( normalMatrix ) { - - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); - - } - - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - - normal = faceVertexNormals[ j ].clone(); - - if ( normalMatrix ) { - - normal.applyMatrix3( normalMatrix ).normalize(); - - } - - faceCopy.vertexNormals.push( normal ); - - } - - faceCopy.color.copy( face.color ); - - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); - - } - - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - - faceCopy.centroid.copy( face.centroid ); - - if ( matrix ) { - - faceCopy.centroid.applyMatrix4( matrix ); - - } - - faces1.push( faceCopy ); - - } - - // uvs - - for ( i = 0, il = uvs2.length; i < il; i ++ ) { - - var uv = uvs2[ i ], uvCopy = []; - - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - - uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) ); - - } - - uvs1.push( uvCopy ); - - } - - }, - - // Get random point in triangle (via barycentric coordinates) - // (uniform distribution) - // http://www.cgafaq.info/wiki/Random_Point_In_Triangle - - randomPointInTriangle: function () { - - var vector = new THREE.Vector3(); - - return function ( vectorA, vectorB, vectorC ) { - - var point = new THREE.Vector3(); - - var a = THREE.Math.random16(); - var b = THREE.Math.random16(); - - if ( ( a + b ) > 1 ) { - - a = 1 - a; - b = 1 - b; - - } - - var c = 1 - a - b; - - point.copy( vectorA ); - point.multiplyScalar( a ); - - vector.copy( vectorB ); - vector.multiplyScalar( b ); - - point.add( vector ); - - vector.copy( vectorC ); - vector.multiplyScalar( c ); - - point.add( vector ); - - return point; - - }; - - }(), - - // Get random point in face (triangle / quad) - // (uniform distribution) - - randomPointInFace: function ( face, geometry, useCachedAreas ) { - - var vA, vB, vC, vD; - - vA = geometry.vertices[ face.a ]; - vB = geometry.vertices[ face.b ]; - vC = geometry.vertices[ face.c ]; - - return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC ); - - }, - - // Get uniformly distributed random points in mesh - // - create array with cumulative sums of face areas - // - pick random number from 0 to total area - // - find corresponding place in area array by binary search - // - get random point in face - - randomPointsInGeometry: function ( geometry, n ) { - - var face, i, - faces = geometry.faces, - vertices = geometry.vertices, - il = faces.length, - totalArea = 0, - cumulativeAreas = [], - vA, vB, vC, vD; - - // precompute face areas - - for ( i = 0; i < il; i ++ ) { - - face = faces[ i ]; - - vA = vertices[ face.a ]; - vB = vertices[ face.b ]; - vC = vertices[ face.c ]; - - face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC ); - - totalArea += face._area; - - cumulativeAreas[ i ] = totalArea; - - } - - // binary search cumulative areas array - - function binarySearchIndices( value ) { - - function binarySearch( start, end ) { - - // return closest larger index - // if exact number is not found - - if ( end < start ) - return start; - - var mid = start + Math.floor( ( end - start ) / 2 ); - - if ( cumulativeAreas[ mid ] > value ) { - - return binarySearch( start, mid - 1 ); - - } else if ( cumulativeAreas[ mid ] < value ) { - - return binarySearch( mid + 1, end ); - - } else { - - return mid; - - } - - } - - var result = binarySearch( 0, cumulativeAreas.length - 1 ) - return result; - - } - - // pick random face weighted by face area - - var r, index, - result = []; - - var stats = {}; - - for ( i = 0; i < n; i ++ ) { - - r = THREE.Math.random16() * totalArea; - - index = binarySearchIndices( r ); - - result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true ); - - if ( ! stats[ index ] ) { - - stats[ index ] = 1; - - } else { - - stats[ index ] += 1; - - } - - } - - return result; - - }, - - // Get triangle area (half of parallelogram) - // http://mathworld.wolfram.com/TriangleArea.html - - triangleArea: function () { - - var vector1 = new THREE.Vector3(); - var vector2 = new THREE.Vector3(); - - return function ( vectorA, vectorB, vectorC ) { - - vector1.subVectors( vectorB, vectorA ); - vector2.subVectors( vectorC, vectorA ); - vector1.cross( vector2 ); - - return 0.5 * vector1.length(); - - }; - - }(), - - // Center geometry so that 0,0,0 is in center of bounding box - - center: function ( geometry ) { - - geometry.computeBoundingBox(); - - var bb = geometry.boundingBox; - - var offset = new THREE.Vector3(); - - offset.addVectors( bb.min, bb.max ); - offset.multiplyScalar( -0.5 ); - - geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) ); - geometry.computeBoundingBox(); - - return offset; - - }, - - triangulateQuads: function ( geometry ) { - - var i, il, j, jl; - - var faces = []; - var faceVertexUvs = []; - - for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) { - - faceVertexUvs[ i ] = []; - - } - - for ( i = 0, il = geometry.faces.length; i < il; i ++ ) { - - var face = geometry.faces[ i ]; - - faces.push( face ); - - for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) { - - faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] ); - - } - - } - - geometry.faces = faces; - geometry.faceVertexUvs = faceVertexUvs; - - geometry.computeCentroids(); - geometry.computeFaceNormals(); - geometry.computeVertexNormals(); - - if ( geometry.hasTangents ) geometry.computeTangents(); - - } - -}; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.ImageUtils = { - - crossOrigin: undefined, - - loadTexture: function ( url, mapping, onLoad, onError ) { - - var loader = new THREE.ImageLoader(); - loader.crossOrigin = this.crossOrigin; - - var texture = new THREE.Texture( undefined, mapping ); - - var image = loader.load( url, function () { - - texture.needsUpdate = true; - - if ( onLoad ) onLoad( texture ); - - } ); - - texture.image = image; - texture.sourceFile = url; - - return texture; - - }, - - loadCompressedTexture: function ( url, mapping, onLoad, onError ) { - - var texture = new THREE.CompressedTexture(); - texture.mapping = mapping; - - var request = new XMLHttpRequest(); - - request.onload = function () { - - var buffer = request.response; - var dds = THREE.ImageUtils.parseDDS( buffer, true ); - - texture.format = dds.format; - - texture.mipmaps = dds.mipmaps; - texture.image.width = dds.width; - texture.image.height = dds.height; - - // gl.generateMipmap fails for compressed textures - // mipmaps must be embedded in the DDS file - // or texture filters must not use mipmapping - - texture.generateMipmaps = false; - - texture.needsUpdate = true; - - if ( onLoad ) onLoad( texture ); - - } - - request.onerror = onError; - - request.open( 'GET', url, true ); - request.responseType = "arraybuffer"; - request.send( null ); - - return texture; - - }, - - loadTextureCube: function ( array, mapping, onLoad, onError ) { - - var images = []; - images.loadCount = 0; - - var texture = new THREE.Texture(); - texture.image = images; - if ( mapping !== undefined ) texture.mapping = mapping; - - // no flipping needed for cube textures - - texture.flipY = false; - - for ( var i = 0, il = array.length; i < il; ++ i ) { - - var cubeImage = new Image(); - images[ i ] = cubeImage; - - cubeImage.onload = function () { - - images.loadCount += 1; - - if ( images.loadCount === 6 ) { - - texture.needsUpdate = true; - if ( onLoad ) onLoad( texture ); - - } - - }; - - cubeImage.onerror = onError; - - cubeImage.crossOrigin = this.crossOrigin; - cubeImage.src = array[ i ]; - - } - - return texture; - - }, - - loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) { - - var images = []; - images.loadCount = 0; - - var texture = new THREE.CompressedTexture(); - texture.image = images; - if ( mapping !== undefined ) texture.mapping = mapping; - - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) - - texture.flipY = false; - - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files - - texture.generateMipmaps = false; - - var generateCubeFaceCallback = function ( rq, img ) { - - return function () { - - var buffer = rq.response; - var dds = THREE.ImageUtils.parseDDS( buffer, true ); - - img.format = dds.format; - - img.mipmaps = dds.mipmaps; - img.width = dds.width; - img.height = dds.height; - - images.loadCount += 1; - - if ( images.loadCount === 6 ) { - - texture.format = dds.format; - texture.needsUpdate = true; - if ( onLoad ) onLoad( texture ); - - } - - } - - } - - // compressed cubemap textures as 6 separate DDS files - - if ( array instanceof Array ) { - - for ( var i = 0, il = array.length; i < il; ++ i ) { - - var cubeImage = {}; - images[ i ] = cubeImage; - - var request = new XMLHttpRequest(); - - request.onload = generateCubeFaceCallback( request, cubeImage ); - request.onerror = onError; - - var url = array[ i ]; - - request.open( 'GET', url, true ); - request.responseType = "arraybuffer"; - request.send( null ); - - } - - // compressed cubemap texture stored in a single DDS file - - } else { - - var url = array; - var request = new XMLHttpRequest(); - - request.onload = function( ) { - - var buffer = request.response; - var dds = THREE.ImageUtils.parseDDS( buffer, true ); - - if ( dds.isCubemap ) { - - var faces = dds.mipmaps.length / dds.mipmapCount; - - for ( var f = 0; f < faces; f ++ ) { - - images[ f ] = { mipmaps : [] }; - - for ( var i = 0; i < dds.mipmapCount; i ++ ) { - - images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] ); - images[ f ].format = dds.format; - images[ f ].width = dds.width; - images[ f ].height = dds.height; - - } - - } - - texture.format = dds.format; - texture.needsUpdate = true; - if ( onLoad ) onLoad( texture ); - - } - - } - - request.onerror = onError; - - request.open( 'GET', url, true ); - request.responseType = "arraybuffer"; - request.send( null ); - - } - - return texture; - - }, - - loadDDSTexture: function ( url, mapping, onLoad, onError ) { - - var images = []; - images.loadCount = 0; - - var texture = new THREE.CompressedTexture(); - texture.image = images; - if ( mapping !== undefined ) texture.mapping = mapping; - - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) - - texture.flipY = false; - - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files - - texture.generateMipmaps = false; - - { - var request = new XMLHttpRequest(); - - request.onload = function( ) { - - var buffer = request.response; - var dds = THREE.ImageUtils.parseDDS( buffer, true ); - - if ( dds.isCubemap ) { - - var faces = dds.mipmaps.length / dds.mipmapCount; - - for ( var f = 0; f < faces; f ++ ) { - - images[ f ] = { mipmaps : [] }; - - for ( var i = 0; i < dds.mipmapCount; i ++ ) { - - images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] ); - images[ f ].format = dds.format; - images[ f ].width = dds.width; - images[ f ].height = dds.height; - - } - - } - - - } else { - texture.image.width = dds.width; - texture.image.height = dds.height; - texture.mipmaps = dds.mipmaps; - } - - texture.format = dds.format; - texture.needsUpdate = true; - if ( onLoad ) onLoad( texture ); - - } - - request.onerror = onError; - - request.open( 'GET', url, true ); - request.responseType = "arraybuffer"; - request.send( null ); - - } - - return texture; - - }, - - parseDDS: function ( buffer, loadMipmaps ) { - - var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 }; - - // Adapted from @toji's DDS utils - // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js - - // All values and structures referenced from: - // http://msdn.microsoft.com/en-us/library/bb943991.aspx/ - - var DDS_MAGIC = 0x20534444; - - var DDSD_CAPS = 0x1, - DDSD_HEIGHT = 0x2, - DDSD_WIDTH = 0x4, - DDSD_PITCH = 0x8, - DDSD_PIXELFORMAT = 0x1000, - DDSD_MIPMAPCOUNT = 0x20000, - DDSD_LINEARSIZE = 0x80000, - DDSD_DEPTH = 0x800000; - - var DDSCAPS_COMPLEX = 0x8, - DDSCAPS_MIPMAP = 0x400000, - DDSCAPS_TEXTURE = 0x1000; - - var DDSCAPS2_CUBEMAP = 0x200, - DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, - DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, - DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, - DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, - DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, - DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, - DDSCAPS2_VOLUME = 0x200000; - - var DDPF_ALPHAPIXELS = 0x1, - DDPF_ALPHA = 0x2, - DDPF_FOURCC = 0x4, - DDPF_RGB = 0x40, - DDPF_YUV = 0x200, - DDPF_LUMINANCE = 0x20000; - - function fourCCToInt32( value ) { - - return value.charCodeAt(0) + - (value.charCodeAt(1) << 8) + - (value.charCodeAt(2) << 16) + - (value.charCodeAt(3) << 24); - - } - - function int32ToFourCC( value ) { - - return String.fromCharCode( - value & 0xff, - (value >> 8) & 0xff, - (value >> 16) & 0xff, - (value >> 24) & 0xff - ); - } - - function loadARGBMip( buffer, dataOffset, width, height ) { - var dataLength = width*height*4; - var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength ); - var byteArray = new Uint8Array( dataLength ); - var dst = 0; - var src = 0; - for ( var y = 0; y < height; y++ ) { - for ( var x = 0; x < width; x++ ) { - var b = srcBuffer[src]; src++; - var g = srcBuffer[src]; src++; - var r = srcBuffer[src]; src++; - var a = srcBuffer[src]; src++; - byteArray[dst] = r; dst++; //r - byteArray[dst] = g; dst++; //g - byteArray[dst] = b; dst++; //b - byteArray[dst] = a; dst++; //a - } - } - return byteArray; - } - - var FOURCC_DXT1 = fourCCToInt32("DXT1"); - var FOURCC_DXT3 = fourCCToInt32("DXT3"); - var FOURCC_DXT5 = fourCCToInt32("DXT5"); - - var headerLengthInt = 31; // The header length in 32 bit ints - - // Offsets into the header array - - var off_magic = 0; - - var off_size = 1; - var off_flags = 2; - var off_height = 3; - var off_width = 4; - - var off_mipmapCount = 7; - - var off_pfFlags = 20; - var off_pfFourCC = 21; - var off_RGBBitCount = 22; - var off_RBitMask = 23; - var off_GBitMask = 24; - var off_BBitMask = 25; - var off_ABitMask = 26; - - var off_caps = 27; - var off_caps2 = 28; - var off_caps3 = 29; - var off_caps4 = 30; - - // Parse header - - var header = new Int32Array( buffer, 0, headerLengthInt ); - - if ( header[ off_magic ] !== DDS_MAGIC ) { - - console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" ); - return dds; - - } - - if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) { - - console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" ); - return dds; - - } - - var blockBytes; - - var fourCC = header[ off_pfFourCC ]; - - var isRGBAUncompressed = false; - - switch ( fourCC ) { - - case FOURCC_DXT1: - - blockBytes = 8; - dds.format = THREE.RGB_S3TC_DXT1_Format; - break; - - case FOURCC_DXT3: - - blockBytes = 16; - dds.format = THREE.RGBA_S3TC_DXT3_Format; - break; - - case FOURCC_DXT5: - - blockBytes = 16; - dds.format = THREE.RGBA_S3TC_DXT5_Format; - break; - - default: - - if( header[off_RGBBitCount] ==32 - && header[off_RBitMask]&0xff0000 - && header[off_GBitMask]&0xff00 - && header[off_BBitMask]&0xff - && header[off_ABitMask]&0xff000000 ) { - isRGBAUncompressed = true; - blockBytes = 64; - dds.format = THREE.RGBAFormat; - } else { - console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) ); - return dds; - } - } - - dds.mipmapCount = 1; - - if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) { - - dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] ); - - } - - //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc. - - dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false; - - dds.width = header[ off_width ]; - dds.height = header[ off_height ]; - - var dataOffset = header[ off_size ] + 4; - - // Extract mipmaps buffers - - var width = dds.width; - var height = dds.height; - - var faces = dds.isCubemap ? 6 : 1; - - for ( var face = 0; face < faces; face ++ ) { - - for ( var i = 0; i < dds.mipmapCount; i ++ ) { - - if( isRGBAUncompressed ) { - var byteArray = loadARGBMip( buffer, dataOffset, width, height ); - var dataLength = byteArray.length; - } else { - var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes; - var byteArray = new Uint8Array( buffer, dataOffset, dataLength ); - } - - var mipmap = { "data": byteArray, "width": width, "height": height }; - dds.mipmaps.push( mipmap ); - - dataOffset += dataLength; - - width = Math.max( width * 0.5, 1 ); - height = Math.max( height * 0.5, 1 ); - - } - - width = dds.width; - height = dds.height; - - } - - return dds; - - }, - - getNormalMap: function ( image, depth ) { - - // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/ - - var cross = function ( a, b ) { - - return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ]; - - } - - var subtract = function ( a, b ) { - - return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ]; - - } - - var normalize = function ( a ) { - - var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] ); - return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ]; - - } - - depth = depth | 1; - - var width = image.width; - var height = image.height; - - var canvas = document.createElement( 'canvas' ); - canvas.width = width; - canvas.height = height; - - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0 ); - - var data = context.getImageData( 0, 0, width, height ).data; - var imageData = context.createImageData( width, height ); - var output = imageData.data; - - for ( var x = 0; x < width; x ++ ) { - - for ( var y = 0; y < height; y ++ ) { - - var ly = y - 1 < 0 ? 0 : y - 1; - var uy = y + 1 > height - 1 ? height - 1 : y + 1; - var lx = x - 1 < 0 ? 0 : x - 1; - var ux = x + 1 > width - 1 ? width - 1 : x + 1; - - var points = []; - var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ]; - points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] ); - points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] ); - points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] ); - points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] ); - points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] ); - - var normals = []; - var num_points = points.length; - - for ( var i = 0; i < num_points; i ++ ) { - - var v1 = points[ i ]; - var v2 = points[ ( i + 1 ) % num_points ]; - v1 = subtract( v1, origin ); - v2 = subtract( v2, origin ); - normals.push( normalize( cross( v1, v2 ) ) ); - - } - - var normal = [ 0, 0, 0 ]; - - for ( var i = 0; i < normals.length; i ++ ) { - - normal[ 0 ] += normals[ i ][ 0 ]; - normal[ 1 ] += normals[ i ][ 1 ]; - normal[ 2 ] += normals[ i ][ 2 ]; - - } - - normal[ 0 ] /= normals.length; - normal[ 1 ] /= normals.length; - normal[ 2 ] /= normals.length; - - var idx = ( y * width + x ) * 4; - - output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0; - output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0; - output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0; - output[ idx + 3 ] = 255; - - } - - } - - context.putImageData( imageData, 0, 0 ); - - return canvas; - - }, - - generateDataTexture: function ( width, height, color ) { - - var size = width * height; - var data = new Uint8Array( 3 * size ); - - var r = Math.floor( color.r * 255 ); - var g = Math.floor( color.g * 255 ); - var b = Math.floor( color.b * 255 ); - - for ( var i = 0; i < size; i ++ ) { - - data[ i * 3 ] = r; - data[ i * 3 + 1 ] = g; - data[ i * 3 + 2 ] = b; - - } - - var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat ); - texture.needsUpdate = true; - - return texture; - - } - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.SceneUtils = { - - createMultiMaterialObject: function ( geometry, materials ) { - - var group = new THREE.Object3D(); - - for ( var i = 0, l = materials.length; i < l; i ++ ) { - - group.add( new THREE.Mesh( geometry, materials[ i ] ) ); - - } - - return group; - - }, - - detach : function ( child, parent, scene ) { - - child.applyMatrix( parent.matrixWorld ); - parent.remove( child ); - scene.add( child ); - - }, - - attach: function ( child, scene, parent ) { - - var matrixWorldInverse = new THREE.Matrix4(); - matrixWorldInverse.getInverse( parent.matrixWorld ); - child.applyMatrix( matrixWorldInverse ); - - scene.remove( child ); - parent.add( child ); - - } - -}; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * For Text operations in three.js (See TextGeometry) - * - * It uses techniques used in: - * - * typeface.js and canvastext - * For converting fonts and rendering with javascript - * http://typeface.neocracy.org - * - * Triangulation ported from AS3 - * Simple Polygon Triangulation - * http://actionsnippet.com/?p=1462 - * - * A Method to triangulate shapes with holes - * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/ - * - */ - -THREE.FontUtils = { - - faces : {}, - - // Just for now. face[weight][style] - - face : "helvetiker", - weight: "normal", - style : "normal", - size : 150, - divisions : 10, - - getFace : function() { - - return this.faces[ this.face ][ this.weight ][ this.style ]; - - }, - - loadFace : function( data ) { - - var family = data.familyName.toLowerCase(); - - var ThreeFont = this; - - ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {}; - - ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {}; - ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; - - var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; - - return data; - - }, - - drawText : function( text ) { - - var characterPts = [], allPts = []; - - // RenderText - - var i, p, - face = this.getFace(), - scale = this.size / face.resolution, - offset = 0, - chars = String( text ).split( '' ), - length = chars.length; - - var fontPaths = []; - - for ( i = 0; i < length; i ++ ) { - - var path = new THREE.Path(); - - var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path ); - offset += ret.offset; - - fontPaths.push( ret.path ); - - } - - // get the width - - var width = offset / 2; - // - // for ( p = 0; p < allPts.length; p++ ) { - // - // allPts[ p ].x -= width; - // - // } - - //var extract = this.extractPoints( allPts, characterPts ); - //extract.contour = allPts; - - //extract.paths = fontPaths; - //extract.offset = width; - - return { paths : fontPaths, offset : width }; - - }, - - - - - extractGlyphPoints : function( c, face, scale, offset, path ) { - - var pts = []; - - var i, i2, divisions, - outline, action, length, - scaleX, scaleY, - x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, - laste, - glyph = face.glyphs[ c ] || face.glyphs[ '?' ]; - - if ( !glyph ) return; - - if ( glyph.o ) { - - outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - length = outline.length; - - scaleX = scale; - scaleY = scale; - - for ( i = 0; i < length; ) { - - action = outline[ i ++ ]; - - //console.log( action ); - - switch( action ) { - - case 'm': - - // Move To - - x = outline[ i++ ] * scaleX + offset; - y = outline[ i++ ] * scaleY; - - path.moveTo( x, y ); - break; - - case 'l': - - // Line To - - x = outline[ i++ ] * scaleX + offset; - y = outline[ i++ ] * scaleY; - path.lineTo(x,y); - break; - - case 'q': - - // QuadraticCurveTo - - cpx = outline[ i++ ] * scaleX + offset; - cpy = outline[ i++ ] * scaleY; - cpx1 = outline[ i++ ] * scaleX + offset; - cpy1 = outline[ i++ ] * scaleY; - - path.quadraticCurveTo(cpx1, cpy1, cpx, cpy); - - laste = pts[ pts.length - 1 ]; - - if ( laste ) { - - cpx0 = laste.x; - cpy0 = laste.y; - - for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { - - var t = i2 / divisions; - var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); - var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); - } - - } - - break; - - case 'b': - - // Cubic Bezier Curve - - cpx = outline[ i++ ] * scaleX + offset; - cpy = outline[ i++ ] * scaleY; - cpx1 = outline[ i++ ] * scaleX + offset; - cpy1 = outline[ i++ ] * -scaleY; - cpx2 = outline[ i++ ] * scaleX + offset; - cpy2 = outline[ i++ ] * -scaleY; - - path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 ); - - laste = pts[ pts.length - 1 ]; - - if ( laste ) { - - cpx0 = laste.x; - cpy0 = laste.y; - - for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { - - var t = i2 / divisions; - var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); - var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); - - } - - } - - break; - - } - - } - } - - - - return { offset: glyph.ha*scale, path:path}; - } - -}; - - -THREE.FontUtils.generateShapes = function( text, parameters ) { - - // Parameters - - parameters = parameters || {}; - - var size = parameters.size !== undefined ? parameters.size : 100; - var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4; - - var font = parameters.font !== undefined ? parameters.font : "helvetiker"; - var weight = parameters.weight !== undefined ? parameters.weight : "normal"; - var style = parameters.style !== undefined ? parameters.style : "normal"; - - THREE.FontUtils.size = size; - THREE.FontUtils.divisions = curveSegments; - - THREE.FontUtils.face = font; - THREE.FontUtils.weight = weight; - THREE.FontUtils.style = style; - - // Get a Font data json object - - var data = THREE.FontUtils.drawText( text ); - - var paths = data.paths; - var shapes = []; - - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); - - } - - return shapes; - -}; - - -/** - * This code is a quick port of code written in C++ which was submitted to - * flipcode.com by John W. Ratcliff // July 22, 2000 - * See original code and more information here: - * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml - * - * ported to actionscript by Zevan Rosser - * www.actionsnippet.com - * - * ported to javascript by Joshua Koo - * http://www.lab4games.net/zz85/blog - * - */ - - -( function( namespace ) { - - var EPSILON = 0.0000000001; - - // takes in an contour array and returns - - var process = function( contour, indices ) { - - var n = contour.length; - - if ( n < 3 ) return null; - - var result = [], - verts = [], - vertIndices = []; - - /* we want a counter-clockwise polygon in verts */ - - var u, v, w; - - if ( area( contour ) > 0.0 ) { - - for ( v = 0; v < n; v++ ) verts[ v ] = v; - - } else { - - for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v; - - } - - var nv = n; - - /* remove nv - 2 vertices, creating 1 triangle every time */ - - var count = 2 * nv; /* error detection */ - - for( v = nv - 1; nv > 2; ) { - - /* if we loop, it is probably a non-simple polygon */ - - if ( ( count-- ) <= 0 ) { - - //** Triangulate: ERROR - probable bad polygon! - - //throw ( "Warning, unable to triangulate polygon!" ); - //return null; - // Sometimes warning is fine, especially polygons are triangulated in reverse. - console.log( "Warning, unable to triangulate polygon!" ); - - if ( indices ) return vertIndices; - return result; - - } - - /* three consecutive vertices in current polygon, */ - - u = v; if ( nv <= u ) u = 0; /* previous */ - v = u + 1; if ( nv <= v ) v = 0; /* new v */ - w = v + 1; if ( nv <= w ) w = 0; /* next */ - - if ( snip( contour, u, v, w, nv, verts ) ) { - - var a, b, c, s, t; - - /* true names of the vertices */ - - a = verts[ u ]; - b = verts[ v ]; - c = verts[ w ]; - - /* output Triangle */ - - result.push( [ contour[ a ], - contour[ b ], - contour[ c ] ] ); - - - vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - - /* remove v from the remaining polygon */ - - for( s = v, t = v + 1; t < nv; s++, t++ ) { - - verts[ s ] = verts[ t ]; - - } - - nv--; - - /* reset error detection counter */ - - count = 2 * nv; - - } - - } - - if ( indices ) return vertIndices; - return result; - - }; - - // calculate area of the contour polygon - - var area = function ( contour ) { - - var n = contour.length; - var a = 0.0; - - for( var p = n - 1, q = 0; q < n; p = q++ ) { - - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - - } - - return a * 0.5; - - }; - - var snip = function ( contour, u, v, w, n, verts ) { - - var p; - var ax, ay, bx, by; - var cx, cy, px, py; - - ax = contour[ verts[ u ] ].x; - ay = contour[ verts[ u ] ].y; - - bx = contour[ verts[ v ] ].x; - by = contour[ verts[ v ] ].y; - - cx = contour[ verts[ w ] ].x; - cy = contour[ verts[ w ] ].y; - - if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false; - - var aX, aY, bX, bY, cX, cY; - var apx, apy, bpx, bpy, cpx, cpy; - var cCROSSap, bCROSScp, aCROSSbp; - - aX = cx - bx; aY = cy - by; - bX = ax - cx; bY = ay - cy; - cX = bx - ax; cY = by - ay; - - for ( p = 0; p < n; p++ ) { - - px = contour[ verts[ p ] ].x - py = contour[ verts[ p ] ].y - - if ( ( (px === ax) && (py === ay) ) || - ( (px === bx) && (py === by) ) || - ( (px === cx) && (py === cy) ) ) continue; - - apx = px - ax; apy = py - ay; - bpx = px - bx; bpy = py - by; - cpx = px - cx; cpy = py - cy; - - // see if p is inside triangle abc - - aCROSSbp = aX*bpy - aY*bpx; - cCROSSap = cX*apy - cY*apx; - bCROSScp = bX*cpy - bY*cpx; - - if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false; - - } - - return true; - - }; - - - namespace.Triangulate = process; - namespace.Triangulate.area = area; - - return namespace; - -})(THREE.FontUtils); - -// To use the typeface.js face files, hook up the API -self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace }; -THREE.typeface_js = self._typeface_js; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Extensible curve object - * - * Some common of Curve methods - * .getPoint(t), getTangent(t) - * .getPointAt(u), getTagentAt(u) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following classes subclasses THREE.Curve: - * - * -- 2d classes -- - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.CubicBezierCurve - * THREE.SplineCurve - * THREE.ArcCurve - * THREE.EllipseCurve - * - * -- 3d classes -- - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * THREE.CubicBezierCurve3 - * THREE.SplineCurve3 - * THREE.ClosedSplineCurve3 - * - * A series of curves can be represented as a THREE.CurvePath - * - **/ - -/************************************************************** - * Abstract Curve base class - **************************************************************/ - -THREE.Curve = function () { - -}; - -// Virtual base class method to overwrite and implement in subclasses -// - t [0 .. 1] - -THREE.Curve.prototype.getPoint = function ( t ) { - - console.log( "Warning, getPoint() not implemented!" ); - return null; - -}; - -// Get point at relative position in curve according to arc length -// - u [0 .. 1] - -THREE.Curve.prototype.getPointAt = function ( u ) { - - var t = this.getUtoTmapping( u ); - return this.getPoint( t ); - -}; - -// Get sequence of points using getPoint( t ) - -THREE.Curve.prototype.getPoints = function ( divisions ) { - - if ( !divisions ) divisions = 5; - - var d, pts = []; - - for ( d = 0; d <= divisions; d ++ ) { - - pts.push( this.getPoint( d / divisions ) ); - - } - - return pts; - -}; - -// Get sequence of points using getPointAt( u ) - -THREE.Curve.prototype.getSpacedPoints = function ( divisions ) { - - if ( !divisions ) divisions = 5; - - var d, pts = []; - - for ( d = 0; d <= divisions; d ++ ) { - - pts.push( this.getPointAt( d / divisions ) ); - - } - - return pts; - -}; - -// Get total curve arc length - -THREE.Curve.prototype.getLength = function () { - - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; - -}; - -// Get list of cumulative segment lengths - -THREE.Curve.prototype.getLengths = function ( divisions ) { - - if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200; - - if ( this.cacheArcLengths - && ( this.cacheArcLengths.length == divisions + 1 ) - && !this.needsUpdate) { - - //console.log( "cached", this.cacheArcLengths ); - return this.cacheArcLengths; - - } - - this.needsUpdate = false; - - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; - - cache.push( 0 ); - - for ( p = 1; p <= divisions; p ++ ) { - - current = this.getPoint ( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; - - } - - this.cacheArcLengths = cache; - - return cache; // { sums: cache, sum:sum }; Sum is in the last element. - -}; - - -THREE.Curve.prototype.updateArcLengths = function() { - this.needsUpdate = true; - this.getLengths(); -}; - -// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance - -THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) { - - var arcLengths = this.getLengths(); - - var i = 0, il = arcLengths.length; - - var targetArcLength; // The targeted u distance value to get - - if ( distance ) { - - targetArcLength = distance; - - } else { - - targetArcLength = u * arcLengths[ il - 1 ]; - - } - - //var time = Date.now(); - - // binary search for the index with largest value smaller than target u distance - - var low = 0, high = il - 1, comparison; - - while ( low <= high ) { - - i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - - comparison = arcLengths[ i ] - targetArcLength; - - if ( comparison < 0 ) { - - low = i + 1; - continue; - - } else if ( comparison > 0 ) { - - high = i - 1; - continue; - - } else { - - high = i; - break; - - // DONE - - } - - } - - i = high; - - //console.log('b' , i, low, high, Date.now()- time); - - if ( arcLengths[ i ] == targetArcLength ) { - - var t = i / ( il - 1 ); - return t; - - } - - // we could get finer grain at lengths, or use simple interpolatation between two points - - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; - - var segmentLength = lengthAfter - lengthBefore; - - // determine where we are between the 'before' and 'after' points - - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - - // add that fractional amount to t - - var t = ( i + segmentFraction ) / ( il -1 ); - - return t; - -}; - -// Returns a unit vector tangent at t -// In case any sub curve does not implement its tangent derivation, -// 2 points a small delta apart will be used to find its gradient -// which seems to give a reasonable approximation - -THREE.Curve.prototype.getTangent = function( t ) { - - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; - - // Capping in case of danger - - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; - - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); - - var vec = pt2.clone().sub(pt1); - return vec.normalize(); - -}; - - -THREE.Curve.prototype.getTangentAt = function ( u ) { - - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); - -}; - - - - - -/************************************************************** - * Utils - **************************************************************/ - -THREE.Curve.Utils = { - - tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - - return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - - }, - - // Puay Bing, thanks for helping with this derivative! - - tangentCubicBezier: function (t, p0, p1, p2, p3 ) { - - return -3 * p0 * (1 - t) * (1 - t) + - 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) + - 6 * t * p2 * (1-t) - 3 * t * t * p2 + - 3 * t * t * p3; - }, - - - tangentSpline: function ( t, p0, p1, p2, p3 ) { - - // To check if my formulas are correct - - var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 - var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t - var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2 - var h11 = 3 * t * t - 2 * t; // t3 − t2 - - return h00 + h10 + h01 + h11; - - }, - - // Catmull-Rom - - interpolate: function( p0, p1, p2, p3, t ) { - - var v0 = ( p2 - p0 ) * 0.5; - var v1 = ( p3 - p1 ) * 0.5; - var t2 = t * t; - var t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - - } - -}; - - -// TODO: Transformation for Curves? - -/************************************************************** - * 3D Curves - **************************************************************/ - -// A Factory method for creating new curve subclasses - -THREE.Curve.create = function ( constructor, getPointFunc ) { - - constructor.prototype = Object.create( THREE.Curve.prototype ); - constructor.prototype.getPoint = getPointFunc; - - return constructor; - -}; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ - -/************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ - -THREE.CurvePath = function () { - - this.curves = []; - this.bends = []; - - this.autoClose = false; // Automatically closes the path -}; - -THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype ); - -THREE.CurvePath.prototype.add = function ( curve ) { - - this.curves.push( curve ); - -}; - -THREE.CurvePath.prototype.checkConnection = function() { - // TODO - // If the ending of curve is not connected to the starting - // or the next curve, then, this is not a real path -}; - -THREE.CurvePath.prototype.closePath = function() { - // TODO Test - // and verify for vector3 (needs to implement equals) - // Add a line curve if start and end of lines are not connected - var startPoint = this.curves[0].getPoint(0); - var endPoint = this.curves[this.curves.length-1].getPoint(1); - - if (!startPoint.equals(endPoint)) { - this.curves.push( new THREE.LineCurve(endPoint, startPoint) ); - } - -}; - -// To get accurate point with reference to -// entire path distance at time t, -// following has to be done: - -// 1. Length of each sub path have to be known -// 2. Locate and identify type of curve -// 3. Get t for the curve -// 4. Return curve.getPointAt(t') - -THREE.CurvePath.prototype.getPoint = function( t ) { - - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0, diff, curve; - - // To think about boundaries points. - - while ( i < curveLengths.length ) { - - if ( curveLengths[ i ] >= d ) { - - diff = curveLengths[ i ] - d; - curve = this.curves[ i ]; - - var u = 1 - diff / curve.getLength(); - - return curve.getPointAt( u ); - - break; - } - - i ++; - - } - - return null; - - // loop where sum != 0, sum > d , sum+1 maxX ) maxX = p.x; - else if ( p.x < minX ) minX = p.x; - - if ( p.y > maxY ) maxY = p.y; - else if ( p.y < minY ) minY = p.y; - - if ( v3 ) { - - if ( p.z > maxZ ) maxZ = p.z; - else if ( p.z < minZ ) minZ = p.z; - - } - - sum.add( p ); - - } - - var ret = { - - minX: minX, - minY: minY, - maxX: maxX, - maxY: maxY, - centroid: sum.divideScalar( il ) - - }; - - if ( v3 ) { - - ret.maxZ = maxZ; - ret.minZ = minZ; - - } - - return ret; - -}; - -/************************************************************** - * Create Geometries Helpers - **************************************************************/ - -/// Generate geometry from path points (for Line or ParticleSystem objects) - -THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) { - - var pts = this.getPoints( divisions, true ); - return this.createGeometry( pts ); - -}; - -// Generate geometry from equidistance sampling along the path - -THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) { - - var pts = this.getSpacedPoints( divisions, true ); - return this.createGeometry( pts ); - -}; - -THREE.CurvePath.prototype.createGeometry = function( points ) { - - var geometry = new THREE.Geometry(); - - for ( var i = 0; i < points.length; i ++ ) { - - geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) ); - - } - - return geometry; - -}; - - -/************************************************************** - * Bend / Wrap Helper Methods - **************************************************************/ - -// Wrap path / Bend modifiers? - -THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) { - - this.bends.push( bendpath ); - -}; - -THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) { - - var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints - var i, il; - - if ( !bends ) { - - bends = this.bends; - - } - - for ( i = 0, il = bends.length; i < il; i ++ ) { - - oldPts = this.getWrapPoints( oldPts, bends[ i ] ); - - } - - return oldPts; - -}; - -THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) { - - var oldPts = this.getSpacedPoints( segments ); - - var i, il; - - if ( !bends ) { - - bends = this.bends; - - } - - for ( i = 0, il = bends.length; i < il; i ++ ) { - - oldPts = this.getWrapPoints( oldPts, bends[ i ] ); - - } - - return oldPts; - -}; - -// This returns getPoints() bend/wrapped around the contour of a path. -// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html - -THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) { - - var bounds = this.getBoundingBox(); - - var i, il, p, oldX, oldY, xNorm; - - for ( i = 0, il = oldPts.length; i < il; i ++ ) { - - p = oldPts[ i ]; - - oldX = p.x; - oldY = p.y; - - xNorm = oldX / bounds.maxX; - - // If using actual distance, for length > path, requires line extrusions - //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance - - xNorm = path.getUtoTmapping( xNorm, oldX ); - - // check for out of bounds? - - var pathPt = path.getPoint( xNorm ); - var normal = path.getTangent( xNorm ); - normal.set( -normal.y, normal.x ).multiplyScalar( oldY ); - - p.x = pathPt.x + normal.x; - p.y = pathPt.y + normal.y; - - } - - return oldPts; - -}; - -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Gyroscope = function () { - - THREE.Object3D.call( this ); - -}; - -THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) { - - this.matrixAutoUpdate && this.updateMatrix(); - - // update matrixWorld - - if ( this.matrixWorldNeedsUpdate || force ) { - - if ( this.parent ) { - - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - - this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld ); - this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject ); - - this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld ); - - - } else { - - this.matrixWorld.copy( this.matrix ); - - } - - - this.matrixWorldNeedsUpdate = false; - - force = true; - - } - - // update children - - for ( var i = 0, l = this.children.length; i < l; i ++ ) { - - this.children[ i ].updateMatrixWorld( force ); - - } - -}; - -THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3(); -THREE.Gyroscope.prototype.translationObject = new THREE.Vector3(); -THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion(); -THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion(); -THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3(); -THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3(); - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - * - **/ - -THREE.Path = function ( points ) { - - THREE.CurvePath.call(this); - - this.actions = []; - - if ( points ) { - - this.fromPoints( points ); - - } - -}; - -THREE.Path.prototype = Object.create( THREE.CurvePath.prototype ); - -THREE.PathActions = { - - MOVE_TO: 'moveTo', - LINE_TO: 'lineTo', - QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve - BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve - CSPLINE_THRU: 'splineThru', // Catmull-rom spline - ARC: 'arc', // Circle - ELLIPSE: 'ellipse' -}; - -// TODO Clean up PATH API - -// Create path using straight lines to connect all points -// - vectors: array of Vector2 - -THREE.Path.prototype.fromPoints = function ( vectors ) { - - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - - for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) { - - this.lineTo( vectors[ v ].x, vectors[ v ].y ); - - }; - -}; - -// startPath() endPath()? - -THREE.Path.prototype.moveTo = function ( x, y ) { - - var args = Array.prototype.slice.call( arguments ); - this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } ); - -}; - -THREE.Path.prototype.lineTo = function ( x, y ) { - - var args = Array.prototype.slice.call( arguments ); - - var lastargs = this.actions[ this.actions.length - 1 ].args; - - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) ); - this.curves.push( curve ); - - this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } ); - -}; - -THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) { - - var args = Array.prototype.slice.call( arguments ); - - var lastargs = this.actions[ this.actions.length - 1 ].args; - - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ), - new THREE.Vector2( aCPx, aCPy ), - new THREE.Vector2( aX, aY ) ); - this.curves.push( curve ); - - this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } ); - -}; - -THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY ) { - - var args = Array.prototype.slice.call( arguments ); - - var lastargs = this.actions[ this.actions.length - 1 ].args; - - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ), - new THREE.Vector2( aCP1x, aCP1y ), - new THREE.Vector2( aCP2x, aCP2y ), - new THREE.Vector2( aX, aY ) ); - this.curves.push( curve ); - - this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } ); - -}; - -THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) { - - var args = Array.prototype.slice.call( arguments ); - var lastargs = this.actions[ this.actions.length - 1 ].args; - - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; -//--- - var npts = [ new THREE.Vector2( x0, y0 ) ]; - Array.prototype.push.apply( npts, pts ); - - var curve = new THREE.SplineCurve( npts ); - this.curves.push( curve ); - - this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } ); - -}; - -// FUTURE: Change the API or follow canvas API? - -THREE.Path.prototype.arc = function ( aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise ) { - - var lastargs = this.actions[ this.actions.length - 1].args; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - this.absarc(aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); - - }; - - THREE.Path.prototype.absarc = function ( aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise ) { - this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); - }; - -THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ) { - - var lastargs = this.actions[ this.actions.length - 1].args; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; - - this.absellipse(aX + x0, aY + y0, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ); - - }; - - -THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ) { - - var args = Array.prototype.slice.call( arguments ); - var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ); - this.curves.push( curve ); - - var lastPoint = curve.getPoint(1); - args.push(lastPoint.x); - args.push(lastPoint.y); - - this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } ); - - }; - -THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) { - - if ( ! divisions ) divisions = 40; - - var points = []; - - for ( var i = 0; i < divisions; i ++ ) { - - points.push( this.getPoint( i / divisions ) ); - - //if( !this.getPoint( i / divisions ) ) throw "DIE"; - - } - - // if ( closedPath ) { - // - // points.push( points[ 0 ] ); - // - // } - - return points; - -}; - -/* Return an array of vectors based on contour of the path */ - -THREE.Path.prototype.getPoints = function( divisions, closedPath ) { - - if (this.useSpacedPoints) { - console.log('tata'); - return this.getSpacedPoints( divisions, closedPath ); - } - - divisions = divisions || 12; - - var points = []; - - var i, il, item, action, args; - var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0, - laste, j, - t, tx, ty; - - for ( i = 0, il = this.actions.length; i < il; i ++ ) { - - item = this.actions[ i ]; - - action = item.action; - args = item.args; - - switch( action ) { - - case THREE.PathActions.MOVE_TO: - - points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); - - break; - - case THREE.PathActions.LINE_TO: - - points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); - - break; - - case THREE.PathActions.QUADRATIC_CURVE_TO: - - cpx = args[ 2 ]; - cpy = args[ 3 ]; - - cpx1 = args[ 0 ]; - cpy1 = args[ 1 ]; - - if ( points.length > 0 ) { - - laste = points[ points.length - 1 ]; - - cpx0 = laste.x; - cpy0 = laste.y; - - } else { - - laste = this.actions[ i - 1 ].args; - - cpx0 = laste[ laste.length - 2 ]; - cpy0 = laste[ laste.length - 1 ]; - - } - - for ( j = 1; j <= divisions; j ++ ) { - - t = j / divisions; - - tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); - ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); - - points.push( new THREE.Vector2( tx, ty ) ); - - } - - break; - - case THREE.PathActions.BEZIER_CURVE_TO: - - cpx = args[ 4 ]; - cpy = args[ 5 ]; - - cpx1 = args[ 0 ]; - cpy1 = args[ 1 ]; - - cpx2 = args[ 2 ]; - cpy2 = args[ 3 ]; - - if ( points.length > 0 ) { - - laste = points[ points.length - 1 ]; - - cpx0 = laste.x; - cpy0 = laste.y; - - } else { - - laste = this.actions[ i - 1 ].args; - - cpx0 = laste[ laste.length - 2 ]; - cpy0 = laste[ laste.length - 1 ]; - - } - - - for ( j = 1; j <= divisions; j ++ ) { - - t = j / divisions; - - tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); - ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); - - points.push( new THREE.Vector2( tx, ty ) ); - - } - - break; - - case THREE.PathActions.CSPLINE_THRU: - - laste = this.actions[ i - 1 ].args; - - var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] ); - var spts = [ last ]; - - var n = divisions * args[ 0 ].length; - - spts = spts.concat( args[ 0 ] ); - - var spline = new THREE.SplineCurve( spts ); - - for ( j = 1; j <= n; j ++ ) { - - points.push( spline.getPointAt( j / n ) ) ; - - } - - break; - - case THREE.PathActions.ARC: - - var aX = args[ 0 ], aY = args[ 1 ], - aRadius = args[ 2 ], - aStartAngle = args[ 3 ], aEndAngle = args[ 4 ], - aClockwise = !!args[ 5 ]; - - var deltaAngle = aEndAngle - aStartAngle; - var angle; - var tdivisions = divisions * 2; - - for ( j = 1; j <= tdivisions; j ++ ) { - - t = j / tdivisions; - - if ( ! aClockwise ) { - - t = 1 - t; - - } - - angle = aStartAngle + t * deltaAngle; - - tx = aX + aRadius * Math.cos( angle ); - ty = aY + aRadius * Math.sin( angle ); - - //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); - - points.push( new THREE.Vector2( tx, ty ) ); - - } - - //console.log(points); - - break; - - case THREE.PathActions.ELLIPSE: - - var aX = args[ 0 ], aY = args[ 1 ], - xRadius = args[ 2 ], - yRadius = args[ 3 ], - aStartAngle = args[ 4 ], aEndAngle = args[ 5 ], - aClockwise = !!args[ 6 ]; - - - var deltaAngle = aEndAngle - aStartAngle; - var angle; - var tdivisions = divisions * 2; - - for ( j = 1; j <= tdivisions; j ++ ) { - - t = j / tdivisions; - - if ( ! aClockwise ) { - - t = 1 - t; - - } - - angle = aStartAngle + t * deltaAngle; - - tx = aX + xRadius * Math.cos( angle ); - ty = aY + yRadius * Math.sin( angle ); - - //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); - - points.push( new THREE.Vector2( tx, ty ) ); - - } - - //console.log(points); - - break; - - } // end switch - - } - - - - // Normalize to remove the closing point by default. - var lastPoint = points[ points.length - 1]; - var EPSILON = 0.0000000001; - if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON && - Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON) - points.splice( points.length - 1, 1); - if ( closedPath ) { - - points.push( points[ 0 ] ); - - } - - return points; - -}; - -// Breaks path into shapes - -THREE.Path.prototype.toShapes = function( isCCW ) { - - function isPointInsidePolygon( inPt, inPolygon ) { - var EPSILON = 0.0000000001; - - var polyLen = inPolygon.length; - - // inPt on polygon contour => immediate success or - // toggling of inside/outside at every single! intersection point of an edge - // with the horizontal line through inPt, left of inPt - // not counting lowerY endpoints of edges and whole edges on that line - var inside = false; - for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) { - var edgeLowPt = inPolygon[ p ]; - var edgeHighPt = inPolygon[ q ]; - - var edgeDx = edgeHighPt.x - edgeLowPt.x; - var edgeDy = edgeHighPt.y - edgeLowPt.y; - - if ( Math.abs(edgeDy) > EPSILON ) { // not parallel - if ( edgeDy < 0 ) { - edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy; - } - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; - - if ( inPt.y == edgeLowPt.y ) { - if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! - } else { - var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); - if ( perpEdge == 0 ) return true; // inPt is on contour ? - if ( perpEdge < 0 ) continue; - inside = !inside; // true intersection left of inPt - } - } else { // parallel or colinear - if ( inPt.y != edgeLowPt.y ) continue; // parallel - // egde lies on the same horizontal line as inPt - if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || - ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! - // continue; - } - } - - return inside; - } - - var i, il, item, action, args; - - var subPaths = [], lastPath = new THREE.Path(); - - for ( i = 0, il = this.actions.length; i < il; i ++ ) { - - item = this.actions[ i ]; - - args = item.args; - action = item.action; - - if ( action == THREE.PathActions.MOVE_TO ) { - - if ( lastPath.actions.length != 0 ) { - - subPaths.push( lastPath ); - lastPath = new THREE.Path(); - - } - - } - - lastPath[ action ].apply( lastPath, args ); - - } - - if ( lastPath.actions.length != 0 ) { - - subPaths.push( lastPath ); - - } - - // console.log(subPaths); - - if ( subPaths.length == 0 ) return []; - - var solid, tmpPath, tmpShape, shapes = []; - - if ( subPaths.length == 1) { - - tmpPath = subPaths[0]; - tmpShape = new THREE.Shape(); - tmpShape.actions = tmpPath.actions; - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; - - } - - var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? !holesFirst : holesFirst; - - // console.log("Holes first", holesFirst); - - var betterShapeHoles = []; - var newShapes = []; - var newShapeHoles = []; - var mainIdx = 0; - var tmpPoints; - - newShapes[mainIdx] = undefined; - newShapeHoles[mainIdx] = []; - - for ( i = 0, il = subPaths.length; i < il; i ++ ) { - - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = THREE.Shape.Utils.isClockWise( tmpPoints ); - solid = isCCW ? !solid : solid; - - if ( solid ) { - - if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++; - - newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints }; - newShapes[mainIdx].s.actions = tmpPath.actions; - newShapes[mainIdx].s.curves = tmpPath.curves; - - if ( holesFirst ) mainIdx++; - newShapeHoles[mainIdx] = []; - - //console.log('cw', i); - - } else { - - newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } ); - - //console.log('ccw', i); - - } - - } - - if ( newShapes.length > 1 ) { - var ambigious = false; - var toChange = []; - - for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) { - betterShapeHoles[sIdx] = []; - } - for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) { - var sh = newShapes[sIdx]; - var sho = newShapeHoles[sIdx]; - for (var hIdx = 0; hIdx < sho.length; hIdx++ ) { - var ho = sho[hIdx]; - var hole_unassigned = true; - for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) { - if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) { - if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { - hole_unassigned = false; - betterShapeHoles[s2Idx].push( ho ); - } else { - ambigious = true; - } - } - } - if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); } - } - } - // console.log("ambigious: ", ambigious); - if ( toChange.length > 0 ) { - // console.log("to change: ", toChange); - if (! ambigious) newShapeHoles = betterShapeHoles; - } - } - - var tmpHoles, j, jl; - for ( i = 0, il = newShapes.length; i < il; i ++ ) { - tmpShape = newShapes[i].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[i]; - for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) { - tmpShape.holes.push( tmpHoles[j].h ); - } - } - - //console.log("shape", shapes); - - return shapes; - -}; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Defines a 2d shape plane using paths. - **/ - -// STEP 1 Create a path. -// STEP 2 Turn path into shape. -// STEP 3 ExtrudeGeometry takes in Shape/Shapes -// STEP 3a - Extract points from each shape, turn to vertices -// STEP 3b - Triangulate each shape, add faces. - -THREE.Shape = function () { - - THREE.Path.apply( this, arguments ); - this.holes = []; - -}; - -THREE.Shape.prototype = Object.create( THREE.Path.prototype ); - -// Convenience method to return ExtrudeGeometry - -THREE.Shape.prototype.extrude = function ( options ) { - - var extruded = new THREE.ExtrudeGeometry( this, options ); - return extruded; - -}; - -// Convenience method to return ShapeGeometry - -THREE.Shape.prototype.makeGeometry = function ( options ) { - - var geometry = new THREE.ShapeGeometry( this, options ); - return geometry; - -}; - -// Get points of holes - -THREE.Shape.prototype.getPointsHoles = function ( divisions ) { - - var i, il = this.holes.length, holesPts = []; - - for ( i = 0; i < il; i ++ ) { - - holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends ); - - } - - return holesPts; - -}; - -// Get points of holes (spaced by regular distance) - -THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) { - - var i, il = this.holes.length, holesPts = []; - - for ( i = 0; i < il; i ++ ) { - - holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends ); - - } - - return holesPts; - -}; - - -// Get points of shape and holes (keypoints based on segments parameter) - -THREE.Shape.prototype.extractAllPoints = function ( divisions ) { - - return { - - shape: this.getTransformedPoints( divisions ), - holes: this.getPointsHoles( divisions ) - - }; - -}; - -THREE.Shape.prototype.extractPoints = function ( divisions ) { - - if (this.useSpacedPoints) { - return this.extractAllSpacedPoints(divisions); - } - - return this.extractAllPoints(divisions); - -}; - -// -// THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) { -// -// return { -// -// shape: this.transform( bend, divisions ), -// holes: this.getPointsHoles( divisions, bend ) -// -// }; -// -// }; - -// Get points of shape and holes (spaced by regular distance) - -THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) { - - return { - - shape: this.getTransformedSpacedPoints( divisions ), - holes: this.getSpacedPointsHoles( divisions ) - - }; - -}; - -/************************************************************** - * Utils - **************************************************************/ - -THREE.Shape.Utils = { - - triangulateShape: function ( contour, holes ) { - - function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - // inOtherPt needs to be colinear to the inSegment - if ( inSegPt1.x != inSegPt2.x ) { - if ( inSegPt1.x < inSegPt2.x ) { - return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); - } else { - return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); - } - } else { - if ( inSegPt1.y < inSegPt2.y ) { - return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); - } else { - return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); - } - } - } - - function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - var EPSILON = 0.0000000001; - - var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; - var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - - var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; - var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - - var limit = seg1dy * seg2dx - seg1dx * seg2dy; - var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - - if ( Math.abs(limit) > EPSILON ) { // not parallel - - var perpSeg2; - if ( limit > 0 ) { - if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; - } else { - if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; - } - - // i.e. to reduce rounding errors - // intersection at endpoint of segment#1? - if ( perpSeg2 == 0 ) { - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return []; - return [ inSeg1Pt1 ]; - } - if ( perpSeg2 == limit ) { - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return []; - return [ inSeg1Pt2 ]; - } - // intersection at endpoint of segment#2? - if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ]; - if ( perpSeg1 == limit ) return [ inSeg2Pt2 ]; - - // return real intersection point - var factorSeg1 = perpSeg2 / limit; - return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, - y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - - } else { // parallel or colinear - if ( ( perpSeg1 != 0 ) || - ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return []; - - // they are collinear or degenerate - var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point? - var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point? - // both segments are points - if ( seg1Pt && seg2Pt ) { - if ( (inSeg1Pt1.x != inSeg2Pt1.x) || - (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points - return [ inSeg1Pt1 ]; // they are the same point - } - // segment#1 is a single point - if ( seg1Pt ) { - if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 - return [ inSeg1Pt1 ]; - } - // segment#2 is a single point - if ( seg2Pt ) { - if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 - return [ inSeg2Pt1 ]; - } - - // they are collinear segments, which might overlap - var seg1min, seg1max, seg1minVal, seg1maxVal; - var seg2min, seg2max, seg2minVal, seg2maxVal; - if (seg1dx != 0) { // the segments are NOT on a vertical line - if ( inSeg1Pt1.x < inSeg1Pt2.x ) { - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; - } else { - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; - } - if ( inSeg2Pt1.x < inSeg2Pt2.x ) { - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; - } else { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; - } - } else { // the segments are on a vertical line - if ( inSeg1Pt1.y < inSeg1Pt2.y ) { - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; - } else { - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; - } - if ( inSeg2Pt1.y < inSeg2Pt2.y ) { - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; - } else { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; - } - } - if ( seg1minVal <= seg2minVal ) { - if ( seg1maxVal < seg2minVal ) return []; - if ( seg1maxVal == seg2minVal ) { - if ( inExcludeAdjacentSegs ) return []; - return [ seg2min ]; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; - return [ seg2min, seg2max ]; - } else { - if ( seg1minVal > seg2maxVal ) return []; - if ( seg1minVal == seg2maxVal ) { - if ( inExcludeAdjacentSegs ) return []; - return [ seg1min ]; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; - return [ seg1min, seg2max ]; - } - } - } - - function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - // The order of legs is important - - var EPSILON = 0.0000000001; - - // translation of all points, so that Vertex is at (0,0) - var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; - var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; - var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; - - // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. - var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; - var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; - - if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg. - - var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; - // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - - if ( from2toAngle > 0 ) { // main angle < 180 deg. - return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); - } else { // main angle > 180 deg. - return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); - } - } else { // angle == 180 deg. - // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); - return ( from2otherAngle > 0 ); - } - } - - - function removeHoles( contour, holes ) { - - var shape = contour.concat(); // work on this shape - var hole; - - function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { - // Check if hole point lies within angle around shape point - var lastShapeIdx = shape.length - 1; - - var prevShapeIdx = inShapeIdx - 1; - if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; - - var nextShapeIdx = inShapeIdx + 1; - if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; - - var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] ); - if (! insideAngle ) { - // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); - return false; - } - - // Check if shape point lies within angle around hole point - var lastHoleIdx = hole.length - 1; - - var prevHoleIdx = inHoleIdx - 1; - if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - - var nextHoleIdx = inHoleIdx + 1; - if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - - insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] ); - if (! insideAngle ) { - // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); - return false; - } - - return true; - } - - function intersectsShapeEdge( inShapePt, inHolePt ) { - // checks for intersections with shape edges - var sIdx, nextIdx, intersection; - for ( sIdx = 0; sIdx < shape.length; sIdx++ ) { - nextIdx = sIdx+1; nextIdx %= shape.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true ); - if ( intersection.length > 0 ) return true; - } - - return false; - } - - var indepHoles = []; - - function intersectsHoleEdge( inShapePt, inHolePt ) { - // checks for intersections with hole edges - var ihIdx, chkHole, - hIdx, nextIdx, intersection; - for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) { - chkHole = holes[indepHoles[ihIdx]]; - for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) { - nextIdx = hIdx+1; nextIdx %= chkHole.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true ); - if ( intersection.length > 0 ) return true; - } - } - return false; - } - - var holeIndex, shapeIndex, - shapePt, holePt, - holeIdx, cutKey, failedCuts = [], - tmpShape1, tmpShape2, - tmpHole1, tmpHole2; - - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - - indepHoles.push( h ); - - } - - var counter = indepHoles.length * 2; - while ( indepHoles.length > 0 ) { - counter --; - if ( counter < 0 ) { - console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); - break; - } - - // search for shape-vertex and hole-vertex, - // which can be connected without intersections - for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) { - - shapePt = shape[ shapeIndex ]; - holeIndex = -1; - - // search for hole which can be reached without intersections - for ( var h = 0; h < indepHoles.length; h ++ ) { - holeIdx = indepHoles[h]; - - // prevent multiple checks - cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; - if ( failedCuts[cutKey] !== undefined ) continue; - - hole = holes[holeIdx]; - for ( var h2 = 0; h2 < hole.length; h2 ++ ) { - holePt = hole[ h2 ]; - if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; - if ( intersectsShapeEdge( shapePt, holePt ) ) continue; - if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - - holeIndex = h2; - indepHoles.splice(h,1); - - tmpShape1 = shape.slice( 0, shapeIndex+1 ); - tmpShape2 = shape.slice( shapeIndex ); - tmpHole1 = hole.slice( holeIndex ); - tmpHole2 = hole.slice( 0, holeIndex+1 ); - - shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - - // Debug only, to show the selected cuts - // glob_CutLines.push( [ shapePt, holePt ] ); - - break; - } - if ( holeIndex >= 0 ) break; // hole-vertex found - - failedCuts[cutKey] = true; // remember failure - } - if ( holeIndex >= 0 ) break; // hole-vertex found - } - } - - return shape; /* shape with no holes */ - } - - - var i, il, f, face, - key, index, - allPointsMap = {}; - - // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. - - var allpoints = contour.concat(); - - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - - Array.prototype.push.apply( allpoints, holes[h] ); - - } - - //console.log( "allpoints",allpoints, allpoints.length ); - - // prepare all points map - - for ( i = 0, il = allpoints.length; i < il; i ++ ) { - - key = allpoints[ i ].x + ":" + allpoints[ i ].y; - - if ( allPointsMap[ key ] !== undefined ) { - - console.log( "Duplicate point", key ); - - } - - allPointsMap[ key ] = i; - - } - - // remove holes by cutting paths to holes and adding them to the shape - var shapeWithoutHoles = removeHoles( contour, holes ); - - var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape - //console.log( "triangles",triangles, triangles.length ); - - // check all face vertices against all points map - - for ( i = 0, il = triangles.length; i < il; i ++ ) { - - face = triangles[ i ]; - - for ( f = 0; f < 3; f ++ ) { - - key = face[ f ].x + ":" + face[ f ].y; - - index = allPointsMap[ key ]; - - if ( index !== undefined ) { - - face[ f ] = index; - - } - - } - - } - - return triangles.concat(); - - }, - - isClockWise: function ( pts ) { - - return THREE.FontUtils.Triangulate.area( pts ) < 0; - - }, - - // Bezier Curves formulas obtained from - // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - - // Quad Bezier Functions - - b2p0: function ( t, p ) { - - var k = 1 - t; - return k * k * p; - - }, - - b2p1: function ( t, p ) { - - return 2 * ( 1 - t ) * t * p; - - }, - - b2p2: function ( t, p ) { - - return t * t * p; - - }, - - b2: function ( t, p0, p1, p2 ) { - - return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 ); - - }, - - // Cubic Bezier Functions - - b3p0: function ( t, p ) { - - var k = 1 - t; - return k * k * k * p; - - }, - - b3p1: function ( t, p ) { - - var k = 1 - t; - return 3 * k * k * t * p; - - }, - - b3p2: function ( t, p ) { - - var k = 1 - t; - return 3 * k * t * t * p; - - }, - - b3p3: function ( t, p ) { - - return t * t * t * p; - - }, - - b3: function ( t, p0, p1, p2, p3 ) { - - return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 ); - - } - -}; - -/************************************************************** - * Line - **************************************************************/ - -THREE.LineCurve = function ( v1, v2 ) { - - this.v1 = v1; - this.v2 = v2; - -}; - -THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); - -THREE.LineCurve.prototype.getPoint = function ( t ) { - - var point = this.v2.clone().sub(this.v1); - point.multiplyScalar( t ).add( this.v1 ); - - return point; - -}; - -// Line curve is linear, so we can overwrite default getPointAt - -THREE.LineCurve.prototype.getPointAt = function ( u ) { - - return this.getPoint( u ); - -}; - -THREE.LineCurve.prototype.getTangent = function( t ) { - - var tangent = this.v2.clone().sub(this.v1); - - return tangent.normalize(); - -};/************************************************************** - * Quadratic Bezier curve - **************************************************************/ - - -THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { - - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - -}; - -THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); - - -THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { - - var tx, ty; - - tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); - ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); - - return new THREE.Vector2( tx, ty ); - -}; - - -THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { - - var tx, ty; - - tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ); - ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ); - - // returns unit vector - - var tangent = new THREE.Vector2( tx, ty ); - tangent.normalize(); - - return tangent; - -};/************************************************************** - * Cubic Bezier curve - **************************************************************/ - -THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { - - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; - -}; - -THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); - -THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { - - var tx, ty; - - tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - - return new THREE.Vector2( tx, ty ); - -}; - -THREE.CubicBezierCurve.prototype.getTangent = function( t ) { - - var tx, ty; - - tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - - var tangent = new THREE.Vector2( tx, ty ); - tangent.normalize(); - - return tangent; - -};/************************************************************** - * Spline curve - **************************************************************/ - -THREE.SplineCurve = function ( points /* array of Vector2 */ ) { - - this.points = (points == undefined) ? [] : points; - -}; - -THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); - -THREE.SplineCurve.prototype.getPoint = function ( t ) { - - var v = new THREE.Vector2(); - var c = []; - var points = this.points, point, intPoint, weight; - point = ( points.length - 1 ) * t; - - intPoint = Math.floor( point ); - weight = point - intPoint; - - c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1; - c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2; - - v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight ); - v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight ); - - return v; - -};/************************************************************** - * Ellipse curve - **************************************************************/ - -THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) { - - this.aX = aX; - this.aY = aY; - - this.xRadius = xRadius; - this.yRadius = yRadius; - - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; - - this.aClockwise = aClockwise; - -}; - -THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); - -THREE.EllipseCurve.prototype.getPoint = function ( t ) { - - var angle; - var deltaAngle = this.aEndAngle - this.aStartAngle; - - if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2; - if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2; - - if ( this.aClockwise === true ) { - - angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle ); - - } else { - - angle = this.aStartAngle + t * deltaAngle; - - } - - var tx = this.aX + this.xRadius * Math.cos( angle ); - var ty = this.aY + this.yRadius * Math.sin( angle ); - - return new THREE.Vector2( tx, ty ); - -}; -/************************************************************** - * Arc curve - **************************************************************/ - -THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - - THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); -}; - -THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );/************************************************************** - * Line3D - **************************************************************/ - -THREE.LineCurve3 = THREE.Curve.create( - - function ( v1, v2 ) { - - this.v1 = v1; - this.v2 = v2; - - }, - - function ( t ) { - - var r = new THREE.Vector3(); - - - r.subVectors( this.v2, this.v1 ); // diff - r.multiplyScalar( t ); - r.add( this.v1 ); - - return r; - - } - -); -/************************************************************** - * Quadratic Bezier 3D curve - **************************************************************/ - -THREE.QuadraticBezierCurve3 = THREE.Curve.create( - - function ( v0, v1, v2 ) { - - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - - }, - - function ( t ) { - - var tx, ty, tz; - - tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); - ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); - tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z ); - - return new THREE.Vector3( tx, ty, tz ); - - } - -);/************************************************************** - * Cubic Bezier 3D curve - **************************************************************/ - -THREE.CubicBezierCurve3 = THREE.Curve.create( - - function ( v0, v1, v2, v3 ) { - - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; - - }, - - function ( t ) { - - var tx, ty, tz; - - tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ); - - return new THREE.Vector3( tx, ty, tz ); - - } - -);/************************************************************** - * Spline 3D curve - **************************************************************/ - - -THREE.SplineCurve3 = THREE.Curve.create( - - function ( points /* array of Vector3 */) { - - this.points = (points == undefined) ? [] : points; - - }, - - function ( t ) { - - var v = new THREE.Vector3(); - var c = []; - var points = this.points, point, intPoint, weight; - point = ( points.length - 1 ) * t; - - intPoint = Math.floor( point ); - weight = point - intPoint; - - c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1; - c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2; - - var pt0 = points[ c[0] ], - pt1 = points[ c[1] ], - pt2 = points[ c[2] ], - pt3 = points[ c[3] ]; - - v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight); - v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight); - v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight); - - return v; - - } - -); - - -/* THREE.SplineCurve3.prototype.getTangent = function(t) { - var v = new THREE.Vector3(); - var c = []; - var points = this.points, point, intPoint, weight; - point = ( points.length - 1 ) * t; - - intPoint = Math.floor( point ); - weight = point - intPoint; - - c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1; - c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2; - - var pt0 = points[ c[0] ], - pt1 = points[ c[1] ], - pt2 = points[ c[2] ], - pt3 = points[ c[3] ]; - - // t = weight; - v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x ); - v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y ); - v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z ); - return v; - -}*/ - -/************************************************************** - * Closed Spline 3D curve - **************************************************************/ - - -THREE.ClosedSplineCurve3 = THREE.Curve.create( - - function ( points /* array of Vector3 */) { - - this.points = (points == undefined) ? [] : points; - - }, - - function ( t ) { - - var v = new THREE.Vector3(); - var c = []; - var points = this.points, point, intPoint, weight; - point = ( points.length - 0 ) * t; - // This needs to be from 0-length +1 - - intPoint = Math.floor( point ); - weight = point - intPoint; - - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; - c[ 0 ] = ( intPoint - 1 ) % points.length; - c[ 1 ] = ( intPoint ) % points.length; - c[ 2 ] = ( intPoint + 1 ) % points.length; - c[ 3 ] = ( intPoint + 2 ) % points.length; - - v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight ); - v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight ); - v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight ); - - return v; - - } - -);/** - * @author mikael emtinger / http://gomo.se/ - */ - -THREE.AnimationHandler = (function() { - - var playing = []; - var library = {}; - var that = {}; - - - //--- update --- - - that.update = function( deltaTimeMS ) { - - for( var i = 0; i < playing.length; i ++ ) - playing[ i ].update( deltaTimeMS ); - - }; - - - //--- add --- - - that.addToUpdate = function( animation ) { - - if ( playing.indexOf( animation ) === -1 ) - playing.push( animation ); - - }; - - - //--- remove --- - - that.removeFromUpdate = function( animation ) { - - var index = playing.indexOf( animation ); - - if( index !== -1 ) - playing.splice( index, 1 ); - - }; - - - //--- add --- - - that.add = function( data ) { - - if ( library[ data.name ] !== undefined ) - console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." ); - - library[ data.name ] = data; - initData( data ); - - }; - - - //--- get --- - - that.get = function( name ) { - - if ( typeof name === "string" ) { - - if ( library[ name ] ) { - - return library[ name ]; - - } else { - - console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name ); - return null; - - } - - } else { - - // todo: add simple tween library - - } - - }; - - //--- parse --- - - that.parse = function( root ) { - - // setup hierarchy - - var hierarchy = []; - - if ( root instanceof THREE.SkinnedMesh ) { - - for( var b = 0; b < root.bones.length; b++ ) { - - hierarchy.push( root.bones[ b ] ); - - } - - } else { - - parseRecurseHierarchy( root, hierarchy ); - - } - - return hierarchy; - - }; - - var parseRecurseHierarchy = function( root, hierarchy ) { - - hierarchy.push( root ); - - for( var c = 0; c < root.children.length; c++ ) - parseRecurseHierarchy( root.children[ c ], hierarchy ); - - } - - - //--- init data --- - - var initData = function( data ) { - - if( data.initialized === true ) - return; - - - // loop through all keys - - for( var h = 0; h < data.hierarchy.length; h ++ ) { - - for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - - // remove minus times - - if( data.hierarchy[ h ].keys[ k ].time < 0 ) - data.hierarchy[ h ].keys[ k ].time = 0; - - - // create quaternions - - if( data.hierarchy[ h ].keys[ k ].rot !== undefined && - !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) { - - var quat = data.hierarchy[ h ].keys[ k ].rot; - data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] ); - - } - - } - - - // prepare morph target keys - - if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) { - - // get all used - - var usedMorphTargets = {}; - - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - - for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { - - var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ]; - usedMorphTargets[ morphTargetName ] = -1; - - } - - } - - data.hierarchy[ h ].usedMorphTargets = usedMorphTargets; - - - // set all used on all frames - - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - - var influences = {}; - - for ( var morphTargetName in usedMorphTargets ) { - - for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { - - if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) { - - influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ]; - break; - - } - - } - - if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) { - - influences[ morphTargetName ] = 0; - - } - - } - - data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences; - - } - - } - - - // remove all keys that are on the same time - - for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) { - - if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) { - - data.hierarchy[ h ].keys.splice( k, 1 ); - k --; - - } - - } - - - // set index - - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - - data.hierarchy[ h ].keys[ k ].index = k; - - } - - } - - // done - - data.initialized = true; - - }; - - - // interpolation types - - that.LINEAR = 0; - that.CATMULLROM = 1; - that.CATMULLROM_FORWARD = 2; - - return that; - -}()); -/** - * @author mikael emtinger / http://gomo.se/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.Animation = function ( root, name ) { - - this.root = root; - this.data = THREE.AnimationHandler.get( name ); - this.hierarchy = THREE.AnimationHandler.parse( root ); - - this.currentTime = 0; - this.timeScale = 1; - - this.isPlaying = false; - this.isPaused = true; - this.loop = true; - - this.interpolationType = THREE.AnimationHandler.LINEAR; - -}; - -THREE.Animation.prototype.play = function ( startTime ) { - - this.currentTime = startTime !== undefined ? startTime : 0; - - if ( this.isPlaying === false ) { - - this.isPlaying = true; - - this.reset(); - this.update( 0 ); - - } - - this.isPaused = false; - - THREE.AnimationHandler.addToUpdate( this ); - -}; - - -THREE.Animation.prototype.pause = function() { - - if ( this.isPaused === true ) { - - THREE.AnimationHandler.addToUpdate( this ); - - } else { - - THREE.AnimationHandler.removeFromUpdate( this ); - - } - - this.isPaused = !this.isPaused; - -}; - - -THREE.Animation.prototype.stop = function() { - - this.isPlaying = false; - this.isPaused = false; - THREE.AnimationHandler.removeFromUpdate( this ); - -}; - -THREE.Animation.prototype.reset = function () { - - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - - var object = this.hierarchy[ h ]; - - object.matrixAutoUpdate = true; - - if ( object.animationCache === undefined ) { - - object.animationCache = {}; - object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 }; - object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 }; - object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix; - - } - - var prevKey = object.animationCache.prevKey; - var nextKey = object.animationCache.nextKey; - - prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ]; - prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ]; - prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ]; - - nextKey.pos = this.getNextKeyWith( "pos", h, 1 ); - nextKey.rot = this.getNextKeyWith( "rot", h, 1 ); - nextKey.scl = this.getNextKeyWith( "scl", h, 1 ); - - } - -}; - - -THREE.Animation.prototype.update = (function(){ - - var points = []; - var target = new THREE.Vector3(); - - // Catmull-Rom spline - - var interpolateCatmullRom = function ( points, scale ) { - - var c = [], v3 = [], - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; - - point = ( points.length - 1 ) * scale; - intPoint = Math.floor( point ); - weight = point - intPoint; - - c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1; - c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2; - - pa = points[ c[ 0 ] ]; - pb = points[ c[ 1 ] ]; - pc = points[ c[ 2 ] ]; - pd = points[ c[ 3 ] ]; - - w2 = weight * weight; - w3 = weight * w2; - - v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 ); - v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 ); - v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 ); - - return v3; - - }; - - var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) { - - var v0 = ( p2 - p0 ) * 0.5, - v1 = ( p3 - p1 ) * 0.5; - - return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; - - }; - - return function ( delta ) { - if ( this.isPlaying === false ) return; - - this.currentTime += delta * this.timeScale; - - // - - var vector; - var types = [ "pos", "rot", "scl" ]; - - var duration = this.data.length; - - if ( this.loop === true && this.currentTime > duration ) { - - this.currentTime %= duration; - this.reset(); - - } else if ( this.loop === false && this.currentTime > duration ) { - - this.stop(); - return; - - } - - this.currentTime = Math.min( this.currentTime, duration ); - - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - - var object = this.hierarchy[ h ]; - var animationCache = object.animationCache; - - // loop through pos/rot/scl - - for ( var t = 0; t < 3; t ++ ) { - - // get keys - - var type = types[ t ]; - var prevKey = animationCache.prevKey[ type ]; - var nextKey = animationCache.nextKey[ type ]; - - if ( nextKey.time <= this.currentTime ) { - - prevKey = this.data.hierarchy[ h ].keys[ 0 ]; - nextKey = this.getNextKeyWith( type, h, 1 ); - - while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { - - prevKey = nextKey; - nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); - - } - - animationCache.prevKey[ type ] = prevKey; - animationCache.nextKey[ type ] = nextKey; - - } - - object.matrixAutoUpdate = true; - object.matrixWorldNeedsUpdate = true; - - var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time ); - - var prevXYZ = prevKey[ type ]; - var nextXYZ = nextKey[ type ]; - - if ( scale < 0 ) scale = 0; - if ( scale > 1 ) scale = 1; - - // interpolate - - if ( type === "pos" ) { - - vector = object.position; - - if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) { - - vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; - vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; - vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; - - } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - - points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ]; - points[ 1 ] = prevXYZ; - points[ 2 ] = nextXYZ; - points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ]; - - scale = scale * 0.33 + 0.33; - - var currentPoint = interpolateCatmullRom( points, scale ); - - vector.x = currentPoint[ 0 ]; - vector.y = currentPoint[ 1 ]; - vector.z = currentPoint[ 2 ]; - - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - - var forwardPoint = interpolateCatmullRom( points, scale * 1.01 ); - - target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] ); - target.sub( vector ); - target.y = 0; - target.normalize(); - - var angle = Math.atan2( target.x, target.z ); - object.rotation.set( 0, angle, 0 ); - - } - - } - - } else if ( type === "rot" ) { - - THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale ); - - } else if ( type === "scl" ) { - - vector = object.scale; - - vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; - vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; - vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; - - } - - } - - } - - }; - -})(); - - - - - -// Get next key with - -THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) { - - var keys = this.data.hierarchy[ h ].keys; - - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - - key = key < keys.length - 1 ? key : keys.length - 1; - - } else { - - key = key % keys.length; - - } - - for ( ; key < keys.length; key++ ) { - - if ( keys[ key ][ type ] !== undefined ) { - - return keys[ key ]; - - } - - } - - return this.data.hierarchy[ h ].keys[ 0 ]; - -}; - -// Get previous key with - -THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) { - - var keys = this.data.hierarchy[ h ].keys; - - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - - key = key > 0 ? key : 0; - - } else { - - key = key >= 0 ? key : key + keys.length; - - } - - - for ( ; key >= 0; key -- ) { - - if ( keys[ key ][ type ] !== undefined ) { - - return keys[ key ]; - - } - - } - - return this.data.hierarchy[ h ].keys[ keys.length - 1 ]; - -}; -/** - * @author mikael emtinger / http://gomo.se/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author khang duong - * @author erik kitson - */ - -THREE.KeyFrameAnimation = function ( root, data ) { - - this.root = root; - this.data = THREE.AnimationHandler.get( data ); - this.hierarchy = THREE.AnimationHandler.parse( root ); - this.currentTime = 0; - this.timeScale = 0.001; - this.isPlaying = false; - this.isPaused = true; - this.loop = true; - - // initialize to first keyframes - - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - - var keys = this.data.hierarchy[h].keys, - sids = this.data.hierarchy[h].sids, - obj = this.hierarchy[h]; - - if ( keys.length && sids ) { - - for ( var s = 0; s < sids.length; s++ ) { - - var sid = sids[ s ], - next = this.getNextKeyWith( sid, h, 0 ); - - if ( next ) { - - next.apply( sid ); - - } - - } - - obj.matrixAutoUpdate = false; - this.data.hierarchy[h].node.updateMatrix(); - obj.matrixWorldNeedsUpdate = true; - - } - - } - -}; - -// Play - -THREE.KeyFrameAnimation.prototype.play = function ( startTime ) { - - this.currentTime = startTime !== undefined ? startTime : 0; - - if ( this.isPlaying === false ) { - - this.isPlaying = true; - - // reset key cache - - var h, hl = this.hierarchy.length, - object, - node; - - for ( h = 0; h < hl; h++ ) { - - object = this.hierarchy[ h ]; - node = this.data.hierarchy[ h ]; - - if ( node.animationCache === undefined ) { - - node.animationCache = {}; - node.animationCache.prevKey = null; - node.animationCache.nextKey = null; - node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix; - - } - - var keys = this.data.hierarchy[h].keys; - - if (keys.length) { - - node.animationCache.prevKey = keys[ 0 ]; - node.animationCache.nextKey = keys[ 1 ]; - - this.startTime = Math.min( keys[0].time, this.startTime ); - this.endTime = Math.max( keys[keys.length - 1].time, this.endTime ); - - } - - } - - this.update( 0 ); - - } - - this.isPaused = false; - - THREE.AnimationHandler.addToUpdate( this ); - -}; - - - -// Pause - -THREE.KeyFrameAnimation.prototype.pause = function() { - - if( this.isPaused ) { - - THREE.AnimationHandler.addToUpdate( this ); - - } else { - - THREE.AnimationHandler.removeFromUpdate( this ); - - } - - this.isPaused = !this.isPaused; - -}; - - -// Stop - -THREE.KeyFrameAnimation.prototype.stop = function() { - - this.isPlaying = false; - this.isPaused = false; - - THREE.AnimationHandler.removeFromUpdate( this ); - - // reset JIT matrix and remove cache - - for ( var h = 0; h < this.data.hierarchy.length; h++ ) { - - var obj = this.hierarchy[ h ]; - var node = this.data.hierarchy[ h ]; - - if ( node.animationCache !== undefined ) { - - var original = node.animationCache.originalMatrix; - - if( obj instanceof THREE.Bone ) { - - original.copy( obj.skinMatrix ); - obj.skinMatrix = original; - - } else { - - original.copy( obj.matrix ); - obj.matrix = original; - - } - - delete node.animationCache; - - } - - } - -}; - - -// Update - -THREE.KeyFrameAnimation.prototype.update = function ( delta ) { - - if ( this.isPlaying === false ) return; - - this.currentTime += delta * this.timeScale; - - // - - var duration = this.data.length; - - if ( this.loop === true && this.currentTime > duration ) { - - this.currentTime %= duration; - - } - - this.currentTime = Math.min( this.currentTime, duration ); - - for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) { - - var object = this.hierarchy[ h ]; - var node = this.data.hierarchy[ h ]; - - var keys = node.keys, - animationCache = node.animationCache; - - - if ( keys.length ) { - - var prevKey = animationCache.prevKey; - var nextKey = animationCache.nextKey; - - if ( nextKey.time <= this.currentTime ) { - - while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { - - prevKey = nextKey; - nextKey = keys[ prevKey.index + 1 ]; - - } - - animationCache.prevKey = prevKey; - animationCache.nextKey = nextKey; - - } - - if ( nextKey.time >= this.currentTime ) { - - prevKey.interpolate( nextKey, this.currentTime ); - - } else { - - prevKey.interpolate( nextKey, nextKey.time ); - - } - - this.data.hierarchy[ h ].node.updateMatrix(); - object.matrixWorldNeedsUpdate = true; - - } - - } - -}; - -// Get next key with - -THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) { - - var keys = this.data.hierarchy[ h ].keys; - key = key % keys.length; - - for ( ; key < keys.length; key++ ) { - - if ( keys[ key ].hasTarget( sid ) ) { - - return keys[ key ]; - - } - - } - - return keys[ 0 ]; - -}; - -// Get previous key with - -THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) { - - var keys = this.data.hierarchy[ h ].keys; - key = key >= 0 ? key : key + keys.length; - - for ( ; key >= 0; key-- ) { - - if ( keys[ key ].hasTarget( sid ) ) { - - return keys[ key ]; - - } - - } - - return keys[ keys.length - 1 ]; - -}; -/** - * @author mrdoob / http://mrdoob.com - */ - -THREE.MorphAnimation = function ( mesh ) { - - this.mesh = mesh; - this.frames = mesh.morphTargetInfluences.length; - this.currentTime = 0; - this.duration = 1000; - this.loop = true; - - this.isPlaying = false; - -}; - -THREE.MorphAnimation.prototype = { - - play: function () { - - this.isPlaying = true; - - }, - - pause: function () { - - this.isPlaying = false; - }, - - update: ( function () { - - var lastFrame = 0; - var currentFrame = 0; - - return function ( delta ) { - - if ( this.isPlaying === false ) return; - - this.currentTime += delta; - - if ( this.loop === true && this.currentTime > this.duration ) { - - this.currentTime %= this.duration; - - } - - this.currentTime = Math.min( this.currentTime, this.duration ); - - var interpolation = this.duration / this.frames; - var frame = Math.floor( this.currentTime / interpolation ); - - if ( frame != currentFrame ) { - - this.mesh.morphTargetInfluences[ lastFrame ] = 0; - this.mesh.morphTargetInfluences[ currentFrame ] = 1; - this.mesh.morphTargetInfluences[ frame ] = 0; - - lastFrame = currentFrame; - currentFrame = frame; - - } - - this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation; - this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ]; - - } - - } )() - -}; -/** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.CubeCamera = function ( near, far, cubeResolution ) { - - THREE.Object3D.call( this ); - - var fov = 90, aspect = 1; - - var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPX.up.set( 0, -1, 0 ); - cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); - this.add( cameraPX ); - - var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNX.up.set( 0, -1, 0 ); - cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) ); - this.add( cameraNX ); - - var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); - this.add( cameraPY ); - - var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNY.up.set( 0, 0, -1 ); - cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) ); - this.add( cameraNY ); - - var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPZ.up.set( 0, -1, 0 ); - cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); - this.add( cameraPZ ); - - var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNZ.up.set( 0, -1, 0 ); - cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) ); - this.add( cameraNZ ); - - this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } ); - - this.updateCubeMap = function ( renderer, scene ) { - - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.generateMipmaps; - - renderTarget.generateMipmaps = false; - - renderTarget.activeCubeFace = 0; - renderer.render( scene, cameraPX, renderTarget ); - - renderTarget.activeCubeFace = 1; - renderer.render( scene, cameraNX, renderTarget ); - - renderTarget.activeCubeFace = 2; - renderer.render( scene, cameraPY, renderTarget ); - - renderTarget.activeCubeFace = 3; - renderer.render( scene, cameraNY, renderTarget ); - - renderTarget.activeCubeFace = 4; - renderer.render( scene, cameraPZ, renderTarget ); - - renderTarget.generateMipmaps = generateMipmaps; - - renderTarget.activeCubeFace = 5; - renderer.render( scene, cameraNZ, renderTarget ); - - }; - -}; - -THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); -/** - * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog - * - * A general perpose camera, for setting FOV, Lens Focal Length, - * and switching between perspective and orthographic views easily. - * Use this only if you do not wish to manage - * both a Orthographic and Perspective Camera - * - */ - - -THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) { - - THREE.Camera.call( this ); - - this.fov = fov; - - this.left = -width / 2; - this.right = width / 2 - this.top = height / 2; - this.bottom = -height / 2; - - // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects - - this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar ); - this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far ); - - this.zoom = 1; - - this.toPerspective(); - - var aspect = width/height; - -}; - -THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype ); - -THREE.CombinedCamera.prototype.toPerspective = function () { - - // Switches to the Perspective Camera - - this.near = this.cameraP.near; - this.far = this.cameraP.far; - - this.cameraP.fov = this.fov / this.zoom ; - - this.cameraP.updateProjectionMatrix(); - - this.projectionMatrix = this.cameraP.projectionMatrix; - - this.inPerspectiveMode = true; - this.inOrthographicMode = false; - -}; - -THREE.CombinedCamera.prototype.toOrthographic = function () { - - // Switches to the Orthographic camera estimating viewport from Perspective - - var fov = this.fov; - var aspect = this.cameraP.aspect; - var near = this.cameraP.near; - var far = this.cameraP.far; - - // The size that we set is the mid plane of the viewing frustum - - var hyperfocus = ( near + far ) / 2; - - var halfHeight = Math.tan( fov / 2 ) * hyperfocus; - var planeHeight = 2 * halfHeight; - var planeWidth = planeHeight * aspect; - var halfWidth = planeWidth / 2; - - halfHeight /= this.zoom; - halfWidth /= this.zoom; - - this.cameraO.left = -halfWidth; - this.cameraO.right = halfWidth; - this.cameraO.top = halfHeight; - this.cameraO.bottom = -halfHeight; - - // this.cameraO.left = -farHalfWidth; - // this.cameraO.right = farHalfWidth; - // this.cameraO.top = farHalfHeight; - // this.cameraO.bottom = -farHalfHeight; - - // this.cameraO.left = this.left / this.zoom; - // this.cameraO.right = this.right / this.zoom; - // this.cameraO.top = this.top / this.zoom; - // this.cameraO.bottom = this.bottom / this.zoom; - - this.cameraO.updateProjectionMatrix(); - - this.near = this.cameraO.near; - this.far = this.cameraO.far; - this.projectionMatrix = this.cameraO.projectionMatrix; - - this.inPerspectiveMode = false; - this.inOrthographicMode = true; - -}; - - -THREE.CombinedCamera.prototype.setSize = function( width, height ) { - - this.cameraP.aspect = width / height; - this.left = -width / 2; - this.right = width / 2 - this.top = height / 2; - this.bottom = -height / 2; - -}; - - -THREE.CombinedCamera.prototype.setFov = function( fov ) { - - this.fov = fov; - - if ( this.inPerspectiveMode ) { - - this.toPerspective(); - - } else { - - this.toOrthographic(); - - } - -}; - -// For mantaining similar API with PerspectiveCamera - -THREE.CombinedCamera.prototype.updateProjectionMatrix = function() { - - if ( this.inPerspectiveMode ) { - - this.toPerspective(); - - } else { - - this.toPerspective(); - this.toOrthographic(); - - } - -}; - -/* -* Uses Focal Length (in mm) to estimate and set FOV -* 35mm (fullframe) camera is used if frame size is not specified; -* Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html -*/ -THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) { - - if ( frameHeight === undefined ) frameHeight = 24; - - var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) ); - - this.setFov( fov ); - - return fov; -}; - - -THREE.CombinedCamera.prototype.setZoom = function( zoom ) { - - this.zoom = zoom; - - if ( this.inPerspectiveMode ) { - - this.toPerspective(); - - } else { - - this.toOrthographic(); - - } - -}; - -THREE.CombinedCamera.prototype.toFrontView = function() { - - this.rotation.x = 0; - this.rotation.y = 0; - this.rotation.z = 0; - - // should we be modifing the matrix instead? - - this.rotationAutoUpdate = false; - -}; - -THREE.CombinedCamera.prototype.toBackView = function() { - - this.rotation.x = 0; - this.rotation.y = Math.PI; - this.rotation.z = 0; - this.rotationAutoUpdate = false; - -}; - -THREE.CombinedCamera.prototype.toLeftView = function() { - - this.rotation.x = 0; - this.rotation.y = - Math.PI / 2; - this.rotation.z = 0; - this.rotationAutoUpdate = false; - -}; - -THREE.CombinedCamera.prototype.toRightView = function() { - - this.rotation.x = 0; - this.rotation.y = Math.PI / 2; - this.rotation.z = 0; - this.rotationAutoUpdate = false; - -}; - -THREE.CombinedCamera.prototype.toTopView = function() { - - this.rotation.x = - Math.PI / 2; - this.rotation.y = 0; - this.rotation.z = 0; - this.rotationAutoUpdate = false; - -}; - -THREE.CombinedCamera.prototype.toBottomView = function() { - - this.rotation.x = Math.PI / 2; - this.rotation.y = 0; - this.rotation.z = 0; - this.rotationAutoUpdate = false; - -}; -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as - */ - -THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { - - THREE.Geometry.call( this ); - - var scope = this; - - this.width = width; - this.height = height; - this.depth = depth; - - this.widthSegments = widthSegments || 1; - this.heightSegments = heightSegments || 1; - this.depthSegments = depthSegments || 1; - - var width_half = this.width / 2; - var height_half = this.height / 2; - var depth_half = this.depth / 2; - - buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px - buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx - buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py - buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny - buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz - buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz - - function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) { - - var w, ix, iy, - gridX = scope.widthSegments, - gridY = scope.heightSegments, - width_half = width / 2, - height_half = height / 2, - offset = scope.vertices.length; - - if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) { - - w = 'z'; - - } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) { - - w = 'y'; - gridY = scope.depthSegments; - - } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) { - - w = 'x'; - gridX = scope.depthSegments; - - } - - var gridX1 = gridX + 1, - gridY1 = gridY + 1, - segment_width = width / gridX, - segment_height = height / gridY, - normal = new THREE.Vector3(); - - normal[ w ] = depth > 0 ? 1 : - 1; - - for ( iy = 0; iy < gridY1; iy ++ ) { - - for ( ix = 0; ix < gridX1; ix ++ ) { - - var vector = new THREE.Vector3(); - vector[ u ] = ( ix * segment_width - width_half ) * udir; - vector[ v ] = ( iy * segment_height - height_half ) * vdir; - vector[ w ] = depth; - - scope.vertices.push( vector ); - - } - - } - - for ( iy = 0; iy < gridY; iy++ ) { - - for ( ix = 0; ix < gridX; ix++ ) { - - var a = ix + gridX1 * iy; - var b = ix + gridX1 * ( iy + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = ( ix + 1 ) + gridX1 * iy; - - var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY ); - var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ); - var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY ); - var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY ); - - var face = new THREE.Face3( a + offset, b + offset, d + offset ); - face.normal.copy( normal ); - face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() ); - face.materialIndex = materialIndex; - - scope.faces.push( face ); - scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - - face = new THREE.Face3( b + offset, c + offset, d + offset ); - face.normal.copy( normal ); - face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() ); - face.materialIndex = materialIndex; - - scope.faces.push( face ); - scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - - } - - } - - } - - this.computeCentroids(); - this.mergeVertices(); - -}; - -THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author hughes - */ - -THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { - - THREE.Geometry.call( this ); - - this.radius = radius = radius || 50; - this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8; - - this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0; - this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - - var i, uvs = [], - center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 ); - - this.vertices.push(center); - uvs.push( centerUV ); - - for ( i = 0; i <= segments; i ++ ) { - - var vertex = new THREE.Vector3(); - var segment = thetaStart + i / segments * thetaLength; - - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); - - this.vertices.push( vertex ); - uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) ); - - } - - var n = new THREE.Vector3( 0, 0, 1 ); - - for ( i = 1; i <= segments; i ++ ) { - - var v1 = i; - var v2 = i + 1 ; - var v3 = 0; - - this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] ); - - } - - this.computeCentroids(); - this.computeFaceNormals(); - - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); - -}; - -THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype ); -// DEPRECATED - -THREE.CubeGeometry = THREE.BoxGeometry; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) { - - THREE.Geometry.call( this ); - - this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20; - this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; - this.height = height = height !== undefined ? height : 100; - - this.radialSegments = radialSegments = radialSegments || 8; - this.heightSegments = heightSegments = heightSegments || 1; - - this.openEnded = openEnded = openEnded !== undefined ? openEnded : false; - - var heightHalf = height / 2; - - var x, y, vertices = [], uvs = []; - - for ( y = 0; y <= heightSegments; y ++ ) { - - var verticesRow = []; - var uvsRow = []; - - var v = y / heightSegments; - var radius = v * ( radiusBottom - radiusTop ) + radiusTop; - - for ( x = 0; x <= radialSegments; x ++ ) { - - var u = x / radialSegments; - - var vertex = new THREE.Vector3(); - vertex.x = radius * Math.sin( u * Math.PI * 2 ); - vertex.y = - v * height + heightHalf; - vertex.z = radius * Math.cos( u * Math.PI * 2 ); - - this.vertices.push( vertex ); - - verticesRow.push( this.vertices.length - 1 ); - uvsRow.push( new THREE.Vector2( u, 1 - v ) ); - - } - - vertices.push( verticesRow ); - uvs.push( uvsRow ); - - } - - var tanTheta = ( radiusBottom - radiusTop ) / height; - var na, nb; - - for ( x = 0; x < radialSegments; x ++ ) { - - if ( radiusTop !== 0 ) { - - na = this.vertices[ vertices[ 0 ][ x ] ].clone(); - nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone(); - - } else { - - na = this.vertices[ vertices[ 1 ][ x ] ].clone(); - nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone(); - - } - - na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize(); - nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize(); - - for ( y = 0; y < heightSegments; y ++ ) { - - var v1 = vertices[ y ][ x ]; - var v2 = vertices[ y + 1 ][ x ]; - var v3 = vertices[ y + 1 ][ x + 1 ]; - var v4 = vertices[ y ][ x + 1 ]; - - var n1 = na.clone(); - var n2 = na.clone(); - var n3 = nb.clone(); - var n4 = nb.clone(); - - var uv1 = uvs[ y ][ x ].clone(); - var uv2 = uvs[ y + 1 ][ x ].clone(); - var uv3 = uvs[ y + 1 ][ x + 1 ].clone(); - var uv4 = uvs[ y ][ x + 1 ].clone(); - - this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] ); - - this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] ); - - } - - } - - // top cap - - if ( openEnded === false && radiusTop > 0 ) { - - this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) ); - - for ( x = 0; x < radialSegments; x ++ ) { - - var v1 = vertices[ 0 ][ x ]; - var v2 = vertices[ 0 ][ x + 1 ]; - var v3 = this.vertices.length - 1; - - var n1 = new THREE.Vector3( 0, 1, 0 ); - var n2 = new THREE.Vector3( 0, 1, 0 ); - var n3 = new THREE.Vector3( 0, 1, 0 ); - - var uv1 = uvs[ 0 ][ x ].clone(); - var uv2 = uvs[ 0 ][ x + 1 ].clone(); - var uv3 = new THREE.Vector2( uv2.x, 0 ); - - this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); - - } - - } - - // bottom cap - - if ( openEnded === false && radiusBottom > 0 ) { - - this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) ); - - for ( x = 0; x < radialSegments; x ++ ) { - - var v1 = vertices[ y ][ x + 1 ]; - var v2 = vertices[ y ][ x ]; - var v3 = this.vertices.length - 1; - - var n1 = new THREE.Vector3( 0, - 1, 0 ); - var n2 = new THREE.Vector3( 0, - 1, 0 ); - var n3 = new THREE.Vector3( 0, - 1, 0 ); - - var uv1 = uvs[ y ][ x + 1 ].clone(); - var uv2 = uvs[ y ][ x ].clone(); - var uv3 = new THREE.Vector2( uv2.x, 1 ); - - this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); - - } - - } - - this.computeCentroids(); - this.computeFaceNormals(); - -} - -THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Creates extruded geometry from a path shape. - * - * parameters = { - * - * curveSegments: , // number of points on the curves - * steps: , // number of points for z-side extrusions / used for subdividing segements of extrude spline too - * amount: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline is bevel - * bevelSegments: , // number of bevel layers - * - * extrudePath: // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) - * frames: // containing arrays of tangents, normals, binormals - * - * material: // material index for front and back faces - * extrudeMaterial: // material index for extrusion and beveled faces - * uvGenerator: // object that provides UV generator functions - * - * } - **/ - -THREE.ExtrudeGeometry = function ( shapes, options ) { - - if ( typeof( shapes ) === "undefined" ) { - shapes = []; - return; - } - - THREE.Geometry.call( this ); - - shapes = shapes instanceof Array ? shapes : [ shapes ]; - - this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox(); - - this.addShapeList( shapes, options ); - - this.computeCentroids(); - this.computeFaceNormals(); - - // can't really use automatic vertex normals - // as then front and back sides get smoothed too - // should do separate smoothing just for sides - - //this.computeVertexNormals(); - - //console.log( "took", ( Date.now() - startTime ) ); - -}; - -THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype ); - -THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { - var sl = shapes.length; - - for ( var s = 0; s < sl; s ++ ) { - var shape = shapes[ s ]; - this.addShape( shape, options ); - } -}; - -THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { - - var amount = options.amount !== undefined ? options.amount : 100; - - var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 - var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 - var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - - var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false - - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - - var steps = options.steps !== undefined ? options.steps : 1; - - var extrudePath = options.extrudePath; - var extrudePts, extrudeByPath = false; - - var material = options.material; - var extrudeMaterial = options.extrudeMaterial; - - // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator; - - var shapebb = this.shapebb; - //shapebb = shape.getBoundingBox(); - - - - var splineTube, binormal, normal, position2; - if ( extrudePath ) { - - extrudePts = extrudePath.getSpacedPoints( steps ); - - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion - - // SETUP TNB variables - - // Reuse TNB from TubeGeomtry for now. - // TODO1 - have a .isClosed in spline? - - splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false); - - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - - binormal = new THREE.Vector3(); - normal = new THREE.Vector3(); - position2 = new THREE.Vector3(); - - } - - // Safeguards if bevels are not enabled - - if ( ! bevelEnabled ) { - - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; - - } - - // Variables initalization - - var ahole, h, hl; // looping of holes - var scope = this; - var bevelPoints = []; - - var shapesOffset = this.vertices.length; - - var shapePoints = shape.extractPoints( curveSegments ); - - var vertices = shapePoints.shape; - var holes = shapePoints.holes; - - var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ; - - if ( reverse ) { - - vertices = vertices.reverse(); - - // Maybe we should also check if holes are in the opposite direction, just to be safe ... - - for ( h = 0, hl = holes.length; h < hl; h ++ ) { - - ahole = holes[ h ]; - - if ( THREE.Shape.Utils.isClockWise( ahole ) ) { - - holes[ h ] = ahole.reverse(); - - } - - } - - reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! - - } - - - var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes ); - - /* Vertices */ - - var contour = vertices; // vertices has all points but contour has only points of circumference - - for ( h = 0, hl = holes.length; h < hl; h ++ ) { - - ahole = holes[ h ]; - - vertices = vertices.concat( ahole ); - - } - - - function scalePt2 ( pt, vec, size ) { - - if ( !vec ) console.log( "die" ); - - return vec.clone().multiplyScalar( size ).add( pt ); - - } - - var b, bs, t, z, - vert, vlen = vertices.length, - face, flen = faces.length, - cont, clen = contour.length; - - - // Find directions for point movement - - var RAD_TO_DEGREES = 180 / Math.PI; - - - function getBevelVec( inPt, inPrev, inNext ) { - - var EPSILON = 0.0000000001; - var sign = THREE.Math.sign; - - // computes for inPt the corresponding point inPt' on a new contour - // shiftet by 1 unit (length of normalized vector) to the left - // if we walk along contour clockwise, this new contour is outside the old one - // - // inPt' is the intersection of the two lines parallel to the two - // adjacent edges of inPt at a distance of 1 unit on the left side. - - var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt - - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html - - var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; - var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; - - var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - - // check for colinear edges - var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - - if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear - - // length of vectors for normalizing - - var v_prev_len = Math.sqrt( v_prev_lensq ); - var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); - - // shift adjacent points by unit vectors to the left - - var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - - var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - - // scaling factor for v_prev to intersection point - - var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - - ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / - ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - - // vector from inPt to intersection point - - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); - - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ) - if ( v_trans_lensq <= 2 ) { - return new THREE.Vector2( v_trans_x, v_trans_y ); - } else { - shrink_by = Math.sqrt( v_trans_lensq / 2 ); - } - - } else { // handle special case of colinear edges - - var direction_eq = false; // assumes: opposite - if ( v_prev_x > EPSILON ) { - if ( v_next_x > EPSILON ) { direction_eq = true; } - } else { - if ( v_prev_x < -EPSILON ) { - if ( v_next_x < -EPSILON ) { direction_eq = true; } - } else { - if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; } - } - } - - if ( direction_eq ) { - // console.log("Warning: lines are a straight sequence"); - v_trans_x = -v_prev_y; - v_trans_y = v_prev_x; - shrink_by = Math.sqrt( v_prev_lensq ); - } else { - // console.log("Warning: lines are a straight spike"); - v_trans_x = v_prev_x; - v_trans_y = v_prev_y; - shrink_by = Math.sqrt( v_prev_lensq / 2 ); - } - - } - - return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - - } - - - var contourMovements = []; - - for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - - if ( j === il ) j = 0; - if ( k === il ) k = 0; - - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) - - var pt_i = contour[ i ]; - var pt_j = contour[ j ]; - var pt_k = contour[ k ]; - - contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); - - } - - var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); - - for ( h = 0, hl = holes.length; h < hl; h ++ ) { - - ahole = holes[ h ]; - - oneHoleMovements = []; - - for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - - if ( j === il ) j = 0; - if ( k === il ) k = 0; - - // (j)---(i)---(k) - oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - - } - - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); - - } - - - // Loop bevelSegments, 1 for the front, 1 for the back - - for ( b = 0; b < bevelSegments; b ++ ) { - //for ( b = bevelSegments; b > 0; b -- ) { - - t = b / bevelSegments; - z = bevelThickness * ( 1 - t ); - - //z = bevelThickness * t; - bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved - //bs = bevelSize * t ; // linear - - // contract shape - - for ( i = 0, il = contour.length; i < il; i ++ ) { - - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - //vert = scalePt( contour[ i ], contourCentroid, bs, false ); - v( vert.x, vert.y, - z ); - - } - - // expand holes - - for ( h = 0, hl = holes.length; h < hl; h++ ) { - - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; - - for ( i = 0, il = ahole.length; i < il; i++ ) { - - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true ); - - v( vert.x, vert.y, -z ); - - } - - } - - } - - bs = bevelSize; - - // Back facing vertices - - for ( i = 0; i < vlen; i ++ ) { - - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - - if ( !extrudeByPath ) { - - v( vert.x, vert.y, 0 ); - - } else { - - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - - normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x); - binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y); - - position2.copy( extrudePts[0] ).add(normal).add(binormal); - - v( position2.x, position2.y, position2.z ); - - } - - } - - // Add stepped vertices... - // Including front facing vertices - - var s; - - for ( s = 1; s <= steps; s ++ ) { - - for ( i = 0; i < vlen; i ++ ) { - - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - - if ( !extrudeByPath ) { - - v( vert.x, vert.y, amount / steps * s ); - - } else { - - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - - normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y ); - - position2.copy( extrudePts[s] ).add( normal ).add( binormal ); - - v( position2.x, position2.y, position2.z ); - - } - - } - - } - - - // Add bevel segments planes - - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( b = bevelSegments - 1; b >= 0; b -- ) { - - t = b / bevelSegments; - z = bevelThickness * ( 1 - t ); - //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) ); - bs = bevelSize * Math.sin ( t * Math.PI/2 ) ; - - // contract shape - - for ( i = 0, il = contour.length; i < il; i ++ ) { - - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, amount + z ); - - } - - // expand holes - - for ( h = 0, hl = holes.length; h < hl; h ++ ) { - - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; - - for ( i = 0, il = ahole.length; i < il; i ++ ) { - - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - - if ( !extrudeByPath ) { - - v( vert.x, vert.y, amount + z ); - - } else { - - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - - } - - } - - } - - } - - /* Faces */ - - // Top and bottom faces - - buildLidFaces(); - - // Sides faces - - buildSideFaces(); - - - ///// Internal functions - - function buildLidFaces() { - - if ( bevelEnabled ) { - - var layer = 0 ; // steps + 1 - var offset = vlen * layer; - - // Bottom faces - - for ( i = 0; i < flen; i ++ ) { - - face = faces[ i ]; - f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true ); - - } - - layer = steps + bevelSegments * 2; - offset = vlen * layer; - - // Top faces - - for ( i = 0; i < flen; i ++ ) { - - face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false ); - - } - - } else { - - // Bottom faces - - for ( i = 0; i < flen; i++ ) { - - face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ], true ); - - } - - // Top faces - - for ( i = 0; i < flen; i ++ ) { - - face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false ); - - } - } - - } - - // Create faces for the z-sides of the shape - - function buildSideFaces() { - - var layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; - - for ( h = 0, hl = holes.length; h < hl; h ++ ) { - - ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); - - //, true - layeroffset += ahole.length; - - } - - } - - function sidewalls( contour, layeroffset ) { - - var j, k; - i = contour.length; - - while ( --i >= 0 ) { - - j = i; - k = i - 1; - if ( k < 0 ) k = contour.length - 1; - - //console.log('b', i,j, i-1, k,vertices.length); - - var s = 0, sl = steps + bevelSegments * 2; - - for ( s = 0; s < sl; s ++ ) { - - var slen1 = vlen * s; - var slen2 = vlen * ( s + 1 ); - - var a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; - - f4( a, b, c, d, contour, s, sl, j, k ); - - } - } - - } - - - function v( x, y, z ) { - - scope.vertices.push( new THREE.Vector3( x, y, z ) ); - - } - - function f3( a, b, c, isBottom ) { - - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; - - // normal, color, material - scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); - - var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c ); - - scope.faceVertexUvs[ 0 ].push( uvs ); - - } - - function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { - - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; - d += shapesOffset; - - scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) ); - scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) ); - - var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d, - stepIndex, stepsLength, contourIndex1, contourIndex2 ); - - scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); - - } - -}; - -THREE.ExtrudeGeometry.WorldUVGenerator = { - - generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) { - var ax = geometry.vertices[ indexA ].x, - ay = geometry.vertices[ indexA ].y, - - bx = geometry.vertices[ indexB ].x, - by = geometry.vertices[ indexB ].y, - - cx = geometry.vertices[ indexC ].x, - cy = geometry.vertices[ indexC ].y; - - return [ - new THREE.Vector2( ax, ay ), - new THREE.Vector2( bx, by ), - new THREE.Vector2( cx, cy ) - ]; - - }, - - generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) { - - return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ); - - }, - - generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions, - indexA, indexB, indexC, indexD, stepIndex, stepsLength, - contourIndex1, contourIndex2 ) { - - var ax = geometry.vertices[ indexA ].x, - ay = geometry.vertices[ indexA ].y, - az = geometry.vertices[ indexA ].z, - - bx = geometry.vertices[ indexB ].x, - by = geometry.vertices[ indexB ].y, - bz = geometry.vertices[ indexB ].z, - - cx = geometry.vertices[ indexC ].x, - cy = geometry.vertices[ indexC ].y, - cz = geometry.vertices[ indexC ].z, - - dx = geometry.vertices[ indexD ].x, - dy = geometry.vertices[ indexD ].y, - dz = geometry.vertices[ indexD ].z; - - if ( Math.abs( ay - by ) < 0.01 ) { - return [ - new THREE.Vector2( ax, 1 - az ), - new THREE.Vector2( bx, 1 - bz ), - new THREE.Vector2( cx, 1 - cz ), - new THREE.Vector2( dx, 1 - dz ) - ]; - } else { - return [ - new THREE.Vector2( ay, 1 - az ), - new THREE.Vector2( by, 1 - bz ), - new THREE.Vector2( cy, 1 - cz ), - new THREE.Vector2( dy, 1 - dz ) - ]; - } - } -}; - -THREE.ExtrudeGeometry.__v1 = new THREE.Vector2(); -THREE.ExtrudeGeometry.__v2 = new THREE.Vector2(); -THREE.ExtrudeGeometry.__v3 = new THREE.Vector2(); -THREE.ExtrudeGeometry.__v4 = new THREE.Vector2(); -THREE.ExtrudeGeometry.__v5 = new THREE.Vector2(); -THREE.ExtrudeGeometry.__v6 = new THREE.Vector2(); -/** - * @author jonobr1 / http://jonobr1.com - * - * Creates a one-sided polygonal geometry from a path shape. Similar to - * ExtrudeGeometry. - * - * parameters = { - * - * curveSegments: , // number of points on the curves. NOT USED AT THE MOMENT. - * - * material: // material index for front and back faces - * uvGenerator: // object that provides UV generator functions - * - * } - **/ - -THREE.ShapeGeometry = function ( shapes, options ) { - - THREE.Geometry.call( this ); - - if ( shapes instanceof Array === false ) shapes = [ shapes ]; - - this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox(); - - this.addShapeList( shapes, options ); - - this.computeCentroids(); - this.computeFaceNormals(); - -}; - -THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype ); - -/** - * Add an array of shapes to THREE.ShapeGeometry. - */ -THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { - - for ( var i = 0, l = shapes.length; i < l; i++ ) { - - this.addShape( shapes[ i ], options ); - - } - - return this; - -}; - -/** - * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. - */ -THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { - - if ( options === undefined ) options = {}; - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - - var material = options.material; - var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; - - var shapebb = this.shapebb; - - // - - var i, l, hole, s; - - var shapesOffset = this.vertices.length; - var shapePoints = shape.extractPoints( curveSegments ); - - var vertices = shapePoints.shape; - var holes = shapePoints.holes; - - var reverse = !THREE.Shape.Utils.isClockWise( vertices ); - - if ( reverse ) { - - vertices = vertices.reverse(); - - // Maybe we should also check if holes are in the opposite direction, just to be safe... - - for ( i = 0, l = holes.length; i < l; i++ ) { - - hole = holes[ i ]; - - if ( THREE.Shape.Utils.isClockWise( hole ) ) { - - holes[ i ] = hole.reverse(); - - } - - } - - reverse = false; - - } - - var faces = THREE.Shape.Utils.triangulateShape( vertices, holes ); - - // Vertices - - var contour = vertices; - - for ( i = 0, l = holes.length; i < l; i++ ) { - - hole = holes[ i ]; - vertices = vertices.concat( hole ); - - } - - // - - var vert, vlen = vertices.length; - var face, flen = faces.length; - var cont, clen = contour.length; - - for ( i = 0; i < vlen; i++ ) { - - vert = vertices[ i ]; - - this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) ); - - } - - for ( i = 0; i < flen; i++ ) { - - face = faces[ i ]; - - var a = face[ 0 ] + shapesOffset; - var b = face[ 1 ] + shapesOffset; - var c = face[ 2 ] + shapesOffset; - - this.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); - this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) ); - - } - -}; -/** - * @author astrodud / http://astrodud.isgreat.org/ - * @author zz85 / https://github.com/zz85 - * @author bhouston / http://exocortex.com - */ - -// points - to create a closed torus, one must use a set of points -// like so: [ a, b, c, d, a ], see first is the same as last. -// segments - the number of circumference segments to create -// phiStart - the starting radian -// phiLength - the radian (0 to 2*PI) range of the lathed section -// 2*pi is a closed lathe, less than 2PI is a portion. -THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { - - THREE.Geometry.call( this ); - - segments = segments || 12; - phiStart = phiStart || 0; - phiLength = phiLength || 2 * Math.PI; - - var inversePointLength = 1.0 / ( points.length - 1 ); - var inverseSegments = 1.0 / segments; - - for ( var i = 0, il = segments; i <= il; i ++ ) { - - var phi = phiStart + i * inverseSegments * phiLength; - - var c = Math.cos( phi ), - s = Math.sin( phi ); - - for ( var j = 0, jl = points.length; j < jl; j ++ ) { - - var pt = points[ j ]; - - var vertex = new THREE.Vector3(); - - vertex.x = c * pt.x - s * pt.y; - vertex.y = s * pt.x + c * pt.y; - vertex.z = pt.z; - - this.vertices.push( vertex ); - - } - - } - - var np = points.length; - - for ( var i = 0, il = segments; i < il; i ++ ) { - - for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) { - - var base = j + np * i; - var a = base; - var b = base + np; - var c = base + 1 + np; - var d = base + 1; - - var u0 = i * inverseSegments; - var v0 = j * inversePointLength; - var u1 = u0 + inverseSegments; - var v1 = v0 + inversePointLength; - - this.faces.push( new THREE.Face3( a, b, d ) ); - - this.faceVertexUvs[ 0 ].push( [ - - new THREE.Vector2( u0, v0 ), - new THREE.Vector2( u1, v0 ), - new THREE.Vector2( u0, v1 ) - - ] ); - - this.faces.push( new THREE.Face3( b, c, d ) ); - - this.faceVertexUvs[ 0 ].push( [ - - new THREE.Vector2( u1, v0 ), - new THREE.Vector2( u1, v1 ), - new THREE.Vector2( u0, v1 ) - - ] ); - - - } - - } - - this.mergeVertices(); - this.computeCentroids(); - this.computeFaceNormals(); - this.computeVertexNormals(); - -}; - -THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ - -THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) { - - THREE.Geometry.call( this ); - - this.width = width; - this.height = height; - - this.widthSegments = widthSegments || 1; - this.heightSegments = heightSegments || 1; - - var ix, iz; - var width_half = width / 2; - var height_half = height / 2; - - var gridX = this.widthSegments; - var gridZ = this.heightSegments; - - var gridX1 = gridX + 1; - var gridZ1 = gridZ + 1; - - var segment_width = this.width / gridX; - var segment_height = this.height / gridZ; - - var normal = new THREE.Vector3( 0, 0, 1 ); - - for ( iz = 0; iz < gridZ1; iz ++ ) { - - for ( ix = 0; ix < gridX1; ix ++ ) { - - var x = ix * segment_width - width_half; - var y = iz * segment_height - height_half; - - this.vertices.push( new THREE.Vector3( x, - y, 0 ) ); - - } - - } - - for ( iz = 0; iz < gridZ; iz ++ ) { - - for ( ix = 0; ix < gridX; ix ++ ) { - - var a = ix + gridX1 * iz; - var b = ix + gridX1 * ( iz + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iz + 1 ); - var d = ( ix + 1 ) + gridX1 * iz; - - var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ ); - var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ); - var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ); - var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ ); - - var face = new THREE.Face3( a, b, d ); - face.normal.copy( normal ); - face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() ); - - this.faces.push( face ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - - face = new THREE.Face3( b, c, d ); - face.normal.copy( normal ); - face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() ); - - this.faces.push( face ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - - } - - } - - this.computeCentroids(); - -}; - -THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author Kaleb Murphy - */ - -THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { - - THREE.Geometry.call( this ); - - innerRadius = innerRadius || 0; - outerRadius = outerRadius || 50; - - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - - thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; - phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8; - - var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - - for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring - - for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle - - var vertex = new THREE.Vector3(); - var segment = thetaStart + o / thetaSegments * thetaLength; - - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); - - this.vertices.push( vertex ); - uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) ); - } - - radius += radiusStep; - - } - - var n = new THREE.Vector3( 0, 0, 1 ); - - for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring - - var thetaSegment = i * thetaSegments; - - for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle - - var segment = o + thetaSegment; - - var v1 = segment + i; - var v2 = segment + thetaSegments + i; - var v3 = segment + thetaSegments + 1 + i; - - this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]); - - v1 = segment + i; - v2 = segment + thetaSegments + 1 + i; - v3 = segment + 1 + i; - - this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]); - - } - } - - this.computeCentroids(); - this.computeFaceNormals(); - - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); - -}; - -THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { - - THREE.Geometry.call( this ); - - this.radius = radius = radius || 50; - - this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); - this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); - - this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0; - this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; - - this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0; - this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; - - var x, y, vertices = [], uvs = []; - - for ( y = 0; y <= heightSegments; y ++ ) { - - var verticesRow = []; - var uvsRow = []; - - for ( x = 0; x <= widthSegments; x ++ ) { - - var u = x / widthSegments; - var v = y / heightSegments; - - var vertex = new THREE.Vector3(); - vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); - vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - - this.vertices.push( vertex ); - - verticesRow.push( this.vertices.length - 1 ); - uvsRow.push( new THREE.Vector2( u, 1 - v ) ); - - } - - vertices.push( verticesRow ); - uvs.push( uvsRow ); - - } - - for ( y = 0; y < this.heightSegments; y ++ ) { - - for ( x = 0; x < this.widthSegments; x ++ ) { - - var v1 = vertices[ y ][ x + 1 ]; - var v2 = vertices[ y ][ x ]; - var v3 = vertices[ y + 1 ][ x ]; - var v4 = vertices[ y + 1 ][ x + 1 ]; - - var n1 = this.vertices[ v1 ].clone().normalize(); - var n2 = this.vertices[ v2 ].clone().normalize(); - var n3 = this.vertices[ v3 ].clone().normalize(); - var n4 = this.vertices[ v4 ].clone().normalize(); - - var uv1 = uvs[ y ][ x + 1 ].clone(); - var uv2 = uvs[ y ][ x ].clone(); - var uv3 = uvs[ y + 1 ][ x ].clone(); - var uv4 = uvs[ y + 1 ][ x + 1 ].clone(); - - if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) { - - uv1.x = ( uv1.x + uv2.x ) / 2; - this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] ); - - } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) { - - uv3.x = ( uv3.x + uv4.x ) / 2; - this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); - - } else { - - this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] ); - - this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] ); - - } - - } - - } - - this.computeCentroids(); - this.computeFaceNormals(); - - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); - -}; - -THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * For creating 3D text geometry in three.js - * - * Text = 3D Text - * - * parameters = { - * size: , // size of the text - * height: , // thickness to extrude text - * curveSegments: , // number of points on the curves - * - * font: , // font name - * weight: , // font weight (normal, bold) - * style: , // font style (normal, italics) - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into text bevel goes - * bevelSize: , // how far from text outline is bevel - * } - * - */ - -/* Usage Examples - - // TextGeometry wrapper - - var text3d = new TextGeometry( text, options ); - - // Complete manner - - var textShapes = THREE.FontUtils.generateShapes( text, options ); - var text3d = new ExtrudeGeometry( textShapes, options ); - -*/ - - -THREE.TextGeometry = function ( text, parameters ) { - - parameters = parameters || {}; - - var textShapes = THREE.FontUtils.generateShapes( text, parameters ); - - // translate parameters to ExtrudeGeometry API - - parameters.amount = parameters.height !== undefined ? parameters.height : 50; - - // defaults - - if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; - if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; - if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; - - THREE.ExtrudeGeometry.call( this, textShapes, parameters ); - -}; - -THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype ); -/** - * @author oosmoxiecode - * @author mrdoob / http://mrdoob.com/ - * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888 - */ - -THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { - - THREE.Geometry.call( this ); - - var scope = this; - - this.radius = radius || 100; - this.tube = tube || 40; - this.radialSegments = radialSegments || 8; - this.tubularSegments = tubularSegments || 6; - this.arc = arc || Math.PI * 2; - - var center = new THREE.Vector3(), uvs = [], normals = []; - - for ( var j = 0; j <= this.radialSegments; j ++ ) { - - for ( var i = 0; i <= this.tubularSegments; i ++ ) { - - var u = i / this.tubularSegments * this.arc; - var v = j / this.radialSegments * Math.PI * 2; - - center.x = this.radius * Math.cos( u ); - center.y = this.radius * Math.sin( u ); - - var vertex = new THREE.Vector3(); - vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u ); - vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u ); - vertex.z = this.tube * Math.sin( v ); - - this.vertices.push( vertex ); - - uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) ); - normals.push( vertex.clone().sub( center ).normalize() ); - - } - - } - - - for ( var j = 1; j <= this.radialSegments; j ++ ) { - - for ( var i = 1; i <= this.tubularSegments; i ++ ) { - - var a = ( this.tubularSegments + 1 ) * j + i - 1; - var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1; - var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i; - var d = ( this.tubularSegments + 1 ) * j + i; - - var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] ); - this.faces.push( face ); - this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] ); - - face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] ); - this.faces.push( face ); - this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] ); - - } - - } - - this.computeCentroids(); - this.computeFaceNormals(); - -}; - -THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author oosmoxiecode - * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 - */ - -THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) { - - THREE.Geometry.call( this ); - - var scope = this; - - this.radius = radius || 100; - this.tube = tube || 40; - this.radialSegments = radialSegments || 64; - this.tubularSegments = tubularSegments || 8; - this.p = p || 2; - this.q = q || 3; - this.heightScale = heightScale || 1; - this.grid = new Array( this.radialSegments ); - - var tang = new THREE.Vector3(); - var n = new THREE.Vector3(); - var bitan = new THREE.Vector3(); - - for ( var i = 0; i < this.radialSegments; ++ i ) { - - this.grid[ i ] = new Array( this.tubularSegments ); - var u = i / this.radialSegments * 2 * this.p * Math.PI; - var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale ); - var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale ); - tang.subVectors( p2, p1 ); - n.addVectors( p2, p1 ); - - bitan.crossVectors( tang, n ); - n.crossVectors( bitan, tang ); - bitan.normalize(); - n.normalize(); - - for ( var j = 0; j < this.tubularSegments; ++ j ) { - - var v = j / this.tubularSegments * 2 * Math.PI; - var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. - var cy = this.tube * Math.sin( v ); - - var pos = new THREE.Vector3(); - pos.x = p1.x + cx * n.x + cy * bitan.x; - pos.y = p1.y + cx * n.y + cy * bitan.y; - pos.z = p1.z + cx * n.z + cy * bitan.z; - - this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1; - - } - - } - - for ( var i = 0; i < this.radialSegments; ++ i ) { - - for ( var j = 0; j < this.tubularSegments; ++ j ) { - - var ip = ( i + 1 ) % this.radialSegments; - var jp = ( j + 1 ) % this.tubularSegments; - - var a = this.grid[ i ][ j ]; - var b = this.grid[ ip ][ j ]; - var c = this.grid[ ip ][ jp ]; - var d = this.grid[ i ][ jp ]; - - var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments ); - var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments ); - var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments ); - var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments ); - - this.faces.push( new THREE.Face3( a, b, d ) ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - - this.faces.push( new THREE.Face3( b, c, d ) ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - - } - } - - this.computeCentroids(); - this.computeFaceNormals(); - this.computeVertexNormals(); - - function getPos( u, in_q, in_p, radius, heightScale ) { - - var cu = Math.cos( u ); - var su = Math.sin( u ); - var quOverP = in_q / in_p * u; - var cs = Math.cos( quOverP ); - - var tx = radius * ( 2 + cs ) * 0.5 * cu; - var ty = radius * ( 2 + cs ) * su * 0.5; - var tz = heightScale * radius * Math.sin( quOverP ) * 0.5; - - return new THREE.Vector3( tx, ty, tz ); - - } - -}; - -THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author WestLangley / https://github.com/WestLangley - * @author zz85 / https://github.com/zz85 - * @author miningold / https://github.com/miningold - * - * Modified from the TorusKnotGeometry by @oosmoxiecode - * - * Creates a tube which extrudes along a 3d spline - * - * Uses parallel transport frames as described in - * http://www.cs.indiana.edu/pub/techreports/TR425.pdf - */ - -THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) { - - THREE.Geometry.call( this ); - - this.path = path; - this.segments = segments || 64; - this.radius = radius || 1; - this.radialSegments = radialSegments || 8; - this.closed = closed || false; - - this.grid = []; - - var scope = this, - - tangent, - normal, - binormal, - - numpoints = this.segments + 1, - - x, y, z, - tx, ty, tz, - u, v, - - cx, cy, - pos, pos2 = new THREE.Vector3(), - i, j, - ip, jp, - a, b, c, d, - uva, uvb, uvc, uvd; - - var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ), - tangents = frames.tangents, - normals = frames.normals, - binormals = frames.binormals; - - // proxy internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; - - function vert( x, y, z ) { - - return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1; - - } - - - // consruct the grid - - for ( i = 0; i < numpoints; i++ ) { - - this.grid[ i ] = []; - - u = i / ( numpoints - 1 ); - - pos = path.getPointAt( u ); - - tangent = tangents[ i ]; - normal = normals[ i ]; - binormal = binormals[ i ]; - - for ( j = 0; j < this.radialSegments; j++ ) { - - v = j / this.radialSegments * 2 * Math.PI; - - cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. - cy = this.radius * Math.sin( v ); - - pos2.copy( pos ); - pos2.x += cx * normal.x + cy * binormal.x; - pos2.y += cx * normal.y + cy * binormal.y; - pos2.z += cx * normal.z + cy * binormal.z; - - this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); - - } - } - - - // construct the mesh - - for ( i = 0; i < this.segments; i++ ) { - - for ( j = 0; j < this.radialSegments; j++ ) { - - ip = ( this.closed ) ? (i + 1) % this.segments : i + 1; - jp = (j + 1) % this.radialSegments; - - a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** - b = this.grid[ ip ][ j ]; - c = this.grid[ ip ][ jp ]; - d = this.grid[ i ][ jp ]; - - uva = new THREE.Vector2( i / this.segments, j / this.radialSegments ); - uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments ); - uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments ); - uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments ); - - this.faces.push( new THREE.Face3( a, b, d ) ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - - this.faces.push( new THREE.Face3( b, c, d ) ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - - } - } - - this.computeCentroids(); - this.computeFaceNormals(); - this.computeVertexNormals(); - -}; - -THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype ); - - -// For computing of Frenet frames, exposing the tangents, normals and binormals the spline -THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) { - - var tangent = new THREE.Vector3(), - normal = new THREE.Vector3(), - binormal = new THREE.Vector3(), - - tangents = [], - normals = [], - binormals = [], - - vec = new THREE.Vector3(), - mat = new THREE.Matrix4(), - - numpoints = segments + 1, - theta, - epsilon = 0.0001, - smallest, - - tx, ty, tz, - i, u, v; - - - // expose internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; - - // compute the tangent vectors for each segment on the path - - for ( i = 0; i < numpoints; i++ ) { - - u = i / ( numpoints - 1 ); - - tangents[ i ] = path.getTangentAt( u ); - tangents[ i ].normalize(); - - } - - initialNormal3(); - - function initialNormal1(lastBinormal) { - // fixed start binormal. Has dangers of 0 vectors - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); - if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 ); - normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize(); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - } - - function initialNormal2() { - - // This uses the Frenet-Serret formula for deriving binormal - var t2 = path.getTangentAt( epsilon ); - - normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); - binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); - - normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - - } - - function initialNormal3() { - // select an initial normal vector perpenicular to the first tangent vector, - // and in the direction of the smallest tangent xyz component - - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); - smallest = Number.MAX_VALUE; - tx = Math.abs( tangents[ 0 ].x ); - ty = Math.abs( tangents[ 0 ].y ); - tz = Math.abs( tangents[ 0 ].z ); - - if ( tx <= smallest ) { - smallest = tx; - normal.set( 1, 0, 0 ); - } - - if ( ty <= smallest ) { - smallest = ty; - normal.set( 0, 1, 0 ); - } - - if ( tz <= smallest ) { - normal.set( 0, 0, 1 ); - } - - vec.crossVectors( tangents[ 0 ], normal ).normalize(); - - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - } - - - // compute the slowly-varying normal and binormal vectors for each segment on the path - - for ( i = 1; i < numpoints; i++ ) { - - normals[ i ] = normals[ i-1 ].clone(); - - binormals[ i ] = binormals[ i-1 ].clone(); - - vec.crossVectors( tangents[ i-1 ], tangents[ i ] ); - - if ( vec.length() > epsilon ) { - - vec.normalize(); - - theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors - - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); - - } - - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - - } - - - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - - if ( closed ) { - - theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) ); - theta /= ( numpoints - 1 ); - - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) { - - theta = -theta; - - } - - for ( i = 1; i < numpoints; i++ ) { - - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - - } - - } -}; -/** - * @author clockworkgeek / https://github.com/clockworkgeek - * @author timothypratley / https://github.com/timothypratley - * @author WestLangley / http://github.com/WestLangley -*/ - -THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) { - - THREE.Geometry.call( this ); - - radius = radius || 1; - detail = detail || 0; - - var that = this; - - for ( var i = 0, l = vertices.length; i < l; i ++ ) { - - prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) ); - - } - - var midpoints = [], p = this.vertices; - - var f = []; - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var v1 = p[ faces[ i ][ 0 ] ]; - var v2 = p[ faces[ i ][ 1 ] ]; - var v3 = p[ faces[ i ][ 2 ] ]; - - f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - - } - - for ( var i = 0, l = f.length; i < l; i ++ ) { - - subdivide(f[ i ], detail); - - } - - - // Handle case when face straddles the seam - - for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { - - var uvs = this.faceVertexUvs[ 0 ][ i ]; - - var x0 = uvs[ 0 ].x; - var x1 = uvs[ 1 ].x; - var x2 = uvs[ 2 ].x; - - var max = Math.max( x0, Math.max( x1, x2 ) ); - var min = Math.min( x0, Math.min( x1, x2 ) ); - - if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary - - if ( x0 < 0.2 ) uvs[ 0 ].x += 1; - if ( x1 < 0.2 ) uvs[ 1 ].x += 1; - if ( x2 < 0.2 ) uvs[ 2 ].x += 1; - - } - - } - - - // Apply radius - - for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { - - this.vertices[ i ].multiplyScalar( radius ); - - } - - - // Merge vertices - - this.mergeVertices(); - - this.computeCentroids(); - - this.computeFaceNormals(); - - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); - - - // Project vector onto sphere's surface - - function prepare( vector ) { - - var vertex = vector.normalize().clone(); - vertex.index = that.vertices.push( vertex ) - 1; - - // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. - - var u = azimuth( vector ) / 2 / Math.PI + 0.5; - var v = inclination( vector ) / Math.PI + 0.5; - vertex.uv = new THREE.Vector2( u, 1 - v ); - - return vertex; - - } - - - // Approximate a curved face with recursively sub-divided triangles. - - function make( v1, v2, v3 ) { - - var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); - that.faces.push( face ); - - var azi = azimuth( face.centroid ); - - that.faceVertexUvs[ 0 ].push( [ - correctUV( v1.uv, v1, azi ), - correctUV( v2.uv, v2, azi ), - correctUV( v3.uv, v3, azi ) - ] ); - - } - - - // Analytically subdivide a face to the required detail level. - - function subdivide(face, detail ) { - - var cols = Math.pow(2, detail); - var cells = Math.pow(4, detail); - var a = prepare( that.vertices[ face.a ] ); - var b = prepare( that.vertices[ face.b ] ); - var c = prepare( that.vertices[ face.c ] ); - var v = []; - - // Construct all of the vertices for this subdivision. - - for ( var i = 0 ; i <= cols; i ++ ) { - - v[ i ] = []; - - var aj = prepare( a.clone().lerp( c, i / cols ) ); - var bj = prepare( b.clone().lerp( c, i / cols ) ); - var rows = cols - i; - - for ( var j = 0; j <= rows; j ++) { - - if ( j == 0 && i == cols ) { - - v[ i ][ j ] = aj; - - } else { - - v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); - - } - - } - - } - - // Construct all of the faces. - - for ( var i = 0; i < cols ; i ++ ) { - - for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) { - - var k = Math.floor( j / 2 ); - - if ( j % 2 == 0 ) { - - make( - v[ i ][ k + 1], - v[ i + 1 ][ k ], - v[ i ][ k ] - ); - - } else { - - make( - v[ i ][ k + 1 ], - v[ i + 1][ k + 1], - v[ i + 1 ][ k ] - ); - - } - - } - - } - - } - - - // Angle around the Y axis, counter-clockwise when looking from above. - - function azimuth( vector ) { - - return Math.atan2( vector.z, -vector.x ); - - } - - - // Angle above the XZ plane. - - function inclination( vector ) { - - return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - - } - - - // Texture fixing helper. Spheres have some odd behaviours. - - function correctUV( uv, vector, azimuth ) { - - if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y ); - if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); - return uv.clone(); - - } - - -}; - -THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author timothypratley / https://github.com/timothypratley - */ - -THREE.IcosahedronGeometry = function ( radius, detail ) { - - this.radius = radius; - this.detail = detail; - - var t = ( 1 + Math.sqrt( 5 ) ) / 2; - - var vertices = [ - [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ], - [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ], - [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ] - ]; - - var faces = [ - [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ], - [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ], - [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ], - [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ] - ]; - - THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail ); - -}; - -THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author timothypratley / https://github.com/timothypratley - */ - -THREE.OctahedronGeometry = function ( radius, detail ) { - - var vertices = [ - [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ] - ]; - - var faces = [ - [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ] - ]; - - THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail ); -}; - -THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author timothypratley / https://github.com/timothypratley - */ - -THREE.TetrahedronGeometry = function ( radius, detail ) { - - var vertices = [ - [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ] - ]; - - var faces = [ - [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ] - ]; - - THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail ); - -}; - -THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author zz85 / https://github.com/zz85 - * Parametric Surfaces Geometry - * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 - * - * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements ); - * - */ - -THREE.ParametricGeometry = function ( func, slices, stacks ) { - - THREE.Geometry.call( this ); - - var verts = this.vertices; - var faces = this.faces; - var uvs = this.faceVertexUvs[ 0 ]; - - var i, il, j, p; - var u, v; - - var stackCount = stacks + 1; - var sliceCount = slices + 1; - - for ( i = 0; i <= stacks; i ++ ) { - - v = i / stacks; - - for ( j = 0; j <= slices; j ++ ) { - - u = j / slices; - - p = func( u, v ); - verts.push( p ); - - } - } - - var a, b, c, d; - var uva, uvb, uvc, uvd; - - for ( i = 0; i < stacks; i ++ ) { - - for ( j = 0; j < slices; j ++ ) { - - a = i * sliceCount + j; - b = i * sliceCount + j + 1; - c = (i + 1) * sliceCount + j + 1; - d = (i + 1) * sliceCount + j; - - uva = new THREE.Vector2( j / slices, i / stacks ); - uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks ); - uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); - uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks ); - - faces.push( new THREE.Face3( a, b, d ) ); - uvs.push( [ uva, uvb, uvd ] ); - - faces.push( new THREE.Face3( b, c, d ) ); - uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); - - } - - } - - // console.log(this); - - // magic bullet - // var diff = this.mergeVertices(); - // console.log('removed ', diff, ' vertices by merging'); - - this.computeCentroids(); - this.computeFaceNormals(); - this.computeVertexNormals(); - -}; - -THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype ); -/** - * @author sroucheray / http://sroucheray.org/ - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.AxisHelper = function ( size ) { - - size = size || 1; - - var geometry = new THREE.Geometry(); - - geometry.vertices.push( - new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ), - new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ), - new THREE.Vector3(), new THREE.Vector3( 0, 0, size ) - ); - - geometry.colors.push( - new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ), - new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ), - new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff ) - ); - - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); - - THREE.Line.call( this, geometry, material, THREE.LinePieces ); - -}; - -THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype ); -/** - * @author WestLangley / http://github.com/WestLangley - * @author zz85 / http://github.com/zz85 - * @author bhouston / http://exocortex.com - * - * Creates an arrow for visualizing directions - * - * Parameters: - * dir - Vector3 - * origin - Vector3 - * length - Number - * hex - color in hex value - * headLength - Number - * headWidth - Number - */ - -THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) { - - // dir is assumed to be normalized - - THREE.Object3D.call( this ); - - if ( hex === undefined ) hex = 0xffff00; - if ( length === undefined ) length = 1; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; - - this.position = origin; - - var lineGeometry = new THREE.Geometry(); - lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) ); - lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) ); - - this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); - - var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 ); - coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) ); - - this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); - - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); - -}; - -THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.ArrowHelper.prototype.setDirection = function () { - - var axis = new THREE.Vector3(); - var radians; - - return function ( dir ) { - - // dir is assumed to be normalized - - if ( dir.y > 0.99999 ) { - - this.quaternion.set( 0, 0, 0, 1 ); - - } else if ( dir.y < - 0.99999 ) { - - this.quaternion.set( 1, 0, 0, 0 ); - - } else { - - axis.set( dir.z, 0, - dir.x ).normalize(); - - radians = Math.acos( dir.y ); - - this.quaternion.setFromAxisAngle( axis, radians ); - - } - - }; - -}(); - -THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { - - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; - - this.line.scale.set( 1, length, 1 ); - this.line.updateMatrix(); - - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); - -}; - -THREE.ArrowHelper.prototype.setColor = function ( hex ) { - - this.line.material.color.setHex( hex ); - this.cone.material.color.setHex( hex ); - -}; -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.BoxHelper = function ( object ) { - - // 5____4 - // 1/___0/| - // | 6__|_7 - // 2/___3/ - - var vertices = [ - new THREE.Vector3( 1, 1, 1 ), - new THREE.Vector3( - 1, 1, 1 ), - new THREE.Vector3( - 1, - 1, 1 ), - new THREE.Vector3( 1, - 1, 1 ), - - new THREE.Vector3( 1, 1, - 1 ), - new THREE.Vector3( - 1, 1, - 1 ), - new THREE.Vector3( - 1, - 1, - 1 ), - new THREE.Vector3( 1, - 1, - 1 ) - ]; - - this.vertices = vertices; - - // TODO: Wouldn't be nice if Line had .segments? - - var geometry = new THREE.Geometry(); - geometry.vertices.push( - vertices[ 0 ], vertices[ 1 ], - vertices[ 1 ], vertices[ 2 ], - vertices[ 2 ], vertices[ 3 ], - vertices[ 3 ], vertices[ 0 ], - - vertices[ 4 ], vertices[ 5 ], - vertices[ 5 ], vertices[ 6 ], - vertices[ 6 ], vertices[ 7 ], - vertices[ 7 ], vertices[ 4 ], - - vertices[ 0 ], vertices[ 4 ], - vertices[ 1 ], vertices[ 5 ], - vertices[ 2 ], vertices[ 6 ], - vertices[ 3 ], vertices[ 7 ] - ); - - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces ); - - if ( object !== undefined ) { - - this.update( object ); - - } - -}; - -THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype ); - -THREE.BoxHelper.prototype.update = function ( object ) { - - var geometry = object.geometry; - - if ( geometry.boundingBox === null ) { - - geometry.computeBoundingBox(); - - } - - var min = geometry.boundingBox.min; - var max = geometry.boundingBox.max; - var vertices = this.vertices; - - vertices[ 0 ].set( max.x, max.y, max.z ); - vertices[ 1 ].set( min.x, max.y, max.z ); - vertices[ 2 ].set( min.x, min.y, max.z ); - vertices[ 3 ].set( max.x, min.y, max.z ); - vertices[ 4 ].set( max.x, max.y, min.z ); - vertices[ 5 ].set( min.x, max.y, min.z ); - vertices[ 6 ].set( min.x, min.y, min.z ); - vertices[ 7 ].set( max.x, min.y, min.z ); - - this.geometry.computeBoundingSphere(); - this.geometry.verticesNeedUpdate = true; - - this.matrixAutoUpdate = false; - this.matrixWorld = object.matrixWorld; - -}; -/** - * @author WestLangley / http://github.com/WestLangley - */ - -// a helper to show the world-axis-aligned bounding box for an object - -THREE.BoundingBoxHelper = function ( object, hex ) { - - var color = ( hex !== undefined ) ? hex : 0x888888; - - this.object = object; - - this.box = new THREE.Box3(); - - THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) ); - -}; - -THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype ); - -THREE.BoundingBoxHelper.prototype.update = function () { - - this.box.setFromObject( this.object ); - - this.box.size( this.scale ); - - this.box.center( this.position ); - -}; -/** - * @author alteredq / http://alteredqualia.com/ - * - * - shows frustum, line of sight and up of the camera - * - suitable for fast updates - * - based on frustum visualization in lightgl.js shadowmap example - * http://evanw.github.com/lightgl.js/tests/shadowmap.html - */ - -THREE.CameraHelper = function ( camera ) { - - var geometry = new THREE.Geometry(); - var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ); - - var pointMap = {}; - - // colors - - var hexFrustum = 0xffaa00; - var hexCone = 0xff0000; - var hexUp = 0x00aaff; - var hexTarget = 0xffffff; - var hexCross = 0x333333; - - // near - - addLine( "n1", "n2", hexFrustum ); - addLine( "n2", "n4", hexFrustum ); - addLine( "n4", "n3", hexFrustum ); - addLine( "n3", "n1", hexFrustum ); - - // far - - addLine( "f1", "f2", hexFrustum ); - addLine( "f2", "f4", hexFrustum ); - addLine( "f4", "f3", hexFrustum ); - addLine( "f3", "f1", hexFrustum ); - - // sides - - addLine( "n1", "f1", hexFrustum ); - addLine( "n2", "f2", hexFrustum ); - addLine( "n3", "f3", hexFrustum ); - addLine( "n4", "f4", hexFrustum ); - - // cone - - addLine( "p", "n1", hexCone ); - addLine( "p", "n2", hexCone ); - addLine( "p", "n3", hexCone ); - addLine( "p", "n4", hexCone ); - - // up - - addLine( "u1", "u2", hexUp ); - addLine( "u2", "u3", hexUp ); - addLine( "u3", "u1", hexUp ); - - // target - - addLine( "c", "t", hexTarget ); - addLine( "p", "c", hexCross ); - - // cross - - addLine( "cn1", "cn2", hexCross ); - addLine( "cn3", "cn4", hexCross ); - - addLine( "cf1", "cf2", hexCross ); - addLine( "cf3", "cf4", hexCross ); - - function addLine( a, b, hex ) { - - addPoint( a, hex ); - addPoint( b, hex ); - - } - - function addPoint( id, hex ) { - - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( hex ) ); - - if ( pointMap[ id ] === undefined ) { - - pointMap[ id ] = []; - - } - - pointMap[ id ].push( geometry.vertices.length - 1 ); - - } - - THREE.Line.call( this, geometry, material, THREE.LinePieces ); - - this.camera = camera; - this.matrixWorld = camera.matrixWorld; - this.matrixAutoUpdate = false; - - this.pointMap = pointMap; - - this.update(); - -}; - -THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype ); - -THREE.CameraHelper.prototype.update = function () { - - var vector = new THREE.Vector3(); - var camera = new THREE.Camera(); - var projector = new THREE.Projector(); - - return function () { - - var scope = this; - - var w = 1, h = 1; - - // we need just camera projection matrix - // world matrix must be identity - - camera.projectionMatrix.copy( this.camera.projectionMatrix ); - - // center / target - - setPoint( "c", 0, 0, -1 ); - setPoint( "t", 0, 0, 1 ); - - // near - - setPoint( "n1", -w, -h, -1 ); - setPoint( "n2", w, -h, -1 ); - setPoint( "n3", -w, h, -1 ); - setPoint( "n4", w, h, -1 ); - - // far - - setPoint( "f1", -w, -h, 1 ); - setPoint( "f2", w, -h, 1 ); - setPoint( "f3", -w, h, 1 ); - setPoint( "f4", w, h, 1 ); - - // up - - setPoint( "u1", w * 0.7, h * 1.1, -1 ); - setPoint( "u2", -w * 0.7, h * 1.1, -1 ); - setPoint( "u3", 0, h * 2, -1 ); - - // cross - - setPoint( "cf1", -w, 0, 1 ); - setPoint( "cf2", w, 0, 1 ); - setPoint( "cf3", 0, -h, 1 ); - setPoint( "cf4", 0, h, 1 ); - - setPoint( "cn1", -w, 0, -1 ); - setPoint( "cn2", w, 0, -1 ); - setPoint( "cn3", 0, -h, -1 ); - setPoint( "cn4", 0, h, -1 ); - - function setPoint( point, x, y, z ) { - - vector.set( x, y, z ); - projector.unprojectVector( vector, camera ); - - var points = scope.pointMap[ point ]; - - if ( points !== undefined ) { - - for ( var i = 0, il = points.length; i < il; i ++ ) { - - scope.geometry.vertices[ points[ i ] ].copy( vector ); - - } - - } - - } - - this.geometry.verticesNeedUpdate = true; - - }; - -}(); -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ - -THREE.DirectionalLightHelper = function ( light, size ) { - - THREE.Object3D.call( this ); - - this.light = light; - this.light.updateMatrixWorld(); - - this.matrixWorld = light.matrixWorld; - this.matrixAutoUpdate = false; - - size = size || 1; - var geometry = new THREE.PlaneGeometry( size, size ); - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - - this.lightPlane = new THREE.Mesh( geometry, material ); - this.add( this.lightPlane ); - - geometry = new THREE.Geometry(); - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); - - material = new THREE.LineBasicMaterial( { fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - - this.targetLine = new THREE.Line( geometry, material ); - this.add( this.targetLine ); - - this.update(); - -}; - -THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.DirectionalLightHelper.prototype.dispose = function () { - - this.lightPlane.geometry.dispose(); - this.lightPlane.material.dispose(); - this.targetLine.geometry.dispose(); - this.targetLine.material.dispose(); -}; - -THREE.DirectionalLightHelper.prototype.update = function () { - - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var v3 = new THREE.Vector3(); - - return function () { - - v1.setFromMatrixPosition( this.light.matrixWorld ); - v2.setFromMatrixPosition( this.light.target.matrixWorld ); - v3.subVectors( v2, v1 ); - - this.lightPlane.lookAt( v3 ); - this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - - this.targetLine.geometry.vertices[ 1 ].copy( v3 ); - this.targetLine.geometry.verticesNeedUpdate = true; - this.targetLine.material.color.copy( this.lightPlane.material.color ); - - } - -}(); - -/** - * @author WestLangley / http://github.com/WestLangley - */ - -THREE.EdgesHelper = function ( object, hex ) { - - var color = ( hex !== undefined ) ? hex : 0xffffff; - - var edge = [ 0, 0 ], hash = {}; - var sortFunction = function ( a, b ) { return a - b }; - - var keys = [ 'a', 'b', 'c' ]; - var geometry = new THREE.BufferGeometry(); - - var geometry2 = object.geometry.clone(); - - geometry2.mergeVertices(); - geometry2.computeFaceNormals(); - - var vertices = geometry2.vertices; - var faces = geometry2.faces; - var numEdges = 0; - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var face = faces[ i ]; - - for ( var j = 0; j < 3; j ++ ) { - - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); - - var key = edge.toString(); - - if ( hash[ key ] === undefined ) { - - hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; - numEdges ++; - - } else { - - hash[ key ].face2 = i; - - } - - } - - } - - geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 ); - - var coords = geometry.attributes.position.array; - - var index = 0; - - for ( var key in hash ) { - - var h = hash[ key ]; - - if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK - - var vertex = vertices[ h.vert1 ]; - coords[ index ++ ] = vertex.x; - coords[ index ++ ] = vertex.y; - coords[ index ++ ] = vertex.z; - - vertex = vertices[ h.vert2 ]; - coords[ index ++ ] = vertex.x; - coords[ index ++ ] = vertex.y; - coords[ index ++ ] = vertex.z; - - } - - } - - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces ); - - this.matrixAutoUpdate = false; - this.matrixWorld = object.matrixWorld; - -}; - -THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ - -THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { - - this.object = object; - - this.size = ( size !== undefined ) ? size : 1; - - var color = ( hex !== undefined ) ? hex : 0xffff00; - - var width = ( linewidth !== undefined ) ? linewidth : 1; - - var geometry = new THREE.Geometry(); - - var faces = this.object.geometry.faces; - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); - - } - - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); - - this.matrixAutoUpdate = false; - - this.normalMatrix = new THREE.Matrix3(); - - this.update(); - -}; - -THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype ); - -THREE.FaceNormalsHelper.prototype.update = ( function ( object ) { - - var v1 = new THREE.Vector3(); - - return function ( object ) { - - this.object.updateMatrixWorld( true ); - - this.normalMatrix.getNormalMatrix( this.object.matrixWorld ); - - var vertices = this.geometry.vertices; - - var faces = this.object.geometry.faces; - - var worldMatrix = this.object.matrixWorld; - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var face = faces[ i ]; - - v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size ); - - var idx = 2 * i; - - vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix ); - - vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 ); - - } - - this.geometry.verticesNeedUpdate = true; - - return this; - - } - -}()); - -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.GridHelper = function ( size, step ) { - - var geometry = new THREE.Geometry(); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); - - this.color1 = new THREE.Color( 0x444444 ); - this.color2 = new THREE.Color( 0x888888 ); - - for ( var i = - size; i <= size; i += step ) { - - geometry.vertices.push( - new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ), - new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size ) - ); - - var color = i === 0 ? this.color1 : this.color2; - - geometry.colors.push( color, color, color, color ); - - } - - THREE.Line.call( this, geometry, material, THREE.LinePieces ); - -}; - -THREE.GridHelper.prototype = Object.create( THREE.Line.prototype ); - -THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) { - - this.color1.set( colorCenterLine ); - this.color2.set( colorGrid ); - - this.geometry.colorsNeedUpdate = true; - -} -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) { - - THREE.Object3D.call( this ); - - this.light = light; - this.light.updateMatrixWorld(); - - this.matrixWorld = light.matrixWorld; - this.matrixAutoUpdate = false; - - this.colors = [ new THREE.Color(), new THREE.Color() ]; - - var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); - geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - - for ( var i = 0, il = 8; i < il; i ++ ) { - - geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; - - } - - var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } ); - - this.lightSphere = new THREE.Mesh( geometry, material ); - this.add( this.lightSphere ); - - this.update(); - -}; - -THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.HemisphereLightHelper.prototype.dispose = function () { - this.lightSphere.geometry.dispose(); - this.lightSphere.material.dispose(); -}; - -THREE.HemisphereLightHelper.prototype.update = function () { - - var vector = new THREE.Vector3(); - - return function () { - - this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); - this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); - - this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - this.lightSphere.geometry.colorsNeedUpdate = true; - - } - -}(); - -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.PointLightHelper = function ( light, sphereSize ) { - - this.light = light; - this.light.updateMatrixWorld(); - - var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - - THREE.Mesh.call( this, geometry, material ); - - this.matrixWorld = this.light.matrixWorld; - this.matrixAutoUpdate = false; - - /* - var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); - var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); - - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); - - var d = light.distance; - - if ( d === 0.0 ) { - - this.lightDistance.visible = false; - - } else { - - this.lightDistance.scale.set( d, d, d ); - - } - - this.add( this.lightDistance ); - */ - -}; - -THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype ); - -THREE.PointLightHelper.prototype.dispose = function () { - - this.geometry.dispose(); - this.material.dispose(); -}; - -THREE.PointLightHelper.prototype.update = function () { - - this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - - /* - var d = this.light.distance; - - if ( d === 0.0 ) { - - this.lightDistance.visible = false; - - } else { - - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); - - } - */ - -}; - -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ - -THREE.SpotLightHelper = function ( light ) { - - THREE.Object3D.call( this ); - - this.light = light; - this.light.updateMatrixWorld(); - - this.matrixWorld = light.matrixWorld; - this.matrixAutoUpdate = false; - - var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true ); - - geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) ); - geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); - - this.cone = new THREE.Mesh( geometry, material ); - this.add( this.cone ); - - this.update(); - -}; - -THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype ); - -THREE.SpotLightHelper.prototype.dispose = function () { - this.cone.geometry.dispose(); - this.cone.material.dispose(); -}; - -THREE.SpotLightHelper.prototype.update = function () { - - var vector = new THREE.Vector3(); - var vector2 = new THREE.Vector3(); - - return function () { - - var coneLength = this.light.distance ? this.light.distance : 10000; - var coneWidth = coneLength * Math.tan( this.light.angle ); - - this.cone.scale.set( coneWidth, coneWidth, coneLength ); - - vector.setFromMatrixPosition( this.light.matrixWorld ); - vector2.setFromMatrixPosition( this.light.target.matrixWorld ); - - this.cone.lookAt( vector2.sub( vector ) ); - - this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - - }; - -}(); -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ - -THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { - - this.object = object; - - this.size = ( size !== undefined ) ? size : 1; - - var color = ( hex !== undefined ) ? hex : 0xff0000; - - var width = ( linewidth !== undefined ) ? linewidth : 1; - - var geometry = new THREE.Geometry(); - - var vertices = object.geometry.vertices; - - var faces = object.geometry.faces; - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var face = faces[ i ]; - - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); - - } - - } - - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); - - this.matrixAutoUpdate = false; - - this.normalMatrix = new THREE.Matrix3(); - - this.update(); - -}; - -THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype ); - -THREE.VertexNormalsHelper.prototype.update = ( function ( object ) { - - var v1 = new THREE.Vector3(); - - return function( object ) { - - var keys = [ 'a', 'b', 'c', 'd' ]; - - this.object.updateMatrixWorld( true ); - - this.normalMatrix.getNormalMatrix( this.object.matrixWorld ); - - var vertices = this.geometry.vertices; - - var verts = this.object.geometry.vertices; - - var faces = this.object.geometry.faces; - - var worldMatrix = this.object.matrixWorld; - - var idx = 0; - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var face = faces[ i ]; - - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - - var vertexId = face[ keys[ j ] ]; - var vertex = verts[ vertexId ]; - - var normal = face.vertexNormals[ j ]; - - vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix ); - - v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size ); - - v1.add( vertices[ idx ] ); - idx = idx + 1; - - vertices[ idx ].copy( v1 ); - idx = idx + 1; - - } - - } - - this.geometry.verticesNeedUpdate = true; - - return this; - - } - -}()); -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ - -THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) { - - this.object = object; - - this.size = ( size !== undefined ) ? size : 1; - - var color = ( hex !== undefined ) ? hex : 0x0000ff; - - var width = ( linewidth !== undefined ) ? linewidth : 1; - - var geometry = new THREE.Geometry(); - - var vertices = object.geometry.vertices; - - var faces = object.geometry.faces; - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var face = faces[ i ]; - - for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) { - - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); - - } - - } - - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); - - this.matrixAutoUpdate = false; - - this.update(); - -}; - -THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype ); - -THREE.VertexTangentsHelper.prototype.update = ( function ( object ) { - - var v1 = new THREE.Vector3(); - - return function( object ) { - - var keys = [ 'a', 'b', 'c', 'd' ]; - - this.object.updateMatrixWorld( true ); - - var vertices = this.geometry.vertices; - - var verts = this.object.geometry.vertices; - - var faces = this.object.geometry.faces; - - var worldMatrix = this.object.matrixWorld; - - var idx = 0; - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var face = faces[ i ]; - - for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) { - - var vertexId = face[ keys[ j ] ]; - var vertex = verts[ vertexId ]; - - var tangent = face.vertexTangents[ j ]; - - vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix ); - - v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size ); - - v1.add( vertices[ idx ] ); - idx = idx + 1; - - vertices[ idx ].copy( v1 ); - idx = idx + 1; - - } - - } - - this.geometry.verticesNeedUpdate = true; - - return this; - - } - -}()); -/** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.WireframeHelper = function ( object, hex ) { - - var color = ( hex !== undefined ) ? hex : 0xffffff; - - var edge = [ 0, 0 ], hash = {}; - var sortFunction = function ( a, b ) { return a - b }; - - var keys = [ 'a', 'b', 'c' ]; - var geometry = new THREE.BufferGeometry(); - - if ( object.geometry instanceof THREE.Geometry ) { - - var vertices = object.geometry.vertices; - var faces = object.geometry.faces; - var numEdges = 0; - - // allocate maximal size - var edges = new Uint32Array( 6 * faces.length ); - - for ( var i = 0, l = faces.length; i < l; i ++ ) { - - var face = faces[ i ]; - - for ( var j = 0; j < 3; j ++ ) { - - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); - - var key = edge.toString(); - - if ( hash[ key ] === undefined ) { - - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; - - } - - } - - } - - geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 ); - - var coords = geometry.attributes.position.array; - - for ( var i = 0, l = numEdges; i < l; i ++ ) { - - for ( var j = 0; j < 2; j ++ ) { - - var vertex = vertices[ edges [ 2 * i + j] ]; - - var index = 6 * i + 3 * j; - coords[ index + 0 ] = vertex.x; - coords[ index + 1 ] = vertex.y; - coords[ index + 2 ] = vertex.z; - - } - - } - - } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry - - var vertices = object.geometry.attributes.position.array; - var indices = object.geometry.attributes.index.array; - var offsets = object.geometry.offsets; - var numEdges = 0; - - // allocate maximal size - var edges = new Uint32Array( 2 * indices.length ); - - for ( var o = 0, ol = offsets.length; o < ol; ++ o ) { - - var start = offsets[ o ].start; - var count = offsets[ o ].count; - var index = offsets[ o ].index; - - for ( var i = start, il = start + count; i < il; i += 3 ) { - - for ( var j = 0; j < 3; j ++ ) { - - edge[ 0 ] = index + indices[ i + j ]; - edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ]; - edge.sort( sortFunction ); - - var key = edge.toString(); - - if ( hash[ key ] === undefined ) { - - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; - - } - - } - - } - - } - - geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 ); - - var coords = geometry.attributes.position.array; - - for ( var i = 0, l = numEdges; i < l; i ++ ) { - - for ( var j = 0; j < 2; j ++ ) { - - var index = 6 * i + 3 * j; - var index2 = 3 * edges[ 2 * i + j]; - coords[ index + 0 ] = vertices[ index2 ]; - coords[ index + 1 ] = vertices[ index2 + 1 ]; - coords[ index + 2 ] = vertices[ index2 + 2 ]; - - } - - } - - } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry - - var vertices = object.geometry.attributes.position.array; - var numEdges = vertices.length / 3; - var numTris = numEdges / 3; - - geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 ); - - var coords = geometry.attributes.position.array; - - for ( var i = 0, l = numTris; i < l; i ++ ) { - - for ( var j = 0; j < 3; j ++ ) { - - var index = 18 * i + 6 * j; - - var index1 = 9 * i + 3 * j; - coords[ index + 0 ] = vertices[ index1 ]; - coords[ index + 1 ] = vertices[ index1 + 1 ]; - coords[ index + 2 ] = vertices[ index1 + 2 ]; - - var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); - coords[ index + 3 ] = vertices[ index2 ]; - coords[ index + 4 ] = vertices[ index2 + 1 ]; - coords[ index + 5 ] = vertices[ index2 + 2 ]; - - } - - } - - } - - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces ); - - this.matrixAutoUpdate = false; - this.matrixWorld = object.matrixWorld; - -}; - -THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype ); -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.ImmediateRenderObject = function () { - - THREE.Object3D.call( this ); - - this.render = function ( renderCallback ) { }; - -}; - -THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.LensFlare = function ( texture, size, distance, blending, color ) { - - THREE.Object3D.call( this ); - - this.lensFlares = []; - - this.positionScreen = new THREE.Vector3(); - this.customUpdateCallback = undefined; - - if( texture !== undefined ) { - - this.add( texture, size, distance, blending, color ); - - } - -}; - -THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype ); - - -/* - * Add: adds another flare - */ - -THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) { - - if( size === undefined ) size = -1; - if( distance === undefined ) distance = 0; - if( opacity === undefined ) opacity = 1; - if( color === undefined ) color = new THREE.Color( 0xffffff ); - if( blending === undefined ) blending = THREE.NormalBlending; - - distance = Math.min( distance, Math.max( 0, distance ) ); - - this.lensFlares.push( { texture: texture, // THREE.Texture - size: size, // size in pixels (-1 = use texture.width) - distance: distance, // distance (0-1) from light source (0=at light source) - x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back - scale: 1, // scale - rotation: 1, // rotation - opacity: opacity, // opacity - color: color, // color - blending: blending } ); // blending - -}; - - -/* - * Update lens flares update positions on all flares based on the screen position - * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. - */ - -THREE.LensFlare.prototype.updateLensFlares = function () { - - var f, fl = this.lensFlares.length; - var flare; - var vecX = -this.positionScreen.x * 2; - var vecY = -this.positionScreen.y * 2; - - for( f = 0; f < fl; f ++ ) { - - flare = this.lensFlares[ f ]; - - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; - - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; - - } - -}; - - - - - - - - - - - - -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.MorphBlendMesh = function( geometry, material ) { - - THREE.Mesh.call( this, geometry, material ); - - this.animationsMap = {}; - this.animationsList = []; - - // prepare default animation - // (all frames played together in 1 second) - - var numFrames = this.geometry.morphTargets.length; - - var name = "__default"; - - var startFrame = 0; - var endFrame = numFrames - 1; - - var fps = numFrames / 1; - - this.createAnimation( name, startFrame, endFrame, fps ); - this.setAnimationWeight( name, 1 ); - -}; - -THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); - -THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { - - var animation = { - - startFrame: start, - endFrame: end, - - length: end - start + 1, - - fps: fps, - duration: ( end - start ) / fps, - - lastFrame: 0, - currentFrame: 0, - - active: false, - - time: 0, - direction: 1, - weight: 1, - - directionBackwards: false, - mirroredLoop: false - - }; - - this.animationsMap[ name ] = animation; - this.animationsList.push( animation ); - -}; - -THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { - - var pattern = /([a-z]+)(\d+)/; - - var firstAnimation, frameRanges = {}; - - var geometry = this.geometry; - - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { - - var morph = geometry.morphTargets[ i ]; - var chunks = morph.name.match( pattern ); - - if ( chunks && chunks.length > 1 ) { - - var name = chunks[ 1 ]; - var num = chunks[ 2 ]; - - if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity }; - - var range = frameRanges[ name ]; - - if ( i < range.start ) range.start = i; - if ( i > range.end ) range.end = i; - - if ( ! firstAnimation ) firstAnimation = name; - - } - - } - - for ( var name in frameRanges ) { - - var range = frameRanges[ name ]; - this.createAnimation( name, range.start, range.end, fps ); - - } - - this.firstAnimation = firstAnimation; - -}; - -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = 1; - animation.directionBackwards = false; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = -1; - animation.directionBackwards = true; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.fps = fps; - animation.duration = ( animation.end - animation.start ) / animation.fps; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.duration = duration; - animation.fps = ( animation.end - animation.start ) / animation.duration; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.weight = weight; - - } - -}; - -THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.time = time; - - } - -}; - -THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { - - var time = 0; - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - time = animation.time; - - } - - return time; - -}; - -THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { - - var duration = -1; - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - duration = animation.duration; - - } - - return duration; - -}; - -THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.time = 0; - animation.active = true; - - } else { - - console.warn( "animation[" + name + "] undefined" ); - - } - -}; - -THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.active = false; - - } - -}; - -THREE.MorphBlendMesh.prototype.update = function ( delta ) { - - for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { - - var animation = this.animationsList[ i ]; - - if ( ! animation.active ) continue; - - var frameTime = animation.duration / animation.length; - - animation.time += animation.direction * delta; - - if ( animation.mirroredLoop ) { - - if ( animation.time > animation.duration || animation.time < 0 ) { - - animation.direction *= -1; - - if ( animation.time > animation.duration ) { - - animation.time = animation.duration; - animation.directionBackwards = true; - - } - - if ( animation.time < 0 ) { - - animation.time = 0; - animation.directionBackwards = false; - - } - - } - - } else { - - animation.time = animation.time % animation.duration; - - if ( animation.time < 0 ) animation.time += animation.duration; - - } - - var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); - var weight = animation.weight; - - if ( keyframe !== animation.currentFrame ) { - - this.morphTargetInfluences[ animation.lastFrame ] = 0; - this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; - - this.morphTargetInfluences[ keyframe ] = 0; - - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; - - } - - var mix = ( animation.time % frameTime ) / frameTime; - - if ( animation.directionBackwards ) mix = 1 - mix; - - this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; - this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; - - } - -}; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.LensFlarePlugin = function () { - - var _gl, _renderer, _precision, _lensFlare = {}; - - this.init = function ( renderer ) { - - _gl = renderer.context; - _renderer = renderer; - - _precision = renderer.getPrecision(); - - _lensFlare.vertices = new Float32Array( 8 + 8 ); - _lensFlare.faces = new Uint16Array( 6 ); - - var i = 0; - _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex - _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc. - - _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1; - _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0; - - _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1; - _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1; - - _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1; - _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1; - - i = 0; - _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2; - _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3; - - // buffers - - _lensFlare.vertexBuffer = _gl.createBuffer(); - _lensFlare.elementBuffer = _gl.createBuffer(); - - _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW ); - - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW ); - - // textures - - _lensFlare.tempTexture = _gl.createTexture(); - _lensFlare.occlusionTexture = _gl.createTexture(); - - _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture ); - _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null ); - _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST ); - _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST ); - - _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture ); - _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null ); - _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST ); - _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST ); - - if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) { - - _lensFlare.hasVertexTexture = false; - _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision ); - - } else { - - _lensFlare.hasVertexTexture = true; - _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision ); - - } - - _lensFlare.attributes = {}; - _lensFlare.uniforms = {}; - - _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" ); - _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" ); - - _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" ); - _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" ); - _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" ); - _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" ); - _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" ); - _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" ); - _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" ); - _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" ); - - }; - - - /* - * Render lens flares - * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, - * reads these back and calculates occlusion. - * Then _lensFlare.update_lensFlares() is called to re-position and - * update transparency of flares. Then they are rendered. - * - */ - - this.render = function ( scene, camera, viewportWidth, viewportHeight ) { - - var flares = scene.__webglFlares, - nFlares = flares.length; - - if ( ! nFlares ) return; - - var tempPosition = new THREE.Vector3(); - - var invAspect = viewportHeight / viewportWidth, - halfViewportWidth = viewportWidth * 0.5, - halfViewportHeight = viewportHeight * 0.5; - - var size = 16 / viewportHeight, - scale = new THREE.Vector2( size * invAspect, size ); - - var screenPosition = new THREE.Vector3( 1, 1, 0 ), - screenPositionPixels = new THREE.Vector2( 1, 1 ); - - var uniforms = _lensFlare.uniforms, - attributes = _lensFlare.attributes; - - // set _lensFlare program and reset blending - - _gl.useProgram( _lensFlare.program ); - - _gl.enableVertexAttribArray( _lensFlare.attributes.vertex ); - _gl.enableVertexAttribArray( _lensFlare.attributes.uv ); - - // loop through all lens flares to update their occlusion and positions - // setup gl and common used attribs/unforms - - _gl.uniform1i( uniforms.occlusionMap, 0 ); - _gl.uniform1i( uniforms.map, 1 ); - - _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer ); - _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 ); - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 ); - - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer ); - - _gl.disable( _gl.CULL_FACE ); - _gl.depthMask( false ); - - var i, j, jl, flare, sprite; - - for ( i = 0; i < nFlares; i ++ ) { - - size = 16 / viewportHeight; - scale.set( size * invAspect, size ); - - // calc object screen position - - flare = flares[ i ]; - - tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] ); - - tempPosition.applyMatrix4( camera.matrixWorldInverse ); - tempPosition.applyProjection( camera.projectionMatrix ); - - // setup arrays for gl programs - - screenPosition.copy( tempPosition ) - - screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth; - screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight; - - // screen cull - - if ( _lensFlare.hasVertexTexture || ( - screenPositionPixels.x > 0 && - screenPositionPixels.x < viewportWidth && - screenPositionPixels.y > 0 && - screenPositionPixels.y < viewportHeight ) ) { - - // save current RGB to temp texture - - _gl.activeTexture( _gl.TEXTURE1 ); - _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture ); - _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 ); - - - // render pink quad - - _gl.uniform1i( uniforms.renderType, 0 ); - _gl.uniform2f( uniforms.scale, scale.x, scale.y ); - _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - - _gl.disable( _gl.BLEND ); - _gl.enable( _gl.DEPTH_TEST ); - - _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 ); - - - // copy result to occlusionMap - - _gl.activeTexture( _gl.TEXTURE0 ); - _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture ); - _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 ); - - - // restore graphics - - _gl.uniform1i( uniforms.renderType, 1 ); - _gl.disable( _gl.DEPTH_TEST ); - - _gl.activeTexture( _gl.TEXTURE1 ); - _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture ); - _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 ); - - - // update object positions - - flare.positionScreen.copy( screenPosition ) - - if ( flare.customUpdateCallback ) { - - flare.customUpdateCallback( flare ); - - } else { - - flare.updateLensFlares(); - - } - - // render flares - - _gl.uniform1i( uniforms.renderType, 2 ); - _gl.enable( _gl.BLEND ); - - for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { - - sprite = flare.lensFlares[ j ]; - - if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { - - screenPosition.x = sprite.x; - screenPosition.y = sprite.y; - screenPosition.z = sprite.z; - - size = sprite.size * sprite.scale / viewportHeight; - - scale.x = size * invAspect; - scale.y = size; - - _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - _gl.uniform2f( uniforms.scale, scale.x, scale.y ); - _gl.uniform1f( uniforms.rotation, sprite.rotation ); - - _gl.uniform1f( uniforms.opacity, sprite.opacity ); - _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); - - _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); - _renderer.setTexture( sprite.texture, 1 ); - - _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 ); - - } - - } - - } - - } - - // restore gl - - _gl.enable( _gl.CULL_FACE ); - _gl.enable( _gl.DEPTH_TEST ); - _gl.depthMask( true ); - - }; - - function createProgram ( shader, precision ) { - - var program = _gl.createProgram(); - - var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER ); - var vertexShader = _gl.createShader( _gl.VERTEX_SHADER ); - - var prefix = "precision " + precision + " float;\n"; - - _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); - _gl.shaderSource( vertexShader, prefix + shader.vertexShader ); - - _gl.compileShader( fragmentShader ); - _gl.compileShader( vertexShader ); - - _gl.attachShader( program, fragmentShader ); - _gl.attachShader( program, vertexShader ); - - _gl.linkProgram( program ); - - return program; - - }; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.ShadowMapPlugin = function () { - - var _gl, - _renderer, - _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, - - _frustum = new THREE.Frustum(), - _projScreenMatrix = new THREE.Matrix4(), - - _min = new THREE.Vector3(), - _max = new THREE.Vector3(), - - _matrixPosition = new THREE.Vector3(); - - this.init = function ( renderer ) { - - _gl = renderer.context; - _renderer = renderer; - - var depthShader = THREE.ShaderLib[ "depthRGBA" ]; - var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); - - _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); - _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } ); - _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } ); - _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } ); - - _depthMaterial._shadowPass = true; - _depthMaterialMorph._shadowPass = true; - _depthMaterialSkin._shadowPass = true; - _depthMaterialMorphSkin._shadowPass = true; - - }; - - this.render = function ( scene, camera ) { - - if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return; - - this.update( scene, camera ); - - }; - - this.update = function ( scene, camera ) { - - var i, il, j, jl, n, - - shadowMap, shadowMatrix, shadowCamera, - program, buffer, material, - webglObject, object, light, - renderList, - - lights = [], - k = 0, - - fog = null; - - // set GL state for depth map - - _gl.clearColor( 1, 1, 1, 1 ); - _gl.disable( _gl.BLEND ); - - _gl.enable( _gl.CULL_FACE ); - _gl.frontFace( _gl.CCW ); - - if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) { - - _gl.cullFace( _gl.FRONT ); - - } else { - - _gl.cullFace( _gl.BACK ); - - } - - _renderer.setDepthTest( true ); - - // preprocess lights - // - skip lights that are not casting shadows - // - create virtual lights for cascaded shadow maps - - for ( i = 0, il = scene.__lights.length; i < il; i ++ ) { - - light = scene.__lights[ i ]; - - if ( ! light.castShadow ) continue; - - if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) { - - for ( n = 0; n < light.shadowCascadeCount; n ++ ) { - - var virtualLight; - - if ( ! light.shadowCascadeArray[ n ] ) { - - virtualLight = createVirtualLight( light, n ); - virtualLight.originalCamera = camera; - - var gyro = new THREE.Gyroscope(); - gyro.position = light.shadowCascadeOffset; - - gyro.add( virtualLight ); - gyro.add( virtualLight.target ); - - camera.add( gyro ); - - light.shadowCascadeArray[ n ] = virtualLight; - - console.log( "Created virtualLight", virtualLight ); - - } else { - - virtualLight = light.shadowCascadeArray[ n ]; - - } - - updateVirtualLight( light, n ); - - lights[ k ] = virtualLight; - k ++; - - } - - } else { - - lights[ k ] = light; - k ++; - - } - - } - - // render depth map - - for ( i = 0, il = lights.length; i < il; i ++ ) { - - light = lights[ i ]; - - if ( ! light.shadowMap ) { - - var shadowFilter = THREE.LinearFilter; - - if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) { - - shadowFilter = THREE.NearestFilter; - - } - - var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat }; - - light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars ); - light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight ); - - light.shadowMatrix = new THREE.Matrix4(); - - } - - if ( ! light.shadowCamera ) { - - if ( light instanceof THREE.SpotLight ) { - - light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar ); - - } else if ( light instanceof THREE.DirectionalLight ) { - - light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar ); - - } else { - - console.error( "Unsupported light type for shadow" ); - continue; - - } - - scene.add( light.shadowCamera ); - - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - - } - - if ( light.shadowCameraVisible && ! light.cameraHelper ) { - - light.cameraHelper = new THREE.CameraHelper( light.shadowCamera ); - light.shadowCamera.add( light.cameraHelper ); - - } - - if ( light.isVirtual && virtualLight.originalCamera == camera ) { - - updateShadowCamera( camera, light ); - - } - - shadowMap = light.shadowMap; - shadowMatrix = light.shadowMatrix; - shadowCamera = light.shadowCamera; - - shadowCamera.position.setFromMatrixPosition( light.matrixWorld ); - _matrixPosition.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _matrixPosition ); - shadowCamera.updateMatrixWorld(); - - shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); - - if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible; - if ( light.shadowCameraVisible ) light.cameraHelper.update(); - - // compute shadow matrix - - shadowMatrix.set( 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, - 0.0, 0.0, 0.5, 0.5, - 0.0, 0.0, 0.0, 1.0 ); - - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - - // update camera matrices and frustum - - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); - - // render shadow map - - _renderer.setRenderTarget( shadowMap ); - _renderer.clear(); - - // set object matrices & frustum culling - - renderList = scene.__webglObjects; - - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - object = webglObject.object; - - webglObject.render = false; - - if ( object.visible && object.castShadow ) { - - if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) { - - object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - - webglObject.render = true; - - } - - } - - } - - // render regular objects - - var objectMaterial, useMorphing, useSkinning; - - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - - if ( webglObject.render ) { - - object = webglObject.object; - buffer = webglObject.buffer; - - // culling is overriden globally for all objects - // while rendering depth map - - // need to deal with MeshFaceMaterial somehow - // in that case just use the first of material.materials for now - // (proper solution would require to break objects by materials - // similarly to regular rendering and then set corresponding - // depth materials per each chunk instead of just once per object) - - objectMaterial = getObjectMaterial( object ); - - useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; - useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; - - if ( object.customDepthMaterial ) { - - material = object.customDepthMaterial; - - } else if ( useSkinning ) { - - material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; - - } else if ( useMorphing ) { - - material = _depthMaterialMorph; - - } else { - - material = _depthMaterial; - - } - - if ( buffer instanceof THREE.BufferGeometry ) { - - _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object ); - - } else { - - _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object ); - - } - - } - - } - - // set matrices and render immediate objects - - renderList = scene.__webglObjectsImmediate; - - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - object = webglObject.object; - - if ( object.visible && object.castShadow ) { - - object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - - _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object ); - - } - - } - - } - - // restore GL state - - var clearColor = _renderer.getClearColor(), - clearAlpha = _renderer.getClearAlpha(); - - _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha ); - _gl.enable( _gl.BLEND ); - - if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) { - - _gl.cullFace( _gl.BACK ); - - } - - }; - - function createVirtualLight( light, cascade ) { - - var virtualLight = new THREE.DirectionalLight(); - - virtualLight.isVirtual = true; - - virtualLight.onlyShadow = true; - virtualLight.castShadow = true; - - virtualLight.shadowCameraNear = light.shadowCameraNear; - virtualLight.shadowCameraFar = light.shadowCameraFar; - - virtualLight.shadowCameraLeft = light.shadowCameraLeft; - virtualLight.shadowCameraRight = light.shadowCameraRight; - virtualLight.shadowCameraBottom = light.shadowCameraBottom; - virtualLight.shadowCameraTop = light.shadowCameraTop; - - virtualLight.shadowCameraVisible = light.shadowCameraVisible; - - virtualLight.shadowDarkness = light.shadowDarkness; - - virtualLight.shadowBias = light.shadowCascadeBias[ cascade ]; - virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ]; - virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ]; - - virtualLight.pointsWorld = []; - virtualLight.pointsFrustum = []; - - var pointsWorld = virtualLight.pointsWorld, - pointsFrustum = virtualLight.pointsFrustum; - - for ( var i = 0; i < 8; i ++ ) { - - pointsWorld[ i ] = new THREE.Vector3(); - pointsFrustum[ i ] = new THREE.Vector3(); - - } - - var nearZ = light.shadowCascadeNearZ[ cascade ]; - var farZ = light.shadowCascadeFarZ[ cascade ]; - - pointsFrustum[ 0 ].set( -1, -1, nearZ ); - pointsFrustum[ 1 ].set( 1, -1, nearZ ); - pointsFrustum[ 2 ].set( -1, 1, nearZ ); - pointsFrustum[ 3 ].set( 1, 1, nearZ ); - - pointsFrustum[ 4 ].set( -1, -1, farZ ); - pointsFrustum[ 5 ].set( 1, -1, farZ ); - pointsFrustum[ 6 ].set( -1, 1, farZ ); - pointsFrustum[ 7 ].set( 1, 1, farZ ); - - return virtualLight; - - } - - // Synchronize virtual light with the original light - - function updateVirtualLight( light, cascade ) { - - var virtualLight = light.shadowCascadeArray[ cascade ]; - - virtualLight.position.copy( light.position ); - virtualLight.target.position.copy( light.target.position ); - virtualLight.lookAt( virtualLight.target ); - - virtualLight.shadowCameraVisible = light.shadowCameraVisible; - virtualLight.shadowDarkness = light.shadowDarkness; - - virtualLight.shadowBias = light.shadowCascadeBias[ cascade ]; - - var nearZ = light.shadowCascadeNearZ[ cascade ]; - var farZ = light.shadowCascadeFarZ[ cascade ]; - - var pointsFrustum = virtualLight.pointsFrustum; - - pointsFrustum[ 0 ].z = nearZ; - pointsFrustum[ 1 ].z = nearZ; - pointsFrustum[ 2 ].z = nearZ; - pointsFrustum[ 3 ].z = nearZ; - - pointsFrustum[ 4 ].z = farZ; - pointsFrustum[ 5 ].z = farZ; - pointsFrustum[ 6 ].z = farZ; - pointsFrustum[ 7 ].z = farZ; - - } - - // Fit shadow camera's ortho frustum to camera frustum - - function updateShadowCamera( camera, light ) { - - var shadowCamera = light.shadowCamera, - pointsFrustum = light.pointsFrustum, - pointsWorld = light.pointsWorld; - - _min.set( Infinity, Infinity, Infinity ); - _max.set( -Infinity, -Infinity, -Infinity ); - - for ( var i = 0; i < 8; i ++ ) { - - var p = pointsWorld[ i ]; - - p.copy( pointsFrustum[ i ] ); - THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera ); - - p.applyMatrix4( shadowCamera.matrixWorldInverse ); - - if ( p.x < _min.x ) _min.x = p.x; - if ( p.x > _max.x ) _max.x = p.x; - - if ( p.y < _min.y ) _min.y = p.y; - if ( p.y > _max.y ) _max.y = p.y; - - if ( p.z < _min.z ) _min.z = p.z; - if ( p.z > _max.z ) _max.z = p.z; - - } - - shadowCamera.left = _min.x; - shadowCamera.right = _max.x; - shadowCamera.top = _max.y; - shadowCamera.bottom = _min.y; - - // can't really fit near/far - //shadowCamera.near = _min.z; - //shadowCamera.far = _max.z; - - shadowCamera.updateProjectionMatrix(); - - } - - // For the moment just ignore objects that have multiple materials with different animation methods - // Only the first material will be taken into account for deciding which depth material to use for shadow maps - - function getObjectMaterial( object ) { - - return object.material instanceof THREE.MeshFaceMaterial - ? object.material.materials[ 0 ] - : object.material; - - }; - -}; - -THREE.ShadowMapPlugin.__projector = new THREE.Projector(); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.SpritePlugin = function () { - - var _gl, _renderer, _texture; - - var vertices, faces, vertexBuffer, elementBuffer; - var program, attributes, uniforms; - - this.init = function ( renderer ) { - - _gl = renderer.context; - _renderer = renderer; - - vertices = new Float32Array( [ - - 0.5, - 0.5, 0, 0, - 0.5, - 0.5, 1, 0, - 0.5, 0.5, 1, 1, - - 0.5, 0.5, 0, 1 - ] ); - - faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); - - vertexBuffer = _gl.createBuffer(); - elementBuffer = _gl.createBuffer(); - - _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW ); - - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW ); - - program = createProgram(); - - attributes = { - position: _gl.getAttribLocation ( program, 'position' ), - uv: _gl.getAttribLocation ( program, 'uv' ) - }; - - uniforms = { - uvOffset: _gl.getUniformLocation( program, 'uvOffset' ), - uvScale: _gl.getUniformLocation( program, 'uvScale' ), - - rotation: _gl.getUniformLocation( program, 'rotation' ), - scale: _gl.getUniformLocation( program, 'scale' ), - - color: _gl.getUniformLocation( program, 'color' ), - map: _gl.getUniformLocation( program, 'map' ), - opacity: _gl.getUniformLocation( program, 'opacity' ), - - modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ), - projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ), - - fogType: _gl.getUniformLocation( program, 'fogType' ), - fogDensity: _gl.getUniformLocation( program, 'fogDensity' ), - fogNear: _gl.getUniformLocation( program, 'fogNear' ), - fogFar: _gl.getUniformLocation( program, 'fogFar' ), - fogColor: _gl.getUniformLocation( program, 'fogColor' ), - - alphaTest: _gl.getUniformLocation( program, 'alphaTest' ) - }; - - var canvas = document.createElement( 'canvas' ); - canvas.width = 8; - canvas.height = 8; - - var context = canvas.getContext( '2d' ); - context.fillStyle = '#ffffff'; - context.fillRect( 0, 0, canvas.width, canvas.height ); - - _texture = new THREE.Texture( canvas ); - _texture.needsUpdate = true; - - }; - - this.render = function ( scene, camera, viewportWidth, viewportHeight ) { - - var sprites = scene.__webglSprites, - nSprites = sprites.length; - - if ( ! nSprites ) return; - - // setup gl - - _gl.useProgram( program ); - - _gl.enableVertexAttribArray( attributes.position ); - _gl.enableVertexAttribArray( attributes.uv ); - - _gl.disable( _gl.CULL_FACE ); - _gl.enable( _gl.BLEND ); - - _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer ); - _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 ); - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 ); - - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - - _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - - _gl.activeTexture( _gl.TEXTURE0 ); - _gl.uniform1i( uniforms.map, 0 ); - - var oldFogType = 0; - var sceneFogType = 0; - var fog = scene.fog; - - if ( fog ) { - - _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - - if ( fog instanceof THREE.Fog ) { - - _gl.uniform1f( uniforms.fogNear, fog.near ); - _gl.uniform1f( uniforms.fogFar, fog.far ); - - _gl.uniform1i( uniforms.fogType, 1 ); - oldFogType = 1; - sceneFogType = 1; - - } else if ( fog instanceof THREE.FogExp2 ) { - - _gl.uniform1f( uniforms.fogDensity, fog.density ); - - _gl.uniform1i( uniforms.fogType, 2 ); - oldFogType = 2; - sceneFogType = 2; - - } - - } else { - - _gl.uniform1i( uniforms.fogType, 0 ); - oldFogType = 0; - sceneFogType = 0; - - } - - - // update positions and sort - - var i, sprite, material, fogType, scale = []; - - for( i = 0; i < nSprites; i ++ ) { - - sprite = sprites[ i ]; - material = sprite.material; - - if ( sprite.visible === false ) continue; - - sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); - sprite.z = - sprite._modelViewMatrix.elements[ 14 ]; - - } - - sprites.sort( painterSortStable ); - - // render all sprites - - for( i = 0; i < nSprites; i ++ ) { - - sprite = sprites[ i ]; - - if ( sprite.visible === false ) continue; - - material = sprite.material; - - _gl.uniform1f( uniforms.alphaTest, material.alphaTest ); - _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements ); - - scale[ 0 ] = sprite.scale.x; - scale[ 1 ] = sprite.scale.y; - - if ( scene.fog && material.fog ) { - - fogType = sceneFogType; - - } else { - - fogType = 0; - - } - - if ( oldFogType !== fogType ) { - - _gl.uniform1i( uniforms.fogType, fogType ); - oldFogType = fogType; - - } - - if ( material.map !== null ) { - - _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); - _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); - - } else { - - _gl.uniform2f( uniforms.uvOffset, 0, 0 ); - _gl.uniform2f( uniforms.uvScale, 1, 1 ); - - } - - _gl.uniform1f( uniforms.opacity, material.opacity ); - _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); - - _gl.uniform1f( uniforms.rotation, material.rotation ); - _gl.uniform2fv( uniforms.scale, scale ); - - _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - _renderer.setDepthTest( material.depthTest ); - _renderer.setDepthWrite( material.depthWrite ); - - if ( material.map && material.map.image && material.map.image.width ) { - - _renderer.setTexture( material.map, 0 ); - - } else { - - _renderer.setTexture( _texture, 0 ); - - } - - _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 ); - - } - - // restore gl - - _gl.enable( _gl.CULL_FACE ); - - }; - - function createProgram () { - - var program = _gl.createProgram(); - - var vertexShader = _gl.createShader( _gl.VERTEX_SHADER ); - var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER ); - - _gl.shaderSource( vertexShader, [ - - 'precision ' + _renderer.getPrecision() + ' float;', - - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform float rotation;', - 'uniform vec2 scale;', - 'uniform vec2 uvOffset;', - 'uniform vec2 uvScale;', - - 'attribute vec2 position;', - 'attribute vec2 uv;', - - 'varying vec2 vUV;', - - 'void main() {', - - 'vUV = uvOffset + uv * uvScale;', - - 'vec2 alignedPosition = position * scale;', - - 'vec2 rotatedPosition;', - 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', - 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', - - 'vec4 finalPosition;', - - 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', - 'finalPosition.xy += rotatedPosition;', - 'finalPosition = projectionMatrix * finalPosition;', - - 'gl_Position = finalPosition;', - - '}' - - ].join( '\n' ) ); - - _gl.shaderSource( fragmentShader, [ - - 'precision ' + _renderer.getPrecision() + ' float;', - - 'uniform vec3 color;', - 'uniform sampler2D map;', - 'uniform float opacity;', - - 'uniform int fogType;', - 'uniform vec3 fogColor;', - 'uniform float fogDensity;', - 'uniform float fogNear;', - 'uniform float fogFar;', - 'uniform float alphaTest;', - - 'varying vec2 vUV;', - - 'void main() {', - - 'vec4 texture = texture2D( map, vUV );', - - 'if ( texture.a < alphaTest ) discard;', - - 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', - - 'if ( fogType > 0 ) {', - - 'float depth = gl_FragCoord.z / gl_FragCoord.w;', - 'float fogFactor = 0.0;', - - 'if ( fogType == 1 ) {', - - 'fogFactor = smoothstep( fogNear, fogFar, depth );', - - '} else {', - - 'const float LOG2 = 1.442695;', - 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', - 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', - - '}', - - 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', - - '}', - - '}' - - ].join( '\n' ) ); - - _gl.compileShader( vertexShader ); - _gl.compileShader( fragmentShader ); - - _gl.attachShader( program, vertexShader ); - _gl.attachShader( program, fragmentShader ); - - _gl.linkProgram( program ); - - return program; - - }; - - function painterSortStable ( a, b ) { - - if ( a.z !== b.z ) { - - return b.z - a.z; - - } else { - - return b.id - a.id; - - } - - }; - -}; -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.DepthPassPlugin = function () { - - this.enabled = false; - this.renderTarget = null; - - var _gl, - _renderer, - _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, - - _frustum = new THREE.Frustum(), - _projScreenMatrix = new THREE.Matrix4(); - - this.init = function ( renderer ) { - - _gl = renderer.context; - _renderer = renderer; - - var depthShader = THREE.ShaderLib[ "depthRGBA" ]; - var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); - - _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); - _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } ); - _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } ); - _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } ); - - _depthMaterial._shadowPass = true; - _depthMaterialMorph._shadowPass = true; - _depthMaterialSkin._shadowPass = true; - _depthMaterialMorphSkin._shadowPass = true; - - }; - - this.render = function ( scene, camera ) { - - if ( ! this.enabled ) return; - - this.update( scene, camera ); - - }; - - this.update = function ( scene, camera ) { - - var i, il, j, jl, n, - - program, buffer, material, - webglObject, object, light, - renderList, - - fog = null; - - // set GL state for depth map - - _gl.clearColor( 1, 1, 1, 1 ); - _gl.disable( _gl.BLEND ); - - _renderer.setDepthTest( true ); - - // update scene - - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - - // update camera matrices and frustum - - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); - - // render depth map - - _renderer.setRenderTarget( this.renderTarget ); - _renderer.clear(); - - // set object matrices & frustum culling - - renderList = scene.__webglObjects; - - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - object = webglObject.object; - - webglObject.render = false; - - if ( object.visible ) { - - if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) { - - object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - - webglObject.render = true; - - } - - } - - } - - // render regular objects - - var objectMaterial, useMorphing, useSkinning; - - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - - if ( webglObject.render ) { - - object = webglObject.object; - buffer = webglObject.buffer; - - // todo: create proper depth material for particles - - if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue; - - objectMaterial = getObjectMaterial( object ); - - if ( objectMaterial ) _renderer.setMaterialFaces( object.material ); - - useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; - useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; - - if ( object.customDepthMaterial ) { - - material = object.customDepthMaterial; - - } else if ( useSkinning ) { - - material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; - - } else if ( useMorphing ) { - - material = _depthMaterialMorph; - - } else { - - material = _depthMaterial; - - } - - if ( buffer instanceof THREE.BufferGeometry ) { - - _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object ); - - } else { - - _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object ); - - } - - } - - } - - // set matrices and render immediate objects - - renderList = scene.__webglObjectsImmediate; - - for ( j = 0, jl = renderList.length; j < jl; j ++ ) { - - webglObject = renderList[ j ]; - object = webglObject.object; - - if ( object.visible ) { - - object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - - _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object ); - - } - - } - - // restore GL state - - var clearColor = _renderer.getClearColor(), - clearAlpha = _renderer.getClearAlpha(); - - _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha ); - _gl.enable( _gl.BLEND ); - - }; - - // For the moment just ignore objects that have multiple materials with different animation methods - // Only the first material will be taken into account for deciding which depth material to use - - function getObjectMaterial( object ) { - - return object.material instanceof THREE.MeshFaceMaterial - ? object.material.materials[ 0 ] - : object.material; - - }; - -}; - -/** - * @author mikael emtinger / http://gomo.se/ - */ - -THREE.ShaderFlares = { - - 'lensFlareVertexTexture': { - - vertexShader: [ - - "uniform lowp int renderType;", - - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", - - "uniform sampler2D occlusionMap;", - - "attribute vec2 position;", - "attribute vec2 uv;", - - "varying vec2 vUV;", - "varying float vVisibility;", - - "void main() {", - - "vUV = uv;", - - "vec2 pos = position;", - - "if( renderType == 2 ) {", - - "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );", - - "vVisibility = visibility.r / 9.0;", - "vVisibility *= 1.0 - visibility.g / 9.0;", - "vVisibility *= visibility.b / 9.0;", - "vVisibility *= 1.0 - visibility.a / 9.0;", - - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", - - "}", - - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - - "}" - - ].join( "\n" ), - - fragmentShader: [ - - "uniform lowp int renderType;", - - "uniform sampler2D map;", - "uniform float opacity;", - "uniform vec3 color;", - - "varying vec2 vUV;", - "varying float vVisibility;", - - "void main() {", - - // pink square - - "if( renderType == 0 ) {", - - "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", - - // restore - - "} else if( renderType == 1 ) {", - - "gl_FragColor = texture2D( map, vUV );", - - // flare - - "} else {", - - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * vVisibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", - - "}", - - "}" - ].join( "\n" ) - - }, - - - 'lensFlare': { - - vertexShader: [ - - "uniform lowp int renderType;", - - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", - - "attribute vec2 position;", - "attribute vec2 uv;", - - "varying vec2 vUV;", - - "void main() {", - - "vUV = uv;", - - "vec2 pos = position;", - - "if( renderType == 2 ) {", - - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", - - "}", - - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - - "}" - - ].join( "\n" ), - - fragmentShader: [ - - "precision mediump float;", - - "uniform lowp int renderType;", - - "uniform sampler2D map;", - "uniform sampler2D occlusionMap;", - "uniform float opacity;", - "uniform vec3 color;", - - "varying vec2 vUV;", - - "void main() {", - - // pink square - - "if( renderType == 0 ) {", - - "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );", - - // restore - - "} else if( renderType == 1 ) {", - - "gl_FragColor = texture2D( map, vUV );", - - // flare - - "} else {", - - "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;", - "visibility = ( 1.0 - visibility / 4.0 );", - - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * visibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", - - "}", - - "}" - - ].join( "\n" ) - - } - -}; - -// Export the THREE object for **Node.js**, with -// backwards-compatibility for the old `require()` API. If we're in -// the browser, add `_` as a global object via a string identifier, -// for Closure Compiler "advanced" mode. -if (typeof exports !== 'undefined') { - if (typeof module !== 'undefined' && module.exports) { - exports = module.exports = THREE; - } - exports.THREE = THREE; -} else { - this['THREE'] = THREE; -} - -},{}],13:[function(require,module,exports){ -// tween.js - http://github.com/sole/tween.js -/** - * @author sole / http://soledadpenades.com - * @author mrdoob / http://mrdoob.com - * @author Robert Eisele / http://www.xarg.org - * @author Philippe / http://philippe.elsass.me - * @author Robert Penner / http://www.robertpenner.com/easing_terms_of_use.html - * @author Paul Lewis / http://www.aerotwist.com/ - * @author lechecacharro - * @author Josh Faul / http://jocafa.com/ - * @author egraether / http://egraether.com/ - * @author endel / http://endel.me - * @author Ben Delarre / http://delarre.net - */ - -// Date.now shim for (ahem) Internet Explo(d|r)er -if ( Date.now === undefined ) { - - Date.now = function () { - - return new Date().valueOf(); - - }; - -} - -var TWEEN = TWEEN || ( function () { - - var _tweens = []; - - return { - - REVISION: '13', - - getAll: function () { - - return _tweens; - - }, - - removeAll: function () { - - _tweens = []; - - }, - - add: function ( tween ) { - - _tweens.push( tween ); - - }, - - remove: function ( tween ) { - - var i = _tweens.indexOf( tween ); - - if ( i !== -1 ) { - - _tweens.splice( i, 1 ); - - } - - }, - - update: function ( time ) { - - if ( _tweens.length === 0 ) return false; - - var i = 0; - - time = time !== undefined ? time : ( typeof window !== 'undefined' && window.performance !== undefined && window.performance.now !== undefined ? window.performance.now() : Date.now() ); - - while ( i < _tweens.length ) { - - if ( _tweens[ i ].update( time ) ) { - - i++; - - } else { - - _tweens.splice( i, 1 ); - - } - - } - - return true; - - } - }; - -} )(); - -TWEEN.Tween = function ( object ) { - - var _object = object; - var _valuesStart = {}; - var _valuesEnd = {}; - var _valuesStartRepeat = {}; - var _duration = 1000; - var _repeat = 0; - var _yoyo = false; - var _isPlaying = false; - var _reversed = false; - var _delayTime = 0; - var _startTime = null; - var _easingFunction = TWEEN.Easing.Linear.None; - var _interpolationFunction = TWEEN.Interpolation.Linear; - var _chainedTweens = []; - var _onStartCallback = null; - var _onStartCallbackFired = false; - var _onUpdateCallback = null; - var _onCompleteCallback = null; - var _onStopCallback = null; - - // Set all starting values present on the target object - for ( var field in object ) { - - _valuesStart[ field ] = parseFloat(object[field], 10); - - } - - this.to = function ( properties, duration ) { - - if ( duration !== undefined ) { - - _duration = duration; - - } - - _valuesEnd = properties; - - return this; - - }; - - this.start = function ( time ) { - - TWEEN.add( this ); - - _isPlaying = true; - - _onStartCallbackFired = false; - - _startTime = time !== undefined ? time : ( typeof window !== 'undefined' && window.performance !== undefined && window.performance.now !== undefined ? window.performance.now() : Date.now() ); - _startTime += _delayTime; - - for ( var property in _valuesEnd ) { - - // check if an Array was provided as property value - if ( _valuesEnd[ property ] instanceof Array ) { - - if ( _valuesEnd[ property ].length === 0 ) { - - continue; - - } - - // create a local copy of the Array with the start value at the front - _valuesEnd[ property ] = [ _object[ property ] ].concat( _valuesEnd[ property ] ); - - } - - _valuesStart[ property ] = _object[ property ]; - - if( ( _valuesStart[ property ] instanceof Array ) === false ) { - _valuesStart[ property ] *= 1.0; // Ensures we're using numbers, not strings - } - - _valuesStartRepeat[ property ] = _valuesStart[ property ] || 0; - - } - - return this; - - }; - - this.stop = function () { - - if ( !_isPlaying ) { - return this; - } - - TWEEN.remove( this ); - _isPlaying = false; - - if ( _onStopCallback !== null ) { - - _onStopCallback.call( _object ); - - } - - this.stopChainedTweens(); - return this; - - }; - - this.stopChainedTweens = function () { - - for ( var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++ ) { - - _chainedTweens[ i ].stop(); - - } - - }; - - this.delay = function ( amount ) { - - _delayTime = amount; - return this; - - }; - - this.repeat = function ( times ) { - - _repeat = times; - return this; - - }; - - this.yoyo = function( yoyo ) { - - _yoyo = yoyo; - return this; - - }; - - - this.easing = function ( easing ) { - - _easingFunction = easing; - return this; - - }; - - this.interpolation = function ( interpolation ) { - - _interpolationFunction = interpolation; - return this; - - }; - - this.chain = function () { - - _chainedTweens = arguments; - return this; - - }; - - this.onStart = function ( callback ) { - - _onStartCallback = callback; - return this; - - }; - - this.onUpdate = function ( callback ) { - - _onUpdateCallback = callback; - return this; - - }; - - this.onComplete = function ( callback ) { - - _onCompleteCallback = callback; - return this; - - }; - - this.onStop = function ( callback ) { - - _onStopCallback = callback; - return this; - - }; - - this.update = function ( time ) { - - var property; - - if ( time < _startTime ) { - - return true; - - } - - if ( _onStartCallbackFired === false ) { - - if ( _onStartCallback !== null ) { - - _onStartCallback.call( _object ); - - } - - _onStartCallbackFired = true; - - } - - var elapsed = ( time - _startTime ) / _duration; - elapsed = elapsed > 1 ? 1 : elapsed; - - var value = _easingFunction( elapsed ); - - for ( property in _valuesEnd ) { - - var start = _valuesStart[ property ] || 0; - var end = _valuesEnd[ property ]; - - if ( end instanceof Array ) { - - _object[ property ] = _interpolationFunction( end, value ); - - } else { - - // Parses relative end values with start as base (e.g.: +10, -3) - if ( typeof(end) === "string" ) { - end = start + parseFloat(end, 10); - } - - // protect against non numeric properties. - if ( typeof(end) === "number" ) { - _object[ property ] = start + ( end - start ) * value; - } - - } - - } - - if ( _onUpdateCallback !== null ) { - - _onUpdateCallback.call( _object, value ); - - } - - if ( elapsed == 1 ) { - - if ( _repeat > 0 ) { - - if( isFinite( _repeat ) ) { - _repeat--; - } - - // reassign starting values, restart by making startTime = now - for( property in _valuesStartRepeat ) { - - if ( typeof( _valuesEnd[ property ] ) === "string" ) { - _valuesStartRepeat[ property ] = _valuesStartRepeat[ property ] + parseFloat(_valuesEnd[ property ], 10); - } - - if (_yoyo) { - var tmp = _valuesStartRepeat[ property ]; - _valuesStartRepeat[ property ] = _valuesEnd[ property ]; - _valuesEnd[ property ] = tmp; - } - - _valuesStart[ property ] = _valuesStartRepeat[ property ]; - - } - - if (_yoyo) { - _reversed = !_reversed; - } - - _startTime = time + _delayTime; - - return true; - - } else { - - if ( _onCompleteCallback !== null ) { - - _onCompleteCallback.call( _object ); - - } - - for ( var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++ ) { - - _chainedTweens[ i ].start( time ); - - } - - return false; - - } - - } - - return true; - - }; - -}; - - -TWEEN.Easing = { - - Linear: { - - None: function ( k ) { - - return k; - - } - - }, - - Quadratic: { - - In: function ( k ) { - - return k * k; - - }, - - Out: function ( k ) { - - return k * ( 2 - k ); - - }, - - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; - return - 0.5 * ( --k * ( k - 2 ) - 1 ); - - } - - }, - - Cubic: { - - In: function ( k ) { - - return k * k * k; - - }, - - Out: function ( k ) { - - return --k * k * k + 1; - - }, - - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; - return 0.5 * ( ( k -= 2 ) * k * k + 2 ); - - } - - }, - - Quartic: { - - In: function ( k ) { - - return k * k * k * k; - - }, - - Out: function ( k ) { - - return 1 - ( --k * k * k * k ); - - }, - - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; - return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); - - } - - }, - - Quintic: { - - In: function ( k ) { - - return k * k * k * k * k; - - }, - - Out: function ( k ) { - - return --k * k * k * k * k + 1; - - }, - - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; - return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); - - } - - }, - - Sinusoidal: { - - In: function ( k ) { - - return 1 - Math.cos( k * Math.PI / 2 ); - - }, - - Out: function ( k ) { - - return Math.sin( k * Math.PI / 2 ); - - }, - - InOut: function ( k ) { - - return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); - - } - - }, - - Exponential: { - - In: function ( k ) { - - return k === 0 ? 0 : Math.pow( 1024, k - 1 ); - - }, - - Out: function ( k ) { - - return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); - - }, - - InOut: function ( k ) { - - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); - return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); - - } - - }, - - Circular: { - - In: function ( k ) { - - return 1 - Math.sqrt( 1 - k * k ); - - }, - - Out: function ( k ) { - - return Math.sqrt( 1 - ( --k * k ) ); - - }, - - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); - return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); - - } - - }, - - Elastic: { - - In: function ( k ) { - - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); - - }, - - Out: function ( k ) { - - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); - - }, - - InOut: function ( k ) { - - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); - return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; - - } - - }, - - Back: { - - In: function ( k ) { - - var s = 1.70158; - return k * k * ( ( s + 1 ) * k - s ); - - }, - - Out: function ( k ) { - - var s = 1.70158; - return --k * k * ( ( s + 1 ) * k + s ) + 1; - - }, - - InOut: function ( k ) { - - var s = 1.70158 * 1.525; - if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); - return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); - - } - - }, - - Bounce: { - - In: function ( k ) { - - return 1 - TWEEN.Easing.Bounce.Out( 1 - k ); - - }, - - Out: function ( k ) { - - if ( k < ( 1 / 2.75 ) ) { - - return 7.5625 * k * k; - - } else if ( k < ( 2 / 2.75 ) ) { - - return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; - - } else if ( k < ( 2.5 / 2.75 ) ) { - - return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; - - } else { - - return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; - - } - - }, - - InOut: function ( k ) { - - if ( k < 0.5 ) return TWEEN.Easing.Bounce.In( k * 2 ) * 0.5; - return TWEEN.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; - - } - - } - -}; - -TWEEN.Interpolation = { - - Linear: function ( v, k ) { - - var m = v.length - 1, f = m * k, i = Math.floor( f ), fn = TWEEN.Interpolation.Utils.Linear; - - if ( k < 0 ) return fn( v[ 0 ], v[ 1 ], f ); - if ( k > 1 ) return fn( v[ m ], v[ m - 1 ], m - f ); - - return fn( v[ i ], v[ i + 1 > m ? m : i + 1 ], f - i ); - - }, - - Bezier: function ( v, k ) { - - var b = 0, n = v.length - 1, pw = Math.pow, bn = TWEEN.Interpolation.Utils.Bernstein, i; - - for ( i = 0; i <= n; i++ ) { - b += pw( 1 - k, n - i ) * pw( k, i ) * v[ i ] * bn( n, i ); - } - - return b; - - }, - - CatmullRom: function ( v, k ) { - - var m = v.length - 1, f = m * k, i = Math.floor( f ), fn = TWEEN.Interpolation.Utils.CatmullRom; - - if ( v[ 0 ] === v[ m ] ) { - - if ( k < 0 ) i = Math.floor( f = m * ( 1 + k ) ); - - return fn( v[ ( i - 1 + m ) % m ], v[ i ], v[ ( i + 1 ) % m ], v[ ( i + 2 ) % m ], f - i ); - - } else { - - if ( k < 0 ) return v[ 0 ] - ( fn( v[ 0 ], v[ 0 ], v[ 1 ], v[ 1 ], -f ) - v[ 0 ] ); - if ( k > 1 ) return v[ m ] - ( fn( v[ m ], v[ m ], v[ m - 1 ], v[ m - 1 ], f - m ) - v[ m ] ); - - return fn( v[ i ? i - 1 : 0 ], v[ i ], v[ m < i + 1 ? m : i + 1 ], v[ m < i + 2 ? m : i + 2 ], f - i ); - - } - - }, - - Utils: { - - Linear: function ( p0, p1, t ) { - - return ( p1 - p0 ) * t + p0; - - }, - - Bernstein: function ( n , i ) { - - var fc = TWEEN.Interpolation.Utils.Factorial; - return fc( n ) / fc( i ) / fc( n - i ); - - }, - - Factorial: ( function () { - - var a = [ 1 ]; - - return function ( n ) { - - var s = 1, i; - if ( a[ n ] ) return a[ n ]; - for ( i = n; i > 1; i-- ) s *= i; - return a[ n ] = s; - - }; - - } )(), - - CatmullRom: function ( p0, p1, p2, p3, t ) { - - var v0 = ( p2 - p0 ) * 0.5, v1 = ( p3 - p1 ) * 0.5, t2 = t * t, t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - - } - - } - -}; - -module.exports=TWEEN; -},{}],14:[function(require,module,exports){ -;(function inject(clean, precision, undef) { - - var isArray = function (a) { - return Object.prototype.toString.call(a) === "[object Array]"; - }; - - var defined = function(a) { - return a !== undef; - }; - - function Vec2(x, y) { - if (!(this instanceof Vec2)) { - return new Vec2(x, y); + function denormalize(value, array) { + switch (array.constructor) { + case Float32Array: + return value; + case Uint32Array: + return value / 4294967295; + case Uint16Array: + return value / 65535; + case Uint8Array: + return value / 255; + case Int32Array: + return Math.max(value / 2147483647, -1); + case Int16Array: + return Math.max(value / 32767, -1); + case Int8Array: + return Math.max(value / 127, -1); + default: + throw new Error("Invalid component type."); + } } - - if (isArray(x)) { - y = x[1]; - x = x[0]; - } else if('object' === typeof x && x) { - y = x.y; - x = x.x; + function normalize(value, array) { + switch (array.constructor) { + case Float32Array: + return value; + case Uint32Array: + return Math.round(value * 4294967295); + case Uint16Array: + return Math.round(value * 65535); + case Uint8Array: + return Math.round(value * 255); + case Int32Array: + return Math.round(value * 2147483647); + case Int16Array: + return Math.round(value * 32767); + case Int8Array: + return Math.round(value * 127); + default: + throw new Error("Invalid component type."); + } } - - this.x = Vec2.clean(x || 0); - this.y = Vec2.clean(y || 0); - } - - Vec2.prototype = { - change : function(fn) { - if (typeof fn === 'function') { - if (this.observers) { - this.observers.push(fn); - } else { - this.observers = [fn]; - } - } else if (this.observers && this.observers.length) { - for (var i=this.observers.length-1; i>=0; i--) { - this.observers[i](this, fn); - } + const MathUtils = { + DEG2RAD, + RAD2DEG, + /** + * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) + * (universally unique identifier). + * + * @static + * @method + * @return {string} The UUID. + */ + generateUUID, + /** + * Clamps the given value between min and max. + * + * @static + * @method + * @param {number} value - The value to clamp. + * @param {number} min - The min value. + * @param {number} max - The max value. + * @return {number} The clamped value. + */ + clamp, + /** + * Computes the Euclidean modulo of the given parameters that + * is `( ( n % m ) + m ) % m`. + * + * @static + * @method + * @param {number} n - The first parameter. + * @param {number} m - The second parameter. + * @return {number} The Euclidean modulo. + */ + euclideanModulo, + /** + * Performs a linear mapping from range `` to range `` + * for the given value. + * + * @static + * @method + * @param {number} x - The value to be mapped. + * @param {number} a1 - Minimum value for range A. + * @param {number} a2 - Maximum value for range A. + * @param {number} b1 - Minimum value for range B. + * @param {number} b2 - Maximum value for range B. + * @return {number} The mapped value. + */ + mapLinear, + /** + * Returns the percentage in the closed interval `[0, 1]` of the given value + * between the start and end point. + * + * @static + * @method + * @param {number} x - The start point + * @param {number} y - The end point. + * @param {number} value - A value between start and end. + * @return {number} The interpolation factor. + */ + inverseLerp, + /** + * Returns a value linearly interpolated from two known points based on the given interval - + * `t = 0` will return `x` and `t = 1` will return `y`. + * + * @static + * @method + * @param {number} x - The start point + * @param {number} y - The end point. + * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. + * @return {number} The interpolated value. + */ + lerp, + /** + * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta + * time to maintain frame rate independent movement. For details, see + * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/). + * + * @static + * @method + * @param {number} x - The current point. + * @param {number} y - The target point. + * @param {number} lambda - A higher lambda value will make the movement more sudden, + * and a lower value will make the movement more gradual. + * @param {number} dt - Delta time in seconds. + * @return {number} The interpolated value. + */ + damp, + /** + * Returns a value that alternates between `0` and the given `length` parameter. + * + * @static + * @method + * @param {number} x - The value to pingpong. + * @param {number} [length=1] - The positive value the function will pingpong to. + * @return {number} The alternated value. + */ + pingpong, + /** + * Returns a value in the range `[0,1]` that represents the percentage that `x` has + * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to + * the `min` and `max`. + * + * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details. + * + * @static + * @method + * @param {number} x - The value to evaluate based on its position between min and max. + * @param {number} min - The min value. Any x value below min will be `0`. + * @param {number} max - The max value. Any x value above max will be `1`. + * @return {number} The alternated value. + */ + smoothstep, + /** + * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations) + * that has zero 1st and 2nd order derivatives at x=0 and x=1. + * + * @static + * @method + * @param {number} x - The value to evaluate based on its position between min and max. + * @param {number} min - The min value. Any x value below min will be `0`. + * @param {number} max - The max value. Any x value above max will be `1`. + * @return {number} The alternated value. + */ + smootherstep, + /** + * Returns a random integer from `` interval. + * + * @static + * @method + * @param {number} low - The lower value boundary. + * @param {number} high - The upper value boundary + * @return {number} A random integer. + */ + randInt, + /** + * Returns a random float from `` interval. + * + * @static + * @method + * @param {number} low - The lower value boundary. + * @param {number} high - The upper value boundary + * @return {number} A random float. + */ + randFloat, + /** + * Returns a random integer from `<-range/2, range/2>` interval. + * + * @static + * @method + * @param {number} range - Defines the value range. + * @return {number} A random float. + */ + randFloatSpread, + /** + * Returns a deterministic pseudo-random float in the interval `[0, 1]`. + * + * @static + * @method + * @param {number} [s] - The integer seed. + * @return {number} A random float. + */ + seededRandom, + /** + * Converts degrees to radians. + * + * @static + * @method + * @param {number} degrees - A value in degrees. + * @return {number} The converted value in radians. + */ + degToRad, + /** + * Converts radians to degrees. + * + * @static + * @method + * @param {number} radians - A value in radians. + * @return {number} The converted value in degrees. + */ + radToDeg, + /** + * Returns `true` if the given number is a power of two. + * + * @static + * @method + * @param {number} value - The value to check. + * @return {boolean} Whether the given number is a power of two or not. + */ + isPowerOfTwo, + /** + * Returns the smallest power of two that is greater than or equal to the given number. + * + * @static + * @method + * @param {number} value - The value to find a POT for. + * @return {number} The smallest power of two that is greater than or equal to the given number. + */ + ceilPowerOfTwo, + /** + * Returns the largest power of two that is less than or equal to the given number. + * + * @static + * @method + * @param {number} value - The value to find a POT for. + * @return {number} The largest power of two that is less than or equal to the given number. + */ + floorPowerOfTwo, + /** + * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles) + * defined by the given angles and order. + * + * Rotations are applied to the axes in the order specified by order: + * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`. + * + * @static + * @method + * @param {Quaternion} q - The quaternion to set. + * @param {number} a - The rotation applied to the first axis, in radians. + * @param {number} b - The rotation applied to the second axis, in radians. + * @param {number} c - The rotation applied to the third axis, in radians. + * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order. + */ + setQuaternionFromProperEuler, + /** + * Normalizes the given value according to the given typed array. + * + * @static + * @method + * @param {number} value - The float value in the range `[0,1]` to normalize. + * @param {TypedArray} array - The typed array that defines the data type of the value. + * @return {number} The normalize value. + */ + normalize, + /** + * Denormalizes the given value according to the given typed array. + * + * @static + * @method + * @param {number} value - The value to denormalize. + * @param {TypedArray} array - The typed array that defines the data type of the value. + * @return {number} The denormalize (float) value in the range `[0,1]`. + */ + denormalize + }; + const _Vector2 = class _Vector2 { + /** + * Constructs a new 2D vector. + * + * @param {number} [x=0] - The x value of this vector. + * @param {number} [y=0] - The y value of this vector. + */ + constructor(x = 0, y = 0) { + this.x = x; + this.y = y; } - - return this; - }, - - ignore : function(fn) { - if (this.observers) { - if (!fn) { - this.observers = []; - } else { - var o = this.observers, l = o.length; - while(l--) { - o[l] === fn && o.splice(l, 1); - } - } + /** + * Alias for {@link Vector2#x}. + * + * @type {number} + */ + get width() { + return this.x; } - return this; - }, - - // set x and y - set: function(x, y, notify) { - if('number' != typeof x) { - notify = y; - y = x.y; - x = x.x; + set width(value) { + this.x = value; } - - if(this.x === x && this.y === y) { + /** + * Alias for {@link Vector2#y}. + * + * @type {number} + */ + get height() { + return this.y; + } + set height(value) { + this.y = value; + } + /** + * Sets the vector components. + * + * @param {number} x - The value of the x component. + * @param {number} y - The value of the y component. + * @return {Vector2} A reference to this vector. + */ + set(x, y) { + this.x = x; + this.y = y; return this; } - - var orig = null; - if (notify !== false && this.observers && this.observers.length) { - orig = this.clone(); + /** + * Sets the vector components to the same value. + * + * @param {number} scalar - The value to set for all vector components. + * @return {Vector2} A reference to this vector. + */ + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; } - - this.x = Vec2.clean(x); - this.y = Vec2.clean(y); - - if(notify !== false) { - return this.change(orig); + /** + * Sets the vector's x component to the given value + * + * @param {number} x - The value to set. + * @return {Vector2} A reference to this vector. + */ + setX(x) { + this.x = x; + return this; } - }, - - // reset x and y to zero - zero : function() { - return this.set(0, 0); - }, - - // return a new vector with the same component values - // as this one - clone : function() { - return new (this.constructor)(this.x, this.y); - }, - - // negate the values of this vector - negate : function(returnNew) { - if (returnNew) { - return new (this.constructor)(-this.x, -this.y); - } else { - return this.set(-this.x, -this.y); + /** + * Sets the vector's y component to the given value + * + * @param {number} y - The value to set. + * @return {Vector2} A reference to this vector. + */ + setY(y) { + this.y = y; + return this; } - }, - - // Add the incoming `vec2` vector to this vector - add : function(x, y, returnNew) { - - if (typeof x != 'number') { - returnNew = y; - if (isArray(x)) { - y = x[1]; - x = x[0]; - } else { - y = x.y; - x = x.x; + /** + * Allows to set a vector component with an index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y. + * @param {number} value - The value to set. + * @return {Vector2} A reference to this vector. + */ + setComponent(index, value) { + switch (index) { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + default: + throw new Error("index is out of range: " + index); } + return this; } - - x += this.x; - y += this.y; - - - if (!returnNew) { - return this.set(x, y); - } else { - // Return a new vector if `returnNew` is truthy - return new (this.constructor)(x, y); - } - }, - - // Subtract the incoming `vec2` from this vector - subtract : function(x, y, returnNew) { - if (typeof x != 'number') { - returnNew = y; - if (isArray(x)) { - y = x[1]; - x = x[0]; - } else { - y = x.y; - x = x.x; + /** + * Returns the value of the vector component which matches the given index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y. + * @return {number} A vector component value. + */ + getComponent(index) { + switch (index) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index); } } - - x = this.x - x; - y = this.y - y; - - if (!returnNew) { - return this.set(x, y); - } else { - // Return a new vector if `returnNew` is truthy - return new (this.constructor)(x, y); + /** + * Returns a new vector with copied values from this instance. + * + * @return {Vector2} A clone of this instance. + */ + clone() { + return new this.constructor(this.x, this.y); } - }, - - // Multiply this vector by the incoming `vec2` - multiply : function(x, y, returnNew) { - if (typeof x != 'number') { - returnNew = y; - if (isArray(x)) { - y = x[1]; - x = x[0]; - } else { - y = x.y; - x = x.x; - } - } else if (typeof y != 'number') { - returnNew = y; - y = x; + /** + * Copies the values of the given vector to this instance. + * + * @param {Vector2} v - The vector to copy. + * @return {Vector2} A reference to this vector. + */ + copy(v) { + this.x = v.x; + this.y = v.y; + return this; } - - x *= this.x; - y *= this.y; - - if (!returnNew) { - return this.set(x, y); - } else { - return new (this.constructor)(x, y); + /** + * Adds the given vector to this instance. + * + * @param {Vector2} v - The vector to add. + * @return {Vector2} A reference to this vector. + */ + add(v) { + this.x += v.x; + this.y += v.y; + return this; } - }, - - // Rotate this vector. Accepts a `Rotation` or angle in radians. - // - // Passing a truthy `inverse` will cause the rotation to - // be reversed. - // - // If `returnNew` is truthy, a new - // `Vec2` will be created with the values resulting from - // the rotation. Otherwise the rotation will be applied - // to this vector directly, and this vector will be returned. - rotate : function(r, inverse, returnNew) { - var - x = this.x, - y = this.y, - cos = Math.cos(r), - sin = Math.sin(r), - rx, ry; - - inverse = (inverse) ? -1 : 1; - - rx = cos * x - (inverse * sin) * y; - ry = (inverse * sin) * x + cos * y; - - if (returnNew) { - return new (this.constructor)(rx, ry); - } else { - return this.set(rx, ry); + /** + * Adds the given scalar value to all components of this instance. + * + * @param {number} s - The scalar to add. + * @return {Vector2} A reference to this vector. + */ + addScalar(s) { + this.x += s; + this.y += s; + return this; } - }, - - // Calculate the length of this vector - length : function() { - var x = this.x, y = this.y; - return Math.sqrt(x * x + y * y); - }, - - // Get the length squared. For performance, use this instead of `Vec2#length` (if possible). - lengthSquared : function() { - var x = this.x, y = this.y; - return x*x+y*y; - }, - - // Return the distance betwen this `Vec2` and the incoming vec2 vector - // and return a scalar - distance : function(vec2) { - var x = this.x - vec2.x; - var y = this.y - vec2.y; - return Math.sqrt(x*x + y*y); - }, - - // Convert this vector into a unit vector. - // Returns the length. - normalize : function(returnNew) { - var length = this.length(); - - // Collect a ratio to shrink the x and y coords - var invertedLength = (length < Number.MIN_VALUE) ? 0 : 1/length; - - if (!returnNew) { - // Convert the coords to be greater than zero - // but smaller than or equal to 1.0 - return this.set(this.x * invertedLength, this.y * invertedLength); - } else { - return new (this.constructor)(this.x * invertedLength, this.y * invertedLength); + /** + * Adds the given vectors and stores the result in this instance. + * + * @param {Vector2} a - The first vector. + * @param {Vector2} b - The second vector. + * @return {Vector2} A reference to this vector. + */ + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + return this; } - }, - - // Determine if another `Vec2`'s components match this one's - // also accepts 2 scalars - equal : function(v, w) { - if (typeof v != 'number') { - if (isArray(v)) { - w = v[1]; - v = v[0]; + /** + * Adds the given vector scaled by the given factor to this instance. + * + * @param {Vector2} v - The vector. + * @param {number} s - The factor that scales `v`. + * @return {Vector2} A reference to this vector. + */ + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + return this; + } + /** + * Subtracts the given vector from this instance. + * + * @param {Vector2} v - The vector to subtract. + * @return {Vector2} A reference to this vector. + */ + sub(v) { + this.x -= v.x; + this.y -= v.y; + return this; + } + /** + * Subtracts the given scalar value from all components of this instance. + * + * @param {number} s - The scalar to subtract. + * @return {Vector2} A reference to this vector. + */ + subScalar(s) { + this.x -= s; + this.y -= s; + return this; + } + /** + * Subtracts the given vectors and stores the result in this instance. + * + * @param {Vector2} a - The first vector. + * @param {Vector2} b - The second vector. + * @return {Vector2} A reference to this vector. + */ + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + return this; + } + /** + * Multiplies the given vector with this instance. + * + * @param {Vector2} v - The vector to multiply. + * @return {Vector2} A reference to this vector. + */ + multiply(v) { + this.x *= v.x; + this.y *= v.y; + return this; + } + /** + * Multiplies the given scalar value with all components of this instance. + * + * @param {number} scalar - The scalar to multiply. + * @return {Vector2} A reference to this vector. + */ + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + /** + * Divides this instance by the given vector. + * + * @param {Vector2} v - The vector to divide. + * @return {Vector2} A reference to this vector. + */ + divide(v) { + this.x /= v.x; + this.y /= v.y; + return this; + } + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector2} A reference to this vector. + */ + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + /** + * Multiplies this vector (with an implicit 1 as the 3rd component) by + * the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to apply. + * @return {Vector2} A reference to this vector. + */ + applyMatrix3(m) { + const x = this.x, y = this.y; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6]; + this.y = e[1] * x + e[4] * y + e[7]; + return this; + } + /** + * If this vector's x or y value is greater than the given vector's x or y + * value, replace that value with the corresponding min value. + * + * @param {Vector2} v - The vector. + * @return {Vector2} A reference to this vector. + */ + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + return this; + } + /** + * If this vector's x or y value is less than the given vector's x or y + * value, replace that value with the corresponding max value. + * + * @param {Vector2} v - The vector. + * @return {Vector2} A reference to this vector. + */ + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + return this; + } + /** + * If this vector's x or y value is greater than the max vector's x or y + * value, it is replaced by the corresponding value. + * If this vector's x or y value is less than the min vector's x or y value, + * it is replaced by the corresponding value. + * + * @param {Vector2} min - The minimum x and y values. + * @param {Vector2} max - The maximum x and y values in the desired range. + * @return {Vector2} A reference to this vector. + */ + clamp(min, max) { + this.x = clamp(this.x, min.x, max.x); + this.y = clamp(this.y, min.y, max.y); + return this; + } + /** + * If this vector's x or y values are greater than the max value, they are + * replaced by the max value. + * If this vector's x or y values are less than the min value, they are + * replaced by the min value. + * + * @param {number} minVal - The minimum value the components will be clamped to. + * @param {number} maxVal - The maximum value the components will be clamped to. + * @return {Vector2} A reference to this vector. + */ + clampScalar(minVal, maxVal) { + this.x = clamp(this.x, minVal, maxVal); + this.y = clamp(this.y, minVal, maxVal); + return this; + } + /** + * If this vector's length is greater than the max value, it is replaced by + * the max value. + * If this vector's length is less than the min value, it is replaced by the + * min value. + * + * @param {number} min - The minimum value the vector length will be clamped to. + * @param {number} max - The maximum value the vector length will be clamped to. + * @return {Vector2} A reference to this vector. + */ + clampLength(min, max) { + const length = this.length(); + return this.divideScalar(length || 1).multiplyScalar(clamp(length, min, max)); + } + /** + * The components of this vector are rounded down to the nearest integer value. + * + * @return {Vector2} A reference to this vector. + */ + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + /** + * The components of this vector are rounded up to the nearest integer value. + * + * @return {Vector2} A reference to this vector. + */ + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + /** + * The components of this vector are rounded to the nearest integer value + * + * @return {Vector2} A reference to this vector. + */ + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + /** + * The components of this vector are rounded towards zero (up if negative, + * down if positive) to an integer value. + * + * @return {Vector2} A reference to this vector. + */ + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + /** + * Inverts this vector - i.e. sets x = -x and y = -y. + * + * @return {Vector2} A reference to this vector. + */ + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + /** + * Calculates the dot product of the given vector with this instance. + * + * @param {Vector2} v - The vector to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot(v) { + return this.x * v.x + this.y * v.y; + } + /** + * Calculates the cross product of the given vector with this instance. + * + * @param {Vector2} v - The vector to compute the cross product with. + * @return {number} The result of the cross product. + */ + cross(v) { + return this.x * v.y - this.y * v.x; + } + /** + * Computes the square of the Euclidean length (straight-line length) from + * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should + * compare the length squared instead as it is slightly more efficient to calculate. + * + * @return {number} The square length of this vector. + */ + lengthSq() { + return this.x * this.x + this.y * this.y; + } + /** + * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y). + * + * @return {number} The length of this vector. + */ + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + /** + * Computes the Manhattan length of this vector. + * + * @return {number} The length of this vector. + */ + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + /** + * Converts this vector to a unit vector - that is, sets it equal to a vector + * with the same direction as this one, but with a vector length of `1`. + * + * @return {Vector2} A reference to this vector. + */ + normalize() { + return this.divideScalar(this.length() || 1); + } + /** + * Computes the angle in radians of this vector with respect to the positive x-axis. + * + * @return {number} The angle in radians. + */ + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + /** + * Returns the angle between the given vector and this instance in radians. + * + * @param {Vector2} v - The vector to compute the angle with. + * @return {number} The angle in radians. + */ + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp(theta, -1, 1)); + } + /** + * Computes the distance from the given vector to this instance. + * + * @param {Vector2} v - The vector to compute the distance to. + * @return {number} The distance. + */ + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + /** + * Computes the squared distance from the given vector to this instance. + * If you are just comparing the distance with another distance, you should compare + * the distance squared instead as it is slightly more efficient to calculate. + * + * @param {Vector2} v - The vector to compute the squared distance to. + * @return {number} The squared distance. + */ + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + } + /** + * Computes the Manhattan distance from the given vector to this instance. + * + * @param {Vector2} v - The vector to compute the Manhattan distance to. + * @return {number} The Manhattan distance. + */ + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + } + /** + * Sets this vector to a vector with the same direction as this one, but + * with the specified length. + * + * @param {number} length - The new length of this vector. + * @return {Vector2} A reference to this vector. + */ + setLength(length) { + return this.normalize().multiplyScalar(length); + } + /** + * Linearly interpolates between the given vector and this instance, where + * alpha is the percent distance along the line - alpha = 0 will be this + * vector, and alpha = 1 will be the given one. + * + * @param {Vector2} v - The vector to interpolate towards. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector2} A reference to this vector. + */ + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + return this; + } + /** + * Linearly interpolates between the given vectors, where alpha is the percent + * distance along the line - alpha = 0 will be first vector, and alpha = 1 will + * be the second one. The result is stored in this instance. + * + * @param {Vector2} v1 - The first vector. + * @param {Vector2} v2 - The second vector. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector2} A reference to this vector. + */ + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + return this; + } + /** + * Returns `true` if this vector is equal with the given one. + * + * @param {Vector2} v - The vector to test for equality. + * @return {boolean} Whether this vector is equal with the given one. + */ + equals(v) { + return v.x === this.x && v.y === this.y; + } + /** + * Sets this vector's x value to be `array[ offset ]` and y + * value to be `array[ offset + 1 ]`. + * + * @param {Array} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector2} A reference to this vector. + */ + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector2} A reference to this vector. + */ + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + return this; + } + /** + * Rotates this vector around the given center by the given angle. + * + * @param {Vector2} center - The point around which to rotate. + * @param {number} angle - The angle to rotate, in radians. + * @return {Vector2} A reference to this vector. + */ + rotateAround(center, angle) { + const c = Math.cos(angle), s = Math.sin(angle); + const x = this.x - center.x; + const y = this.y - center.y; + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + return this; + } + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector2} A reference to this vector. + */ + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } + }; + _Vector2.prototype.isVector2 = true; + let Vector2 = _Vector2; + class Quaternion { + /** + * Constructs a new quaternion. + * + * @param {number} [x=0] - The x value of this quaternion. + * @param {number} [y=0] - The y value of this quaternion. + * @param {number} [z=0] - The z value of this quaternion. + * @param {number} [w=1] - The w value of this quaternion. + */ + constructor(x = 0, y = 0, z = 0, w = 1) { + this.isQuaternion = true; + this._x = x; + this._y = y; + this._z = z; + this._w = w; + } + /** + * Interpolates between two quaternions via SLERP. This implementation assumes the + * quaternion data are managed in flat arrays. + * + * @param {Array} dst - The destination array. + * @param {number} dstOffset - An offset into the destination array. + * @param {Array} src0 - The source array of the first quaternion. + * @param {number} srcOffset0 - An offset into the first source array. + * @param {Array} src1 - The source array of the second quaternion. + * @param {number} srcOffset1 - An offset into the second source array. + * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate. + * @see {@link Quaternion#slerp} + */ + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) { + let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; + let x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { + let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1; + if (dot < 0) { + x1 = -x1; + y1 = -y1; + z1 = -z1; + w1 = -w1; + dot = -dot; + } + let s = 1 - t; + if (dot < 0.9995) { + const theta = Math.acos(dot); + const sin = Math.sin(theta); + s = Math.sin(s * theta) / sin; + t = Math.sin(t * theta) / sin; + x0 = x0 * s + x1 * t; + y0 = y0 * s + y1 * t; + z0 = z0 * s + z1 * t; + w0 = w0 * s + w1 * t; + } else { + x0 = x0 * s + x1 * t; + y0 = y0 * s + y1 * t; + z0 = z0 * s + z1 * t; + w0 = w0 * s + w1 * t; + const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + } + } + dst[dstOffset] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + } + /** + * Multiplies two quaternions. This implementation assumes the quaternion data are managed + * in flat arrays. + * + * @param {Array} dst - The destination array. + * @param {number} dstOffset - An offset into the destination array. + * @param {Array} src0 - The source array of the first quaternion. + * @param {number} srcOffset0 - An offset into the first source array. + * @param {Array} src1 - The source array of the second quaternion. + * @param {number} srcOffset1 - An offset into the second source array. + * @return {Array} The destination array. + * @see {@link Quaternion#multiplyQuaternions}. + */ + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x0 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + return dst; + } + /** + * The x value of this quaternion. + * + * @type {number} + * @default 0 + */ + get x() { + return this._x; + } + set x(value) { + this._x = value; + this._onChangeCallback(); + } + /** + * The y value of this quaternion. + * + * @type {number} + * @default 0 + */ + get y() { + return this._y; + } + set y(value) { + this._y = value; + this._onChangeCallback(); + } + /** + * The z value of this quaternion. + * + * @type {number} + * @default 0 + */ + get z() { + return this._z; + } + set z(value) { + this._z = value; + this._onChangeCallback(); + } + /** + * The w value of this quaternion. + * + * @type {number} + * @default 1 + */ + get w() { + return this._w; + } + set w(value) { + this._w = value; + this._onChangeCallback(); + } + /** + * Sets the quaternion components. + * + * @param {number} x - The x value of this quaternion. + * @param {number} y - The y value of this quaternion. + * @param {number} z - The z value of this quaternion. + * @param {number} w - The w value of this quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + set(x, y, z, w) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; + this._onChangeCallback(); + return this; + } + /** + * Returns a new quaternion with copied values from this instance. + * + * @return {Quaternion} A clone of this instance. + */ + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + /** + * Copies the values of the given quaternion to this instance. + * + * @param {Quaternion} quaternion - The quaternion to copy. + * @return {Quaternion} A reference to this quaternion. + */ + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + /** + * Sets this quaternion from the rotation specified by the given + * Euler angles. + * + * @param {Euler} euler - The Euler angles. + * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. + * @return {Quaternion} A reference to this quaternion. + */ + setFromEuler(euler, update = true) { + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x / 2); + const c2 = cos(y / 2); + const c3 = cos(z / 2); + const s1 = sin(x / 2); + const s2 = sin(y / 2); + const s3 = sin(z / 2); + switch (order) { + case "XYZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "YXZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "ZXY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "ZYX": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "YZX": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "XZY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + default: + warn("Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) this._onChangeCallback(); + return this; + } + /** + * Sets this quaternion from the given axis and angle. + * + * @param {Vector3} axis - The normalized axis. + * @param {number} angle - The angle in radians. + * @return {Quaternion} A reference to this quaternion. + */ + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s = Math.sin(halfAngle); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + /** + * Sets this quaternion from the given rotation matrix. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). + * @return {Quaternion} A reference to this quaternion. + */ + setFromRotationMatrix(m) { + const te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s; + this._x = (m32 - m23) * s; + this._y = (m13 - m31) * s; + this._z = (m21 - m12) * s; + } else if (m11 > m22 && m11 > m33) { + const s = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s; + this._x = 0.25 * s; + this._y = (m12 + m21) / s; + this._z = (m13 + m31) / s; + } else if (m22 > m33) { + const s = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s; + this._x = (m12 + m21) / s; + this._y = 0.25 * s; + this._z = (m23 + m32) / s; } else { - w = v.y; - v = v.x; + const s = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s; + this._x = (m13 + m31) / s; + this._y = (m23 + m32) / s; + this._z = 0.25 * s; } + this._onChangeCallback(); + return this; } - - return (Vec2.clean(v) === this.x && Vec2.clean(w) === this.y); - }, - - // Return a new `Vec2` that contains the absolute value of - // each of this vector's parts - abs : function(returnNew) { - var x = Math.abs(this.x), y = Math.abs(this.y); - - if (returnNew) { - return new (this.constructor)(x, y); - } else { - return this.set(x, y); + /** + * Sets this quaternion to the rotation required to rotate the direction vector + * `vFrom` to the direction vector `vTo`. + * + * @param {Vector3} vFrom - The first (normalized) direction vector. + * @param {Vector3} vTo - The second (normalized) direction vector. + * @return {Quaternion} A reference to this quaternion. + */ + setFromUnitVectors(vFrom, vTo) { + let r = vFrom.dot(vTo) + 1; + if (r < 1e-8) { + r = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } + return this.normalize(); } - }, - - // Return a new `Vec2` consisting of the smallest values - // from this vector and the incoming - // - // When returnNew is truthy, a new `Vec2` will be returned - // otherwise the minimum values in either this or `v` will - // be applied to this vector. - min : function(v, returnNew) { - var - tx = this.x, - ty = this.y, - vx = v.x, - vy = v.y, - x = tx < vx ? tx : vx, - y = ty < vy ? ty : vy; - - if (returnNew) { - return new (this.constructor)(x, y); - } else { - return this.set(x, y); + /** + * Returns the angle between this quaternion and the given one in radians. + * + * @param {Quaternion} q - The quaternion to compute the angle with. + * @return {number} The angle in radians. + */ + angleTo(q) { + return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1))); } - }, - - // Return a new `Vec2` consisting of the largest values - // from this vector and the incoming - // - // When returnNew is truthy, a new `Vec2` will be returned - // otherwise the minimum values in either this or `v` will - // be applied to this vector. - max : function(v, returnNew) { - var - tx = this.x, - ty = this.y, - vx = v.x, - vy = v.y, - x = tx > vx ? tx : vx, - y = ty > vy ? ty : vy; - - if (returnNew) { - return new (this.constructor)(x, y); - } else { - return this.set(x, y); + /** + * Rotates this quaternion by a given angular step to the given quaternion. + * The method ensures that the final quaternion will not overshoot `q`. + * + * @param {Quaternion} q - The target quaternion. + * @param {number} step - The angular step in radians. + * @return {Quaternion} A reference to this quaternion. + */ + rotateTowards(q, step) { + const angle = this.angleTo(q); + if (angle === 0) return this; + const t = Math.min(1, step / angle); + this.slerp(q, t); + return this; } - }, - - // Clamp values into a range. - // If this vector's values are lower than the `low`'s - // values, then raise them. If they are higher than - // `high`'s then lower them. - // - // Passing returnNew as true will cause a new Vec2 to be - // returned. Otherwise, this vector's values will be clamped - clamp : function(low, high, returnNew) { - var ret = this.min(high, true).max(low); - if (returnNew) { - return ret; - } else { - return this.set(ret.x, ret.y); + /** + * Sets this quaternion to the identity quaternion; that is, to the + * quaternion that represents "no rotation". + * + * @return {Quaternion} A reference to this quaternion. + */ + identity() { + return this.set(0, 0, 0, 1); } - }, - - // Perform linear interpolation between two vectors - // amount is a decimal between 0 and 1 - lerp : function(vec, amount, returnNew) { - return this.add(vec.subtract(this, true).multiply(amount), returnNew); - }, - - // Get the skew vector such that dot(skew_vec, other) == cross(vec, other) - skew : function(returnNew) { - if (!returnNew) { - return this.set(-this.y, this.x) - } else { - return new (this.constructor)(-this.y, this.x); + /** + * Inverts this quaternion via {@link Quaternion#conjugate}. The + * quaternion is assumed to have unit length. + * + * @return {Quaternion} A reference to this quaternion. + */ + invert() { + return this.conjugate(); } - }, - - // calculate the dot product between - // this vector and the incoming - dot : function(b) { - return Vec2.clean(this.x * b.x + b.y * this.y); - }, - - // calculate the perpendicular dot product between - // this vector and the incoming - perpDot : function(b) { - return Vec2.clean(this.x * b.y - this.y * b.x); - }, - - // Determine the angle between two vec2s - angleTo : function(vec) { - return Math.atan2(this.perpDot(vec), this.dot(vec)); - }, - - // Divide this vector's components by a scalar - divide : function(x, y, returnNew) { - if (typeof x != 'number') { - returnNew = y; - if (isArray(x)) { - y = x[1]; - x = x[0]; + /** + * Returns the rotational conjugate of this quaternion. The conjugate of a + * quaternion represents the same rotation in the opposite direction about + * the rotational axis. + * + * @return {Quaternion} A reference to this quaternion. + */ + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + /** + * Calculates the dot product of this quaternion and the given one. + * + * @param {Quaternion} v - The quaternion to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot(v) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } + /** + * Computes the squared Euclidean length (straight-line length) of this quaternion, + * considered as a 4 dimensional vector. This can be useful if you are comparing the + * lengths of two quaternions, as this is a slightly more efficient calculation than + * {@link Quaternion#length}. + * + * @return {number} The squared Euclidean length. + */ + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + /** + * Computes the Euclidean length (straight-line length) of this quaternion, + * considered as a 4 dimensional vector. + * + * @return {number} The Euclidean length. + */ + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + /** + * Normalizes this quaternion - that is, calculated the quaternion that performs + * the same rotation as this one, but has a length equal to `1`. + * + * @return {Quaternion} A reference to this quaternion. + */ + normalize() { + let l = this.length(); + if (l === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; } else { - y = x.y; - x = x.x; + l = 1 / l; + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; } - } else if (typeof y != 'number') { - returnNew = y; - y = x; + this._onChangeCallback(); + return this; } - - if (x === 0 || y === 0) { - throw new Error('division by zero') + /** + * Multiplies this quaternion by the given one. + * + * @param {Quaternion} q - The quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + multiply(q) { + return this.multiplyQuaternions(this, q); } - - if (isNaN(x) || isNaN(y)) { - throw new Error('NaN detected'); + /** + * Pre-multiplies this quaternion by the given one. + * + * @param {Quaternion} q - The quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + premultiply(q) { + return this.multiplyQuaternions(q, this); } - - if (returnNew) { - return new (this.constructor)(this.x / x, this.y / y); + /** + * Multiplies the given quaternions and stores the result in this instance. + * + * @param {Quaternion} a - The first quaternion. + * @param {Quaternion} b - The second quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + multiplyQuaternions(a, b) { + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; } - - return this.set(this.x / x, this.y / y); - }, - - isPointOnLine : function(start, end) { - return (start.y - this.y) * (start.x - end.x) === - (start.y - end.y) * (start.x - this.x); - }, - - toArray: function() { - return [this.x, this.y]; - }, - - fromArray: function(array) { - return this.set(array[0], array[1]); - }, - toJSON: function () { - return {x: this.x, y: this.y}; - }, - toString: function() { - return '(' + this.x + ', ' + this.y + ')'; - }, - constructor : Vec2 - }; - - Vec2.fromArray = function(array, ctor) { - return new (ctor || Vec2)(array[0], array[1]); - }; - - // Floating point stability - Vec2.precision = precision || 8; - var p = Math.pow(10, Vec2.precision); - - Vec2.clean = clean || function(val) { - if (isNaN(val)) { - throw new Error('NaN detected'); - } - - if (!isFinite(val)) { - throw new Error('Infinity detected'); - } - - if(Math.round(val) === val) { - return val; - } - - return Math.round(val * p)/p; - }; - - Vec2.inject = inject; - - if(!clean) { - Vec2.fast = inject(function (k) { return k; }); - - // Expose, but also allow creating a fresh Vec2 subclass. - if (typeof module !== 'undefined' && typeof module.exports == 'object') { - module.exports = Vec2; - } else { - window.Vec2 = window.Vec2 || Vec2; - } - } - return Vec2; -})(); - -},{}],15:[function(require,module,exports){ -var TWEEN = require('tween.js'), - THREE = require('three'), - Hexasphere = require('hexasphere.js'), - Quadtree2 = require('quadtree2'), - Vec2 = require('vec2'), - Pin = require('./Pin'), - Marker = require('./Marker'), - Satellite = require('./Satellite'), - SmokeProvider = require('./SmokeProvider'), - pusherColor = require('pusher.color'), - utils = require('./utils'); - -var latLonToXYZ = function(width, height, lat,lon){ - - var x = Math.floor(width/2.0 + (width/360.0)*lon); - var y = Math.floor((height/2.0 + (height/180.0)*lat)); - - return {x: x, y:y}; -}; - -var latLon2d = function(lat,lon){ - - var rad = 2 + (Math.abs(lat)/90) * 15; - return {x: lat+90, y:lon + 180, rad: rad}; -}; - - - -var addInitialData = function(){ - if(this.data.length == 0){ - return; - } - while(this.data.length > 0 && this.firstRunTime + (next = this.data.pop()).when < Date.now()){ - this.addPin(next.lat, next.lng, next.label); - } - - if(this.firstRunTime + next.when >= Date.now()){ - this.data.push(next); - } -}; - - -var createParticles = function(){ - - if(this.hexGrid){ - this.scene.remove(this.hexGrid); - } - - var pointVertexShader = [ - "#define PI 3.141592653589793238462643", - "#define DISTANCE 500.0", - "#define INTRODURATION " + (parseFloat(this.introLinesDuration) + .00001), - "#define INTROALTITUDE " + (parseFloat(this.introLinesAltitude) + .00001), - "attribute float lng;", - "uniform float currentTime;", - "varying vec4 vColor;", - "", - "void main()", - "{", - " vec3 newPos = position;", - " float opacityVal = 0.0;", - " float introStart = INTRODURATION * ((180.0 + lng)/360.0);", - " if(currentTime > introStart){", - " opacityVal = 1.0;", - " }", - " if(currentTime > introStart && currentTime < introStart + INTRODURATION / 8.0){", - " newPos = position * INTROALTITUDE;", - " opacityVal = .3;", - " }", - " if(currentTime > introStart + INTRODURATION / 8.0 && currentTime < introStart + INTRODURATION / 8.0 + 200.0){", - " newPos = position * (1.0 + ((INTROALTITUDE-1.0) * (1.0-(currentTime - introStart-(INTRODURATION/8.0))/200.0)));", - " }", - " vColor = vec4( color, opacityVal );", // set color associated to vertex; use later in fragment shader. - " gl_Position = projectionMatrix * modelViewMatrix * vec4(newPos, 1.0);", - "}" - ].join("\n"); - - var pointFragmentShader = [ - "varying vec4 vColor;", - "void main()", - "{", - " gl_FragColor = vColor;", - " float depth = gl_FragCoord.z / gl_FragCoord.w;", - " float fogFactor = smoothstep(" + parseInt(this.cameraDistance) +".0," + (parseInt(this.cameraDistance+300)) +".0, depth );", - " vec3 fogColor = vec3(0.0);", - " gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w ), fogFactor );", - "}" - ].join("\n"); - - var pointAttributes = { - lng: {type: 'f', value: null} - }; - - this.pointUniforms = { - currentTime: { type: 'f', value: 0.0} - } - - var pointMaterial = new THREE.ShaderMaterial( { - uniforms: this.pointUniforms, - attributes: pointAttributes, - vertexShader: pointVertexShader, - fragmentShader: pointFragmentShader, - transparent: true, - vertexColors: THREE.VertexColors, - side: THREE.DoubleSide - }); - - var triangles = this.tiles.length * 4; - - var geometry = new THREE.BufferGeometry(); - - geometry.addAttribute( 'index', Uint16Array, triangles * 3, 1 ); - geometry.addAttribute( 'position', Float32Array, triangles * 3, 3 ); - geometry.addAttribute( 'normal', Float32Array, triangles * 3, 3 ); - geometry.addAttribute( 'color', Float32Array, triangles * 3, 3 ); - geometry.addAttribute( 'lng', Float32Array, triangles * 3, 1 ); - - var lng_values = geometry.attributes.lng.array; - - var baseColorSet = pusherColor(this.baseColor).hueSet(); - var myColors = []; - for(var i = 0; i< baseColorSet.length; i++){ - myColors.push(baseColorSet[i].shade(Math.random()/3.0)); - } - - // break geometry into - // chunks of 21,845 triangles (3 unique vertices per triangle) - // for indices to fit into 16 bit integer number - // floor(2^16 / 3) = 21845 - - var chunkSize = 21845; - - var indices = geometry.attributes.index.array; - - for ( var i = 0; i < indices.length; i ++ ) { - - indices[ i ] = i % ( 3 * chunkSize ); - - } - - var positions = geometry.attributes.position.array; - var colors = geometry.attributes.color.array; - - - var n = 800, n2 = n/2; // triangles spread in the cube - var d = 12, d2 = d/2; // individual triangle size - - var addTriangle = function(k, ax, ay, az, bx, by, bz, cx, cy, cz, lat, lng, color){ - var p = k * 3; - var i = p * 3; - var colorIndex = Math.floor(Math.random()*myColors.length); - var colorRGB = myColors[colorIndex].rgb(); - - lng_values[p] = lng; - lng_values[p+1] = lng; - lng_values[p+2] = lng; - - positions[ i ] = ax; - positions[ i + 1 ] = ay; - positions[ i + 2 ] = az; - - positions[ i + 3 ] = bx; - positions[ i + 4 ] = by; - positions[ i + 5 ] = bz; - - positions[ i + 6 ] = cx; - positions[ i + 7 ] = cy; - positions[ i + 8 ] = cz; - - colors[ i ] = color.r; - colors[ i + 1 ] = color.g; - colors[ i + 2 ] = color.b; - - colors[ i + 3 ] = color.r; - colors[ i + 4 ] = color.g; - colors[ i + 5 ] = color.b; - - colors[ i + 6 ] = color.r; - colors[ i + 7 ] = color.g; - colors[ i + 8 ] = color.b; - - }; - - for(var i =0; i< this.tiles.length; i++){ - var t = this.tiles[i]; - var k = i * 4; - - var colorIndex = Math.floor(Math.random()*myColors.length); - var colorRGB = myColors[colorIndex].rgb(); - var color = new THREE.Color(); - - color.setRGB(colorRGB[0]/255.0, colorRGB[1]/255.0, colorRGB[2]/255.0); - - addTriangle(k, t.b[0].x, t.b[0].y, t.b[0].z, t.b[1].x, t.b[1].y, t.b[1].z, t.b[2].x, t.b[2].y, t.b[2].z, t.lat, t.lon, color); - addTriangle(k+1, t.b[0].x, t.b[0].y, t.b[0].z, t.b[2].x, t.b[2].y, t.b[2].z, t.b[3].x, t.b[3].y, t.b[3].z, t.lat, t.lon, color); - addTriangle(k+2, t.b[0].x, t.b[0].y, t.b[0].z, t.b[3].x, t.b[3].y, t.b[3].z, t.b[4].x, t.b[4].y, t.b[4].z, t.lat, t.lon, color); - - if(t.b.length > 5){ // for the occasional pentagon that i have to deal with - addTriangle(k+3, t.b[0].x, t.b[0].y, t.b[0].z, t.b[5].x, t.b[5].y, t.b[5].z, t.b[4].x, t.b[4].y, t.b[4].z, t.lat, t.lon, color); + /** + * Performs a spherical linear interpolation between this quaternion and the target quaternion. + * + * @param {Quaternion} qb - The target quaternion. + * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate. + * @return {Quaternion} A reference to this quaternion. + */ + slerp(qb, t) { + let x = qb._x, y = qb._y, z = qb._z, w = qb._w; + let dot = this.dot(qb); + if (dot < 0) { + x = -x; + y = -y; + z = -z; + w = -w; + dot = -dot; } - - } - - geometry.offsets = []; - - var offsets = triangles / chunkSize; - - for ( var i = 0; i < offsets; i ++ ) { - - var offset = { - start: i * chunkSize * 3, - index: i * chunkSize * 3, - count: Math.min( triangles - ( i * chunkSize ), chunkSize ) * 3 - }; - - geometry.offsets.push( offset ); - + let s = 1 - t; + if (dot < 0.9995) { + const theta = Math.acos(dot); + const sin = Math.sin(theta); + s = Math.sin(s * theta) / sin; + t = Math.sin(t * theta) / sin; + this._x = this._x * s + x * t; + this._y = this._y * s + y * t; + this._z = this._z * s + z * t; + this._w = this._w * s + w * t; + this._onChangeCallback(); + } else { + this._x = this._x * s + x * t; + this._y = this._y * s + y * t; + this._z = this._z * s + z * t; + this._w = this._w * s + w * t; + this.normalize(); + } + return this; + } + /** + * Performs a spherical linear interpolation between the given quaternions + * and stores the result in this quaternion. + * + * @param {Quaternion} qa - The source quaternion. + * @param {Quaternion} qb - The target quaternion. + * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. + * @return {Quaternion} A reference to this quaternion. + */ + slerpQuaternions(qa, qb, t) { + return this.copy(qa).slerp(qb, t); + } + /** + * Sets this quaternion to a uniformly random, normalized quaternion. + * + * @return {Quaternion} A reference to this quaternion. + */ + random() { + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt(1 - x0); + const r2 = Math.sqrt(x0); + return this.set( + r1 * Math.sin(theta1), + r1 * Math.cos(theta1), + r2 * Math.sin(theta2), + r2 * Math.cos(theta2) + ); + } + /** + * Returns `true` if this quaternion is equal with the given one. + * + * @param {Quaternion} quaternion - The quaternion to test for equality. + * @return {boolean} Whether this quaternion is equal with the given one. + */ + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + /** + * Sets this quaternion's components from the given array. + * + * @param {Array} array - An array holding the quaternion component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Quaternion} A reference to this quaternion. + */ + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + /** + * Writes the components of this quaternion to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the quaternion components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The quaternion components. + */ + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + /** + * Sets the components of this quaternion from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data. + * @param {number} index - The index into the attribute. + * @return {Quaternion} A reference to this quaternion. + */ + fromBufferAttribute(attribute, index) { + this._x = attribute.getX(index); + this._y = attribute.getY(index); + this._z = attribute.getZ(index); + this._w = attribute.getW(index); + this._onChangeCallback(); + return this; + } + /** + * This methods defines the serialization result of this class. Returns the + * numerical elements of this quaternion in an array of format `[x, y, z, w]`. + * + * @return {Array} The serialized quaternion. + */ + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } } - - geometry.computeBoundingSphere(); - - this.hexGrid = new THREE.Mesh( geometry, pointMaterial ); - this.scene.add( this.hexGrid ); - -}; - -var createIntroLines = function(){ - var sPoint; - var introLinesMaterial = new THREE.LineBasicMaterial({ - color: this.introLinesColor, - transparent: true, - linewidth: 2, - opacity: .5 - }); - - for(var i = 0; i} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector3} A reference to this vector. + */ + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector3} A reference to this vector. + */ + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + this.z = attribute.getZ(index); + return this; + } + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector3} A reference to this vector. + */ + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + /** + * Sets this vector to a uniformly random point on a unit sphere. + * + * @return {Vector3} A reference to this vector. + */ + randomDirection() { + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt(1 - u * u); + this.x = c * Math.cos(theta); + this.y = u; + this.z = c * Math.sin(theta); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } }; - - for(var i in defaults){ - if(!this[i]){ - this[i] = defaults[i]; - if(opts[i]){ - this[i] = opts[i]; - } + _Vector3.prototype.isVector3 = true; + let Vector3 = _Vector3; + const _vector$c = /* @__PURE__ */ new Vector3(); + const _quaternion$5 = /* @__PURE__ */ new Quaternion(); + const _Matrix3 = class _Matrix3 { + /** + * Constructs a new 3x3 matrix. The arguments are supposed to be + * in row-major order. If no arguments are provided, the constructor + * initializes the matrix as an identity matrix. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + */ + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== void 0) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); } - } - - this.setScale(this.scale); - - this.renderer = new THREE.WebGLRenderer( { antialias: true } ); - this.renderer.setSize( this.width, this.height); - - this.renderer.gammaInput = true; - this.renderer.gammaOutput = true; - - this.domElement = this.renderer.domElement; - - this.data.sort(function(a,b){return (b.lng - b.label.length * 2) - (a.lng - a.label.length * 2)}); - - for(var i = 0; i< this.data.length; i++){ - this.data[i].when = this.introLinesDuration*((180+this.data[i].lng)/360.0) + 500; - } - - -} - -/* public globe functions */ - -Globe.prototype.init = function(cb){ - - // create the camera - this.camera = new THREE.PerspectiveCamera( 50, this.width / this.height, 1, this.cameraDistance + 300 ); - this.camera.position.z = this.cameraDistance; - - this.cameraAngle=(Math.PI); - - // create the scene - this.scene = new THREE.Scene(); - - this.scene.fog = new THREE.Fog( 0x000000, this.cameraDistance, this.cameraDistance+300 ); - - createIntroLines.call(this); - - // create the smoke particles - - this.smokeProvider = new SmokeProvider(this.scene); - - createParticles.call(this); - setTimeout(cb, 500); -}; - -Globe.prototype.destroy = function(callback){ - - var _this = this; - this.active = false; - - setTimeout(function(){ - while(_this.scene.children.length > 0){ - _this.scene.remove(_this.scene.children[0]); + } + /** + * Sets the elements of the matrix.The arguments are supposed to be + * in row-major order. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @return {Matrix3} A reference to this matrix. + */ + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te = this.elements; + te[0] = n11; + te[1] = n21; + te[2] = n31; + te[3] = n12; + te[4] = n22; + te[5] = n32; + te[6] = n13; + te[7] = n23; + te[8] = n33; + return this; + } + /** + * Sets this matrix to the 3x3 identity matrix. + * + * @return {Matrix3} A reference to this matrix. + */ + identity() { + this.set( + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Copies the values of the given matrix to this instance. + * + * @param {Matrix3} m - The matrix to copy. + * @return {Matrix3} A reference to this matrix. + */ + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + return this; + } + /** + * Extracts the basis of this matrix into the three axis vectors provided. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix3} A reference to this matrix. + */ + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrix3Column(this, 0); + yAxis.setFromMatrix3Column(this, 1); + zAxis.setFromMatrix3Column(this, 2); + return this; + } + /** + * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Matrix3} A reference to this matrix. + */ + setFromMatrix4(m) { + const me = m.elements; + this.set( + me[0], + me[4], + me[8], + me[1], + me[5], + me[9], + me[2], + me[6], + me[10] + ); + return this; + } + /** + * Post-multiplies this matrix by the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to multiply with. + * @return {Matrix3} A reference to this matrix. + */ + multiply(m) { + return this.multiplyMatrices(this, m); + } + /** + * Pre-multiplies this matrix by the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to multiply with. + * @return {Matrix3} A reference to this matrix. + */ + premultiply(m) { + return this.multiplyMatrices(m, this); + } + /** + * Multiples the given 3x3 matrices and stores the result + * in this matrix. + * + * @param {Matrix3} a - The first matrix. + * @param {Matrix3} b - The second matrix. + * @return {Matrix3} A reference to this matrix. + */ + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[3], a13 = ae[6]; + const a21 = ae[1], a22 = ae[4], a23 = ae[7]; + const a31 = ae[2], a32 = ae[5], a33 = ae[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31; + te[3] = a11 * b12 + a12 * b22 + a13 * b32; + te[6] = a11 * b13 + a12 * b23 + a13 * b33; + te[1] = a21 * b11 + a22 * b21 + a23 * b31; + te[4] = a21 * b12 + a22 * b22 + a23 * b32; + te[7] = a21 * b13 + a22 * b23 + a23 * b33; + te[2] = a31 * b11 + a32 * b21 + a33 * b31; + te[5] = a31 * b12 + a32 * b22 + a33 * b32; + te[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + /** + * Multiplies every component of the matrix by the given scalar. + * + * @param {number} s - The scalar. + * @return {Matrix3} A reference to this matrix. + */ + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[3] *= s; + te[6] *= s; + te[1] *= s; + te[4] *= s; + te[7] *= s; + te[2] *= s; + te[5] *= s; + te[8] *= s; + return this; + } + /** + * Computes and returns the determinant of this matrix. + * + * @return {number} The determinant. + */ + determinant() { + const te = this.elements; + const a = te[0], b = te[1], c = te[2], d = te[3], e = te[4], f = te[5], g = te[6], h = te[7], i = te[8]; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + } + /** + * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution). + * You can not invert with a determinant of zero. If you attempt this, the method produces + * a zero matrix instead. + * + * @return {Matrix3} A reference to this matrix. + */ + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n12 = te[3], n22 = te[4], n32 = te[5], n13 = te[6], n23 = te[7], n33 = te[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n31 * n23 - n33 * n21) * detInv; + te[2] = (n32 * n21 - n31 * n22) * detInv; + te[3] = t12 * detInv; + te[4] = (n33 * n11 - n31 * n13) * detInv; + te[5] = (n31 * n12 - n32 * n11) * detInv; + te[6] = t13 * detInv; + te[7] = (n21 * n13 - n23 * n11) * detInv; + te[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + /** + * Transposes this matrix in place. + * + * @return {Matrix3} A reference to this matrix. + */ + transpose() { + let tmp3; + const m = this.elements; + tmp3 = m[1]; + m[1] = m[3]; + m[3] = tmp3; + tmp3 = m[2]; + m[2] = m[6]; + m[6] = tmp3; + tmp3 = m[5]; + m[5] = m[7]; + m[7] = tmp3; + return this; + } + /** + * Computes the normal matrix which is the inverse transpose of the upper + * left 3x3 portion of the given 4x4 matrix. + * + * @param {Matrix4} matrix4 - The 4x4 matrix. + * @return {Matrix3} A reference to this matrix. + */ + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + /** + * Transposes this matrix into the supplied array, and returns itself unchanged. + * + * @param {Array} r - An array to store the transposed matrix elements. + * @return {Matrix3} A reference to this matrix. + */ + transposeIntoArray(r) { + const m = this.elements; + r[0] = m[0]; + r[1] = m[3]; + r[2] = m[6]; + r[3] = m[1]; + r[4] = m[4]; + r[5] = m[7]; + r[6] = m[2]; + r[7] = m[5]; + r[8] = m[8]; + return this; + } + /** + * Sets the UV transform matrix from offset, repeat, rotation, and center. + * + * @param {number} tx - Offset x. + * @param {number} ty - Offset y. + * @param {number} sx - Repeat x. + * @param {number} sy - Repeat y. + * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise. + * @param {number} cx - Center x of rotation. + * @param {number} cy - Center y of rotation + * @return {Matrix3} A reference to this matrix. + */ + setUvTransform(tx, ty, sx, sy, rotation, cx, cy) { + const c = Math.cos(rotation); + const s = Math.sin(rotation); + this.set( + sx * c, + sx * s, + -sx * (c * cx + s * cy) + cx + tx, + -sy * s, + sy * c, + -sy * (-s * cx + c * cy) + cy + ty, + 0, + 0, + 1 + ); + return this; + } + /** + * Scales this matrix with the given scalar values. + * + * @param {number} sx - The amount to scale in the X axis. + * @param {number} sy - The amount to scale in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + scale(sx, sy) { + this.premultiply(_m3.makeScale(sx, sy)); + return this; + } + /** + * Rotates this matrix by the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix3} A reference to this matrix. + */ + rotate(theta) { + this.premultiply(_m3.makeRotation(-theta)); + return this; + } + /** + * Translates this matrix by the given scalar values. + * + * @param {number} tx - The amount to translate in the X axis. + * @param {number} ty - The amount to translate in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + translate(tx, ty) { + this.premultiply(_m3.makeTranslation(tx, ty)); + return this; + } + // for 2D Transforms + /** + * Sets this matrix as a 2D translation transform. + * + * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector. + * @param {number} y - The amount to translate in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + makeTranslation(x, y) { + if (x.isVector2) { + this.set( + 1, + 0, + x.x, + 0, + 1, + x.y, + 0, + 0, + 1 + ); + } else { + this.set( + 1, + 0, + x, + 0, + 1, + y, + 0, + 0, + 1 + ); } - if(typeof callback == "function"){ - callback(); + return this; + } + /** + * Sets this matrix as a 2D rotational transformation. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix3} A reference to this matrix. + */ + makeRotation(theta) { + const c = Math.cos(theta); + const s = Math.sin(theta); + this.set( + c, + -s, + 0, + s, + c, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a 2D scale transform. + * + * @param {number} x - The amount to scale in the X axis. + * @param {number} y - The amount to scale in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + makeScale(x, y) { + this.set( + x, + 0, + 0, + 0, + y, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Returns `true` if this matrix is equal with the given one. + * + * @param {Matrix3} matrix - The matrix to test for equality. + * @return {boolean} Whether this matrix is equal with the given one. + */ + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0; i < 9; i++) { + if (te[i] !== me[i]) return false; } - - }, 1000); - -}; - -Globe.prototype.addPin = function(lat, lon, text){ - - lat = parseFloat(lat); - lon = parseFloat(lon); - - var opts = { - lineColor: this.pinColor, - topColor: this.pinColor + return true; + } + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} array - The matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Matrix3} A reference to this matrix. + */ + fromArray(array, offset = 0) { + for (let i = 0; i < 9; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + /** + * Writes the elements of this matrix to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The matrix elements in column-major order. + */ + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + return array; + } + /** + * Returns a matrix with copied values from this instance. + * + * @return {Matrix3} A clone of this instance. + */ + clone() { + return new this.constructor().fromArray(this.elements); + } + }; + _Matrix3.prototype.isMatrix3 = true; + let Matrix3 = _Matrix3; + const _m3 = /* @__PURE__ */ new Matrix3(); + const LINEAR_REC709_TO_XYZ = /* @__PURE__ */ new Matrix3().set( + 0.4123908, + 0.3575843, + 0.1804808, + 0.212639, + 0.7151687, + 0.0721923, + 0.0193308, + 0.1191948, + 0.9505322 + ); + const XYZ_TO_LINEAR_REC709 = /* @__PURE__ */ new Matrix3().set( + 3.2409699, + -1.5373832, + -0.4986108, + -0.9692436, + 1.8759675, + 0.0415551, + 0.0556301, + -0.203977, + 1.0569715 + ); + function createColorManagement() { + const ColorManagement2 = { + enabled: true, + workingColorSpace: LinearSRGBColorSpace, + /** + * Implementations of supported color spaces. + * + * Required: + * - primaries: chromaticity coordinates [ rx ry gx gy bx by ] + * - whitePoint: reference white [ x y ] + * - transfer: transfer function (pre-defined) + * - toXYZ: Matrix3 RGB to XYZ transform + * - fromXYZ: Matrix3 XYZ to RGB transform + * - luminanceCoefficients: RGB luminance coefficients + * + * Optional: + * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' } + * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace } + * + * Reference: + * - https://www.russellcottrell.com/photo/matrixCalculator.htm + */ + spaces: {}, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + if (this.spaces[sourceColorSpace].transfer === SRGBTransfer) { + color.r = SRGBToLinear(color.r); + color.g = SRGBToLinear(color.g); + color.b = SRGBToLinear(color.b); + } + if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) { + color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ); + color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ); + } + if (this.spaces[targetColorSpace].transfer === SRGBTransfer) { + color.r = LinearToSRGB(color.r); + color.g = LinearToSRGB(color.g); + color.b = LinearToSRGB(color.b); + } + return color; + }, + workingToColorSpace: function(color, targetColorSpace) { + return this.convert(color, this.workingColorSpace, targetColorSpace); + }, + colorSpaceToWorking: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this.workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return this.spaces[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace) return LinearTransfer; + return this.spaces[colorSpace].transfer; + }, + getToneMappingMode: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.toneMappingMode || "standard"; + }, + getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) { + return target.fromArray(this.spaces[colorSpace].luminanceCoefficients); + }, + define: function(colorSpaces) { + Object.assign(this.spaces, colorSpaces); + }, + // Internal APIs + _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) { + return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ); + }, + _getDrawingBufferColorSpace: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) { + return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace; + }, + // Deprecated + fromWorkingColorSpace: function(color, targetColorSpace) { + warnOnce("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."); + return ColorManagement2.workingToColorSpace(color, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + warnOnce("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."); + return ColorManagement2.colorSpaceToWorking(color, sourceColorSpace); + } + }; + const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06]; + const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]; + const D65 = [0.3127, 0.329]; + ColorManagement2.define({ + [LinearSRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + }, + [SRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + } + }); + return ColorManagement2; } - - var altitude = 1.2; - - if(typeof text != "string" || text.length === 0){ - altitude -= .05 + Math.random() * .05; + const ColorManagement = /* @__PURE__ */ createColorManagement(); + function SRGBToLinear(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); } - - var pin = new Pin(lat, lon, text, altitude, this.scene, this.smokeProvider, opts); - - this.pins.push(pin); - - // lets add quadtree stuff - - var pos = latLon2d(lat, lon); - - pin.pos_ = new Vec2(parseInt(pos.x),parseInt(pos.y)); - - if(text.length > 0){ - pin.rad_ = pos.rad; - } else { - pin.rad_ = 1; + function LinearToSRGB(c) { + return c < 31308e-7 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055; } - - this.quadtree.addObject(pin); - - if(text.length > 0){ - var collisions = this.quadtree.getCollisionsForObject(pin); - var collisionCount = 0; - var tooYoungCount = 0; - var hidePins = []; - - for(var i in collisions){ - if(collisions[i].text.length > 0){ - collisionCount++; - if(collisions[i].age() > 5000){ - hidePins.push(collisions[i]); - } else { - tooYoungCount++; - } - } + let _canvas; + class ImageUtils { + /** + * Returns a data URI containing a representation of the given image. + * + * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object. + * @param {string} [type='image/png'] - Indicates the image format. + * @return {string} The data URI. + */ + static getDataURL(image, type = "image/png") { + if (/^data:/i.test(image.src)) { + return image.src; } - - if(collisionCount > 0 && tooYoungCount == 0){ - for(var i = 0; i< hidePins.length; i++){ - hidePins[i].hideLabel(); - hidePins[i].hideSmoke(); - hidePins[i].hideTop(); - hidePins[i].changeAltitude(Math.random() * .05 + 1.1); + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas === void 0) _canvas = createElementNS("canvas"); + _canvas.width = image.width; + _canvas.height = image.height; + const context = _canvas.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas; + } + return canvas.toDataURL(type); + } + /** + * Converts the given sRGB image data to linear color space. + * + * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object. + * @return {HTMLCanvasElement|Object} The converted image. + */ + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data = imageData.data; + for (let i = 0; i < data.length; i++) { + data[i] = SRGBToLinear(data[i] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data = image.data.slice(0); + for (let i = 0; i < data.length; i++) { + if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) { + data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255); + } else { + data[i] = SRGBToLinear(data[i]); } - } else if (collisionCount > 0){ - pin.hideLabel(); - pin.hideSmoke(); - pin.hideTop(); - pin.changeAltitude(Math.random() * .05 + 1.1); + } + return { + data, + width: image.width, + height: image.height + }; + } else { + warn("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; } + } } - - if(this.pins.length > this.maxPins){ - var oldPin = this.pins.shift(); - this.quadtree.removeObject(oldPin); - oldPin.remove(); - - } - - return pin; - -} - -Globe.prototype.addMarker = function(lat, lon, text, connected){ - - var marker; - var opts = { - markerColor: this.markerColor, - lineColor: this.markerColor - }; - - if(typeof connected == "boolean" && connected){ - marker = new Marker(lat, lon, text, 1.2, this.markers[this.markers.length-1], this.scene, opts); - } else if(typeof connected == "object"){ - marker = new Marker(lat, lon, text, 1.2, connected, this.scene, opts); - } else { - marker = new Marker(lat, lon, text, 1.2, null, this.scene, opts); - } - - this.markers.push(marker); - - if(this.markers.length > this.maxMarkers){ - this.markers.shift().remove(); - } - - return marker; -} - -Globe.prototype.addSatellite = function(lat, lon, altitude, opts, texture, animator){ - /* texture and animator are optimizations so we don't have to regenerate certain - * redundant assets */ - - if(!opts){ - opts = {}; - } - - if(opts.coreColor == undefined){ - opts.coreColor = this.satelliteColor; - } - - var satellite = new Satellite(lat, lon, altitude, this.scene, opts, texture, animator); - - if(!this.satellites[satellite.toString()]){ - this.satellites[satellite.toString()] = satellite; - } - - satellite.onRemove(function(){ - delete this.satellites[satellite.toString()]; - }.bind(this)); - - return satellite; - -}; - -Globe.prototype.addConstellation = function(sats, opts){ - - /* TODO: make it so that when you remove the first in a constellation it removes all others */ - - var texture, - animator, - satellite, - constellation = []; - - for(var i = 0; i< sats.length; i++){ - if(i === 0){ - satellite = this.addSatellite(sats[i].lat, sats[i].lon, sats[i].altitude, opts); + let _sourceId = 0; + class Source { + /** + * Constructs a new video texture. + * + * @param {any} [data=null] - The data definition of a texture. + */ + constructor(data = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId++ }); + this.uuid = generateUUID(); + this.data = data; + this.dataReady = true; + this.version = 0; + } + /** + * Returns the dimensions of the source into the given target vector. + * + * @param {(Vector2|Vector3)} target - The target object the result is written into. + * @return {(Vector2|Vector3)} The dimensions of the source. + */ + getSize(target) { + const data = this.data; + if (typeof HTMLVideoElement !== "undefined" && data instanceof HTMLVideoElement) { + target.set(data.videoWidth, data.videoHeight, 0); + } else if (typeof VideoFrame !== "undefined" && data instanceof VideoFrame) { + target.set(data.displayWidth, data.displayHeight, 0); + } else if (data !== null) { + target.set(data.width, data.height, data.depth || 0); } else { - satellite = this.addSatellite(sats[i].lat, sats[i].lon, sats[i].altitude, opts, constellation[0].canvas, constellation[0].texture); + target.set(0, 0, 0); } - constellation.push(satellite); - - } - - return constellation; - -}; - - -Globe.prototype.setMaxPins = function(_maxPins){ - this.maxPins = _maxPins; - - while(this.pins.length > this.maxPins){ - var oldPin = this.pins.shift(); - this.quadtree.removeObject(oldPin); - oldPin.remove(); - } -}; - -Globe.prototype.setMaxMarkers = function(_maxMarkers){ - this.maxMarkers = _maxMarkers; - while(this.markers.length > this.maxMarkers){ - this.markers.shift().remove(); - } -}; - -Globe.prototype.setBaseColor = function(_color){ - this.baseColor = _color; - createParticles.call(this); -}; - -Globe.prototype.setMarkerColor = function(_color){ - this.markerColor = _color; - this.scene._encom_markerTexture = null; - -}; - -Globe.prototype.setPinColor = function(_color){ - this.pinColor = _color; -}; - -Globe.prototype.setScale = function(_scale){ - this.scale = _scale; - this.cameraDistance = 1700/_scale; - if(this.scene && this.scene.fog){ - this.scene.fog.near = this.cameraDistance; - this.scene.fog.far = this.cameraDistance + 300; - createParticles.call(this); - this.camera.far = this.cameraDistance + 300; - this.camera.updateProjectionMatrix(); - } -}; - -Globe.prototype.tick = function(){ - - if(!this.camera){ - return; - } - - if(!this.firstRunTime){ - this.firstRunTime = Date.now(); - } - addInitialData.call(this); - TWEEN.update(); - - if(!this.lastRenderDate){ - this.lastRenderDate = new Date(); - } - - if(!this.firstRenderDate){ - this.firstRenderDate = new Date(); - } - - this.totalRunTime = new Date() - this.firstRenderDate; - - var renderTime = new Date() - this.lastRenderDate; - this.lastRenderDate = new Date(); - var rotateCameraBy = (2 * Math.PI)/(this.dayLength/renderTime); - - this.cameraAngle += rotateCameraBy; - - if(!this.active){ - this.cameraDistance += (1000 * renderTime/1000); - } - - - this.camera.position.x = this.cameraDistance * Math.cos(this.cameraAngle) * Math.cos(this.viewAngle); - this.camera.position.y = Math.sin(this.viewAngle) * this.cameraDistance; - this.camera.position.z = this.cameraDistance * Math.sin(this.cameraAngle) * Math.cos(this.viewAngle); - - - for(var i in this.satellites){ - this.satellites[i].tick(this.camera.position, this.cameraAngle, renderTime); - } - - for(var i = 0; i< this.satelliteMeshes.length; i++){ - var mesh = this.satelliteMeshes[i]; - mesh.lookAt(this.camera.position); - mesh.rotateZ(mesh.tiltDirection * Math.PI/2); - mesh.rotateZ(Math.sin(this.cameraAngle + (mesh.lon / 180) * Math.PI) * mesh.tiltMultiplier * mesh.tiltDirection * -1); - + return target; + } + /** + * When the property is set to `true`, the engine allocates the memory + * for the texture (if necessary) and triggers the actual texture upload + * to the GPU next time the source is used. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) this.version++; + } + /** + * Serializes the source into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized source. + * @see {@link ObjectLoader#parse} + */ + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (!isRootObject && meta.images[this.uuid] !== void 0) { + return meta.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data = this.data; + if (data !== null) { + let url; + if (Array.isArray(data)) { + url = []; + for (let i = 0, l = data.length; i < l; i++) { + if (data[i].isDataTexture) { + url.push(serializeImage(data[i].image)); + } else { + url.push(serializeImage(data[i])); + } + } + } else { + url = serializeImage(data); + } + output.url = url; + } + if (!isRootObject) { + meta.images[this.uuid] = output; + } + return output; + } } - - if(this.introLinesDuration > this.totalRunTime){ - if(this.totalRunTime/this.introLinesDuration < .1){ - this.introLines.children[0].material.opacity = (this.totalRunTime/this.introLinesDuration) * (1 / .1) - .2; - }if(this.totalRunTime/this.introLinesDuration > .8){ - this.introLines.children[0].material.opacity = Math.max(1-this.totalRunTime/this.introLinesDuration,0) * (1 / .2); + function serializeImage(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; } else { - this.introLines.children[0].material.opacity = 1; + warn("Texture: Unable to serialize Texture."); + return {}; } - this.introLines.rotateY((2 * Math.PI)/(this.introLinesDuration/renderTime)); - } else if(this.introLines){ - this.scene.remove(this.introLines); - delete[this.introLines]; - } - - // do the shaders - - this.pointUniforms.currentTime.value = this.totalRunTime; - - this.smokeProvider.tick(this.totalRunTime); - - this.camera.lookAt( this.scene.position ); - this.renderer.render( this.scene, this.camera ); - -} - -module.exports = Globe; - - -},{"./Marker":16,"./Pin":17,"./Satellite":18,"./SmokeProvider":19,"./utils":21,"hexasphere.js":3,"pusher.color":6,"quadtree2":8,"three":12,"tween.js":13,"vec2":14}],16:[function(require,module,exports){ -var THREE = require('three'), - TWEEN = require('tween.js'), - utils = require('./utils'); - -var createMarkerTexture = function(markerColor) { - var markerWidth = 30, - markerHeight = 30, - canvas, - texture; - - canvas = utils.renderToCanvas(markerWidth, markerHeight, function(ctx){ - ctx.fillStyle=markerColor; - ctx.strokeStyle=markerColor; - ctx.lineWidth=3; - ctx.beginPath(); - ctx.arc(markerWidth/2, markerHeight/2, markerWidth/3, 0, 2* Math.PI); - ctx.stroke(); - - ctx.beginPath(); - ctx.arc(markerWidth/2, markerHeight/2, markerWidth/5, 0, 2* Math.PI); - ctx.fill(); - - }); - - texture = new THREE.Texture(canvas); - texture.needsUpdate = true; - - return texture; - -}; - -var Marker = function(lat, lon, text, altitude, previous, scene, _opts){ - - /* options that can be passed in */ - var opts = { - lineColor: "#FFCC00", - lineWidth: 1, - markerColor: "#FFCC00", - labelColor: "#FFF", - font: "Inconsolata", - fontSize: 20, - drawTime: 2000, - lineSegments: 150 - } - - var point, - previousPoint, - markerMaterial, - labelCanvas, - labelTexture, - labelMaterial - ; - - - this.lat = parseFloat(lat); - this.lon = parseFloat(lon); - this.text = text; - this.altitude = parseFloat(altitude); - this.scene = scene; - this.previous = previous; - this.next = []; - - if(this.previous){ - this.previous.next.push(this); + } } - - if(_opts){ - for(var i in opts){ - if(_opts[i] != undefined){ - opts[i] = _opts[i]; - } + let _textureId = 0; + const _tempVec3 = /* @__PURE__ */ new Vector3(); + class Texture extends EventDispatcher { + /** + * Constructs a new texture. + * + * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space. + */ + constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.source = new Source(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector2(0, 0); + this.repeat = new Vector2(1, 1); + this.center = new Vector2(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + this.colorSpace = colorSpace; + this.userData = {}; + this.updateRanges = []; + this.version = 0; + this.onUpdate = null; + this.renderTarget = null; + this.isRenderTargetTexture = false; + this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false; + this.pmremVersion = 0; + this.normalized = false; + } + /** + * The width of the texture in pixels. + */ + get width() { + return this.source.getSize(_tempVec3).x; + } + /** + * The height of the texture in pixels. + */ + get height() { + return this.source.getSize(_tempVec3).y; + } + /** + * The depth of the texture in pixels. + */ + get depth() { + return this.source.getSize(_tempVec3).z; + } + /** + * The image object holding the texture data. + * + * @type {?Object} + */ + get image() { + return this.source.data; + } + set image(value) { + this.source.data = value; + } + /** + * Updates the texture transformation matrix from the properties {@link Texture#offset}, + * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}. + */ + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + /** + * Adds a range of data in the data texture to be updated on the GPU. + * + * @param {number} start - Position at which to start update. + * @param {number} count - The number of components to update. + */ + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + /** + * Clears the update ranges. + */ + clearUpdateRanges() { + this.updateRanges.length = 0; + } + /** + * Returns a new texture with copied values from this instance. + * + * @return {Texture} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given texture to this instance. + * + * @param {Texture} source - The texture to copy. + * @return {Texture} A reference to this instance. + */ + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.normalized = source.normalized; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.isArrayTexture = source.isArrayTexture; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + /** + * Sets this texture's properties based on `values`. + * @param {Object} values - A container with texture parameters. + */ + setValues(values) { + for (const key in values) { + const newValue = values[key]; + if (newValue === void 0) { + warn(`Texture.setValues(): parameter '${key}' has value of undefined.`); + continue; + } + const currentValue = this[key]; + if (currentValue === void 0) { + warn(`Texture.setValues(): property '${key}' does not exist.`); + continue; + } + if (currentValue && newValue && (currentValue.isVector2 && newValue.isVector2)) { + currentValue.copy(newValue); + } else if (currentValue && newValue && (currentValue.isVector3 && newValue.isVector3)) { + currentValue.copy(newValue); + } else if (currentValue && newValue && (currentValue.isMatrix3 && newValue.isMatrix3)) { + currentValue.copy(newValue); + } else { + this[key] = newValue; + } } + } + /** + * Serializes the texture into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized texture. + * @see {@link ObjectLoader#parse} + */ + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (!isRootObject && meta.textures[this.uuid] !== void 0) { + return meta.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.7, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta).uuid, + mapping: this.mapping, + channel: this.channel, + 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, + internalFormat: this.internalFormat, + type: this.type, + normalized: this.normalized, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) output.userData = this.userData; + if (!isRootObject) { + meta.textures[this.uuid] = output; + } + return output; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires Texture#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + /** + * Transforms the given uv vector with the textures uv transformation matrix. + * + * @param {Vector2} uv - The uv vector. + * @return {Vector2} The transformed uv vector. + */ + transformUv(uv) { + if (this.mapping !== UVMapping) return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + /** + * Setting this property to `true` indicates the engine the texture + * must be updated in the next render. This triggers a texture upload + * to the GPU and ensures correct texture parameter configuration. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) { + this.version++; + this.source.needsUpdate = true; + } + } + /** + * Setting this property to `true` indicates the engine the PMREM + * must be regenerated. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsPMREMUpdate(value) { + if (value === true) { + this.pmremVersion++; + } + } } - - this.opts = opts; - - - point = utils.mapPoint(lat, lon); - - if(previous){ - previousPoint = utils.mapPoint(previous.lat, previous.lon); - } - - if(!scene._encom_markerTexture){ - scene._encom_markerTexture = createMarkerTexture(this.opts.markerColor); - } - - markerMaterial = new THREE.SpriteMaterial({map: scene._encom_markerTexture, opacity: .7, depthTest: true, fog: true}); - this.marker = new THREE.Sprite(markerMaterial); - - this.marker.scale.set(0, 0); - this.marker.position.set(point.x * altitude, point.y * altitude, point.z * altitude); - - labelCanvas = utils.createLabel(text.toUpperCase(), this.opts.fontSize, this.opts.labelColor, this.opts.font, this.opts.markerColor); - labelTexture = new THREE.Texture(labelCanvas); - labelTexture.needsUpdate = true; - - labelMaterial = new THREE.SpriteMaterial({ - map : labelTexture, - useScreenCoordinates: false, - opacity: 0, - depthTest: true, - fog: true - }); - - this.labelSprite = new THREE.Sprite(labelMaterial); - this.labelSprite.position = {x: point.x * altitude * 1.1, y: point.y*altitude*1.05 + (point.y < 0 ? -15 : 30), z: point.z * altitude * 1.1}; - this.labelSprite.scale.set(labelCanvas.width, labelCanvas.height); - - new TWEEN.Tween( {opacity: 0}) - .to( {opacity: 1}, 500 ) - .onUpdate(function(){ - labelMaterial.opacity = this.opacity - }).start(); - - - var _this = this; //arrghghh - - new TWEEN.Tween({x: 0, y: 0}) - .to({x: 50, y: 50}, 2000) - .easing( TWEEN.Easing.Elastic.Out ) - .onUpdate(function(){ - _this.marker.scale.set(this.x, this.y); - }) - .delay((this.previous ? _this.opts.drawTime : 0)) - .start(); - - if(this.previous){ - - var materialSpline, - materialSplineDotted, - latdist, - londist, - startPoint, - pointList = [], - pointList2 = [], - nextlat, - nextlon, - currentLat, - currentLon, - currentPoint, - currentVert, - update; - - _this.geometrySpline = new THREE.Geometry(); - materialSpline = new THREE.LineBasicMaterial({ - color: this.opts.lineColor, - transparent: true, - linewidth: 3, - opacity: .5 - }); - - _this.geometrySplineDotted = new THREE.Geometry(); - materialSplineDotted = new THREE.LineBasicMaterial({ - color: this.opts.lineColor, - linewidth: 1, - transparent: true, - opacity: .5 - }); - - latdist = (lat - previous.lat)/_this.opts.lineSegments; - londist = (lon - previous.lon)/_this.opts.lineSegments; - startPoint = utils.mapPoint(previous.lat,previous.lon); - pointList = []; - pointList2 = []; - - for(var j = 0; j< _this.opts.lineSegments + 1; j++){ - // var nextlat = ((90 + lat1 + j*1)%180)-90; - // var nextlon = ((180 + lng1 + j*1)%360)-180; - - - var nextlat = (((90 + previous.lat + j*latdist)%180)-90) * (.5 + Math.cos(j*(5*Math.PI/2)/_this.opts.lineSegments)/2) + (j*lat/_this.opts.lineSegments/2); - var nextlon = ((180 + previous.lon + j*londist)%360)-180; - pointList.push({lat: nextlat, lon: nextlon, index: j}); - if(j == 0 || j == _this.opts.lineSegments){ - pointList2.push({lat: nextlat, lon: nextlon, index: j}); + Texture.DEFAULT_IMAGE = null; + Texture.DEFAULT_MAPPING = UVMapping; + Texture.DEFAULT_ANISOTROPY = 1; + const _Vector4 = class _Vector4 { + /** + * Constructs a new 4D vector. + * + * @param {number} [x=0] - The x value of this vector. + * @param {number} [y=0] - The y value of this vector. + * @param {number} [z=0] - The z value of this vector. + * @param {number} [w=1] - The w value of this vector. + */ + constructor(x = 0, y = 0, z = 0, w = 1) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + /** + * Alias for {@link Vector4#z}. + * + * @type {number} + */ + get width() { + return this.z; + } + set width(value) { + this.z = value; + } + /** + * Alias for {@link Vector4#w}. + * + * @type {number} + */ + get height() { + return this.w; + } + set height(value) { + this.w = value; + } + /** + * Sets the vector components. + * + * @param {number} x - The value of the x component. + * @param {number} y - The value of the y component. + * @param {number} z - The value of the z component. + * @param {number} w - The value of the w component. + * @return {Vector4} A reference to this vector. + */ + set(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + /** + * Sets the vector components to the same value. + * + * @param {number} scalar - The value to set for all vector components. + * @return {Vector4} A reference to this vector. + */ + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + /** + * Sets the vector's x component to the given value + * + * @param {number} x - The value to set. + * @return {Vector4} A reference to this vector. + */ + setX(x) { + this.x = x; + return this; + } + /** + * Sets the vector's y component to the given value + * + * @param {number} y - The value to set. + * @return {Vector4} A reference to this vector. + */ + setY(y) { + this.y = y; + return this; + } + /** + * Sets the vector's z component to the given value + * + * @param {number} z - The value to set. + * @return {Vector4} A reference to this vector. + */ + setZ(z) { + this.z = z; + return this; + } + /** + * Sets the vector's w component to the given value + * + * @param {number} w - The value to set. + * @return {Vector4} A reference to this vector. + */ + setW(w) { + this.w = w; + return this; + } + /** + * Allows to set a vector component with an index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, + * `2` equals to z, `3` equals to w. + * @param {number} value - The value to set. + * @return {Vector4} A reference to this vector. + */ + setComponent(index, value) { + switch (index) { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + case 2: + this.z = value; + break; + case 3: + this.w = value; + break; + default: + throw new Error("index is out of range: " + index); + } + return this; + } + /** + * Returns the value of the vector component which matches the given index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, + * `2` equals to z, `3` equals to w. + * @return {number} A vector component value. + */ + getComponent(index) { + switch (index) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index); + } + } + /** + * Returns a new vector with copied values from this instance. + * + * @return {Vector4} A clone of this instance. + */ + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + /** + * Copies the values of the given vector to this instance. + * + * @param {Vector3|Vector4} v - The vector to copy. + * @return {Vector4} A reference to this vector. + */ + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = v.w !== void 0 ? v.w : 1; + return this; + } + /** + * Adds the given vector to this instance. + * + * @param {Vector4} v - The vector to add. + * @return {Vector4} A reference to this vector. + */ + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + return this; + } + /** + * Adds the given scalar value to all components of this instance. + * + * @param {number} s - The scalar to add. + * @return {Vector4} A reference to this vector. + */ + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; + return this; + } + /** + * Adds the given vectors and stores the result in this instance. + * + * @param {Vector4} a - The first vector. + * @param {Vector4} b - The second vector. + * @return {Vector4} A reference to this vector. + */ + addVectors(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; + } + /** + * Adds the given vector scaled by the given factor to this instance. + * + * @param {Vector4} v - The vector. + * @param {number} s - The factor that scales `v`. + * @return {Vector4} A reference to this vector. + */ + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + return this; + } + /** + * Subtracts the given vector from this instance. + * + * @param {Vector4} v - The vector to subtract. + * @return {Vector4} A reference to this vector. + */ + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + return this; + } + /** + * Subtracts the given scalar value from all components of this instance. + * + * @param {number} s - The scalar to subtract. + * @return {Vector4} A reference to this vector. + */ + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + return this; + } + /** + * Subtracts the given vectors and stores the result in this instance. + * + * @param {Vector4} a - The first vector. + * @param {Vector4} b - The second vector. + * @return {Vector4} A reference to this vector. + */ + subVectors(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; + } + /** + * Multiplies the given vector with this instance. + * + * @param {Vector4} v - The vector to multiply. + * @return {Vector4} A reference to this vector. + */ + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + return this; + } + /** + * Multiplies the given scalar value with all components of this instance. + * + * @param {number} scalar - The scalar to multiply. + * @return {Vector4} A reference to this vector. + */ + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + /** + * Multiplies this vector with the given 4x4 matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector4} A reference to this vector. + */ + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; + this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; + this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; + this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; + return this; + } + /** + * Divides this instance by the given vector. + * + * @param {Vector4} v - The vector to divide. + * @return {Vector4} A reference to this vector. + */ + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + this.w /= v.w; + return this; + } + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector4} A reference to this vector. + */ + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + /** + * Sets the x, y and z components of this + * vector to the quaternion's axis and w to the angle. + * + * @param {Quaternion} q - The Quaternion to set. + * @return {Vector4} A reference to this vector. + */ + setAxisAngleFromQuaternion(q) { + this.w = 2 * Math.acos(q.w); + const s = Math.sqrt(1 - q.w * q.w); + if (s < 1e-4) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + } + return this; + } + /** + * Sets the x, y and z components of this + * vector to the axis of rotation and w to the angle. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix. + * @return {Vector4} A reference to this vector. + */ + setAxisAngleFromRotationMatrix(m) { + let angle, x, y, z; + const epsilon = 0.01, epsilon2 = 0.1, te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy && xx > zz) { + if (xx < epsilon) { + x = 0; + y = 0.707106781; + z = 0.707106781; } else { - pointList2.push({lat: nextlat+1, lon: nextlon, index: j}); + x = Math.sqrt(xx); + y = xy / x; + z = xz / x; } - // var thisPoint = mapPoint(nextlat, nextlon); - sPoint = new THREE.Vector3(startPoint.x*1.2, startPoint.y*1.2, startPoint.z*1.2); - sPoint2 = new THREE.Vector3(startPoint.x*1.2, startPoint.y*1.2, startPoint.z*1.2); - // sPoint = new THREE.Vector3(thisPoint.x*1.2, thisPoint.y*1.2, thisPoint.z*1.2); - - sPoint.globe_index = j; - sPoint2.globe_index = j; - - _this.geometrySpline.vertices.push(sPoint); - _this.geometrySplineDotted.vertices.push(sPoint2); - } - - - currentLat = previous.lat; - currentLon = previous.lon; - currentPoint; - currentVert; - - update = function(){ - var nextSpot = pointList.shift(); - var nextSpot2 = pointList2.shift(); - - for(var x = 0; x< _this.geometrySpline.vertices.length; x++){ - - currentVert = _this.geometrySpline.vertices[x]; - currentPoint = utils.mapPoint(nextSpot.lat, nextSpot.lon); - - currentVert2 = _this.geometrySplineDotted.vertices[x]; - currentPoint2 = utils.mapPoint(nextSpot2.lat, nextSpot2.lon); - - if(x >= nextSpot.index){ - currentVert.set(currentPoint.x*1.2, currentPoint.y*1.2, currentPoint.z*1.2); - currentVert2.set(currentPoint2.x*1.19, currentPoint2.y*1.19, currentPoint2.z*1.19); - } - _this.geometrySpline.verticesNeedUpdate = true; - _this.geometrySplineDotted.verticesNeedUpdate = true; + } else if (yy > zz) { + if (yy < epsilon) { + x = 0.707106781; + y = 0; + z = 0.707106781; + } else { + y = Math.sqrt(yy); + x = xy / y; + z = yz / y; } - if(pointList.length > 0){ - setTimeout(update,_this.opts.drawTime/_this.opts.lineSegments); + } else { + if (zz < epsilon) { + x = 0.707106781; + y = 0.707106781; + z = 0; + } else { + z = Math.sqrt(zz); + x = xz / z; + y = yz / z; } - - }; - - update(); - - this.scene.add(new THREE.Line(_this.geometrySpline, materialSpline)); - this.scene.add(new THREE.Line(_this.geometrySplineDotted, materialSplineDotted, THREE.LinePieces)); - } - - this.scene.add(this.marker); - this.scene.add(this.labelSprite); - -}; - -Marker.prototype.remove = function(){ - var x = 0; - var _this = this; - - var update = function(ref){ - - for(var i = 0; i< x; i++){ - ref.geometrySpline.vertices[i].set(ref.geometrySpline.vertices[i+1]); - ref.geometrySplineDotted.vertices[i].set(ref.geometrySplineDotted.vertices[i+1]); - ref.geometrySpline.verticesNeedUpdate = true; - ref.geometrySplineDotted.verticesNeedUpdate = true; + } + this.set(x, y, z, angle); + return this; } - - x++; - if(x < ref.geometrySpline.vertices.length){ - setTimeout(function(){update(ref)}, _this.opts.drawTime/_this.opts.lineSegments) - } else { - _this.scene.remove(ref.geometrySpline); - _this.scene.remove(ref.geometrySplineDotted); + let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s) < 1e-3) s = 1; + this.x = (m32 - m23) / s; + this.y = (m13 - m31) / s; + this.z = (m21 - m12) / s; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + /** + * Sets the vector components to the position elements of the + * given transformation matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector4} A reference to this vector. + */ + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + this.w = e[15]; + return this; + } + /** + * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w + * value, replace that value with the corresponding min value. + * + * @param {Vector4} v - The vector. + * @return {Vector4} A reference to this vector. + */ + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + this.w = Math.min(this.w, v.w); + return this; + } + /** + * If this vector's x, y, z or w value is less than the given vector's x, y, z or w + * value, replace that value with the corresponding max value. + * + * @param {Vector4} v - The vector. + * @return {Vector4} A reference to this vector. + */ + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + this.w = Math.max(this.w, v.w); + return this; + } + /** + * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w + * value, it is replaced by the corresponding value. + * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value, + * it is replaced by the corresponding value. + * + * @param {Vector4} min - The minimum x, y and z values. + * @param {Vector4} max - The maximum x, y and z values in the desired range. + * @return {Vector4} A reference to this vector. + */ + clamp(min, max) { + this.x = clamp(this.x, min.x, max.x); + this.y = clamp(this.y, min.y, max.y); + this.z = clamp(this.z, min.z, max.z); + this.w = clamp(this.w, min.w, max.w); + return this; + } + /** + * If this vector's x, y, z or w values are greater than the max value, they are + * replaced by the max value. + * If this vector's x, y, z or w values are less than the min value, they are + * replaced by the min value. + * + * @param {number} minVal - The minimum value the components will be clamped to. + * @param {number} maxVal - The maximum value the components will be clamped to. + * @return {Vector4} A reference to this vector. + */ + clampScalar(minVal, maxVal) { + this.x = clamp(this.x, minVal, maxVal); + this.y = clamp(this.y, minVal, maxVal); + this.z = clamp(this.z, minVal, maxVal); + this.w = clamp(this.w, minVal, maxVal); + return this; + } + /** + * If this vector's length is greater than the max value, it is replaced by + * the max value. + * If this vector's length is less than the min value, it is replaced by the + * min value. + * + * @param {number} min - The minimum value the vector length will be clamped to. + * @param {number} max - The maximum value the vector length will be clamped to. + * @return {Vector4} A reference to this vector. + */ + clampLength(min, max) { + const length = this.length(); + return this.divideScalar(length || 1).multiplyScalar(clamp(length, min, max)); + } + /** + * The components of this vector are rounded down to the nearest integer value. + * + * @return {Vector4} A reference to this vector. + */ + floor() { + 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; + } + /** + * The components of this vector are rounded up to the nearest integer value. + * + * @return {Vector4} A reference to this vector. + */ + ceil() { + 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; + } + /** + * The components of this vector are rounded to the nearest integer value + * + * @return {Vector4} A reference to this vector. + */ + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + /** + * The components of this vector are rounded towards zero (up if negative, + * down if positive) to an integer value. + * + * @return {Vector4} A reference to this vector. + */ + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + /** + * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w. + * + * @return {Vector4} A reference to this vector. + */ + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + /** + * Calculates the dot product of the given vector with this instance. + * + * @param {Vector4} v - The vector to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + /** + * Computes the square of the Euclidean length (straight-line length) from + * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should + * compare the length squared instead as it is slightly more efficient to calculate. + * + * @return {number} The square length of this vector. + */ + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + /** + * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w). + * + * @return {number} The length of this vector. + */ + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + /** + * Computes the Manhattan length of this vector. + * + * @return {number} The length of this vector. + */ + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + /** + * Converts this vector to a unit vector - that is, sets it equal to a vector + * with the same direction as this one, but with a vector length of `1`. + * + * @return {Vector4} A reference to this vector. + */ + normalize() { + return this.divideScalar(this.length() || 1); + } + /** + * Sets this vector to a vector with the same direction as this one, but + * with the specified length. + * + * @param {number} length - The new length of this vector. + * @return {Vector4} A reference to this vector. + */ + setLength(length) { + return this.normalize().multiplyScalar(length); + } + /** + * Linearly interpolates between the given vector and this instance, where + * alpha is the percent distance along the line - alpha = 0 will be this + * vector, and alpha = 1 will be the given one. + * + * @param {Vector4} v - The vector to interpolate towards. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector4} A reference to this vector. + */ + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + this.w += (v.w - this.w) * alpha; + return this; + } + /** + * Linearly interpolates between the given vectors, where alpha is the percent + * distance along the line - alpha = 0 will be first vector, and alpha = 1 will + * be the second one. The result is stored in this instance. + * + * @param {Vector4} v1 - The first vector. + * @param {Vector4} v2 - The second vector. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector4} A reference to this vector. + */ + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + this.w = v1.w + (v2.w - v1.w) * alpha; + return this; + } + /** + * Returns `true` if this vector is equal with the given one. + * + * @param {Vector4} v - The vector to test for equality. + * @return {boolean} Whether this vector is equal with the given one. + */ + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + } + /** + * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`, + * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`. + * + * @param {Array} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector4} A reference to this vector. + */ + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector4} A reference to this vector. + */ + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + this.z = attribute.getZ(index); + this.w = attribute.getW(index); + return this; + } + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector4} A reference to this vector. + */ + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } + }; + _Vector4.prototype.isVector4 = true; + let Vector4 = _Vector4; + class RenderTarget extends EventDispatcher { + /** + * Render target options. + * + * @typedef {Object} RenderTarget~Options + * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not. + * @property {number} [magFilter=LinearFilter] - The mag filter. + * @property {number} [minFilter=LinearFilter] - The min filter. + * @property {number} [format=RGBAFormat] - The texture format. + * @property {number} [type=UnsignedByteType] - The texture type. + * @property {?string} [internalFormat=null] - The texture's internal format. + * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode. + * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode. + * @property {number} [anisotropy=1] - The texture's anisotropy value. + * @property {string} [colorSpace=NoColorSpace] - The texture's color space. + * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not. + * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not. + * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not. + * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not. + * @property {?Texture} [depthTexture=null] - Reference to a depth texture. + * @property {number} [samples=0] - The MSAA samples count. + * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`. + * @property {number} [depth=1] - The texture depth. + * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering. + */ + /** + * Constructs a new render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(width = 1, height = 1, options = {}) { + super(); + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter, + depthBuffer: true, + stencilBuffer: false, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1, + depth: 1, + multiview: false + }, options); + this.isRenderTarget = true; + this.width = width; + this.height = height; + this.depth = options.depth; + this.scissor = new Vector4(0, 0, width, height); + this.scissorTest = false; + this.viewport = new Vector4(0, 0, width, height); + this.textures = []; + const image = { width, height, depth: options.depth }; + const texture = new Texture(image); + const count = options.count; + for (let i = 0; i < count; i++) { + this.textures[i] = texture.clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; } - } - - for(var j = 0; j< _this.next.length; j++){ - (function(k){ - update(_this.next[k]); - })(j); - } - - _this.scene.remove(_this.marker); - _this.scene.remove(_this.labelSprite); - -}; - -module.exports = Marker; - -},{"./utils":21,"three":12,"tween.js":13}],17:[function(require,module,exports){ -var THREE = require('three'), - TWEEN = require('tween.js'), - utils = require('./utils'); - - -var createTopCanvas = function(color) { - var markerWidth = 20, - markerHeight = 20; - - return utils.renderToCanvas(markerWidth, markerHeight, function(ctx){ - ctx.fillStyle=color; - ctx.beginPath(); - ctx.arc(markerWidth/2, markerHeight/2, markerWidth/4, 0, 2* Math.PI); - ctx.fill(); - }); - -}; - -var Pin = function(lat, lon, text, altitude, scene, smokeProvider, _opts){ - - /* options that can be passed in */ - var opts = { - lineColor: "#8FD8D8", - lineWidth: 1, - topColor: "#8FD8D8", - smokeColor: "#FFF", - labelColor: "#FFF", - font: "Inconsolata", - showLabel: (text.length > 0), - showTop: (text.length > 0), - showSmoke: (text.length > 0) - } - - var lineMaterial, - labelCanvas, - labelTexture, - labelMaterial, - topTexture, - topMaterial, - point, - line; - - this.lat = lat; - this.lon = lon; - this.text = text; - this.altitude = altitude; - this.scene = scene; - this.smokeProvider = smokeProvider; - this.dateCreated = Date.now(); - - if(_opts){ - for(var i in opts){ - if(_opts[i] != undefined){ - opts[i] = _opts[i]; + this._setTextureOptions(options); + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.resolveDepthBuffer = options.resolveDepthBuffer; + this.resolveStencilBuffer = options.resolveStencilBuffer; + this._depthTexture = null; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + this.multiview = options.multiview; + } + _setTextureOptions(options = {}) { + const values = { + minFilter: LinearFilter, + generateMipmaps: false, + flipY: false, + internalFormat: null + }; + if (options.mapping !== void 0) values.mapping = options.mapping; + if (options.wrapS !== void 0) values.wrapS = options.wrapS; + if (options.wrapT !== void 0) values.wrapT = options.wrapT; + if (options.wrapR !== void 0) values.wrapR = options.wrapR; + if (options.magFilter !== void 0) values.magFilter = options.magFilter; + if (options.minFilter !== void 0) values.minFilter = options.minFilter; + if (options.format !== void 0) values.format = options.format; + if (options.type !== void 0) values.type = options.type; + if (options.anisotropy !== void 0) values.anisotropy = options.anisotropy; + if (options.colorSpace !== void 0) values.colorSpace = options.colorSpace; + if (options.flipY !== void 0) values.flipY = options.flipY; + if (options.generateMipmaps !== void 0) values.generateMipmaps = options.generateMipmaps; + if (options.internalFormat !== void 0) values.internalFormat = options.internalFormat; + for (let i = 0; i < this.textures.length; i++) { + const texture = this.textures[i]; + texture.setValues(values); + } + } + /** + * The texture representing the default color attachment. + * + * @type {Texture} + */ + get texture() { + return this.textures[0]; + } + set texture(value) { + this.textures[0] = value; + } + set depthTexture(current) { + if (this._depthTexture !== null) this._depthTexture.renderTarget = null; + if (current !== null) current.renderTarget = this; + this._depthTexture = current; + } + /** + * Instead of saving the depth in a renderbuffer, a texture + * can be used instead which is useful for further processing + * e.g. in context of post-processing. + * + * @type {?DepthTexture} + * @default null + */ + get depthTexture() { + return this._depthTexture; + } + /** + * Sets the size of this render target. + * + * @param {number} width - The width. + * @param {number} height - The height. + * @param {number} [depth=1] - The depth. + */ + setSize(width, height, depth = 1) { + if (this.width !== width || this.height !== height || this.depth !== depth) { + this.width = width; + this.height = height; + this.depth = depth; + for (let i = 0, il = this.textures.length; i < il; i++) { + this.textures[i].image.width = width; + this.textures[i].image.height = height; + this.textures[i].image.depth = depth; + if (this.textures[i].isData3DTexture !== true) { + this.textures[i].isArrayTexture = this.textures[i].image.depth > 1; } + } + this.dispose(); } + this.viewport.set(0, 0, width, height); + this.scissor.set(0, 0, width, height); + } + /** + * Returns a new render target with copied values from this instance. + * + * @return {RenderTarget} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the settings of the given render target. This is a structural copy so + * no resources are shared between render targets after the copy. That includes + * all MRT textures and the depth texture. + * + * @param {RenderTarget} source - The render target to copy. + * @return {RenderTarget} A reference to this instance. + */ + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.textures.length = 0; + for (let i = 0, il = source.textures.length; i < il; i++) { + this.textures[i] = source.textures[i].clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + const image = Object.assign({}, source.textures[i].image); + this.textures[i].source = new Source(image); + } + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + this.multiview = source.multiview; + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires RenderTarget#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } } - - this.opts = opts; - - this.topVisible = opts.showTop; - this.smokeVisible = opts.showSmoke; - this.labelVisible = opts.showLabel; - - /* the line */ - - this.lineGeometry = new THREE.Geometry(); - lineMaterial = new THREE.LineBasicMaterial({ - color: opts.lineColor, - linewidth: opts.lineWidth - }); - - point = utils.mapPoint(lat,lon); - - this.lineGeometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)); - this.lineGeometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)); - this.line = new THREE.Line(this.lineGeometry, lineMaterial); - - /* the label */ - - labelCanvas = utils.createLabel(text, 18, opts.labelColor, opts.font); - labelTexture = new THREE.Texture(labelCanvas); - labelTexture.needsUpdate = true; - - labelMaterial = new THREE.SpriteMaterial({ - map : labelTexture, - useScreenCoordinates: false, - opacity:0, - depthTest: true, - fog: true - }); - - this.labelSprite = new THREE.Sprite(labelMaterial); - this.labelSprite.position = {x: point.x*altitude*1.1, y: point.y*altitude + (point.y < 0 ? -15 : 30), z: point.z*altitude*1.1}; - this.labelSprite.scale.set(labelCanvas.width, labelCanvas.height); - - /* the top */ - - topTexture = new THREE.Texture(createTopCanvas(opts.topColor)); - topTexture.needsUpdate = true; - topMaterial = new THREE.SpriteMaterial({map: topTexture, depthTest: true, fog: true, opacity: 0}); - this.topSprite = new THREE.Sprite(topMaterial); - this.topSprite.scale.set(20, 20); - this.topSprite.position.set(point.x * altitude, point.y * altitude, point.z * altitude); - - /* the smoke */ - if(this.smokeVisible){ - this.smokeId = smokeProvider.setFire(lat, lon, altitude); - } - - var _this = this; //arghhh - - /* intro animations */ - - if(opts.showTop || opts.showLabel){ - new TWEEN.Tween( {opacity: 0}) - .to( {opacity: 1}, 500 ) - .onUpdate(function(){ - if(_this.topVisible){ - topMaterial.opacity = this.opacity; - } else { - topMaterial.opacity = 0; - } - if(_this.labelVisible){ - labelMaterial.opacity = this.opacity; - } else { - labelMaterial.opacity = 0; - } - }).delay(1000) - .start(); - } - - - new TWEEN.Tween(point) - .to( {x: point.x*altitude, y: point.y*altitude, z: point.z*altitude}, 1500 ) - .easing( TWEEN.Easing.Elastic.Out ) - .onUpdate(function(){ - _this.lineGeometry.vertices[1].x = this.x; - _this.lineGeometry.vertices[1].y = this.y; - _this.lineGeometry.vertices[1].z = this.z; - _this.lineGeometry.verticesNeedUpdate = true; - }).start(); - - /* add to scene */ - - this.scene.add(this.labelSprite); - this.scene.add(this.line); - this.scene.add(this.topSprite); - -}; - -Pin.prototype.toString = function(){ - return "" + this.lat + "_" + this.lon; -} - -Pin.prototype.changeAltitude = function(altitude){ - var point = utils.mapPoint(this.lat, this.lon); - var _this = this; // arghhhh - - new TWEEN.Tween({altitude: this.altitude}) - .to( {altitude: altitude}, 1500 ) - .easing( TWEEN.Easing.Elastic.Out ) - .onUpdate(function(){ - if(_this.smokeVisible){ - _this.smokeProvider.changeAltitude(this.altitude, _this.smokeId); - } - if(_this.topVisible){ - _this.topSprite.position.set(point.x * this.altitude, point.y * this.altitude, point.z * this.altitude); - } - if(_this.labelVisible){ - _this.labelSprite.position = {x: point.x*this.altitude*1.1, y: point.y*this.altitude + (point.y < 0 ? -15 : 30), z: point.z*this.altitude*1.1}; - } - _this.lineGeometry.vertices[1].x = point.x * this.altitude; - _this.lineGeometry.vertices[1].y = point.y * this.altitude; - _this.lineGeometry.vertices[1].z = point.z * this.altitude; - _this.lineGeometry.verticesNeedUpdate = true; - - }) - .onComplete(function(){ - _this.altitude = altitude; - - }).start(); - -}; - -Pin.prototype.hideTop = function(){ - if(this.topVisible){ - this.topSprite.material.opacity = 0.0; - this.topVisible = false; - } -}; - -Pin.prototype.showTop = function(){ - if(!this.topVisible){ - this.topSprite.material.opacity = 1.0; - this.topVisible = true; + class WebGLRenderTarget extends RenderTarget { + /** + * Constructs a new 3D render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(width = 1, height = 1, options = {}) { + super(width, height, options); + this.isWebGLRenderTarget = true; + } } -}; - -Pin.prototype.hideLabel = function(){ - if(this.labelVisible){ - this.labelSprite.material.opacity = 0.0; - this.labelVisible = false; + class DataArrayTexture extends Texture { + /** + * Constructs a new data array texture. + * + * @param {?TypedArray} [data=null] - The buffer data. + * @param {number} [width=1] - The width of the texture. + * @param {number} [height=1] - The height of the texture. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor(data = null, width = 1, height = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data, width, height, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + this.layerUpdates = /* @__PURE__ */ new Set(); + } + /** + * Describes that a specific layer of the texture needs to be updated. + * Normally when {@link Texture#needsUpdate} is set to `true`, the + * entire data texture array is sent to the GPU. Marking specific + * layers will only transmit subsets of all mipmaps associated with a + * specific depth in the array which is often much more performant. + * + * @param {number} layerIndex - The layer index that should be updated. + */ + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + /** + * Resets the layer updates registry. + */ + clearLayerUpdates() { + this.layerUpdates.clear(); + } } -}; - -Pin.prototype.showLabel = function(){ - if(!this.labelVisible){ - this.labelSprite.material.opacity = 1.0; - this.labelVisible = true; + class WebGLArrayRenderTarget extends WebGLRenderTarget { + /** + * Constructs a new array render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {number} [depth=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(width = 1, height = 1, depth = 1, options = {}) { + super(width, height, options); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; + this.texture = new DataArrayTexture(null, width, height, depth); + this._setTextureOptions(options); + this.texture.isRenderTargetTexture = true; + } } -}; - -Pin.prototype.hideSmoke = function(){ - if(this.smokeVisible){ - this.smokeProvider.extinguish(this.smokeId); - this.smokeVisible = false; + class Data3DTexture extends Texture { + /** + * Constructs a new data array texture. + * + * @param {?TypedArray} [data=null] - The buffer data. + * @param {number} [width=1] - The width of the texture. + * @param {number} [height=1] - The height of the texture. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor(data = null, width = 1, height = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data, width, height, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } } -}; - -Pin.prototype.showSmoke = function(){ - if(!this.smokeVisible){ - this.smokeId = this.smokeProvider.setFire(this.lat, this.lon, this.altitude); - this.smokeVisible = true; + class WebGL3DRenderTarget extends WebGLRenderTarget { + /** + * Constructs a new 3D render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {number} [depth=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(width = 1, height = 1, depth = 1, options = {}) { + super(width, height, options); + this.isWebGL3DRenderTarget = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width, height, depth); + this._setTextureOptions(options); + this.texture.isRenderTargetTexture = true; + } } -}; - -Pin.prototype.age = function(){ - return Date.now() - this.dateCreated; - -}; - -Pin.prototype.remove = function(){ - this.scene.remove(this.labelSprite); - this.scene.remove(this.line); - this.scene.remove(this.topSprite); - - if(this.smokeVisible){ - this.smokeProvider.extinguish(this.smokeId); - } -}; - -module.exports = Pin; - - -},{"./utils":21,"three":12,"tween.js":13}],18:[function(require,module,exports){ -var TextureAnimator = require('./TextureAnimator'), - THREE = require('three'), - utils = require('./utils'); - - -var createCanvas = function(numFrames, pixels, rows, waveStart, numWaves, waveColor, coreColor, shieldColor) { - - var cols = numFrames / rows; - var waveInterval = Math.floor((numFrames-waveStart)/numWaves); - var waveDist = pixels - 25; // width - center of satellite - var distPerFrame = waveDist / (numFrames-waveStart) - var offsetx = 0; - var offsety = 0; - var curRow = 0; - - var waveColorRGB = utils.hexToRgb(waveColor); - - return utils.renderToCanvas(numFrames * pixels / rows, pixels * rows, function(ctx){ - - for(var i = 0; i< numFrames; i++){ - if(i - curRow * cols >= cols){ - offsetx = 0; - offsety += pixels; - curRow++; + const _Matrix4 = class _Matrix4 { + /** + * Constructs a new 4x4 matrix. The arguments are supposed to be + * in row-major order. If no arguments are provided, the constructor + * initializes the matrix as an identity matrix. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n14] - 1-4 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n24] - 2-4 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @param {number} [n34] - 3-4 matrix element. + * @param {number} [n41] - 4-1 matrix element. + * @param {number} [n42] - 4-2 matrix element. + * @param {number} [n43] - 4-3 matrix element. + * @param {number} [n44] - 4-4 matrix element. + */ + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== void 0) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + /** + * Sets the elements of the matrix.The arguments are supposed to be + * in row-major order. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n14] - 1-4 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n24] - 2-4 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @param {number} [n34] - 3-4 matrix element. + * @param {number} [n41] - 4-1 matrix element. + * @param {number} [n42] - 4-2 matrix element. + * @param {number} [n43] - 4-3 matrix element. + * @param {number} [n44] - 4-4 matrix element. + * @return {Matrix4} A reference to this matrix. + */ + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te = this.elements; + te[0] = n11; + te[4] = n12; + te[8] = n13; + te[12] = n14; + te[1] = n21; + te[5] = n22; + te[9] = n23; + te[13] = n24; + te[2] = n31; + te[6] = n32; + te[10] = n33; + te[14] = n34; + te[3] = n41; + te[7] = n42; + te[11] = n43; + te[15] = n44; + return this; + } + /** + * Sets this matrix to the 4x4 identity matrix. + * + * @return {Matrix4} A reference to this matrix. + */ + identity() { + this.set( + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Returns a matrix with copied values from this instance. + * + * @return {Matrix4} A clone of this instance. + */ + clone() { + return new _Matrix4().fromArray(this.elements); + } + /** + * Copies the values of the given matrix to this instance. + * + * @param {Matrix4} m - The matrix to copy. + * @return {Matrix4} A reference to this matrix. + */ + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + te[9] = me[9]; + te[10] = me[10]; + te[11] = me[11]; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + te[15] = me[15]; + return this; + } + /** + * Copies the translation component of the given matrix + * into this matrix's translation component. + * + * @param {Matrix4} m - The matrix to copy the translation component. + * @return {Matrix4} A reference to this matrix. + */ + copyPosition(m) { + const te = this.elements, me = m.elements; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + return this; + } + /** + * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix. + * + * @param {Matrix3} m - The 3x3 matrix. + * @return {Matrix4} A reference to this matrix. + */ + setFromMatrix3(m) { + const me = m.elements; + this.set( + me[0], + me[3], + me[6], + 0, + me[1], + me[4], + me[7], + 0, + me[2], + me[5], + me[8], + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Extracts the basis of this matrix into the three axis vectors provided. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix4} A reference to this matrix. + */ + extractBasis(xAxis, yAxis, zAxis) { + if (this.determinant() === 0) { + xAxis.set(1, 0, 0); + yAxis.set(0, 1, 0); + zAxis.set(0, 0, 1); + return this; + } + xAxis.setFromMatrixColumn(this, 0); + yAxis.setFromMatrixColumn(this, 1); + zAxis.setFromMatrixColumn(this, 2); + return this; + } + /** + * Sets the given basis vectors to this matrix. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeBasis(xAxis, yAxis, zAxis) { + this.set( + xAxis.x, + yAxis.x, + zAxis.x, + 0, + xAxis.y, + yAxis.y, + zAxis.y, + 0, + xAxis.z, + yAxis.z, + zAxis.z, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Extracts the rotation component of the given matrix + * into this matrix's rotation component. + * + * Note: This method does not support reflection matrices. + * + * @param {Matrix4} m - The matrix. + * @return {Matrix4} A reference to this matrix. + */ + extractRotation(m) { + if (m.determinant() === 0) { + return this.identity(); + } + const te = this.elements; + const me = m.elements; + const scaleX = 1 / _v1$7.setFromMatrixColumn(m, 0).length(); + const scaleY = 1 / _v1$7.setFromMatrixColumn(m, 1).length(); + const scaleZ = 1 / _v1$7.setFromMatrixColumn(m, 2).length(); + te[0] = me[0] * scaleX; + te[1] = me[1] * scaleX; + te[2] = me[2] * scaleX; + te[3] = 0; + te[4] = me[4] * scaleY; + te[5] = me[5] * scaleY; + te[6] = me[6] * scaleY; + te[7] = 0; + te[8] = me[8] * scaleZ; + te[9] = me[9] * scaleZ; + te[10] = me[10] * scaleZ; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + /** + * Sets the rotation component (the upper left 3x3 matrix) of this matrix to + * the rotation specified by the given Euler angles. The rest of + * the matrix is set to the identity. Depending on the {@link Euler#order}, + * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix) + * for a complete list. + * + * @param {Euler} euler - The Euler angles. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationFromEuler(euler) { + const te = this.elements; + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos(x), b = Math.sin(x); + const c = Math.cos(y), d = Math.sin(y); + const e = Math.cos(z), f = Math.sin(z); + if (euler.order === "XYZ") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = -c * f; + te[8] = d; + te[1] = af + be * d; + te[5] = ae - bf * d; + te[9] = -b * c; + te[2] = bf - ae * d; + te[6] = be + af * d; + te[10] = a * c; + } else if (euler.order === "YXZ") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce + df * b; + te[4] = de * b - cf; + te[8] = a * d; + te[1] = a * f; + te[5] = a * e; + te[9] = -b; + te[2] = cf * b - de; + te[6] = df + ce * b; + te[10] = a * c; + } else if (euler.order === "ZXY") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce - df * b; + te[4] = -a * f; + te[8] = de + cf * b; + te[1] = cf + de * b; + te[5] = a * e; + te[9] = df - ce * b; + te[2] = -a * d; + te[6] = b; + te[10] = a * c; + } else if (euler.order === "ZYX") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = be * d - af; + te[8] = ae * d + bf; + te[1] = c * f; + te[5] = bf * d + ae; + te[9] = af * d - be; + te[2] = -d; + te[6] = b * c; + te[10] = a * c; + } else if (euler.order === "YZX") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = bd - ac * f; + te[8] = bc * f + ad; + te[1] = f; + te[5] = a * e; + te[9] = -b * e; + te[2] = -d * e; + te[6] = ad * f + bc; + te[10] = ac - bd * f; + } else if (euler.order === "XZY") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = -f; + te[8] = d * e; + te[1] = ac * f + bd; + te[5] = a * e; + te[9] = ad * f - bc; + te[2] = bc * f - ad; + te[6] = b * e; + te[10] = bd * f + ac; + } + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + /** + * Sets the rotation component of this matrix to the rotation specified by + * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion) + * The rest of the matrix is set to the identity. + * + * @param {Quaternion} q - The Quaternion. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationFromQuaternion(q) { + return this.compose(_zero, q, _one); + } + /** + * Sets the rotation component of the transformation matrix, looking from `eye` towards + * `target`, and oriented by the up-direction. + * + * @param {Vector3} eye - The eye vector. + * @param {Vector3} target - The target vector. + * @param {Vector3} up - The up vector. + * @return {Matrix4} A reference to this matrix. + */ + lookAt(eye, target, up) { + const te = this.elements; + _z.subVectors(eye, target); + if (_z.lengthSq() === 0) { + _z.z = 1; + } + _z.normalize(); + _x.crossVectors(up, _z); + if (_x.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z.x += 1e-4; + } else { + _z.z += 1e-4; + } + _z.normalize(); + _x.crossVectors(up, _z); + } + _x.normalize(); + _y.crossVectors(_z, _x); + te[0] = _x.x; + te[4] = _y.x; + te[8] = _z.x; + te[1] = _x.y; + te[5] = _y.y; + te[9] = _z.y; + te[2] = _x.z; + te[6] = _y.z; + te[10] = _z.z; + return this; + } + /** + * Post-multiplies this matrix by the given 4x4 matrix. + * + * @param {Matrix4} m - The matrix to multiply with. + * @return {Matrix4} A reference to this matrix. + */ + multiply(m) { + return this.multiplyMatrices(this, m); + } + /** + * Pre-multiplies this matrix by the given 4x4 matrix. + * + * @param {Matrix4} m - The matrix to multiply with. + * @return {Matrix4} A reference to this matrix. + */ + premultiply(m) { + return this.multiplyMatrices(m, this); + } + /** + * Multiples the given 4x4 matrices and stores the result + * in this matrix. + * + * @param {Matrix4} a - The first matrix. + * @param {Matrix4} b - The second matrix. + * @return {Matrix4} A reference to this matrix. + */ + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; + const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; + const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; + const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + /** + * Multiplies every component of the matrix by the given scalar. + * + * @param {number} s - The scalar. + * @return {Matrix4} A reference to this matrix. + */ + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[4] *= s; + te[8] *= s; + te[12] *= s; + te[1] *= s; + te[5] *= s; + te[9] *= s; + te[13] *= s; + te[2] *= s; + te[6] *= s; + te[10] *= s; + te[14] *= s; + te[3] *= s; + te[7] *= s; + te[11] *= s; + te[15] *= s; + return this; + } + /** + * Computes and returns the determinant of this matrix. + * + * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html). + * + * @return {number} The determinant. + */ + determinant() { + const te = this.elements; + const n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; + const n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; + const n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; + const n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; + const t11 = n23 * n34 - n24 * n33; + const t12 = n22 * n34 - n24 * n32; + const t13 = n22 * n33 - n23 * n32; + const t21 = n21 * n34 - n24 * n31; + const t22 = n21 * n33 - n23 * n31; + const t23 = n21 * n32 - n22 * n31; + return n11 * (n42 * t11 - n43 * t12 + n44 * t13) - n12 * (n41 * t11 - n43 * t21 + n44 * t22) + n13 * (n41 * t12 - n42 * t21 + n44 * t23) - n14 * (n41 * t13 - n42 * t22 + n43 * t23); + } + /** + * Transposes this matrix in place. + * + * @return {Matrix4} A reference to this matrix. + */ + transpose() { + const te = this.elements; + let tmp3; + tmp3 = te[1]; + te[1] = te[4]; + te[4] = tmp3; + tmp3 = te[2]; + te[2] = te[8]; + te[8] = tmp3; + tmp3 = te[6]; + te[6] = te[9]; + te[9] = tmp3; + tmp3 = te[3]; + te[3] = te[12]; + te[12] = tmp3; + tmp3 = te[7]; + te[7] = te[13]; + te[13] = tmp3; + tmp3 = te[11]; + te[11] = te[14]; + te[14] = tmp3; + return this; + } + /** + * Sets the position component for this matrix from the given vector, + * without affecting the rest of the matrix. + * + * @param {number|Vector3} x - The x component of the vector or alternatively the vector object. + * @param {number} y - The y component of the vector. + * @param {number} z - The z component of the vector. + * @return {Matrix4} A reference to this matrix. + */ + setPosition(x, y, z) { + const te = this.elements; + if (x.isVector3) { + te[12] = x.x; + te[13] = x.y; + te[14] = x.z; + } else { + te[12] = x; + te[13] = y; + te[14] = z; + } + return this; + } + /** + * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution). + * You can not invert with a determinant of zero. If you attempt this, the method produces + * a zero matrix instead. + * + * @return {Matrix4} A reference to this matrix. + */ + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n41 = te[3], n12 = te[4], n22 = te[5], n32 = te[6], n42 = te[7], n13 = te[8], n23 = te[9], n33 = te[10], n43 = te[11], n14 = te[12], n24 = te[13], n34 = te[14], n44 = te[15], t1 = n11 * n22 - n21 * n12, t2 = n11 * n32 - n31 * n12, t3 = n11 * n42 - n41 * n12, t4 = n21 * n32 - n31 * n22, t5 = n21 * n42 - n41 * n22, t6 = n31 * n42 - n41 * n32, t7 = n13 * n24 - n23 * n14, t8 = n13 * n34 - n33 * n14, t9 = n13 * n44 - n43 * n14, t10 = n23 * n34 - n33 * n24, t11 = n23 * n44 - n43 * n24, t12 = n33 * n44 - n43 * n34; + const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7; + if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = (n22 * t12 - n32 * t11 + n42 * t10) * detInv; + te[1] = (n31 * t11 - n21 * t12 - n41 * t10) * detInv; + te[2] = (n24 * t6 - n34 * t5 + n44 * t4) * detInv; + te[3] = (n33 * t5 - n23 * t6 - n43 * t4) * detInv; + te[4] = (n32 * t9 - n12 * t12 - n42 * t8) * detInv; + te[5] = (n11 * t12 - n31 * t9 + n41 * t8) * detInv; + te[6] = (n34 * t3 - n14 * t6 - n44 * t2) * detInv; + te[7] = (n13 * t6 - n33 * t3 + n43 * t2) * detInv; + te[8] = (n12 * t11 - n22 * t9 + n42 * t7) * detInv; + te[9] = (n21 * t9 - n11 * t11 - n41 * t7) * detInv; + te[10] = (n14 * t5 - n24 * t3 + n44 * t1) * detInv; + te[11] = (n23 * t3 - n13 * t5 - n43 * t1) * detInv; + te[12] = (n22 * t8 - n12 * t10 - n32 * t7) * detInv; + te[13] = (n11 * t10 - n21 * t8 + n31 * t7) * detInv; + te[14] = (n24 * t2 - n14 * t4 - n34 * t1) * detInv; + te[15] = (n13 * t4 - n23 * t2 + n33 * t1) * detInv; + return this; + } + /** + * Multiplies the columns of this matrix by the given vector. + * + * @param {Vector3} v - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + scale(v) { + const te = this.elements; + const x = v.x, y = v.y, z = v.z; + te[0] *= x; + te[4] *= y; + te[8] *= z; + te[1] *= x; + te[5] *= y; + te[9] *= z; + te[2] *= x; + te[6] *= y; + te[10] *= z; + te[3] *= x; + te[7] *= y; + te[11] *= z; + return this; + } + /** + * Gets the maximum scale value of the three axes. + * + * @return {number} The maximum scale. + */ + getMaxScaleOnAxis() { + const te = this.elements; + const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; + const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; + const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + /** + * Sets this matrix as a translation transform from the given vector. + * + * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector. + * @param {number} y - The amount to translate in the Y axis. + * @param {number} z - The amount to translate in the z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeTranslation(x, y, z) { + if (x.isVector3) { + this.set( + 1, + 0, + 0, + x.x, + 0, + 1, + 0, + x.y, + 0, + 0, + 1, + x.z, + 0, + 0, + 0, + 1 + ); + } else { + this.set( + 1, + 0, + 0, + x, + 0, + 1, + 0, + y, + 0, + 0, + 1, + z, + 0, + 0, + 0, + 1 + ); + } + return this; + } + /** + * Sets this matrix as a rotational transformation around the X axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationX(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set( + 1, + 0, + 0, + 0, + 0, + c, + -s, + 0, + 0, + s, + c, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a rotational transformation around the Y axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationY(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set( + c, + 0, + s, + 0, + 0, + 1, + 0, + 0, + -s, + 0, + c, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a rotational transformation around the Z axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationZ(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set( + c, + -s, + 0, + 0, + s, + c, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a rotational transformation around the given axis by + * the given angle. + * + * This is a somewhat controversial but mathematically sound alternative to + * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199). + * + * @param {Vector3} axis - The normalized rotation axis. + * @param {number} angle - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationAxis(axis, angle) { + const c = Math.cos(angle); + const s = Math.sin(angle); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; + this.set( + tx * x + c, + tx * y - s * z, + tx * z + s * y, + 0, + tx * y + s * z, + ty * y + c, + ty * z - s * x, + 0, + tx * z - s * y, + ty * z + s * x, + t * z * z + c, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a scale transformation. + * + * @param {number} x - The amount to scale in the X axis. + * @param {number} y - The amount to scale in the Y axis. + * @param {number} z - The amount to scale in the Z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeScale(x, y, z) { + this.set( + x, + 0, + 0, + 0, + 0, + y, + 0, + 0, + 0, + 0, + z, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a shear transformation. + * + * @param {number} xy - The amount to shear X by Y. + * @param {number} xz - The amount to shear X by Z. + * @param {number} yx - The amount to shear Y by X. + * @param {number} yz - The amount to shear Y by Z. + * @param {number} zx - The amount to shear Z by X. + * @param {number} zy - The amount to shear Z by Y. + * @return {Matrix4} A reference to this matrix. + */ + makeShear(xy, xz, yx, yz, zx, zy) { + this.set( + 1, + yx, + zx, + 0, + xy, + 1, + zy, + 0, + xz, + yz, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix to the transformation composed of the given position, + * rotation (Quaternion) and scale. + * + * @param {Vector3} position - The position vector. + * @param {Quaternion} quaternion - The rotation as a Quaternion. + * @param {Vector3} scale - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + compose(position, quaternion, scale) { + const te = this.elements; + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + const sx = scale.x, sy = scale.y, sz = scale.z; + te[0] = (1 - (yy + zz)) * sx; + te[1] = (xy + wz) * sx; + te[2] = (xz - wy) * sx; + te[3] = 0; + te[4] = (xy - wz) * sy; + te[5] = (1 - (xx + zz)) * sy; + te[6] = (yz + wx) * sy; + te[7] = 0; + te[8] = (xz + wy) * sz; + te[9] = (yz - wx) * sz; + te[10] = (1 - (xx + yy)) * sz; + te[11] = 0; + te[12] = position.x; + te[13] = position.y; + te[14] = position.z; + te[15] = 1; + return this; + } + /** + * Decomposes this matrix into its position, rotation and scale components + * and provides the result in the given objects. + * + * Note: Not all matrices are decomposable in this way. For example, if an + * object has a non-uniformly scaled parent, then the object's world matrix + * may not be decomposable, and this method may not be appropriate. + * + * @param {Vector3} position - The position vector. + * @param {Quaternion} quaternion - The rotation as a Quaternion. + * @param {Vector3} scale - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + decompose(position, quaternion, scale) { + const te = this.elements; + position.x = te[12]; + position.y = te[13]; + position.z = te[14]; + const det = this.determinant(); + if (det === 0) { + scale.set(1, 1, 1); + quaternion.identity(); + return this; + } + let sx = _v1$7.set(te[0], te[1], te[2]).length(); + const sy = _v1$7.set(te[4], te[5], te[6]).length(); + const sz = _v1$7.set(te[8], te[9], te[10]).length(); + if (det < 0) sx = -sx; + _m1$4.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$4.elements[0] *= invSX; + _m1$4.elements[1] *= invSX; + _m1$4.elements[2] *= invSX; + _m1$4.elements[4] *= invSY; + _m1$4.elements[5] *= invSY; + _m1$4.elements[6] *= invSY; + _m1$4.elements[8] *= invSZ; + _m1$4.elements[9] *= invSZ; + _m1$4.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$4); + scale.x = sx; + scale.y = sy; + scale.z = sz; + return this; + } + /** + * Creates a perspective projection matrix. This is used internally by + * {@link PerspectiveCamera#updateProjectionMatrix}. + + * @param {number} left - Left boundary of the viewing frustum at the near plane. + * @param {number} right - Right boundary of the viewing frustum at the near plane. + * @param {number} top - Top boundary of the viewing frustum at the near plane. + * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. + * @param {number} near - The distance from the camera to the near plane. + * @param {number} far - The distance from the camera to the far plane. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Matrix4} A reference to this matrix. + */ + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false) { + const te = this.elements; + const x = 2 * near / (right - left); + const y = 2 * near / (top - bottom); + const a = (right + left) / (right - left); + const b = (top + bottom) / (top - bottom); + let c, d; + if (reversedDepth) { + c = near / (far - near); + d = far * near / (far - near); + } else { + if (coordinateSystem === WebGLCoordinateSystem) { + c = -(far + near) / (far - near); + d = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + c = -far / (far - near); + d = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + } + te[0] = x; + te[4] = 0; + te[8] = a; + te[12] = 0; + te[1] = 0; + te[5] = y; + te[9] = b; + te[13] = 0; + te[2] = 0; + te[6] = 0; + te[10] = c; + te[14] = d; + te[3] = 0; + te[7] = 0; + te[11] = -1; + te[15] = 0; + return this; + } + /** + * Creates a orthographic projection matrix. This is used internally by + * {@link OrthographicCamera#updateProjectionMatrix}. + + * @param {number} left - Left boundary of the viewing frustum at the near plane. + * @param {number} right - Right boundary of the viewing frustum at the near plane. + * @param {number} top - Top boundary of the viewing frustum at the near plane. + * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. + * @param {number} near - The distance from the camera to the near plane. + * @param {number} far - The distance from the camera to the far plane. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Matrix4} A reference to this matrix. + */ + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false) { + const te = this.elements; + const x = 2 / (right - left); + const y = 2 / (top - bottom); + const a = -(right + left) / (right - left); + const b = -(top + bottom) / (top - bottom); + let c, d; + if (reversedDepth) { + c = 1 / (far - near); + d = far / (far - near); + } else { + if (coordinateSystem === WebGLCoordinateSystem) { + c = -2 / (far - near); + d = -(far + near) / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + c = -1 / (far - near); + d = -near / (far - near); + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + } + te[0] = x; + te[4] = 0; + te[8] = 0; + te[12] = a; + te[1] = 0; + te[5] = y; + te[9] = 0; + te[13] = b; + te[2] = 0; + te[6] = 0; + te[10] = c; + te[14] = d; + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[15] = 1; + return this; + } + /** + * Returns `true` if this matrix is equal with the given one. + * + * @param {Matrix4} matrix - The matrix to test for equality. + * @return {boolean} Whether this matrix is equal with the given one. + */ + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0; i < 16; i++) { + if (te[i] !== me[i]) return false; + } + return true; + } + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} array - The matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Matrix4} A reference to this matrix. + */ + fromArray(array, offset = 0) { + for (let i = 0; i < 16; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + /** + * Writes the elements of this matrix to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The matrix elements in column-major order. + */ + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + array[offset + 9] = te[9]; + array[offset + 10] = te[10]; + array[offset + 11] = te[11]; + array[offset + 12] = te[12]; + array[offset + 13] = te[13]; + array[offset + 14] = te[14]; + array[offset + 15] = te[15]; + return array; + } + }; + _Matrix4.prototype.isMatrix4 = true; + let Matrix4 = _Matrix4; + const _v1$7 = /* @__PURE__ */ new Vector3(); + const _m1$4 = /* @__PURE__ */ new Matrix4(); + const _zero = /* @__PURE__ */ new Vector3(0, 0, 0); + const _one = /* @__PURE__ */ new Vector3(1, 1, 1); + const _x = /* @__PURE__ */ new Vector3(); + const _y = /* @__PURE__ */ new Vector3(); + const _z = /* @__PURE__ */ new Vector3(); + const _matrix$2 = /* @__PURE__ */ new Matrix4(); + const _quaternion$4 = /* @__PURE__ */ new Quaternion(); + class Euler { + /** + * Constructs a new euler instance. + * + * @param {number} [x=0] - The angle of the x axis in radians. + * @param {number} [y=0] - The angle of the y axis in radians. + * @param {number} [z=0] - The angle of the z axis in radians. + * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied. + */ + constructor(x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x; + this._y = y; + this._z = z; + this._order = order; + } + /** + * The angle of the x axis in radians. + * + * @type {number} + * @default 0 + */ + get x() { + return this._x; + } + set x(value) { + this._x = value; + this._onChangeCallback(); + } + /** + * The angle of the y axis in radians. + * + * @type {number} + * @default 0 + */ + get y() { + return this._y; + } + set y(value) { + this._y = value; + this._onChangeCallback(); + } + /** + * The angle of the z axis in radians. + * + * @type {number} + * @default 0 + */ + get z() { + return this._z; + } + set z(value) { + this._z = value; + this._onChangeCallback(); + } + /** + * A string representing the order that the rotations are applied. + * + * @type {string} + * @default 'XYZ' + */ + get order() { + return this._order; + } + set order(value) { + this._order = value; + this._onChangeCallback(); + } + /** + * Sets the Euler components. + * + * @param {number} x - The angle of the x axis in radians. + * @param {number} y - The angle of the y axis in radians. + * @param {number} z - The angle of the z axis in radians. + * @param {string} [order] - A string representing the order that the rotations are applied. + * @return {Euler} A reference to this Euler instance. + */ + set(x, y, z, order = this._order) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; + this._onChangeCallback(); + return this; + } + /** + * Returns a new Euler instance with copied values from this instance. + * + * @return {Euler} A clone of this instance. + */ + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + /** + * Copies the values of the given Euler instance to this instance. + * + * @param {Euler} euler - The Euler instance to copy. + * @return {Euler} A reference to this Euler instance. + */ + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + /** + * Sets the angles of this Euler instance from a pure rotation matrix. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). + * @param {string} [order] - A string representing the order that the rotations are applied. + * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. + * @return {Euler} A reference to this Euler instance. + */ + setFromRotationMatrix(m, order = this._order, update = true) { + const te = m.elements; + const m11 = te[0], m12 = te[4], m13 = te[8]; + const m21 = te[1], m22 = te[5], m23 = te[9]; + const m31 = te[2], m32 = te[6], m33 = te[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; } - - var centerx = offsetx + 25; - var centery = offsety + Math.floor(pixels/2); - - /* circle around core */ - // i have between 0 and wavestart to fade in - // i have between wavestart and waveend - (time between waves*2) - // to do a full spin close and then back open - // i have between waveend-2*(timebetween waves)/2 and waveend to rotate Math.PI/4 degrees - // this is probably the ugliest code in all of here -- basically I just messed arund with stuff until it looked ok - - ctx.lineWidth=2; - ctx.strokeStyle=shieldColor; - var buffer=Math.PI/16; - var start = -Math.PI + Math.PI/4; - var radius = 8; - var repeatAt = Math.floor(numFrames-2*(numFrames-waveStart)/numWaves)+1; - - /* fade in and out */ - if(i=numFrames){ - - ctx.arc(centerx, centery, radius,n* Math.PI/2 + start+buffer, n*Math.PI/2 + start+Math.PI/2-2*buffer); - - } else if(i > waveStart && i < swirlDone){ - var totalTimeToComplete = swirlDone - waveStart; - var distToGo = 3*Math.PI/2; - var currentStep = (i-waveStart); - var movementPerStep = distToGo / totalTimeToComplete; - - var startAngle = -Math.PI + Math.PI/4 + buffer + movementPerStep*currentStep; - - ctx.arc(centerx, centery, radius,Math.max(n*Math.PI/2 + start,startAngle), Math.max(n*Math.PI/2 + start + Math.PI/2 - 2*buffer, startAngle +Math.PI/2 - 2*buffer)); - - } else if(i >= swirlDone && i< repeatAt){ - var totalTimeToComplete = repeatAt - swirlDone; - var distToGo = n*2*Math.PI/4; - var currentStep = (i-swirlDone); - var movementPerStep = distToGo / totalTimeToComplete; - - - var startAngle = Math.PI/2 + Math.PI/4 + buffer + movementPerStep*currentStep; - ctx.arc(centerx, centery, radius,startAngle, startAngle + Math.PI/2 - 2*buffer); - - } else if(i >= repeatAt && i < (numFrames-repeatAt)/2 + repeatAt){ - - var totalTimeToComplete = (numFrames-repeatAt)/2; - var distToGo = Math.PI/2; - var currentStep = (i-repeatAt); - var movementPerStep = distToGo / totalTimeToComplete; - var startAngle = n*(Math.PI/2)+ Math.PI/4 + buffer + movementPerStep*currentStep; - - ctx.arc(centerx, centery, radius,startAngle, startAngle + Math.PI/2 - 2*buffer); - - } else{ - ctx.arc(centerx, centery, radius,n* Math.PI/2 + start+buffer, n*Math.PI/2 + start+Math.PI/2-2*buffer); - } - ctx.stroke(); + break; + case "ZXY": + this._x = Math.asin(clamp(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); } - - // frame i'm on * distance per frame - - /* waves going out */ - var frameOn; - - for(var wi = 0; wi 0 && frameOn * distPerFrame < pixels - 25){ - ctx.strokeStyle="rgba(" + waveColorRGB.r + "," + waveColorRGB.g + "," + waveColorRGB.b + "," + (.9-frameOn*distPerFrame/(pixels-25)) + ")"; - ctx.lineWidth=2; - ctx.beginPath(); - ctx.arc(centerx, centery, frameOn * distPerFrame, -Math.PI/12, Math.PI/12); - ctx.stroke(); - } + break; + case "ZYX": + this._y = Math.asin(-clamp(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); } - /* red circle in middle */ - - ctx.fillStyle="#000"; - ctx.beginPath(); - ctx.arc(centerx,centery,3,0,2*Math.PI); - ctx.fill(); - - ctx.strokeStyle=coreColor; - ctx.lineWidth=2; - ctx.beginPath(); - if(i} array - An array holding the Euler component values. + * @return {Euler} A reference to this Euler instance. + */ + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== void 0) this._order = array[3]; + this._onChangeCallback(); + return this; + } + /** + * Writes the components of this Euler instance to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the Euler components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The Euler components. + */ + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } + } + Euler.DEFAULT_ORDER = "XYZ"; + class Layers { + /** + * Constructs a new layers instance, with membership + * initially set to layer `0`. + */ + constructor() { + this.mask = 1 | 0; + } + /** + * Sets membership to the given layer, and remove membership all other layers. + * + * @param {number} layer - The layer to set. + */ + set(layer) { + this.mask = (1 << layer | 0) >>> 0; + } + /** + * Adds membership of the given layer. + * + * @param {number} layer - The layer to enable. + */ + enable(layer) { + this.mask |= 1 << layer | 0; + } + /** + * Adds membership to all layers. + */ + enableAll() { + this.mask = 4294967295 | 0; + } + /** + * Toggles the membership of the given layer. + * + * @param {number} layer - The layer to toggle. + */ + toggle(layer) { + this.mask ^= 1 << layer | 0; + } + /** + * Removes membership of the given layer. + * + * @param {number} layer - The layer to enable. + */ + disable(layer) { + this.mask &= ~(1 << layer | 0); + } + /** + * Removes the membership from all layers. + */ + disableAll() { + this.mask = 0; + } + /** + * Returns `true` if this and the given layers object have at least one + * layer in common. + * + * @param {Layers} layers - The layers to test. + * @return {boolean } Whether this and the given layers object have at least one layer in common or not. + */ + test(layers) { + return (this.mask & layers.mask) !== 0; + } + /** + * Returns `true` if the given layer is enabled. + * + * @param {number} layer - The layer to test. + * @return {boolean } Whether the given layer is enabled or not. + */ + isEnabled(layer) { + return (this.mask & (1 << layer | 0)) !== 0; + } + } + let _object3DId = 0; + const _v1$6 = /* @__PURE__ */ new Vector3(); + const _q1 = /* @__PURE__ */ new Quaternion(); + const _m1$3 = /* @__PURE__ */ new Matrix4(); + const _target = /* @__PURE__ */ new Vector3(); + const _position$4 = /* @__PURE__ */ new Vector3(); + const _scale$3 = /* @__PURE__ */ new Vector3(); + const _quaternion$3 = /* @__PURE__ */ new Quaternion(); + const _xAxis = /* @__PURE__ */ new Vector3(1, 0, 0); + const _yAxis = /* @__PURE__ */ new Vector3(0, 1, 0); + const _zAxis = /* @__PURE__ */ new Vector3(0, 0, 1); + const _addedEvent = { type: "added" }; + const _removedEvent = { type: "removed" }; + const _childaddedEvent = { type: "childadded", child: null }; + const _childremovedEvent = { type: "childremoved", child: null }; + class Object3D extends EventDispatcher { + /** + * Constructs a new 3D object. + */ + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = Object3D.DEFAULT_UP.clone(); + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation, false); + } + function onQuaternionChange() { + rotation.setFromQuaternion(quaternion, void 0, false); + } + rotation._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + /** + * Represents the object's local position. + * + * @name Object3D#position + * @type {Vector3} + * @default (0,0,0) + */ + position: { + configurable: true, + enumerable: true, + value: position + }, + /** + * Represents the object's local rotation as Euler angles, in radians. + * + * @name Object3D#rotation + * @type {Euler} + * @default (0,0,0) + */ + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + /** + * Represents the object's local rotation as Quaternions. + * + * @name Object3D#quaternion + * @type {Quaternion} + */ + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + /** + * Represents the object's local scale. + * + * @name Object3D#scale + * @type {Vector3} + * @default (1,1,1) + */ + scale: { + configurable: true, + enumerable: true, + value: scale + }, + /** + * Represents the object's model-view matrix. + * + * @name Object3D#modelViewMatrix + * @type {Matrix4} + */ + modelViewMatrix: { + value: new Matrix4() + }, + /** + * Represents the object's normal matrix. + * + * @name Object3D#normalMatrix + * @type {Matrix3} + */ + normalMatrix: { + value: new Matrix3() + } + }); + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers(); + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.customDepthMaterial = void 0; + this.customDistanceMaterial = void 0; + this.static = false; + this.userData = {}; + this.pivot = null; + } + /** + * A callback that is executed immediately before a 3D object is rendered to a shadow map. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {Camera} shadowCamera - The shadow camera. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} depthMaterial - The depth material. + * @param {Object} group - The geometry group data. + */ + onBeforeShadow() { + } + /** + * A callback that is executed immediately after a 3D object is rendered to a shadow map. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {Camera} shadowCamera - The shadow camera. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} depthMaterial - The depth material. + * @param {Object} group - The geometry group data. + */ + onAfterShadow() { + } + /** + * A callback that is executed immediately before a 3D object is rendered. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} material - The 3D object's material. + * @param {Object} group - The geometry group data. + */ + onBeforeRender() { + } + /** + * A callback that is executed immediately after a 3D object is rendered. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} material - The 3D object's material. + * @param {Object} group - The geometry group data. + */ + onAfterRender() { + } + /** + * Applies the given transformation matrix to the object and updates the object's position, + * rotation and scale. + * + * @param {Matrix4} matrix - The transformation matrix. + */ + applyMatrix4(matrix) { + if (this.matrixAutoUpdate) this.updateMatrix(); + this.matrix.premultiply(matrix); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + /** + * Applies a rotation represented by given the quaternion to the 3D object. + * + * @param {Quaternion} q - The quaternion. + * @return {Object3D} A reference to this instance. + */ + applyQuaternion(q) { + this.quaternion.premultiply(q); + return this; + } + /** + * Sets the given rotation represented as an axis/angle couple to the 3D object. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + */ + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + /** + * Sets the given rotation represented as Euler angles to the 3D object. + * + * @param {Euler} euler - The Euler angles. + */ + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + /** + * Sets the given rotation represented as rotation matrix to the 3D object. + * + * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be + * a pure rotation matrix (i.e, unscaled). + */ + setRotationFromMatrix(m) { + this.quaternion.setFromRotationMatrix(m); + } + /** + * Sets the given rotation represented as a Quaternion to the 3D object. + * + * @param {Quaternion} q - The Quaternion + */ + setRotationFromQuaternion(q) { + this.quaternion.copy(q); + } + /** + * Rotates the 3D object along an axis in local space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateOnAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q1); + return this; + } + /** + * Rotates the 3D object along an axis in world space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateOnWorldAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q1); + return this; + } + /** + * Rotates the 3D object around its X axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateX(angle) { + return this.rotateOnAxis(_xAxis, angle); + } + /** + * Rotates the 3D object around its Y axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateY(angle) { + return this.rotateOnAxis(_yAxis, angle); + } + /** + * Rotates the 3D object around its Z axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateZ(angle) { + return this.rotateOnAxis(_zAxis, angle); + } + /** + * Translate the 3D object by a distance along the given axis in local space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateOnAxis(axis, distance) { + _v1$6.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$6.multiplyScalar(distance)); + return this; + } + /** + * Translate the 3D object by a distance along its X-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateX(distance) { + return this.translateOnAxis(_xAxis, distance); + } + /** + * Translate the 3D object by a distance along its Y-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateY(distance) { + return this.translateOnAxis(_yAxis, distance); + } + /** + * Translate the 3D object by a distance along its Z-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateZ(distance) { + return this.translateOnAxis(_zAxis, distance); + } + /** + * Converts the given vector from this 3D object's local space to world space. + * + * @param {Vector3} vector - The vector to convert. + * @return {Vector3} The converted vector. + */ + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + /** + * Converts the given vector from this 3D object's world space to local space. + * + * @param {Vector3} vector - The vector to convert. + * @return {Vector3} The converted vector. + */ + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$3.copy(this.matrixWorld).invert()); + } + /** + * Rotates the object to face a point in world space. + * + * This method does not support objects having non-uniformly-scaled parent(s). + * + * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space + * @param {number} [y] - The y coordinate in world space. + * @param {number} [z] - The z coordinate in world space. + */ + lookAt(x, y, z) { + if (x.isVector3) { + _target.copy(x); + } else { + _target.set(x, y, z); + } + const parent = this.parent; + this.updateWorldMatrix(true, false); + _position$4.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$3.lookAt(_position$4, _target, this.up); + } else { + _m1$3.lookAt(_target, _position$4, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$3); + if (parent) { + _m1$3.extractRotation(parent.matrixWorld); + _q1.setFromRotationMatrix(_m1$3); + this.quaternion.premultiply(_q1.invert()); + } + } + /** + * Adds the given 3D object as a child to this 3D object. An arbitrary number of + * objects may be added. Any current parent on an object passed in here will be + * removed, since an object can have at most one parent. + * + * @fires Object3D#added + * @fires Object3D#childadded + * @param {Object3D} object - The 3D object to add. + * @return {Object3D} A reference to this instance. + */ + add(object) { + if (arguments.length > 1) { + for (let i = 0; i < arguments.length; i++) { + this.add(arguments[i]); + } + return this; + } + if (object === this) { + error("Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + } else { + error("Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + /** + * Removes the given 3D object as child from this 3D object. + * An arbitrary number of objects may be removed. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @param {Object3D} object - The 3D object to remove. + * @return {Object3D} A reference to this instance. + */ + remove(object) { + if (arguments.length > 1) { + for (let i = 0; i < arguments.length; i++) { + this.remove(arguments[i]); + } + return this; + } + const index = this.children.indexOf(object); + if (index !== -1) { + object.parent = null; + this.children.splice(index, 1); + object.dispatchEvent(_removedEvent); + _childremovedEvent.child = object; + this.dispatchEvent(_childremovedEvent); + _childremovedEvent.child = null; + } + return this; + } + /** + * Removes this 3D object from its current parent. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @return {Object3D} A reference to this instance. + */ + removeFromParent() { + const parent = this.parent; + if (parent !== null) { + parent.remove(this); + } + return this; + } + /** + * Removes all child objects. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @return {Object3D} A reference to this instance. + */ + clear() { + return this.remove(...this.children); + } + /** + * Adds the given 3D object as a child of this 3D object, while maintaining the object's world + * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s). + * + * @fires Object3D#added + * @fires Object3D#childadded + * @param {Object3D} object - The 3D object to attach. + * @return {Object3D} A reference to this instance. + */ + attach(object) { + this.updateWorldMatrix(true, false); + _m1$3.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$3.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$3); + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.updateWorldMatrix(false, true); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + return this; + } + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching ID. + * + * @param {number} id - The id. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching name. + * + * @param {string} name - The name. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectByName(name) { + return this.getObjectByProperty("name", name); + } + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching property value. + * + * @param {string} name - The name of the property. + * @param {any} value - The value. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectByProperty(name, value) { + if (this[name] === value) return this; + for (let i = 0, l = this.children.length; i < l; i++) { + const child = this.children[i]; + const object = child.getObjectByProperty(name, value); + if (object !== void 0) { + return object; + } + } + return void 0; + } + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns all 3D objects with a matching property value. + * + * @param {string} name - The name of the property. + * @param {any} value - The value. + * @param {Array} result - The method stores the result in this array. + * @return {Array} The found 3D objects. + */ + getObjectsByProperty(name, value, result = []) { + if (this[name] === value) result.push(this); + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + children[i].getObjectsByProperty(name, value, result); + } + return result; + } + /** + * Returns a vector representing the position of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's position in world space. + */ + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + /** + * Returns a Quaternion representing the position of the 3D object in world space. + * + * @param {Quaternion} target - The target Quaternion the result is stored to. + * @return {Quaternion} The 3D object's rotation in world space. + */ + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$4, target, _scale$3); + return target; + } + /** + * Returns a vector representing the scale of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's scale in world space. + */ + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$4, _quaternion$3, target); + return target; + } + /** + * Returns a vector representing the ("look") direction of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's direction in world space. + */ + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e = this.matrixWorld.elements; + return target.set(e[8], e[9], e[10]).normalize(); + } + /** + * Abstract method to get intersections between a casted ray and this + * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points} + * implement this method in order to use raycasting. + * + * @abstract + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - An array holding the result of the method. + */ + raycast() { + } + /** + * Executes the callback on this 3D object and all descendants. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverse(callback) { + callback(this); + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + children[i].traverse(callback); + } + } + /** + * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects. + * Descendants of invisible 3D objects are not traversed. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverseVisible(callback) { + if (this.visible === false) return; + callback(this); + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + children[i].traverseVisible(callback); + } + } + /** + * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverseAncestors(callback) { + const parent = this.parent; + if (parent !== null) { + callback(parent); + parent.traverseAncestors(callback); + } + } + /** + * Updates the transformation matrix in local space by computing it from the current + * position, rotation and scale values. + */ + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + const pivot = this.pivot; + if (pivot !== null) { + const px2 = pivot.x, py2 = pivot.y, pz2 = pivot.z; + const te = this.matrix.elements; + te[12] += px2 - te[0] * px2 - te[4] * py2 - te[8] * pz2; + te[13] += py2 - te[1] * px2 - te[5] * py2 - te[9] * pz2; + te[14] += pz2 - te[2] * px2 - te[6] * py2 - te[10] * pz2; + } + this.matrixWorldNeedsUpdate = true; + } + /** + * Updates the transformation matrix in world space of this 3D objects and its descendants. + * + * To ensure correct results, this method also recomputes the 3D object's transformation matrix in + * local space. The computation of the local and world matrix can be controlled with the + * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both + * `true` by default. Set these flags to `false` if you need more control over the update matrix process. + * + * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even + * when {@link Object3D#matrixWorldNeedsUpdate} is `false`. + */ + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + const child = children[i]; + child.updateMatrixWorld(force); + } + } + /** + * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the + * update of ancestor and descendant nodes. + * + * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not. + * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not. + */ + updateWorldMatrix(updateParents, updateChildren) { + const parent = this.parent; + if (updateParents === true && parent !== null) { + parent.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) this.updateMatrix(); + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + if (updateChildren === true) { + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + const child = children[i]; + child.updateWorldMatrix(false, true); + } + } + } + /** + * Serializes the 3D object into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized 3D object. + * @see {@link ObjectLoader#parse} + */ + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + const output = {}; + if (isRootObject) { + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.7, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") object.name = this.name; + if (this.castShadow === true) object.castShadow = true; + if (this.receiveShadow === true) object.receiveShadow = true; + if (this.visible === false) object.visible = false; + if (this.frustumCulled === false) object.frustumCulled = false; + if (this.renderOrder !== 0) object.renderOrder = this.renderOrder; + if (this.static !== false) object.static = this.static; + if (Object.keys(this.userData).length > 0) object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.pivot !== null) object.pivot = this.pivot.toArray(); + if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; + if (this.morphTargetDictionary !== void 0) object.morphTargetDictionary = Object.assign({}, this.morphTargetDictionary); + if (this.morphTargetInfluences !== void 0) object.morphTargetInfluences = this.morphTargetInfluences.slice(); + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.geometryInfo = this._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox ? info.boundingBox.toJSON() : void 0, + boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : void 0 + })); + object.instanceInfo = this._instanceInfo.map((info) => ({ ...info })); + object.availableInstanceIds = this._availableInstanceIds.slice(); + object.availableGeometryIds = this._availableGeometryIds.slice(); + object.nextIndexStart = this._nextIndexStart; + object.nextVertexStart = this._nextVertexStart; + object.geometryCount = this._geometryCount; + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.matricesTexture = this._matricesTexture.toJSON(meta); + object.indirectTexture = this._indirectTexture.toJSON(meta); + if (this._colorsTexture !== null) { + object.colorsTexture = this._colorsTexture.toJSON(meta); + } + if (this.boundingSphere !== null) { + object.boundingSphere = this.boundingSphere.toJSON(); + } + if (this.boundingBox !== null) { + object.boundingBox = this.boundingBox.toJSON(); + } + } + function serialize(library, element) { + if (library[element.uuid] === void 0) { + library[element.uuid] = element.toJSON(meta); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== void 0 && parameters.shapes !== void 0) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length; i < l; i++) { + const shape = shapes[i]; + serialize(meta.shapes, shape); + } + } else { + serialize(meta.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== void 0) { + serialize(meta.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== void 0) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i = 0, l = this.material.length; i < l; i++) { + uuids.push(serialize(meta.materials, this.material[i])); + } + object.material = uuids; + } else { + object.material = serialize(meta.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i = 0; i < this.children.length; i++) { + object.children.push(this.children[i].toJSON(meta).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i = 0; i < this.animations.length; i++) { + const animation = this.animations[i]; + object.animations.push(serialize(meta.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta.geometries); + const materials = extractFromCache(meta.materials); + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + const shapes = extractFromCache(meta.shapes); + const skeletons = extractFromCache(meta.skeletons); + const animations = extractFromCache(meta.animations); + const nodes = extractFromCache(meta.nodes); + if (geometries.length > 0) output.geometries = geometries; + if (materials.length > 0) output.materials = materials; + if (textures.length > 0) output.textures = textures; + if (images.length > 0) output.images = images; + if (shapes.length > 0) output.shapes = shapes; + if (skeletons.length > 0) output.skeletons = skeletons; + if (animations.length > 0) output.animations = animations; + if (nodes.length > 0) output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values = []; + for (const key in cache) { + const data = cache[key]; + delete data.metadata; + values.push(data); + } + return values; + } + } + /** + * Returns a new 3D object with copied values from this instance. + * + * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned. + * @return {Object3D} A clone of this instance. + */ + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + /** + * Copies the values of the given 3D object to this instance. + * + * @param {Object3D} source - The 3D object to copy. + * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned. + * @return {Object3D} A reference to this instance. + */ + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.pivot = source.pivot !== null ? source.pivot.clone() : null; + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.static = source.static; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i = 0; i < source.children.length; i++) { + const child = source.children[i]; + this.add(child.clone()); + } + } + return this; + } + } + Object3D.DEFAULT_UP = /* @__PURE__ */ new Vector3(0, 1, 0); + Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; + Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + class Group extends Object3D { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } + } + const _moveEvent = { type: "move" }; + class WebXRController { + /** + * Constructs a new XR controller. + */ + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + /** + * Returns a group representing the hand space of the XR controller. + * + * @return {Group} A group representing the hand space of the XR controller. + */ + getHandSpace() { + if (this._hand === null) { + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + /** + * Returns a group representing the target ray space of the XR controller. + * + * @return {Group} A group representing the target ray space of the XR controller. + */ + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); + } + return this._targetRay; + } + /** + * Returns a group representing the grip space of the XR controller. + * + * @return {Group} A group representing the grip space of the XR controller. + */ + getGripSpace() { + if (this._grip === null) { + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); + this._grip.eventsEnabled = false; + } + return this._grip; + } + /** + * Dispatches the given event to the groups representing + * the different coordinate spaces of the XR controller. + * + * @param {Object} event - The event to dispatch. + * @return {WebXRController} A reference to this instance. + */ + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + /** + * Connects the controller with the given XR input source. + * + * @param {XRInputSource} inputSource - The input source. + * @return {WebXRController} A reference to this instance. + */ + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + /** + * Disconnects the controller from the given XR input source. + * + * @param {XRInputSource} inputSource - The input source. + * @return {WebXRController} A reference to this instance. + */ + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + /** + * Updates the controller with the given input source, XR frame and reference space. + * This updates the transformations of the groups that represent the different + * coordinate systems of the controller. + * + * @param {XRInputSource} inputSource - The input source. + * @param {XRFrame} frame - The XR frame. + * @param {XRReferenceSpace} referenceSpace - The reference space. + * @return {WebXRController} A reference to this instance. + */ + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 5e-3; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + if (grip.eventsEnabled) { + grip.dispatchEvent({ + type: "gripUpdated", + data: inputSource, + target: this + }); + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + /** + * Returns a group representing the hand joint for the given input joint. + * + * @private + * @param {Group} hand - The group representing the hand space. + * @param {XRJointSpace} inputjoint - The hand joint data. + * @return {Group} A group representing the hand joint for the given input joint. + */ + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === void 0) { + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } + } + const _colorKeywords = { + "aliceblue": 15792383, + "antiquewhite": 16444375, + "aqua": 65535, + "aquamarine": 8388564, + "azure": 15794175, + "beige": 16119260, + "bisque": 16770244, + "black": 0, + "blanchedalmond": 16772045, + "blue": 255, + "blueviolet": 9055202, + "brown": 10824234, + "burlywood": 14596231, + "cadetblue": 6266528, + "chartreuse": 8388352, + "chocolate": 13789470, + "coral": 16744272, + "cornflowerblue": 6591981, + "cornsilk": 16775388, + "crimson": 14423100, + "cyan": 65535, + "darkblue": 139, + "darkcyan": 35723, + "darkgoldenrod": 12092939, + "darkgray": 11119017, + "darkgreen": 25600, + "darkgrey": 11119017, + "darkkhaki": 12433259, + "darkmagenta": 9109643, + "darkolivegreen": 5597999, + "darkorange": 16747520, + "darkorchid": 10040012, + "darkred": 9109504, + "darksalmon": 15308410, + "darkseagreen": 9419919, + "darkslateblue": 4734347, + "darkslategray": 3100495, + "darkslategrey": 3100495, + "darkturquoise": 52945, + "darkviolet": 9699539, + "deeppink": 16716947, + "deepskyblue": 49151, + "dimgray": 6908265, + "dimgrey": 6908265, + "dodgerblue": 2003199, + "firebrick": 11674146, + "floralwhite": 16775920, + "forestgreen": 2263842, + "fuchsia": 16711935, + "gainsboro": 14474460, + "ghostwhite": 16316671, + "gold": 16766720, + "goldenrod": 14329120, + "gray": 8421504, + "green": 32768, + "greenyellow": 11403055, + "grey": 8421504, + "honeydew": 15794160, + "hotpink": 16738740, + "indianred": 13458524, + "indigo": 4915330, + "ivory": 16777200, + "khaki": 15787660, + "lavender": 15132410, + "lavenderblush": 16773365, + "lawngreen": 8190976, + "lemonchiffon": 16775885, + "lightblue": 11393254, + "lightcoral": 15761536, + "lightcyan": 14745599, + "lightgoldenrodyellow": 16448210, + "lightgray": 13882323, + "lightgreen": 9498256, + "lightgrey": 13882323, + "lightpink": 16758465, + "lightsalmon": 16752762, + "lightseagreen": 2142890, + "lightskyblue": 8900346, + "lightslategray": 7833753, + "lightslategrey": 7833753, + "lightsteelblue": 11584734, + "lightyellow": 16777184, + "lime": 65280, + "limegreen": 3329330, + "linen": 16445670, + "magenta": 16711935, + "maroon": 8388608, + "mediumaquamarine": 6737322, + "mediumblue": 205, + "mediumorchid": 12211667, + "mediumpurple": 9662683, + "mediumseagreen": 3978097, + "mediumslateblue": 8087790, + "mediumspringgreen": 64154, + "mediumturquoise": 4772300, + "mediumvioletred": 13047173, + "midnightblue": 1644912, + "mintcream": 16121850, + "mistyrose": 16770273, + "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, + "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 + }; + const _hslA = { h: 0, s: 0, l: 0 }; + const _hslB = { h: 0, s: 0, l: 0 }; + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t); + return p; + } + class Color { + /** + * Constructs a new color. + * + * Note that standard method of specifying color in three.js is with a hexadecimal triplet, + * and that method is used throughout the rest of the documentation. + * + * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are + * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. + * @param {number} [g] - The green component. + * @param {number} [b] - The blue component. + */ + constructor(r, g, b) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r, g, b); + } + /** + * Sets the colors's components from the given values. + * + * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are + * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. + * @param {number} [g] - The green component. + * @param {number} [b] - The blue component. + * @return {Color} A reference to this color. + */ + set(r, g, b) { + if (g === void 0 && b === void 0) { + const value = r; + if (value && value.isColor) { + this.copy(value); + } else if (typeof value === "number") { + this.setHex(value); + } else if (typeof value === "string") { + this.setStyle(value); + } + } else { + this.setRGB(r, g, b); + } + return this; + } + /** + * Sets the colors's components to the given scalar value. + * + * @param {number} scalar - The scalar value. + * @return {Color} A reference to this color. + */ + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + /** + * Sets this color from a hexadecimal value. + * + * @param {number} hex - The hexadecimal value. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setHex(hex, colorSpace = SRGBColorSpace) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement.colorSpaceToWorking(this, colorSpace); + return this; + } + /** + * Sets this color from RGB values. + * + * @param {number} r - Red channel value between `0.0` and `1.0`. + * @param {number} g - Green channel value between `0.0` and `1.0`. + * @param {number} b - Blue channel value between `0.0` and `1.0`. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setRGB(r, g, b, colorSpace = ColorManagement.workingColorSpace) { + this.r = r; + this.g = g; + this.b = b; + ColorManagement.colorSpaceToWorking(this, colorSpace); + return this; + } + /** + * Sets this color from RGB values. + * + * @param {number} h - Hue value between `0.0` and `1.0`. + * @param {number} s - Saturation value between `0.0` and `1.0`. + * @param {number} l - Lightness value between `0.0` and `1.0`. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setHSL(h, s, l, colorSpace = ColorManagement.workingColorSpace) { + h = euclideanModulo(h, 1); + s = clamp(s, 0, 1); + l = clamp(l, 0, 1); + if (s === 0) { + this.r = this.g = this.b = l; + } else { + const p = l <= 0.5 ? l * (1 + s) : l + s - l * s; + const q = 2 * l - p; + this.r = hue2rgb(q, p, h + 1 / 3); + this.g = hue2rgb(q, p, h); + this.b = hue2rgb(q, p, h - 1 / 3); + } + ColorManagement.colorSpaceToWorking(this, colorSpace); + return this; + } + /** + * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`, + * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or + * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) - + * all 140 color names are supported). + * + * @param {string} style - Color as a CSS-style string. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setStyle(style, colorSpace = SRGBColorSpace) { + function handleAlpha(string) { + if (string === void 0) return; + if (parseFloat(string) < 1) { + warn("Color: Alpha component of " + style + " will be ignored."); + } + } + let m; + if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name = m[1]; + const components = m[2]; + switch (name) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB( + Math.min(255, parseInt(color[1], 10)) / 255, + Math.min(255, parseInt(color[2], 10)) / 255, + Math.min(255, parseInt(color[3], 10)) / 255, + colorSpace + ); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB( + Math.min(100, parseInt(color[1], 10)) / 100, + Math.min(100, parseInt(color[2], 10)) / 100, + Math.min(100, parseInt(color[3], 10)) / 100, + colorSpace + ); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL( + parseFloat(color[1]) / 360, + parseFloat(color[2]) / 100, + parseFloat(color[3]) / 100, + colorSpace + ); + } + break; + default: + warn("Color: Unknown color model " + style); + } + } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m[1]; + const size = hex.length; + if (size === 3) { + return this.setRGB( + parseInt(hex.charAt(0), 16) / 15, + parseInt(hex.charAt(1), 16) / 15, + parseInt(hex.charAt(2), 16) / 15, + colorSpace + ); + } else if (size === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + warn("Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + /** + * Sets this color from a color name. Faster than {@link Color#setStyle} if + * you don't need the other CSS-style formats. + * + * For convenience, the list of names is exposed in `Color.NAMES` as a hash. + * ```js + * Color.NAMES.aliceblue // returns 0xF0F8FF + * ``` + * + * @param {string} style - The color name. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setColorName(style, colorSpace = SRGBColorSpace) { + const hex = _colorKeywords[style.toLowerCase()]; + if (hex !== void 0) { + this.setHex(hex, colorSpace); + } else { + warn("Color: Unknown color " + style); + } + return this; + } + /** + * Returns a new color with copied values from this instance. + * + * @return {Color} A clone of this instance. + */ + clone() { + return new this.constructor(this.r, this.g, this.b); + } + /** + * Copies the values of the given color to this instance. + * + * @param {Color} color - The color to copy. + * @return {Color} A reference to this color. + */ + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + /** + * Copies the given color into this color, and then converts this color from + * `SRGBColorSpace` to `LinearSRGBColorSpace`. + * + * @param {Color} color - The color to copy/convert. + * @return {Color} A reference to this color. + */ + copySRGBToLinear(color) { + this.r = SRGBToLinear(color.r); + this.g = SRGBToLinear(color.g); + this.b = SRGBToLinear(color.b); + return this; + } + /** + * Copies the given color into this color, and then converts this color from + * `LinearSRGBColorSpace` to `SRGBColorSpace`. + * + * @param {Color} color - The color to copy/convert. + * @return {Color} A reference to this color. + */ + copyLinearToSRGB(color) { + this.r = LinearToSRGB(color.r); + this.g = LinearToSRGB(color.g); + this.b = LinearToSRGB(color.b); + return this; + } + /** + * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`. + * + * @return {Color} A reference to this color. + */ + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + /** + * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`. + * + * @return {Color} A reference to this color. + */ + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + /** + * Returns the hexadecimal value of this color. + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {number} The hexadecimal value. + */ + getHex(colorSpace = SRGBColorSpace) { + ColorManagement.workingToColorSpace(_color.copy(this), colorSpace); + return Math.round(clamp(_color.r * 255, 0, 255)) * 65536 + Math.round(clamp(_color.g * 255, 0, 255)) * 256 + Math.round(clamp(_color.b * 255, 0, 255)); + } + /** + * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF'). + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {string} The hexadecimal value as a string. + */ + getHexString(colorSpace = SRGBColorSpace) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + /** + * Converts the colors RGB values into the HSL format and stores them into the + * given target object. + * + * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {{h:number,s:number,l:number}} The HSL representation of this color. + */ + getHSL(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.workingToColorSpace(_color.copy(this), colorSpace); + const r = _color.r, g = _color.g, b = _color.b; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let hue, saturation; + const lightness = (min + max) / 2; + if (min === max) { + hue = 0; + saturation = 0; + } else { + const delta = max - min; + saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); + switch (max) { + case r: + hue = (g - b) / delta + (g < b ? 6 : 0); + break; + case g: + hue = (b - r) / delta + 2; + break; + case b: + hue = (r - g) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + /** + * Returns the RGB values of this color and stores them into the given target object. + * + * @param {Color} target - The target color that is used to store the method's result. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} The RGB representation of this color. + */ + getRGB(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.workingToColorSpace(_color.copy(this), colorSpace); + target.r = _color.r; + target.g = _color.g; + target.b = _color.b; + return target; + } + /** + * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`. + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {string} The CSS representation of this color. + */ + getStyle(colorSpace = SRGBColorSpace) { + ColorManagement.workingToColorSpace(_color.copy(this), colorSpace); + const r = _color.r, g = _color.g, b = _color.b; + if (colorSpace !== SRGBColorSpace) { + return `color(${colorSpace} ${r.toFixed(3)} ${g.toFixed(3)} ${b.toFixed(3)})`; + } + return `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`; + } + /** + * Adds the given HSL values to this color's values. + * Internally, this converts the color's RGB values to HSL, adds HSL + * and then converts the color back to RGB. + * + * @param {number} h - Hue value between `0.0` and `1.0`. + * @param {number} s - Saturation value between `0.0` and `1.0`. + * @param {number} l - Lightness value between `0.0` and `1.0`. + * @return {Color} A reference to this color. + */ + offsetHSL(h, s, l) { + this.getHSL(_hslA); + return this.setHSL(_hslA.h + h, _hslA.s + s, _hslA.l + l); + } + /** + * Adds the RGB values of the given color to the RGB values of this color. + * + * @param {Color} color - The color to add. + * @return {Color} A reference to this color. + */ + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + /** + * Adds the RGB values of the given colors and stores the result in this instance. + * + * @param {Color} color1 - The first color. + * @param {Color} color2 - The second color. + * @return {Color} A reference to this color. + */ + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + /** + * Adds the given scalar value to the RGB values of this color. + * + * @param {number} s - The scalar to add. + * @return {Color} A reference to this color. + */ + addScalar(s) { + this.r += s; + this.g += s; + this.b += s; + return this; + } + /** + * Subtracts the RGB values of the given color from the RGB values of this color. + * + * @param {Color} color - The color to subtract. + * @return {Color} A reference to this color. + */ + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + /** + * Multiplies the RGB values of the given color with the RGB values of this color. + * + * @param {Color} color - The color to multiply. + * @return {Color} A reference to this color. + */ + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + /** + * Multiplies the given scalar value with the RGB values of this color. + * + * @param {number} s - The scalar to multiply. + * @return {Color} A reference to this color. + */ + multiplyScalar(s) { + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } + /** + * Linearly interpolates this color's RGB values toward the RGB values of the + * given color. The alpha argument can be thought of as the ratio between + * the two colors, where `0.0` is this color and `1.0` is the first argument. + * + * @param {Color} color - The color to converge on. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + /** + * Linearly interpolates between the given colors and stores the result in this instance. + * The alpha argument can be thought of as the ratio between the two colors, where `0.0` + * is the first and `1.0` is the second color. + * + * @param {Color} color1 - The first color. + * @param {Color} color2 - The second color. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + /** + * Linearly interpolates this color's HSL values toward the HSL values of the + * given color. It differs from {@link Color#lerp} by not interpolating straight + * from one color to the other, but instead going through all the hues in between + * those two colors. The alpha argument can be thought of as the ratio between + * the two colors, where 0.0 is this color and 1.0 is the first argument. + * + * @param {Color} color - The color to converge on. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerpHSL(color, alpha) { + this.getHSL(_hslA); + color.getHSL(_hslB); + const h = lerp(_hslA.h, _hslB.h, alpha); + const s = lerp(_hslA.s, _hslB.s, alpha); + const l = lerp(_hslA.l, _hslB.l, alpha); + this.setHSL(h, s, l); + return this; + } + /** + * Sets the color's RGB components from the given 3D vector. + * + * @param {Vector3} v - The vector to set. + * @return {Color} A reference to this color. + */ + setFromVector3(v) { + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } + /** + * Transforms this color with the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix. + * @return {Color} A reference to this color. + */ + applyMatrix3(m) { + const r = this.r, g = this.g, b = this.b; + const e = m.elements; + this.r = e[0] * r + e[3] * g + e[6] * b; + this.g = e[1] * r + e[4] * g + e[7] * b; + this.b = e[2] * r + e[5] * g + e[8] * b; + return this; + } + /** + * Returns `true` if this color is equal with the given one. + * + * @param {Color} c - The color to test for equality. + * @return {boolean} Whether this bounding color is equal with the given one. + */ + equals(c) { + return c.r === this.r && c.g === this.g && c.b === this.b; + } + /** + * Sets this color's RGB components from the given array. + * + * @param {Array} array - An array holding the RGB values. + * @param {number} [offset=0] - The offset into the array. + * @return {Color} A reference to this color. + */ + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + /** + * Writes the RGB components of this color to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the color components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The color components. + */ + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + /** + * Sets the components of this color from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding color data. + * @param {number} index - The index into the attribute. + * @return {Color} A reference to this color. + */ + fromBufferAttribute(attribute, index) { + this.r = attribute.getX(index); + this.g = attribute.getY(index); + this.b = attribute.getZ(index); + return this; + } + /** + * This methods defines the serialization result of this class. Returns the color + * as a hexadecimal value. + * + * @return {number} The hexadecimal value. + */ + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } + } + const _color = /* @__PURE__ */ new Color(); + Color.NAMES = _colorKeywords; + class FogExp2 { + /** + * Constructs a new fog. + * + * @param {number|Color} color - The fog's color. + * @param {number} [density=0.00025] - Defines how fast the fog will grow dense. + */ + constructor(color, density = 25e-5) { + this.isFogExp2 = true; + this.name = ""; + this.color = new Color(color); + this.density = density; + } + /** + * Returns a new fog with copied values from this instance. + * + * @return {FogExp2} A clone of this instance. + */ + clone() { + return new FogExp2(this.color, this.density); + } + /** + * Serializes the fog into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized fog + */ + toJSON() { + return { + type: "FogExp2", + name: this.name, + color: this.color.getHex(), + density: this.density + }; + } + } + class Fog { + /** + * Constructs a new fog. + * + * @param {number|Color} color - The fog's color. + * @param {number} [near=1] - The minimum distance to start applying fog. + * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied. + */ + constructor(color, near = 1, far = 1e3) { + this.isFog = true; + this.name = ""; + this.color = new Color(color); + this.near = near; + this.far = far; + } + /** + * Returns a new fog with copied values from this instance. + * + * @return {Fog} A clone of this instance. + */ + clone() { + return new Fog(this.color, this.near, this.far); + } + /** + * Serializes the fog into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized fog + */ + toJSON() { + return { + type: "Fog", + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + } + } + class Scene extends Object3D { + /** + * Constructs a new scene. + */ + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.backgroundRotation = new Euler(); + this.environmentIntensity = 1; + this.environmentRotation = new Euler(); + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) this.background = source.background.clone(); + if (source.environment !== null) this.environment = source.environment.clone(); + if (source.fog !== null) this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy(source.backgroundRotation); + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy(source.environmentRotation); + if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + if (this.fog !== null) data.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) data.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) data.object.backgroundIntensity = this.backgroundIntensity; + data.object.backgroundRotation = this.backgroundRotation.toArray(); + if (this.environmentIntensity !== 1) data.object.environmentIntensity = this.environmentIntensity; + data.object.environmentRotation = this.environmentRotation.toArray(); + return data; + } + } + const _v0$3 = /* @__PURE__ */ new Vector3(); + const _v1$5 = /* @__PURE__ */ new Vector3(); + const _v2$4 = /* @__PURE__ */ new Vector3(); + const _v3$2 = /* @__PURE__ */ new Vector3(); + const _vab = /* @__PURE__ */ new Vector3(); + const _vac = /* @__PURE__ */ new Vector3(); + const _vbc = /* @__PURE__ */ new Vector3(); + const _vap = /* @__PURE__ */ new Vector3(); + const _vbp = /* @__PURE__ */ new Vector3(); + const _vcp = /* @__PURE__ */ new Vector3(); + const _v40 = /* @__PURE__ */ new Vector4(); + const _v41 = /* @__PURE__ */ new Vector4(); + const _v42 = /* @__PURE__ */ new Vector4(); + class Triangle { + /** + * Constructs a new triangle. + * + * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle. + * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle. + * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle. + */ + constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) { + this.a = a; + this.b = b; + this.c = c; + } + /** + * Computes the normal vector of a triangle. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's normal. + */ + static getNormal(a, b, c, target) { + target.subVectors(c, b); + _v0$3.subVectors(a, b); + target.cross(_v0$3); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + /** + * Computes a barycentric coordinates from the given vector. + * Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The barycentric coordinates for the given point + */ + static getBarycoord(point2, a, b, c, target) { + _v0$3.subVectors(c, a); + _v1$5.subVectors(b, a); + _v2$4.subVectors(point2, a); + const dot00 = _v0$3.dot(_v0$3); + const dot01 = _v0$3.dot(_v1$5); + const dot02 = _v0$3.dot(_v2$4); + const dot11 = _v1$5.dot(_v1$5); + const dot12 = _v1$5.dot(_v2$4); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u - v, v, u); + } + /** + * Returns `true` if the given point, when projected onto the plane of the + * triangle, lies within the triangle. + * + * @param {Vector3} point - The point in 3D space to test. + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @return {boolean} Whether the given point, when projected onto the plane of the + * triangle, lies within the triangle or not. + */ + static containsPoint(point2, a, b, c) { + if (this.getBarycoord(point2, a, b, c, _v3$2) === null) { + return false; + } + return _v3$2.x >= 0 && _v3$2.y >= 0 && _v3$2.x + _v3$2.y <= 1; + } + /** + * Computes the value barycentrically interpolated for the given point on the + * triangle. Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - Position of interpolated point. + * @param {Vector3} p1 - The first corner of the triangle. + * @param {Vector3} p2 - The second corner of the triangle. + * @param {Vector3} p3 - The third corner of the triangle. + * @param {Vector3} v1 - Value to interpolate of first vertex. + * @param {Vector3} v2 - Value to interpolate of second vertex. + * @param {Vector3} v3 - Value to interpolate of third vertex. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The interpolated value. + */ + static getInterpolation(point2, p1, p2, p3, v1, v2, v3, target) { + if (this.getBarycoord(point2, p1, p2, p3, _v3$2) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) target.z = 0; + if ("w" in target) target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v1, _v3$2.x); + target.addScaledVector(v2, _v3$2.y); + target.addScaledVector(v3, _v3$2.z); + return target; + } + /** + * Computes the value barycentrically interpolated for the given attribute and indices. + * + * @param {BufferAttribute} attr - The attribute to interpolate. + * @param {number} i1 - Index of first vertex. + * @param {number} i2 - Index of second vertex. + * @param {number} i3 - Index of third vertex. + * @param {Vector3} barycoord - The barycoordinate value to use to interpolate. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The interpolated attribute value. + */ + static getInterpolatedAttribute(attr, i1, i2, i3, barycoord, target) { + _v40.setScalar(0); + _v41.setScalar(0); + _v42.setScalar(0); + _v40.fromBufferAttribute(attr, i1); + _v41.fromBufferAttribute(attr, i2); + _v42.fromBufferAttribute(attr, i3); + target.setScalar(0); + target.addScaledVector(_v40, barycoord.x); + target.addScaledVector(_v41, barycoord.y); + target.addScaledVector(_v42, barycoord.z); + return target; + } + /** + * Returns `true` if the triangle is oriented towards the given direction. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} direction - The (normalized) direction vector. + * @return {boolean} Whether the triangle is oriented towards the given direction or not. + */ + static isFrontFacing(a, b, c, direction) { + _v0$3.subVectors(c, b); + _v1$5.subVectors(a, b); + return _v0$3.cross(_v1$5).dot(direction) < 0; + } + /** + * Sets the triangle's vertices by copying the given values. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + set(a, b, c) { + this.a.copy(a); + this.b.copy(b); + this.c.copy(c); + return this; + } + /** + * Sets the triangle's vertices by copying the given array values. + * + * @param {Array} points - An array with 3D points. + * @param {number} i0 - The array index representing the first corner of the triangle. + * @param {number} i1 - The array index representing the second corner of the triangle. + * @param {number} i2 - The array index representing the third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + setFromPointsAndIndices(points, i0, i1, i2) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i2]); + return this; + } + /** + * Sets the triangle's vertices by copying the given attribute values. + * + * @param {BufferAttribute} attribute - A buffer attribute with 3D points data. + * @param {number} i0 - The attribute index representing the first corner of the triangle. + * @param {number} i1 - The attribute index representing the second corner of the triangle. + * @param {number} i2 - The attribute index representing the third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + setFromAttributeAndIndices(attribute, i0, i1, i2) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i2); + return this; + } + /** + * Returns a new triangle with copied values from this instance. + * + * @return {Triangle} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given triangle to this instance. + * + * @param {Triangle} triangle - The triangle to copy. + * @return {Triangle} A reference to this triangle. + */ + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + /** + * Computes the area of the triangle. + * + * @return {number} The triangle's area. + */ + getArea() { + _v0$3.subVectors(this.c, this.b); + _v1$5.subVectors(this.a, this.b); + return _v0$3.cross(_v1$5).length() * 0.5; + } + /** + * Computes the midpoint of the triangle. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's midpoint. + */ + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + /** + * Computes the normal of the triangle. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's normal. + */ + getNormal(target) { + return Triangle.getNormal(this.a, this.b, this.c, target); + } + /** + * Computes a plane the triangle lies within. + * + * @param {Plane} target - The target vector that is used to store the method's result. + * @return {Plane} The plane the triangle lies within. + */ + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + /** + * Computes a barycentric coordinates from the given vector. + * Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The barycentric coordinates for the given point + */ + getBarycoord(point2, target) { + return Triangle.getBarycoord(point2, this.a, this.b, this.c, target); + } + /** + * Computes the value barycentrically interpolated for the given point on the + * triangle. Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - Position of interpolated point. + * @param {Vector3} v1 - Value to interpolate of first vertex. + * @param {Vector3} v2 - Value to interpolate of second vertex. + * @param {Vector3} v3 - Value to interpolate of third vertex. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The interpolated value. + */ + getInterpolation(point2, v1, v2, v3, target) { + return Triangle.getInterpolation(point2, this.a, this.b, this.c, v1, v2, v3, target); + } + /** + * Returns `true` if the given point, when projected onto the plane of the + * triangle, lies within the triangle. + * + * @param {Vector3} point - The point in 3D space to test. + * @return {boolean} Whether the given point, when projected onto the plane of the + * triangle, lies within the triangle or not. + */ + containsPoint(point2) { + return Triangle.containsPoint(point2, this.a, this.b, this.c); + } + /** + * Returns `true` if the triangle is oriented towards the given direction. + * + * @param {Vector3} direction - The (normalized) direction vector. + * @return {boolean} Whether the triangle is oriented towards the given direction or not. + */ + isFrontFacing(direction) { + return Triangle.isFrontFacing(this.a, this.b, this.c, direction); + } + /** + * Returns `true` if this triangle intersects with the given box. + * + * @param {Box3} box - The box to intersect. + * @return {boolean} Whether this triangle intersects with the given box or not. + */ + intersectsBox(box) { + return box.intersectsTriangle(this); + } + /** + * Returns the closest point on the triangle to the given point. + * + * @param {Vector3} p - The point to compute the closest point for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The closest point on the triangle. + */ + closestPointToPoint(p, target) { + const a = this.a, b = this.b, c = this.c; + let v, w; + _vab.subVectors(b, a); + _vac.subVectors(c, a); + _vap.subVectors(p, a); + const d1 = _vab.dot(_vap); + const d2 = _vac.dot(_vap); + if (d1 <= 0 && d2 <= 0) { + return target.copy(a); + } + _vbp.subVectors(p, b); + const d3 = _vab.dot(_vbp); + const d4 = _vac.dot(_vbp); + if (d3 >= 0 && d4 <= d3) { + return target.copy(b); + } + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + v = d1 / (d1 - d3); + return target.copy(a).addScaledVector(_vab, v); + } + _vcp.subVectors(p, c); + const d5 = _vab.dot(_vcp); + const d6 = _vac.dot(_vcp); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c); + } + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + w = d2 / (d2 - d6); + return target.copy(a).addScaledVector(_vac, w); + } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + _vbc.subVectors(c, b); + w = (d4 - d3) / (d4 - d3 + (d5 - d6)); + return target.copy(b).addScaledVector(_vbc, w); + } + const denom = 1 / (va + vb + vc); + v = vb * denom; + w = vc * denom; + return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w); + } + /** + * Returns `true` if this triangle is equal with the given one. + * + * @param {Triangle} triangle - The triangle to test for equality. + * @return {boolean} Whether this triangle is equal with the given one. + */ + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } + } + class Box3 { + /** + * Constructs a new bounding box. + * + * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box. + * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box. + */ + constructor(min = new Vector3(Infinity, Infinity, Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max; + } + /** + * Sets the lower and upper boundaries of this box. + * Please note that this method only copies the values from the given objects. + * + * @param {Vector3} min - The lower boundary of the box. + * @param {Vector3} max - The upper boundary of the box. + * @return {Box3} A reference to this bounding box. + */ + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} array - An array holding 3D position data. + * @return {Box3} A reference to this bounding box. + */ + setFromArray(array) { + this.makeEmpty(); + for (let i = 0, il = array.length; i < il; i += 3) { + this.expandByPoint(_vector$b.fromArray(array, i)); + } + return this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given buffer attribute. + * + * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data. + * @return {Box3} A reference to this bounding box. + */ + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i = 0, il = attribute.count; i < il; i++) { + this.expandByPoint(_vector$b.fromBufferAttribute(attribute, i)); + } + return this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} points - An array holding 3D position data as instances of {@link Vector3}. + * @return {Box3} A reference to this bounding box. + */ + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length; i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + /** + * Centers this box on the given center vector and sets this box's width, height and + * depth to the given size values. + * + * @param {Vector3} center - The center of the box. + * @param {Vector3} size - The x, y and z dimensions of the box. + * @return {Box3} A reference to this bounding box. + */ + setFromCenterAndSize(center, size) { + const halfSize = _vector$b.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + /** + * Computes the world-axis-aligned bounding box for the given 3D object + * (including its children), accounting for the object's, and children's, + * world transforms. The function may result in a larger box than strictly necessary. + * + * @param {Object3D} object - The 3D object to compute the bounding box for. + * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest + * world-axis-aligned bounding box at the expense of more computation. + * @return {Box3} A reference to this bounding box. + */ + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + /** + * Returns a new box with copied values from this instance. + * + * @return {Box3} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given box to this instance. + * + * @param {Box3} box - The box to copy. + * @return {Box3} A reference to this bounding box. + */ + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + /** + * Makes this box empty which means in encloses a zero space in 3D. + * + * @return {Box3} A reference to this bounding box. + */ + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + /** + * Returns true if this box includes zero points within its bounds. + * Note that a box with equal lower and upper bounds still includes one + * point, the one both bounds share. + * + * @return {boolean} Whether this box is empty or not. + */ + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + /** + * Returns the center point of this box. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The center point. + */ + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + /** + * Returns the dimensions of this box. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The size. + */ + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + /** + * Expands the boundaries of this box to include the given point. + * + * @param {Vector3} point - The point that should be included by the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByPoint(point2) { + this.min.min(point2); + this.max.max(point2); + return this; + } + /** + * Expands this box equilaterally by the given vector. The width of this + * box will be expanded by the x component of the vector in both + * directions. The height of this box will be expanded by the y component of + * the vector in both directions. The depth of this box will be + * expanded by the z component of the vector in both directions. + * + * @param {Vector3} vector - The vector that should expand the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + /** + * Expands each dimension of the box by the given scalar. If negative, the + * dimensions of the box will be contracted. + * + * @param {number} scalar - The scalar value that should expand the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + /** + * Expands the boundaries of this box to include the given 3D object and + * its children, accounting for the object's, and children's, world + * transforms. The function may result in a larger box than strictly + * necessary (unless the precise parameter is set to true). + * + * @param {Object3D} object - The 3D object that should expand the bounding box. + * @param {boolean} precise - If set to `true`, the method expands the bounding box + * as little as necessary at the expense of more computation. + * @return {Box3} A reference to this bounding box. + */ + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== void 0) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== void 0 && object.isInstancedMesh !== true) { + for (let i = 0, l = positionAttribute.count; i < l; i++) { + if (object.isMesh === true) { + object.getVertexPosition(i, _vector$b); + } else { + _vector$b.fromBufferAttribute(positionAttribute, i); + } + _vector$b.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b); + } + } else { + if (object.boundingBox !== void 0) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$4.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$4.copy(geometry.boundingBox); + } + _box$4.applyMatrix4(object.matrixWorld); + this.union(_box$4); + } + } + const children = object.children; + for (let i = 0, l = children.length; i < l; i++) { + this.expandByObject(children[i], precise); + } + return this; + } + /** + * Returns `true` if the given point lies within or on the boundaries of this box. + * + * @param {Vector3} point - The point to test. + * @return {boolean} Whether the bounding box contains the given point or not. + */ + containsPoint(point2) { + return point2.x >= this.min.x && point2.x <= this.max.x && point2.y >= this.min.y && point2.y <= this.max.y && point2.z >= this.min.z && point2.z <= this.max.z; + } + /** + * Returns `true` if this bounding box includes the entirety of the given bounding box. + * If this box and the given one are identical, this function also returns `true`. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the bounding box contains the given bounding box or not. + */ + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + /** + * Returns a point as a proportion of this box's width, height and depth. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} A point as a proportion of this box's width, height and depth. + */ + getParameter(point2, target) { + return target.set( + (point2.x - this.min.x) / (this.max.x - this.min.x), + (point2.y - this.min.y) / (this.max.y - this.min.y), + (point2.z - this.min.z) / (this.max.z - this.min.z) + ); + } + /** + * Returns `true` if the given bounding box intersects with this bounding box. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the given bounding box intersects with this bounding box. + */ + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z; + } + /** + * Returns `true` if the given bounding sphere intersects with this bounding box. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the given bounding sphere intersects with this bounding box. + */ + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b); + return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + /** + * Returns `true` if the given plane intersects with this bounding box. + * + * @param {Plane} plane - The plane to test. + * @return {boolean} Whether the given plane intersects with this bounding box. + */ + intersectsPlane(plane) { + let min, max; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max >= -plane.constant; + } + /** + * Returns `true` if the given triangle intersects with this bounding box. + * + * @param {Triangle} triangle - The triangle to test. + * @return {boolean} Whether the given triangle intersects with this bounding box. + */ + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center); + _extents.subVectors(this.max, _center); + _v0$2.subVectors(triangle.a, _center); + _v1$4.subVectors(triangle.b, _center); + _v2$3.subVectors(triangle.c, _center); + _f0.subVectors(_v1$4, _v0$2); + _f1.subVectors(_v2$3, _v1$4); + _f2.subVectors(_v0$2, _v2$3); + let axes = [ + 0, + -_f0.z, + _f0.y, + 0, + -_f1.z, + _f1.y, + 0, + -_f2.z, + _f2.y, + _f0.z, + 0, + -_f0.x, + _f1.z, + 0, + -_f1.x, + _f2.z, + 0, + -_f2.x, + -_f0.y, + _f0.x, + 0, + -_f1.y, + _f1.x, + 0, + -_f2.y, + _f2.x, + 0 + ]; + if (!satForAxes(axes, _v0$2, _v1$4, _v2$3, _extents)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes(axes, _v0$2, _v1$4, _v2$3, _extents)) { + return false; + } + _triangleNormal.crossVectors(_f0, _f1); + axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z]; + return satForAxes(axes, _v0$2, _v1$4, _v2$3, _extents); + } + /** + * Clamps the given point within the bounds of this box. + * + * @param {Vector3} point - The point to clamp. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The clamped point. + */ + clampPoint(point2, target) { + return target.copy(point2).clamp(this.min, this.max); + } + /** + * Returns the euclidean distance from any edge of this box to the specified point. If + * the given point lies inside of this box, the distance will be `0`. + * + * @param {Vector3} point - The point to compute the distance to. + * @return {number} The euclidean distance. + */ + distanceToPoint(point2) { + return this.clampPoint(point2, _vector$b).distanceTo(point2); + } + /** + * Returns a bounding sphere that encloses this bounding box. + * + * @param {Sphere} target - The target sphere that is used to store the method's result. + * @return {Sphere} The bounding sphere that encloses this bounding box. + */ + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b).length() * 0.5; + } + return target; + } + /** + * Computes the intersection of this bounding box and the given one, setting the upper + * bound of this box to the lesser of the two boxes' upper bounds and the + * lower bound of this box to the greater of the two boxes' lower bounds. If + * there's no overlap, makes this box empty. + * + * @param {Box3} box - The bounding box to intersect with. + * @return {Box3} A reference to this bounding box. + */ + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) this.makeEmpty(); + return this; + } + /** + * Computes the union of this box and another and the given one, setting the upper + * bound of this box to the greater of the two boxes' upper bounds and the + * lower bound of this box to the lesser of the two boxes' lower bounds. + * + * @param {Box3} box - The bounding box that will be unioned with this instance. + * @return {Box3} A reference to this bounding box. + */ + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + /** + * Transforms this bounding box by the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Box3} A reference to this bounding box. + */ + applyMatrix4(matrix) { + if (this.isEmpty()) return this; + _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); + _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); + this.setFromPoints(_points); + return this; + } + /** + * Adds the given offset to both the upper and lower bounds of this bounding box, + * effectively moving it in 3D space. + * + * @param {Vector3} offset - The offset that should be used to translate the bounding box. + * @return {Box3} A reference to this bounding box. + */ + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + /** + * Returns `true` if this bounding box is equal with the given one. + * + * @param {Box3} box - The box to test for equality. + * @return {boolean} Whether this bounding box is equal with the given one. + */ + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + /** + * Returns a serialized structure of the bounding box. + * + * @return {Object} Serialized structure with fields representing the object state. + */ + toJSON() { + return { + min: this.min.toArray(), + max: this.max.toArray() + }; + } + /** + * Returns a serialized structure of the bounding box. + * + * @param {Object} json - The serialized json to set the box from. + * @return {Box3} A reference to this bounding box. + */ + fromJSON(json) { + this.min.fromArray(json.min); + this.max.fromArray(json.max); + return this; + } + } + const _points = [ + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3() + ]; + const _vector$b = /* @__PURE__ */ new Vector3(); + const _box$4 = /* @__PURE__ */ new Box3(); + const _v0$2 = /* @__PURE__ */ new Vector3(); + const _v1$4 = /* @__PURE__ */ new Vector3(); + const _v2$3 = /* @__PURE__ */ new Vector3(); + const _f0 = /* @__PURE__ */ new Vector3(); + const _f1 = /* @__PURE__ */ new Vector3(); + const _f2 = /* @__PURE__ */ new Vector3(); + const _center = /* @__PURE__ */ new Vector3(); + const _extents = /* @__PURE__ */ new Vector3(); + const _triangleNormal = /* @__PURE__ */ new Vector3(); + const _testAxis = /* @__PURE__ */ new Vector3(); + function satForAxes(axes, v0, v1, v2, extents) { + for (let i = 0, j = axes.length - 3; i <= j; i += 3) { + _testAxis.fromArray(axes, i); + const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); + const p0 = v0.dot(_testAxis); + const p1 = v1.dot(_testAxis); + const p2 = v2.dot(_testAxis); + if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { + return false; + } + } + return true; + } + const _tables = /* @__PURE__ */ _generateTables(); + function _generateTables() { + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0; i < 256; ++i) { + const e = i - 127; + if (e < -27) { + baseTable[i] = 0; + baseTable[i | 256] = 32768; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else if (e < -14) { + baseTable[i] = 1024 >> -e - 14; + baseTable[i | 256] = 1024 >> -e - 14 | 32768; + shiftTable[i] = -e - 1; + shiftTable[i | 256] = -e - 1; + } else if (e <= 15) { + baseTable[i] = e + 15 << 10; + baseTable[i | 256] = e + 15 << 10 | 32768; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } else if (e < 128) { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } + } + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1; i < 1024; ++i) { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + m <<= 1; + e -= 8388608; + } + m &= -8388609; + e += 947912704; + mantissaTable[i] = m | e; + } + for (let i = 1024; i < 2048; ++i) { + mantissaTable[i] = 939524096 + (i - 1024 << 13); + } + for (let i = 1; i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + for (let i = 33; i < 63; ++i) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + exponentTable[63] = 3347054592; + for (let i = 1; i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView, + uint32View, + baseTable, + shiftTable, + mantissaTable, + exponentTable, + offsetTable + }; + } + function toHalfFloat(val) { + if (Math.abs(val) > 65504) warn("DataUtils.toHalfFloat(): Value out of range."); + val = clamp(val, -65504, 65504); + _tables.floatView[0] = val; + const f = _tables.uint32View[0]; + const e = f >> 23 & 511; + return _tables.baseTable[e] + ((f & 8388607) >> _tables.shiftTable[e]); + } + function fromHalfFloat(val) { + const m = val >> 10; + _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 1023)] + _tables.exponentTable[m]; + return _tables.floatView[0]; + } + class DataUtils { + /** + * Returns a half precision floating point value (FP16) from the given single + * precision floating point value (FP32). + * + * @param {number} val - A single precision floating point value. + * @return {number} The FP16 value. + */ + static toHalfFloat(val) { + return toHalfFloat(val); + } + /** + * Returns a single precision floating point value (FP32) from the given half + * precision floating point value (FP16). + * + * @param {number} val - A half precision floating point value. + * @return {number} The FP32 value. + */ + static fromHalfFloat(val) { + return fromHalfFloat(val); + } + } + const _vector$a = /* @__PURE__ */ new Vector3(); + const _vector2$1 = /* @__PURE__ */ new Vector2(); + let _id$3 = 0; + class BufferAttribute extends EventDispatcher { + /** + * Constructs a new buffer attribute. + * + * @param {TypedArray} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized = false) { + super(); + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + Object.defineProperty(this, "id", { value: _id$3++ }); + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== void 0 ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.gpuType = FloatType; + this.version = 0; + } + /** + * A callback function that is executed after the renderer has transferred the attribute + * array data to the GPU. + */ + onUploadCallback() { + } + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) this.version++; + } + /** + * Sets the usage of this buffer attribute. + * + * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. + * @return {BufferAttribute} A reference to this buffer attribute. + */ + setUsage(value) { + this.usage = value; + return this; + } + /** + * Adds a range of data in the data array to be updated on the GPU. + * + * @param {number} start - Position at which to start update. + * @param {number} count - The number of components to update. + */ + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + /** + * Clears the update ranges. + */ + clearUpdateRanges() { + this.updateRanges.length = 0; + } + /** + * Copies the values of the given buffer attribute to this instance. + * + * @param {BufferAttribute} source - The buffer attribute to copy. + * @return {BufferAttribute} A reference to this instance. + */ + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + /** + * Copies a vector from the given buffer attribute to this one. The start + * and destination position in the attribute buffers are represented by the + * given indices. + * + * @param {number} index1 - The destination index into this buffer attribute. + * @param {BufferAttribute} attribute - The buffer attribute to copy from. + * @param {number} index2 - The source index into the given buffer attribute. + * @return {BufferAttribute} A reference to this instance. + */ + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i = 0, l = this.itemSize; i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + /** + * Copies the given array data into this buffer attribute. + * + * @param {(TypedArray|Array)} array - The array to copy. + * @return {BufferAttribute} A reference to this instance. + */ + copyArray(array) { + this.array.set(array); + return this; + } + /** + * Applies the given 3x3 matrix to the given attribute. Works with + * item size `2` and `3`. + * + * @param {Matrix3} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyMatrix3(m) { + if (this.itemSize === 2) { + for (let i = 0, l = this.count; i < l; i++) { + _vector2$1.fromBufferAttribute(this, i); + _vector2$1.applyMatrix3(m); + this.setXY(i, _vector2$1.x, _vector2$1.y); + } + } else if (this.itemSize === 3) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$a.fromBufferAttribute(this, i); + _vector$a.applyMatrix3(m); + this.setXYZ(i, _vector$a.x, _vector$a.y, _vector$a.z); + } + } + return this; + } + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix4} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyMatrix4(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$a.fromBufferAttribute(this, i); + _vector$a.applyMatrix4(m); + this.setXYZ(i, _vector$a.x, _vector$a.y, _vector$a.z); + } + return this; + } + /** + * Applies the given 3x3 normal matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix3} m - The normal matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyNormalMatrix(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$a.fromBufferAttribute(this, i); + _vector$a.applyNormalMatrix(m); + this.setXYZ(i, _vector$a.x, _vector$a.y, _vector$a.z); + } + return this; + } + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3` and with direction vectors. + * + * @param {Matrix4} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + transformDirection(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$a.fromBufferAttribute(this, i); + _vector$a.transformDirection(m); + this.setXYZ(i, _vector$a.x, _vector$a.y, _vector$a.z); + } + return this; + } + /** + * Sets the given array data in the buffer attribute. + * + * @param {(TypedArray|Array)} value - The array data to set. + * @param {number} [offset=0] - The offset in this buffer attribute's array. + * @return {BufferAttribute} A reference to this instance. + */ + set(value, offset = 0) { + this.array.set(value, offset); + return this; + } + /** + * Returns the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @return {number} The returned value. + */ + getComponent(index, component) { + let value = this.array[index * this.itemSize + component]; + if (this.normalized) value = denormalize(value, this.array); + return value; + } + /** + * Sets the given value to the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @param {number} value - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setComponent(index, component, value) { + if (this.normalized) value = normalize(value, this.array); + this.array[index * this.itemSize + component] = value; + return this; + } + /** + * Returns the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The x component. + */ + getX(index) { + let x = this.array[index * this.itemSize]; + if (this.normalized) x = denormalize(x, this.array); + return x; + } + /** + * Sets the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setX(index, x) { + if (this.normalized) x = normalize(x, this.array); + this.array[index * this.itemSize] = x; + return this; + } + /** + * Returns the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The y component. + */ + getY(index) { + let y = this.array[index * this.itemSize + 1]; + if (this.normalized) y = denormalize(y, this.array); + return y; + } + /** + * Sets the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} y - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setY(index, y) { + if (this.normalized) y = normalize(y, this.array); + this.array[index * this.itemSize + 1] = y; + return this; + } + /** + * Returns the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The z component. + */ + getZ(index) { + let z = this.array[index * this.itemSize + 2]; + if (this.normalized) z = denormalize(z, this.array); + return z; + } + /** + * Sets the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} z - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setZ(index, z) { + if (this.normalized) z = normalize(z, this.array); + this.array[index * this.itemSize + 2] = z; + return this; + } + /** + * Returns the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The w component. + */ + getW(index) { + let w = this.array[index * this.itemSize + 3]; + if (this.normalized) w = denormalize(w, this.array); + return w; + } + /** + * Sets the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} w - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setW(index, w) { + if (this.normalized) w = normalize(w, this.array); + this.array[index * this.itemSize + 3] = w; + return this; + } + /** + * Sets the x and y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXY(index, x, y) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + } + this.array[index + 0] = x; + this.array[index + 1] = y; + return this; + } + /** + * Sets the x, y and z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXYZ(index, x, y, z) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + } + this.array[index + 0] = x; + this.array[index + 1] = y; + this.array[index + 2] = z; + return this; + } + /** + * Sets the x, y, z and w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @param {number} w - The value for the w component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXYZW(index, x, y, z, w) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + w = normalize(w, this.array); + } + this.array[index + 0] = x; + this.array[index + 1] = y; + this.array[index + 2] = z; + this.array[index + 3] = w; + return this; + } + /** + * Sets the given callback function that is executed after the Renderer has transferred + * the attribute array data to the GPU. Can be used to perform clean-up operations after + * the upload when attribute data are not needed anymore on the CPU side. + * + * @param {Function} callback - The `onUpload()` callback. + * @return {BufferAttribute} A reference to this instance. + */ + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + /** + * Returns a new buffer attribute with copied values from this instance. + * + * @return {BufferAttribute} A clone of this instance. + */ + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + /** + * Serializes the buffer attribute into JSON. + * + * @return {Object} A JSON object representing the serialized buffer attribute. + */ + toJSON() { + const data = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") data.name = this.name; + if (this.usage !== StaticDrawUsage) data.usage = this.usage; + return data; + } + /** + * Disposes of the buffer attribute. Available only in {@link WebGPURenderer}. + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + } + class Int8BufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Int8Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Int8Array(array), itemSize, normalized); + } + } + class Uint8BufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint8Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Uint8Array(array), itemSize, normalized); + } + } + class Uint8ClampedBufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint8ClampedArray)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Uint8ClampedArray(array), itemSize, normalized); + } + } + class Int16BufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Int16Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Int16Array(array), itemSize, normalized); + } + } + class Uint16BufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint16Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } + } + class Int32BufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Int32Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Int32Array(array), itemSize, normalized); + } + } + class Uint32BufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint32Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } + } + class Float16BufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint16Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + this.isFloat16BufferAttribute = true; + } + getX(index) { + let x = fromHalfFloat(this.array[index * this.itemSize]); + if (this.normalized) x = denormalize(x, this.array); + return x; + } + setX(index, x) { + if (this.normalized) x = normalize(x, this.array); + this.array[index * this.itemSize] = toHalfFloat(x); + return this; + } + getY(index) { + let y = fromHalfFloat(this.array[index * this.itemSize + 1]); + if (this.normalized) y = denormalize(y, this.array); + return y; + } + setY(index, y) { + if (this.normalized) y = normalize(y, this.array); + this.array[index * this.itemSize + 1] = toHalfFloat(y); + return this; + } + getZ(index) { + let z = fromHalfFloat(this.array[index * this.itemSize + 2]); + if (this.normalized) z = denormalize(z, this.array); + return z; + } + setZ(index, z) { + if (this.normalized) z = normalize(z, this.array); + this.array[index * this.itemSize + 2] = toHalfFloat(z); + return this; + } + getW(index) { + let w = fromHalfFloat(this.array[index * this.itemSize + 3]); + if (this.normalized) w = denormalize(w, this.array); + return w; + } + setW(index, w) { + if (this.normalized) w = normalize(w, this.array); + this.array[index * this.itemSize + 3] = toHalfFloat(w); + return this; + } + setXY(index, x, y) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + } + this.array[index + 0] = toHalfFloat(x); + this.array[index + 1] = toHalfFloat(y); + return this; + } + setXYZ(index, x, y, z) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + } + this.array[index + 0] = toHalfFloat(x); + this.array[index + 1] = toHalfFloat(y); + this.array[index + 2] = toHalfFloat(z); + return this; + } + setXYZW(index, x, y, z, w) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + w = normalize(w, this.array); + } + this.array[index + 0] = toHalfFloat(x); + this.array[index + 1] = toHalfFloat(y); + this.array[index + 2] = toHalfFloat(z); + this.array[index + 3] = toHalfFloat(w); + return this; + } + } + class Float32BufferAttribute extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Float32Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } + } + const _box$3 = /* @__PURE__ */ new Box3(); + const _v1$3 = /* @__PURE__ */ new Vector3(); + const _v2$2 = /* @__PURE__ */ new Vector3(); + class Sphere { + /** + * Constructs a new sphere. + * + * @param {Vector3} [center=(0,0,0)] - The center of the sphere + * @param {number} [radius=-1] - The radius of the sphere. + */ + constructor(center = new Vector3(), radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + /** + * Sets the sphere's components by copying the given values. + * + * @param {Vector3} center - The center. + * @param {number} radius - The radius. + * @return {Sphere} A reference to this sphere. + */ + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + /** + * Computes the minimum bounding sphere for list of points. + * If the optional center point is given, it is used as the sphere's + * center. Otherwise, the center of the axis-aligned bounding box + * encompassing the points is calculated. + * + * @param {Array} points - A list of points in 3D space. + * @param {Vector3} [optionalCenter] - The center of the sphere. + * @return {Sphere} A reference to this sphere. + */ + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== void 0) { + center.copy(optionalCenter); + } else { + _box$3.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i = 0, il = points.length; i < il; i++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + /** + * Copies the values of the given sphere to this instance. + * + * @param {Sphere} sphere - The sphere to copy. + * @return {Sphere} A reference to this sphere. + */ + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + /** + * Returns `true` if the sphere is empty (the radius set to a negative number). + * + * Spheres with a radius of `0` contain only their center point and are not + * considered to be empty. + * + * @return {boolean} Whether this sphere is empty or not. + */ + isEmpty() { + return this.radius < 0; + } + /** + * Makes this sphere empty which means in encloses a zero space in 3D. + * + * @return {Sphere} A reference to this sphere. + */ + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + /** + * Returns `true` if this sphere contains the given point inclusive of + * the surface of the sphere. + * + * @param {Vector3} point - The point to check. + * @return {boolean} Whether this sphere contains the given point or not. + */ + containsPoint(point2) { + return point2.distanceToSquared(this.center) <= this.radius * this.radius; + } + /** + * Returns the closest distance from the boundary of the sphere to the + * given point. If the sphere contains the point, the distance will + * be negative. + * + * @param {Vector3} point - The point to compute the distance to. + * @return {number} The distance to the point. + */ + distanceToPoint(point2) { + return point2.distanceTo(this.center) - this.radius; + } + /** + * Returns `true` if this sphere intersects with the given one. + * + * @param {Sphere} sphere - The sphere to test. + * @return {boolean} Whether this sphere intersects with the given one or not. + */ + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + /** + * Returns `true` if this sphere intersects with the given box. + * + * @param {Box3} box - The box to test. + * @return {boolean} Whether this sphere intersects with the given box or not. + */ + intersectsBox(box) { + return box.intersectsSphere(this); + } + /** + * Returns `true` if this sphere intersects with the given plane. + * + * @param {Plane} plane - The plane to test. + * @return {boolean} Whether this sphere intersects with the given plane or not. + */ + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + /** + * Clamps a point within the sphere. If the point is outside the sphere, it + * will clamp it to the closest point on the edge of the sphere. Points + * already inside the sphere will not be affected. + * + * @param {Vector3} point - The plane to clamp. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The clamped point. + */ + clampPoint(point2, target) { + const deltaLengthSq = this.center.distanceToSquared(point2); + target.copy(point2); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + /** + * Returns a bounding box that encloses this sphere. + * + * @param {Box3} target - The target box that is used to store the method's result. + * @return {Box3} The bounding box that encloses this sphere. + */ + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + /** + * Transforms this sphere with the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Sphere} A reference to this sphere. + */ + applyMatrix4(matrix) { + this.center.applyMatrix4(matrix); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + return this; + } + /** + * Translates the sphere's center by the given offset. + * + * @param {Vector3} offset - The offset. + * @return {Sphere} A reference to this sphere. + */ + translate(offset) { + this.center.add(offset); + return this; + } + /** + * Expands the boundaries of this sphere to include the given point. + * + * @param {Vector3} point - The point to include. + * @return {Sphere} A reference to this sphere. + */ + expandByPoint(point2) { + if (this.isEmpty()) { + this.center.copy(point2); + this.radius = 0; + return this; + } + _v1$3.subVectors(point2, this.center); + const lengthSq = _v1$3.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length = Math.sqrt(lengthSq); + const delta = (length - this.radius) * 0.5; + this.center.addScaledVector(_v1$3, delta / length); + this.radius += delta; + } + return this; + } + /** + * Expands this sphere to enclose both the original sphere and the given sphere. + * + * @param {Sphere} sphere - The sphere to include. + * @return {Sphere} A reference to this sphere. + */ + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$2.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$3.copy(sphere.center).add(_v2$2)); + this.expandByPoint(_v1$3.copy(sphere.center).sub(_v2$2)); + } + return this; + } + /** + * Returns `true` if this sphere is equal with the given one. + * + * @param {Sphere} sphere - The sphere to test for equality. + * @return {boolean} Whether this bounding sphere is equal with the given one. + */ + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + /** + * Returns a new sphere with copied values from this instance. + * + * @return {Sphere} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Returns a serialized structure of the bounding sphere. + * + * @return {Object} Serialized structure with fields representing the object state. + */ + toJSON() { + return { + radius: this.radius, + center: this.center.toArray() + }; + } + /** + * Returns a serialized structure of the bounding sphere. + * + * @param {Object} json - The serialized json to set the sphere from. + * @return {Sphere} A reference to this bounding sphere. + */ + fromJSON(json) { + this.radius = json.radius; + this.center.fromArray(json.center); + return this; + } + } + let _id$2 = 0; + const _m1$2 = /* @__PURE__ */ new Matrix4(); + const _obj = /* @__PURE__ */ new Object3D(); + const _offset = /* @__PURE__ */ new Vector3(); + const _box$2 = /* @__PURE__ */ new Box3(); + const _boxMorphTargets = /* @__PURE__ */ new Box3(); + const _vector$9 = /* @__PURE__ */ new Vector3(); + class BufferGeometry extends EventDispatcher { + /** + * Constructs a new geometry. + */ + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$2++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.indirect = null; + this.indirectOffset = 0; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + /** + * Returns the index of this geometry. + * + * @return {?BufferAttribute} The index. Returns `null` if no index is defined. + */ + getIndex() { + return this.index; + } + /** + * Sets the given index to this geometry. + * + * @param {Array|BufferAttribute} index - The index to set. + * @return {BufferGeometry} A reference to this instance. + */ + setIndex(index) { + if (Array.isArray(index)) { + this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1); + } else { + this.index = index; + } + return this; + } + /** + * Sets the given indirect attribute to this geometry. + * + * @param {BufferAttribute} indirect - The attribute holding indirect draw calls. + * @param {number|Array} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset. + * @return {BufferGeometry} A reference to this instance. + */ + setIndirect(indirect, indirectOffset = 0) { + this.indirect = indirect; + this.indirectOffset = indirectOffset; + return this; + } + /** + * Returns the indirect attribute of this geometry. + * + * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined. + */ + getIndirect() { + return this.indirect; + } + /** + * Returns the buffer attribute for the given name. + * + * @param {string} name - The attribute name. + * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute. + * Returns `undefined` if not attribute has been found. + */ + getAttribute(name) { + return this.attributes[name]; + } + /** + * Sets the given attribute for the given name. + * + * @param {string} name - The attribute name. + * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set. + * @return {BufferGeometry} A reference to this instance. + */ + setAttribute(name, attribute) { + this.attributes[name] = attribute; + return this; + } + /** + * Deletes the attribute for the given name. + * + * @param {string} name - The attribute name to delete. + * @return {BufferGeometry} A reference to this instance. + */ + deleteAttribute(name) { + delete this.attributes[name]; + return this; + } + /** + * Returns `true` if this geometry has an attribute for the given name. + * + * @param {string} name - The attribute name. + * @return {boolean} Whether this geometry has an attribute for the given name or not. + */ + hasAttribute(name) { + return this.attributes[name] !== void 0; + } + /** + * Adds a group to this geometry. + * + * @param {number} start - The first element in this draw call. That is the first + * vertex for non-indexed geometry, otherwise the first triangle index. + * @param {number} count - Specifies how many vertices (or indices) are part of this group. + * @param {number} [materialIndex=0] - The material array index to use. + */ + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + /** + * Clears all groups. + */ + clearGroups() { + this.groups = []; + } + /** + * Sets the draw range for this geometry. + * + * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index. + * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render. + * For indexed BufferGeometry, `count` is the number of indices to render. + */ + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + /** + * Applies the given 4x4 transformation matrix to the geometry. + * + * @param {Matrix4} matrix - The matrix to apply. + * @return {BufferGeometry} A reference to this instance. + */ + applyMatrix4(matrix) { + const position = this.attributes.position; + if (position !== void 0) { + position.applyMatrix4(matrix); + position.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== void 0) { + const normalMatrix = new Matrix3().getNormalMatrix(matrix); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== void 0) { + tangent.transformDirection(matrix); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + /** + * Applies the rotation represented by the Quaternion to the geometry. + * + * @param {Quaternion} q - The Quaternion to apply. + * @return {BufferGeometry} A reference to this instance. + */ + applyQuaternion(q) { + _m1$2.makeRotationFromQuaternion(q); + this.applyMatrix4(_m1$2); + return this; + } + /** + * Rotates the geometry about the X axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateX(angle) { + _m1$2.makeRotationX(angle); + this.applyMatrix4(_m1$2); + return this; + } + /** + * Rotates the geometry about the Y axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateY(angle) { + _m1$2.makeRotationY(angle); + this.applyMatrix4(_m1$2); + return this; + } + /** + * Rotates the geometry about the Z axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateZ(angle) { + _m1$2.makeRotationZ(angle); + this.applyMatrix4(_m1$2); + return this; + } + /** + * Translates the geometry. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#position} for typical + * real-time mesh rotation. + * + * @param {number} x - The x offset. + * @param {number} y - The y offset. + * @param {number} z - The z offset. + * @return {BufferGeometry} A reference to this instance. + */ + translate(x, y, z) { + _m1$2.makeTranslation(x, y, z); + this.applyMatrix4(_m1$2); + return this; + } + /** + * Scales the geometry. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#scale} for typical + * real-time mesh rotation. + * + * @param {number} x - The x scale. + * @param {number} y - The y scale. + * @param {number} z - The z scale. + * @return {BufferGeometry} A reference to this instance. + */ + scale(x, y, z) { + _m1$2.makeScale(x, y, z); + this.applyMatrix4(_m1$2); + return this; + } + /** + * Rotates the geometry to face a point in 3D space. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#lookAt} for typical + * real-time mesh rotation. + * + * @param {Vector3} vector - The target point. + * @return {BufferGeometry} A reference to this instance. + */ + lookAt(vector) { + _obj.lookAt(vector); + _obj.updateMatrix(); + this.applyMatrix4(_obj.matrix); + return this; + } + /** + * Center the geometry based on its bounding box. + * + * @return {BufferGeometry} A reference to this instance. + */ + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset).negate(); + this.translate(_offset.x, _offset.y, _offset.z); + return this; + } + /** + * Defines a geometry by creating a `position` attribute based on the given array of points. The array + * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is + * set to `0`. + * + * If the method is used with an existing `position` attribute, the vertex data are overwritten with the + * data from the array. The length of the array must match the vertex count. + * + * @param {Array|Array} points - The points. + * @return {BufferGeometry} A reference to this instance. + */ + setFromPoints(points) { + const positionAttribute = this.getAttribute("position"); + if (positionAttribute === void 0) { + const position = []; + for (let i = 0, l = points.length; i < l; i++) { + const point2 = points[i]; + position.push(point2.x, point2.y, point2.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute(position, 3)); + } else { + const l = Math.min(points.length, positionAttribute.count); + for (let i = 0; i < l; i++) { + const point2 = points[i]; + positionAttribute.setXYZ(i, point2.x, point2.y, point2.z || 0); + } + if (points.length > positionAttribute.count) { + warn("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."); + } + positionAttribute.needsUpdate = true; + } + return this; + } + /** + * Computes the bounding box of the geometry, and updates the `boundingBox` member. + * The bounding box is not computed by the engine; it must be computed by your app. + * You may need to recompute the bounding box if the geometry vertices are modified. + */ + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position && position.isGLBufferAttribute) { + error("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this); + this.boundingBox.set( + new Vector3(-Infinity, -Infinity, -Infinity), + new Vector3(Infinity, Infinity, Infinity) + ); + return; + } + if (position !== void 0) { + this.boundingBox.setFromBufferAttribute(position); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _box$2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$9.addVectors(this.boundingBox.min, _box$2.min); + this.boundingBox.expandByPoint(_vector$9); + _vector$9.addVectors(this.boundingBox.max, _box$2.max); + this.boundingBox.expandByPoint(_vector$9); + } else { + this.boundingBox.expandByPoint(_box$2.min); + this.boundingBox.expandByPoint(_box$2.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + error('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + /** + * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member. + * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. + * You may need to recompute the bounding sphere if the geometry vertices are modified. + */ + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position && position.isGLBufferAttribute) { + error("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this); + this.boundingSphere.set(new Vector3(), Infinity); + return; + } + if (position) { + const center = this.boundingSphere.center; + _box$2.setFromBufferAttribute(position); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _boxMorphTargets.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$9.addVectors(_box$2.min, _boxMorphTargets.min); + _box$2.expandByPoint(_vector$9); + _vector$9.addVectors(_box$2.max, _boxMorphTargets.max); + _box$2.expandByPoint(_vector$9); + } else { + _box$2.expandByPoint(_boxMorphTargets.min); + _box$2.expandByPoint(_boxMorphTargets.max); + } + } + } + _box$2.getCenter(center); + let maxRadiusSq = 0; + for (let i = 0, il = position.count; i < il; i++) { + _vector$9.fromBufferAttribute(position, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$9)); + } + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j = 0, jl = morphAttribute.count; j < jl; j++) { + _vector$9.fromBufferAttribute(morphAttribute, j); + if (morphTargetsRelative) { + _offset.fromBufferAttribute(position, j); + _vector$9.add(_offset); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$9)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + error('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + /** + * Calculates and adds a tangent attribute to this geometry. + * + * The computation is only supported for indexed geometries and if position, normal, and uv attributes + * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by + * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead. + */ + computeTangents() { + const index = this.index; + const attributes = this.attributes; + if (index === null || attributes.position === void 0 || attributes.normal === void 0 || attributes.uv === void 0) { + error("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * positionAttribute.count), 4)); + } + const tangentAttribute = this.getAttribute("tangent"); + const tan1 = [], tan2 = []; + for (let i = 0; i < positionAttribute.count; i++) { + tan1[i] = new Vector3(); + tan2[i] = new Vector3(); + } + const vA = new Vector3(), vB = new Vector3(), vC = new Vector3(), uvA = new Vector2(), uvB = new Vector2(), uvC = new Vector2(), sdir = new Vector3(), tdir = new Vector3(); + function handleTriangle(a, b, c) { + vA.fromBufferAttribute(positionAttribute, a); + vB.fromBufferAttribute(positionAttribute, b); + vC.fromBufferAttribute(positionAttribute, c); + uvA.fromBufferAttribute(uvAttribute, a); + uvB.fromBufferAttribute(uvAttribute, b); + uvC.fromBufferAttribute(uvAttribute, c); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r)) return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); + tan1[a].add(sdir); + tan1[b].add(sdir); + tan1[c].add(sdir); + tan2[a].add(tdir); + tan2[b].add(tdir); + tan2[c].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: index.count + }]; + } + for (let i = 0, il = groups.length; i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count; j < jl; j += 3) { + handleTriangle( + index.getX(j + 0), + index.getX(j + 1), + index.getX(j + 2) + ); + } + } + const tmp3 = new Vector3(), tmp22 = new Vector3(); + const n = new Vector3(), n2 = new Vector3(); + function handleVertex(v) { + n.fromBufferAttribute(normalAttribute, v); + n2.copy(n); + const t = tan1[v]; + tmp3.copy(t); + tmp3.sub(n.multiplyScalar(n.dot(t))).normalize(); + tmp22.crossVectors(n2, t); + const test = tmp22.dot(tan2[v]); + const w = test < 0 ? -1 : 1; + tangentAttribute.setXYZW(v, tmp3.x, tmp3.y, tmp3.z, w); + } + for (let i = 0, il = groups.length; i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count; j < jl; j += 3) { + handleVertex(index.getX(j + 0)); + handleVertex(index.getX(j + 1)); + handleVertex(index.getX(j + 2)); + } + } + } + /** + * Computes vertex normals for the given vertex data. For indexed geometries, the method sets + * each vertex normal to be the average of the face normals of the faces that share that vertex. + * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal + * to be the same as the face normal. + */ + computeVertexNormals() { + const index = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== void 0) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === void 0) { + normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i = 0, il = normalAttribute.count; i < il; i++) { + normalAttribute.setXYZ(i, 0, 0, 0); + } + } + const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); + const cb = new Vector3(), ab = new Vector3(); + if (index) { + for (let i = 0, il = index.count; i < il; i += 3) { + const vA = index.getX(i + 0); + const vB = index.getX(i + 1); + const vC = index.getX(i + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i = 0, il = positionAttribute.count; i < il; i += 3) { + pA.fromBufferAttribute(positionAttribute, i + 0); + pB.fromBufferAttribute(positionAttribute, i + 1); + pC.fromBufferAttribute(positionAttribute, i + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + /** + * Ensures every normal vector in a geometry will have a magnitude of `1`. This will + * correct lighting on the geometry surfaces. + */ + normalizeNormals() { + const normals = this.attributes.normal; + for (let i = 0, il = normals.count; i < il; i++) { + _vector$9.fromBufferAttribute(normals, i); + _vector$9.normalize(); + normals.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + } + /** + * Return a new non-index version of this indexed geometry. If the geometry + * is already non-indexed, the method is a NOOP. + * + * @return {BufferGeometry} The non-indexed version of this indexed geometry. + */ + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index = 0, index2 = 0; + for (let i = 0, l = indices2.length; i < l; i++) { + if (attribute.isInterleavedBufferAttribute) { + index = indices2[i] * attribute.data.stride + attribute.offset; + } else { + index = indices2[i] * itemSize; + } + for (let j = 0; j < itemSize; j++) { + array2[index2++] = array[index++]; + } + } + return new BufferAttribute(array2, itemSize, normalized); + } + if (this.index === null) { + warn("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new BufferGeometry(); + const indices = this.index.array; + const attributes = this.attributes; + for (const name in attributes) { + const attribute = attributes[name]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name]; + for (let i = 0, il = morphAttribute.length; i < il; i++) { + const attribute = morphAttribute[i]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i = 0, l = groups.length; i < l; i++) { + const group = groups[i]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + /** + * Serializes the geometry into JSON. + * + * @return {Object} A JSON object representing the serialized geometry. + */ + toJSON() { + const data = { + metadata: { + version: 4.7, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data.uuid = this.uuid; + data.type = this.type; + if (this.name !== "") data.name = this.name; + if (Object.keys(this.userData).length > 0) data.userData = this.userData; + if (this.parameters !== void 0) { + const parameters = this.parameters; + for (const key in parameters) { + if (parameters[key] !== void 0) data[key] = parameters[key]; + } + return data; + } + data.data = { attributes: {} }; + const index = this.index; + if (index !== null) { + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call(index.array) + }; + } + const attributes = this.attributes; + for (const key in attributes) { + const attribute = attributes[key]; + data.data.attributes[key] = attribute.toJSON(data.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key in this.morphAttributes) { + const attributeArray = this.morphAttributes[key]; + const array = []; + for (let i = 0, il = attributeArray.length; i < il; i++) { + const attribute = attributeArray[i]; + array.push(attribute.toJSON(data.data)); + } + if (array.length > 0) { + morphAttributes[key] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data.data.boundingSphere = boundingSphere.toJSON(); + } + return data; + } + /** + * Returns a new geometry with copied values from this instance. + * + * @return {BufferGeometry} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given geometry to this instance. + * + * @param {BufferGeometry} source - The geometry to copy. + * @return {BufferGeometry} A reference to this instance. + */ + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data = {}; + this.name = source.name; + const index = source.index; + if (index !== null) { + this.setIndex(index.clone()); + } + const attributes = source.attributes; + for (const name in attributes) { + const attribute = attributes[name]; + this.setAttribute(name, attribute.clone(data)); + } + const morphAttributes = source.morphAttributes; + for (const name in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name]; + for (let i = 0, l = morphAttribute.length; i < l; i++) { + array.push(morphAttribute[i].clone(data)); + } + this.morphAttributes[name] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i = 0, l = groups.length; i < l; i++) { + const group = groups[i]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires BufferGeometry#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + } + class InterleavedBuffer { + /** + * Constructs a new interleaved buffer. + * + * @param {TypedArray} array - A typed array with a shared buffer storing attribute data. + * @param {number} stride - The number of typed-array elements per vertex. + */ + constructor(array, stride) { + this.isInterleavedBuffer = true; + this.array = array; + this.stride = stride; + this.count = array !== void 0 ? array.length / stride : 0; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.version = 0; + this.uuid = generateUUID(); + } + /** + * A callback function that is executed after the renderer has transferred the attribute array + * data to the GPU. + */ + onUploadCallback() { + } + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) this.version++; + } + /** + * Sets the usage of this interleaved buffer. + * + * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. + * @return {InterleavedBuffer} A reference to this interleaved buffer. + */ + setUsage(value) { + this.usage = value; + return this; + } + /** + * Adds a range of data in the data array to be updated on the GPU. + * + * @param {number} start - Position at which to start update. + * @param {number} count - The number of components to update. + */ + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + /** + * Clears the update ranges. + */ + clearUpdateRanges() { + this.updateRanges.length = 0; + } + /** + * Copies the values of the given interleaved buffer to this instance. + * + * @param {InterleavedBuffer} source - The interleaved buffer to copy. + * @return {InterleavedBuffer} A reference to this instance. + */ + copy(source) { + this.array = new source.array.constructor(source.array); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + return this; + } + /** + * Copies a vector from the given interleaved buffer to this one. The start + * and destination position in the attribute buffers are represented by the + * given indices. + * + * @param {number} index1 - The destination index into this interleaved buffer. + * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from. + * @param {number} index2 - The source index into the given interleaved buffer. + * @return {InterleavedBuffer} A reference to this instance. + */ + copyAt(index1, interleavedBuffer, index2) { + index1 *= this.stride; + index2 *= interleavedBuffer.stride; + for (let i = 0, l = this.stride; i < l; i++) { + this.array[index1 + i] = interleavedBuffer.array[index2 + i]; + } + return this; + } + /** + * Sets the given array data in the interleaved buffer. + * + * @param {(TypedArray|Array)} value - The array data to set. + * @param {number} [offset=0] - The offset in this interleaved buffer's array. + * @return {InterleavedBuffer} A reference to this instance. + */ + set(value, offset = 0) { + this.array.set(value, offset); + return this; + } + /** + * Returns a new interleaved buffer with copied values from this instance. + * + * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures. + * @return {InterleavedBuffer} A clone of this instance. + */ + clone(data) { + if (data.arrayBuffers === void 0) { + data.arrayBuffers = {}; + } + if (this.array.buffer._uuid === void 0) { + this.array.buffer._uuid = generateUUID(); + } + if (data.arrayBuffers[this.array.buffer._uuid] === void 0) { + data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; + } + const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]); + const ib = new this.constructor(array, this.stride); + ib.setUsage(this.usage); + return ib; + } + /** + * Sets the given callback function that is executed after the Renderer has transferred + * the array data to the GPU. Can be used to perform clean-up operations after + * the upload when data are not needed anymore on the CPU side. + * + * @param {Function} callback - The `onUpload()` callback. + * @return {InterleavedBuffer} A reference to this instance. + */ + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + /** + * Serializes the interleaved buffer into JSON. + * + * @param {Object} [data] - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized interleaved buffer. + */ + toJSON(data) { + if (data.arrayBuffers === void 0) { + data.arrayBuffers = {}; + } + if (this.array.buffer._uuid === void 0) { + this.array.buffer._uuid = generateUUID(); + } + if (data.arrayBuffers[this.array.buffer._uuid] === void 0) { + data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); + } + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + } + } + const _vector$8 = /* @__PURE__ */ new Vector3(); + class InterleavedBufferAttribute { + /** + * Constructs a new interleaved buffer attribute. + * + * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data. + * @param {number} itemSize - The item size. + * @param {number} offset - The attribute offset into the buffer. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(interleavedBuffer, itemSize, offset, normalized = false) { + this.isInterleavedBufferAttribute = true; + this.name = ""; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + this.normalized = normalized; + } + /** + * The item count of this buffer attribute. + * + * @type {number} + * @readonly + */ + get count() { + return this.data.count; + } + /** + * The array holding the interleaved buffer attribute data. + * + * @type {TypedArray} + */ + get array() { + return this.data.array; + } + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + this.data.needsUpdate = value; + } + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix4} m - The matrix to apply. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + applyMatrix4(m) { + for (let i = 0, l = this.data.count; i < l; i++) { + _vector$8.fromBufferAttribute(this, i); + _vector$8.applyMatrix4(m); + this.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); + } + return this; + } + /** + * Applies the given 3x3 normal matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix3} m - The normal matrix to apply. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + applyNormalMatrix(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$8.fromBufferAttribute(this, i); + _vector$8.applyNormalMatrix(m); + this.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); + } + return this; + } + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3` and with direction vectors. + * + * @param {Matrix4} m - The matrix to apply. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + transformDirection(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$8.fromBufferAttribute(this, i); + _vector$8.transformDirection(m); + this.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); + } + return this; + } + /** + * Returns the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @return {number} The returned value. + */ + getComponent(index, component) { + let value = this.array[index * this.data.stride + this.offset + component]; + if (this.normalized) value = denormalize(value, this.array); + return value; + } + /** + * Sets the given value to the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @param {number} value - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setComponent(index, component, value) { + if (this.normalized) value = normalize(value, this.array); + this.data.array[index * this.data.stride + this.offset + component] = value; + return this; + } + /** + * Sets the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setX(index, x) { + if (this.normalized) x = normalize(x, this.array); + this.data.array[index * this.data.stride + this.offset] = x; + return this; + } + /** + * Sets the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} y - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setY(index, y) { + if (this.normalized) y = normalize(y, this.array); + this.data.array[index * this.data.stride + this.offset + 1] = y; + return this; + } + /** + * Sets the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} z - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setZ(index, z) { + if (this.normalized) z = normalize(z, this.array); + this.data.array[index * this.data.stride + this.offset + 2] = z; + return this; + } + /** + * Sets the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} w - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setW(index, w) { + if (this.normalized) w = normalize(w, this.array); + this.data.array[index * this.data.stride + this.offset + 3] = w; + return this; + } + /** + * Returns the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The x component. + */ + getX(index) { + let x = this.data.array[index * this.data.stride + this.offset]; + if (this.normalized) x = denormalize(x, this.array); + return x; + } + /** + * Returns the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The y component. + */ + getY(index) { + let y = this.data.array[index * this.data.stride + this.offset + 1]; + if (this.normalized) y = denormalize(y, this.array); + return y; + } + /** + * Returns the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The z component. + */ + getZ(index) { + let z = this.data.array[index * this.data.stride + this.offset + 2]; + if (this.normalized) z = denormalize(z, this.array); + return z; + } + /** + * Returns the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The w component. + */ + getW(index) { + let w = this.data.array[index * this.data.stride + this.offset + 3]; + if (this.normalized) w = denormalize(w, this.array); + return w; + } + /** + * Sets the x and y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setXY(index, x, y) { + index = index * this.data.stride + this.offset; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + } + this.data.array[index + 0] = x; + this.data.array[index + 1] = y; + return this; + } + /** + * Sets the x, y and z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setXYZ(index, x, y, z) { + index = index * this.data.stride + this.offset; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + } + this.data.array[index + 0] = x; + this.data.array[index + 1] = y; + this.data.array[index + 2] = z; + return this; + } + /** + * Sets the x, y, z and w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @param {number} w - The value for the w component to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setXYZW(index, x, y, z, w) { + index = index * this.data.stride + this.offset; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + w = normalize(w, this.array); + } + this.data.array[index + 0] = x; + this.data.array[index + 1] = y; + this.data.array[index + 2] = z; + this.data.array[index + 3] = w; + return this; + } + /** + * Returns a new buffer attribute with copied values from this instance. + * + * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data. + * + * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property. + * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance. + */ + clone(data) { + if (data === void 0) { + log("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0; i < this.count; i++) { + const index = i * this.data.stride + this.offset; + for (let j = 0; j < this.itemSize; j++) { + array.push(this.data.array[index + j]); + } + } + return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized); + } else { + if (data.interleavedBuffers === void 0) { + data.interleavedBuffers = {}; + } + if (data.interleavedBuffers[this.data.uuid] === void 0) { + data.interleavedBuffers[this.data.uuid] = this.data.clone(data); + } + return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); + } + } + /** + * Serializes the buffer attribute into JSON. + * + * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data. + * + * @param {Object} [data] - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized buffer attribute. + */ + toJSON(data) { + if (data === void 0) { + log("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0; i < this.count; i++) { + const index = i * this.data.stride + this.offset; + for (let j = 0; j < this.itemSize; j++) { + array.push(this.data.array[index + j]); + } + } + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array, + normalized: this.normalized + }; + } else { + if (data.interleavedBuffers === void 0) { + data.interleavedBuffers = {}; + } + if (data.interleavedBuffers[this.data.uuid] === void 0) { + data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data); + } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } + } + } + let _materialId = 0; + class Material extends EventDispatcher { + /** + * Constructs a new material. + */ + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.allowOverride = true; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + /** + * Sets the alpha value to be used when running an alpha test. The material + * will not be rendered if the opacity is lower than this value. + * + * @type {number} + * @readonly + * @default 0 + */ + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value) { + if (this._alphaTest > 0 !== value > 0) { + this.version++; + } + this._alphaTest = value; + } + /** + * An optional callback that is executed immediately before the material is used to render a 3D object. + * + * This method can only be used when rendering with {@link WebGLRenderer}. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {Scene} scene - The scene. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Object3D} object - The 3D object. + * @param {Object} group - The geometry group data. + */ + onBeforeRender() { + } + /** + * An optional callback that is executed immediately before the shader + * program is compiled. This function is called with the shader source code + * as a parameter. Useful for the modification of built-in materials. + * + * This method can only be used when rendering with {@link WebGLRenderer}. The + * recommended approach when customizing materials is to use `WebGPURenderer` with the new + * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language). + * + * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source. + * @param {WebGLRenderer} renderer - A reference to the renderer. + */ + onBeforeCompile() { + } + /** + * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify + * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached + * shader or recompile the shader for this material as needed. + * + * This method can only be used when rendering with {@link WebGLRenderer}. + * + * @return {string} The custom program cache key. + */ + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + /** + * This method can be used to set default values from parameter objects. + * It is a generic implementation so it can be used with different types + * of materials. + * + * @param {Object} [values] - The material values to set. + */ + setValues(values) { + if (values === void 0) return; + for (const key in values) { + const newValue = values[key]; + if (newValue === void 0) { + warn(`Material: parameter '${key}' has value of undefined.`); + continue; + } + const currentValue = this[key]; + if (currentValue === void 0) { + warn(`Material: '${key}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key] = newValue; + } + } + } + /** + * Serializes the material into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized material. + * @see {@link ObjectLoader#parse} + */ + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (isRootObject) { + meta = { + textures: {}, + images: {} + }; + } + const data = { + metadata: { + version: 4.7, + type: "Material", + generator: "Material.toJSON" + } + }; + data.uuid = this.uuid; + data.type = this.type; + if (this.name !== "") data.name = this.name; + if (this.color && this.color.isColor) data.color = this.color.getHex(); + if (this.roughness !== void 0) data.roughness = this.roughness; + if (this.metalness !== void 0) data.metalness = this.metalness; + if (this.sheen !== void 0) data.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== void 0) data.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex(); + if (this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) data.specular = this.specular.getHex(); + if (this.specularIntensity !== void 0) data.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex(); + if (this.shininess !== void 0) data.shininess = this.shininess; + if (this.clearcoat !== void 0) data.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== void 0) data.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.sheenColorMap && this.sheenColorMap.isTexture) { + data.sheenColorMap = this.sheenColorMap.toJSON(meta).uuid; + } + if (this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture) { + data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON(meta).uuid; + } + if (this.dispersion !== void 0) data.dispersion = this.dispersion; + if (this.iridescence !== void 0) data.iridescence = this.iridescence; + if (this.iridescenceIOR !== void 0) data.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== void 0) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; + } + if (this.anisotropy !== void 0) data.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== void 0) data.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data.anisotropyMap = this.anisotropyMap.toJSON(meta).uuid; + } + if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid; + if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid; + if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data.lightMap = this.lightMap.toJSON(meta).uuid; + data.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data.aoMap = this.aoMap.toJSON(meta).uuid; + data.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data.bumpMap = this.bumpMap.toJSON(meta).uuid; + data.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data.normalMap = this.normalMap.toJSON(meta).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data.displacementMap = this.displacementMap.toJSON(meta).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid; + if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid; + if (this.envMap && this.envMap.isTexture) { + data.envMap = this.envMap.toJSON(meta).uuid; + if (this.combine !== void 0) data.combine = this.combine; + } + if (this.envMapRotation !== void 0) data.envMapRotation = this.envMapRotation.toArray(); + if (this.envMapIntensity !== void 0) data.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== void 0) data.reflectivity = this.reflectivity; + if (this.refractionRatio !== void 0) data.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data.gradientMap = this.gradientMap.toJSON(meta).uuid; + } + if (this.transmission !== void 0) data.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid; + if (this.thickness !== void 0) data.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid; + if (this.attenuationDistance !== void 0 && this.attenuationDistance !== Infinity) data.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== void 0) data.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== void 0) data.size = this.size; + if (this.shadowSide !== null) data.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== void 0) data.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending) data.blending = this.blending; + if (this.side !== FrontSide) data.side = this.side; + if (this.vertexColors === true) data.vertexColors = true; + if (this.opacity < 1) data.opacity = this.opacity; + if (this.transparent === true) data.transparent = true; + if (this.blendSrc !== SrcAlphaFactor) data.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor) data.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation) data.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) data.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) data.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) data.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) data.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) data.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth) data.depthFunc = this.depthFunc; + if (this.depthTest === false) data.depthTest = this.depthTest; + if (this.depthWrite === false) data.depthWrite = this.depthWrite; + if (this.colorWrite === false) data.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) data.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc) data.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) data.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) data.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp) data.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp) data.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp) data.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) data.stencilWrite = this.stencilWrite; + if (this.rotation !== void 0 && this.rotation !== 0) data.rotation = this.rotation; + if (this.polygonOffset === true) data.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== void 0 && this.linewidth !== 1) data.linewidth = this.linewidth; + if (this.dashSize !== void 0) data.dashSize = this.dashSize; + if (this.gapSize !== void 0) data.gapSize = this.gapSize; + if (this.scale !== void 0) data.scale = this.scale; + if (this.dithering === true) data.dithering = true; + if (this.alphaTest > 0) data.alphaTest = this.alphaTest; + if (this.alphaHash === true) data.alphaHash = true; + if (this.alphaToCoverage === true) data.alphaToCoverage = true; + if (this.premultipliedAlpha === true) data.premultipliedAlpha = true; + if (this.forceSinglePass === true) data.forceSinglePass = true; + if (this.allowOverride === false) data.allowOverride = false; + if (this.wireframe === true) data.wireframe = true; + if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") data.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") data.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) data.flatShading = true; + if (this.visible === false) data.visible = false; + if (this.toneMapped === false) data.toneMapped = false; + if (this.fog === false) data.fog = false; + if (Object.keys(this.userData).length > 0) data.userData = this.userData; + function extractFromCache(cache) { + const values = []; + for (const key in cache) { + const data2 = cache[key]; + delete data2.metadata; + values.push(data2); + } + return values; + } + if (isRootObject) { + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + if (textures.length > 0) data.textures = textures; + if (images.length > 0) data.images = images; + } + return data; + } + /** + * Returns a new material with copied values from this instance. + * + * @return {Material} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given material to this instance. + * + * @param {Material} source - The material to copy. + * @return {Material} A reference to this instance. + */ + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n = srcPlanes.length; + dstPlanes = new Array(n); + for (let i = 0; i !== n; ++i) { + dstPlanes[i] = srcPlanes[i].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.allowOverride = source.allowOverride; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires Material#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + /** + * Setting this property to `true` indicates the engine the material + * needs to be recompiled. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) this.version++; + } + } + class SpriteMaterial extends Material { + /** + * Constructs a new sprite material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isSpriteMaterial = true; + this.type = "SpriteMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.rotation = 0; + this.sizeAttenuation = true; + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.rotation = source.rotation; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + } + let _geometry; + const _intersectPoint = /* @__PURE__ */ new Vector3(); + const _worldScale = /* @__PURE__ */ new Vector3(); + const _mvPosition = /* @__PURE__ */ new Vector3(); + const _alignedPosition = /* @__PURE__ */ new Vector2(); + const _rotatedPosition = /* @__PURE__ */ new Vector2(); + const _viewWorldMatrix = /* @__PURE__ */ new Matrix4(); + const _vA$1 = /* @__PURE__ */ new Vector3(); + const _vB$1 = /* @__PURE__ */ new Vector3(); + const _vC$1 = /* @__PURE__ */ new Vector3(); + const _uvA = /* @__PURE__ */ new Vector2(); + const _uvB = /* @__PURE__ */ new Vector2(); + const _uvC = /* @__PURE__ */ new Vector2(); + class Sprite extends Object3D { + /** + * Constructs a new sprite. + * + * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material. + */ + constructor(material = new SpriteMaterial()) { + super(); + this.isSprite = true; + this.type = "Sprite"; + if (_geometry === void 0) { + _geometry = new BufferGeometry(); + const float32Array = new Float32Array([ + -0.5, + -0.5, + 0, + 0, + 0, + 0.5, + -0.5, + 0, + 1, + 0, + 0.5, + 0.5, + 0, + 1, + 1, + -0.5, + 0.5, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer(float32Array, 5); + _geometry.setIndex([0, 1, 2, 0, 2, 3]); + _geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); + _geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); + } + this.geometry = _geometry; + this.material = material; + this.center = new Vector2(0.5, 0.5); + this.count = 1; + } + /** + * Computes intersection points between a casted ray and this sprite. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast(raycaster, intersects2) { + if (raycaster.camera === null) { + error('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'); + } + _worldScale.setFromMatrixScale(this.matrixWorld); + _viewWorldMatrix.copy(raycaster.camera.matrixWorld); + this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld); + _mvPosition.setFromMatrixPosition(this.modelViewMatrix); + if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) { + _worldScale.multiplyScalar(-_mvPosition.z); + } + const rotation = this.material.rotation; + let sin, cos; + if (rotation !== 0) { + cos = Math.cos(rotation); + sin = Math.sin(rotation); + } + const center = this.center; + transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvA.set(0, 0); + _uvB.set(1, 0); + _uvC.set(1, 1); + let intersect2 = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint); + if (intersect2 === null) { + transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvB.set(0, 1); + intersect2 = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint); + if (intersect2 === null) { + return; + } + } + const distance = raycaster.ray.origin.distanceTo(_intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) return; + intersects2.push({ + distance, + point: _intersectPoint.clone(), + uv: Triangle.getInterpolation(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA, _uvB, _uvC, new Vector2()), + face: null, + object: this + }); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.center !== void 0) this.center.copy(source.center); + this.material = source.material; + return this; + } + } + function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) { + _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); + if (sin !== void 0) { + _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y; + _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y; + } else { + _rotatedPosition.copy(_alignedPosition); + } + vertexPosition.copy(mvPosition); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + vertexPosition.applyMatrix4(_viewWorldMatrix); + } + const _v1$2 = /* @__PURE__ */ new Vector3(); + const _v2$1 = /* @__PURE__ */ new Vector3(); + class LOD extends Object3D { + /** + * Constructs a new LOD. + */ + constructor() { + super(); + this.isLOD = true; + this._currentLevel = 0; + this.type = "LOD"; + Object.defineProperties(this, { + /** + * This array holds the LOD levels. + * + * @name LOD#levels + * @type {Array<{object:Object3D,distance:number,hysteresis:number}>} + */ + levels: { + enumerable: true, + value: [] + } + }); + this.autoUpdate = true; + } + copy(source) { + super.copy(source, false); + const levels = source.levels; + for (let i = 0, l = levels.length; i < l; i++) { + const level = levels[i]; + this.addLevel(level.object.clone(), level.distance, level.hysteresis); + } + this.autoUpdate = source.autoUpdate; + return this; + } + /** + * Adds a mesh that will display at a certain distance and greater. Typically + * the further away the distance, the lower the detail on the mesh. + * + * @param {Object3D} object - The 3D object to display at this level. + * @param {number} [distance=0] - The distance at which to display this level of detail. + * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance. + * @return {LOD} A reference to this instance. + */ + addLevel(object, distance = 0, hysteresis = 0) { + distance = Math.abs(distance); + const levels = this.levels; + let l; + for (l = 0; l < levels.length; l++) { + if (distance < levels[l].distance) { + break; + } + } + levels.splice(l, 0, { distance, hysteresis, object }); + this.add(object); + return this; + } + /** + * Removes an existing level, based on the distance from the camera. + * Returns `true` when the level has been removed. Otherwise `false`. + * + * @param {number} distance - Distance of the level to remove. + * @return {boolean} Whether the level has been removed or not. + */ + removeLevel(distance) { + const levels = this.levels; + for (let i = 0; i < levels.length; i++) { + if (levels[i].distance === distance) { + const removedElements = levels.splice(i, 1); + this.remove(removedElements[0].object); + return true; + } + } + return false; + } + /** + * Returns the currently active LOD level index. + * + * @return {number} The current active LOD level index. + */ + getCurrentLevel() { + return this._currentLevel; + } + /** + * Returns a reference to the first 3D object that is greater than + * the given distance. + * + * @param {number} distance - The LOD distance. + * @return {?Object3D} The found 3D object. `null` if no 3D object has been found. + */ + getObjectForDistance(distance) { + const levels = this.levels; + if (levels.length > 0) { + let i, l; + for (i = 1, l = levels.length; i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance < levelDistance) { + break; + } + } + return levels[i - 1].object; + } + return null; + } + /** + * Computes intersection points between a casted ray and this LOD. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast(raycaster, intersects2) { + const levels = this.levels; + if (levels.length > 0) { + _v1$2.setFromMatrixPosition(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_v1$2); + this.getObjectForDistance(distance).raycast(raycaster, intersects2); + } + } + /** + * Updates the LOD by computing which LOD level should be visible according + * to the current distance of the given camera. + * + * @param {Camera} camera - The camera the scene is rendered with. + */ + update(camera) { + const levels = this.levels; + if (levels.length > 1) { + _v1$2.setFromMatrixPosition(camera.matrixWorld); + _v2$1.setFromMatrixPosition(this.matrixWorld); + const distance = _v1$2.distanceTo(_v2$1) / camera.zoom; + levels[0].object.visible = true; + let i, l; + for (i = 1, l = levels.length; i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance >= levelDistance) { + levels[i - 1].object.visible = false; + levels[i].object.visible = true; + } else { + break; + } + } + this._currentLevel = i - 1; + for (; i < l; i++) { + levels[i].object.visible = false; + } + } + } + toJSON(meta) { + const data = super.toJSON(meta); + if (this.autoUpdate === false) data.object.autoUpdate = false; + data.object.levels = []; + const levels = this.levels; + for (let i = 0, l = levels.length; i < l; i++) { + const level = levels[i]; + data.object.levels.push({ + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + }); + } + return data; + } + } + const _vector$7 = /* @__PURE__ */ new Vector3(); + const _segCenter = /* @__PURE__ */ new Vector3(); + const _segDir = /* @__PURE__ */ new Vector3(); + const _diff = /* @__PURE__ */ new Vector3(); + const _edge1 = /* @__PURE__ */ new Vector3(); + const _edge2 = /* @__PURE__ */ new Vector3(); + const _normal$1 = /* @__PURE__ */ new Vector3(); + class Ray { + /** + * Constructs a new ray. + * + * @param {Vector3} [origin=(0,0,0)] - The origin of the ray. + * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray. + */ + constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + /** + * Sets the ray's components by copying the given values. + * + * @param {Vector3} origin - The origin. + * @param {Vector3} direction - The direction. + * @return {Ray} A reference to this ray. + */ + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + /** + * Copies the values of the given ray to this instance. + * + * @param {Ray} ray - The ray to copy. + * @return {Ray} A reference to this ray. + */ + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + /** + * Returns a vector that is located at a given distance along this ray. + * + * @param {number} t - The distance along the ray to retrieve a position for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} A position on the ray. + */ + at(t, target) { + return target.copy(this.origin).addScaledVector(this.direction, t); + } + /** + * Adjusts the direction of the ray to point at the given vector in world space. + * + * @param {Vector3} v - The target position. + * @return {Ray} A reference to this ray. + */ + lookAt(v) { + this.direction.copy(v).sub(this.origin).normalize(); + return this; + } + /** + * Shift the origin of this ray along its direction by the given distance. + * + * @param {number} t - The distance along the ray to interpolate. + * @return {Ray} A reference to this ray. + */ + recast(t) { + this.origin.copy(this.at(t, _vector$7)); + return this; + } + /** + * Returns the point along this ray that is closest to the given point. + * + * @param {Vector3} point - A point in 3D space to get the closet location on the ray for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The closest point on this ray. + */ + closestPointToPoint(point2, target) { + target.subVectors(point2, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + /** + * Returns the distance of the closest approach between this ray and the given point. + * + * @param {Vector3} point - A point in 3D space to compute the distance to. + * @return {number} The distance. + */ + distanceToPoint(point2) { + return Math.sqrt(this.distanceSqToPoint(point2)); + } + /** + * Returns the squared distance of the closest approach between this ray and the given point. + * + * @param {Vector3} point - A point in 3D space to compute the distance to. + * @return {number} The squared distance. + */ + distanceSqToPoint(point2) { + const directionDistance = _vector$7.subVectors(point2, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point2); + } + _vector$7.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$7.distanceToSquared(point2); + } + /** + * Returns the squared distance between this ray and the given line segment. + * + * @param {Vector3} v0 - The start point of the line segment. + * @param {Vector3} v1 - The end point of the line segment. + * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment. + * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray. + * @return {number} The squared distance. + */ + distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { + _segCenter.copy(v0).add(v1).multiplyScalar(0.5); + _segDir.copy(v1).sub(v0).normalize(); + _diff.copy(this.origin).sub(_segCenter); + const segExtent = v0.distanceTo(v1) * 0.5; + const a01 = -this.direction.dot(_segDir); + const b0 = _diff.dot(this.direction); + const b1 = -_diff.dot(_segDir); + const c = _diff.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter).addScaledVector(_segDir, s1); + } + return sqrDist; + } + /** + * Intersects this ray with the given sphere, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Sphere} sphere - The sphere to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectSphere(sphere, target) { + _vector$7.subVectors(sphere.center, this.origin); + const tca = _vector$7.dot(this.direction); + const d2 = _vector$7.dot(_vector$7) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d2 > radius2) return null; + const thc = Math.sqrt(radius2 - d2); + const t0 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) return null; + if (t0 < 0) return this.at(t1, target); + return this.at(t0, target); + } + /** + * Returns `true` if this ray intersects with the given sphere. + * + * @param {Sphere} sphere - The sphere to intersect. + * @return {boolean} Whether this ray intersects with the given sphere or not. + */ + intersectsSphere(sphere) { + if (sphere.radius < 0) return false; + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + /** + * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray + * does not intersect with the plane. + * + * @param {Plane} plane - The plane to compute the distance to. + * @return {?number} Whether this ray intersects with the given sphere or not. + */ + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t >= 0 ? t : null; + } + /** + * Intersects this ray with the given plane, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Plane} plane - The plane to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectPlane(plane, target) { + const t = this.distanceToPlane(plane); + if (t === null) { + return null; + } + return this.at(t, target); + } + /** + * Returns `true` if this ray intersects with the given plane. + * + * @param {Plane} plane - The plane to intersect. + * @return {boolean} Whether this ray intersects with the given plane or not. + */ + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + /** + * Intersects this ray with the given bounding box, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Box3} box - The box to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) return null; + if (tymin > tmin || isNaN(tmin)) tmin = tymin; + if (tymax < tmax || isNaN(tmax)) tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) return null; + if (tzmin > tmin || tmin !== tmin) tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) tmax = tzmax; + if (tmax < 0) return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + /** + * Returns `true` if this ray intersects with the given box. + * + * @param {Box3} box - The box to intersect. + * @return {boolean} Whether this ray intersects with the given box or not. + */ + intersectsBox(box) { + return this.intersectBox(box, _vector$7) !== null; + } + /** + * Intersects this ray with the given triangle, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Vector3} a - The first vertex of the triangle. + * @param {Vector3} b - The second vertex of the triangle. + * @param {Vector3} c - The third vertex of the triangle. + * @param {boolean} backfaceCulling - Whether to use backface culling or not. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectTriangle(a, b, c, backfaceCulling, target) { + _edge1.subVectors(b, a); + _edge2.subVectors(c, a); + _normal$1.crossVectors(_edge1, _edge2); + let DdN = this.direction.dot(_normal$1); + let sign2; + if (DdN > 0) { + if (backfaceCulling) return null; + sign2 = 1; + } else if (DdN < 0) { + sign2 = -1; + DdN = -DdN; + } else { + return null; + } + _diff.subVectors(this.origin, a); + const DdQxE2 = sign2 * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign2 * this.direction.dot(_edge1.cross(_diff)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign2 * _diff.dot(_normal$1); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + /** + * Transforms this ray with the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix4 - The transformation matrix. + * @return {Ray} A reference to this ray. + */ + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + /** + * Returns `true` if this ray is equal with the given one. + * + * @param {Ray} ray - The ray to test for equality. + * @return {boolean} Whether this ray is equal with the given one. + */ + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + /** + * Returns a new ray with copied values from this instance. + * + * @return {Ray} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + } + class MeshBasicMaterial extends Material { + /** + * Constructs a new mesh basic material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler(); + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + } + const _inverseMatrix$3 = /* @__PURE__ */ new Matrix4(); + const _ray$3 = /* @__PURE__ */ new Ray(); + const _sphere$6 = /* @__PURE__ */ new Sphere(); + const _sphereHitAt = /* @__PURE__ */ new Vector3(); + const _vA = /* @__PURE__ */ new Vector3(); + const _vB = /* @__PURE__ */ new Vector3(); + const _vC = /* @__PURE__ */ new Vector3(); + const _tempA = /* @__PURE__ */ new Vector3(); + const _morphA = /* @__PURE__ */ new Vector3(); + const _intersectionPoint = /* @__PURE__ */ new Vector3(); + const _intersectionPointWorld = /* @__PURE__ */ new Vector3(); + class Mesh extends Object3D { + /** + * Constructs a new mesh. + * + * @param {BufferGeometry} [geometry] - The mesh geometry. + * @param {Material|Array} [material] - The mesh material. + */ + constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.morphTargetDictionary = void 0; + this.morphTargetInfluences = void 0; + this.count = 1; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== void 0) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== void 0) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + /** + * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences} + * to make sure existing morph targets can influence this 3D object. + */ + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys(morphAttributes); + if (keys.length > 0) { + const morphAttribute = morphAttributes[keys[0]]; + if (morphAttribute !== void 0) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length; m < ml; m++) { + const name = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name] = m; + } + } + } + } + /** + * Returns the local-space position of the vertex at the given index, taking into + * account the current animation state of both morph targets and skinning. + * + * @param {number} index - The vertex index. + * @param {Vector3} target - The target object that is used to store the method's result. + * @return {Vector3} The vertex position in local space. + */ + getVertexPosition(index, target) { + const geometry = this.geometry; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position, index); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA.set(0, 0, 0); + for (let i = 0, il = morphPosition.length; i < il; i++) { + const influence = morphInfluences[i]; + const morphAttribute = morphPosition[i]; + if (influence === 0) continue; + _tempA.fromBufferAttribute(morphAttribute, index); + if (morphTargetsRelative) { + _morphA.addScaledVector(_tempA, influence); + } else { + _morphA.addScaledVector(_tempA.sub(target), influence); + } + } + target.add(_morphA); + } + return target; + } + /** + * Computes intersection points between a casted ray and this line. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast(raycaster, intersects2) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === void 0) return; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere$6.copy(geometry.boundingSphere); + _sphere$6.applyMatrix4(matrixWorld); + _ray$3.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$6.containsPoint(_ray$3.origin) === false) { + if (_ray$3.intersectSphere(_sphere$6, _sphereHitAt) === null) return; + if (_ray$3.origin.distanceToSquared(_sphereHitAt) > (raycaster.far - raycaster.near) ** 2) return; + } + _inverseMatrix$3.copy(matrixWorld).invert(); + _ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3); + if (geometry.boundingBox !== null) { + if (_ray$3.intersectsBox(geometry.boundingBox) === false) return; + } + this._computeIntersections(raycaster, intersects2, _ray$3); + } + _computeIntersections(raycaster, intersects2, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index = geometry.index; + const position = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index !== null) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length; i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end; j < jl; j += 3) { + const a = index.getX(j); + const b = index.getX(j + 1); + const c = index.getX(j + 2); + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects2.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index.count, drawRange.start + drawRange.count); + for (let i = start, il = end; i < il; i += 3) { + const a = index.getX(i); + const b = index.getX(i + 1); + const c = index.getX(i + 2); + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects2.push(intersection); + } + } + } + } else if (position !== void 0) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length; i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end; j < jl; j += 3) { + const a = j; + const b = j + 1; + const c = j + 2; + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects2.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position.count, drawRange.start + drawRange.count); + for (let i = start, il = end; i < il; i += 3) { + const a = i; + const b = i + 1; + const c = i + 2; + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects2.push(intersection); + } + } + } + } + } + } + function checkIntersection$1(object, material, raycaster, ray, pA, pB, pC, point2) { + let intersect2; + if (material.side === BackSide) { + intersect2 = ray.intersectTriangle(pC, pB, pA, true, point2); + } else { + intersect2 = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point2); + } + if (intersect2 === null) return null; + _intersectionPointWorld.copy(point2); + _intersectionPointWorld.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld); + if (distance < raycaster.near || distance > raycaster.far) return null; + return { + distance, + point: _intersectionPointWorld.clone(), + object + }; + } + function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a, b, c) { + object.getVertexPosition(a, _vA); + object.getVertexPosition(b, _vB); + object.getVertexPosition(c, _vC); + const intersection = checkIntersection$1(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint); + if (intersection) { + const barycoord = new Vector3(); + Triangle.getBarycoord(_intersectionPoint, _vA, _vB, _vC, barycoord); + if (uv) { + intersection.uv = Triangle.getInterpolatedAttribute(uv, a, b, c, barycoord, new Vector2()); + } + if (uv1) { + intersection.uv1 = Triangle.getInterpolatedAttribute(uv1, a, b, c, barycoord, new Vector2()); + } + if (normal) { + intersection.normal = Triangle.getInterpolatedAttribute(normal, a, b, c, barycoord, new Vector3()); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face2 = { + a, + b, + c, + normal: new Vector3(), + materialIndex: 0 + }; + Triangle.getNormal(_vA, _vB, _vC, face2.normal); + intersection.face = face2; + intersection.barycoord = barycoord; + } + return intersection; + } + const _baseVector = /* @__PURE__ */ new Vector4(); + const _skinIndex = /* @__PURE__ */ new Vector4(); + const _skinWeight = /* @__PURE__ */ new Vector4(); + const _vector4 = /* @__PURE__ */ new Vector4(); + const _matrix4 = /* @__PURE__ */ new Matrix4(); + const _vertex = /* @__PURE__ */ new Vector3(); + const _sphere$5 = /* @__PURE__ */ new Sphere(); + const _inverseMatrix$2 = /* @__PURE__ */ new Matrix4(); + const _ray$2 = /* @__PURE__ */ new Ray(); + class SkinnedMesh extends Mesh { + /** + * Constructs a new skinned mesh. + * + * @param {BufferGeometry} [geometry] - The mesh geometry. + * @param {Material|Array} [material] - The mesh material. + */ + constructor(geometry, material) { + super(geometry, material); + this.isSkinnedMesh = true; + this.type = "SkinnedMesh"; + this.bindMode = AttachedBindMode; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); + this.boundingBox = null; + this.boundingSphere = null; + } + /** + * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}. + * The bounding box is not automatically computed by the engine; this method must be called by your app. + * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect + * the current animation state. + */ + computeBoundingBox() { + const geometry = this.geometry; + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + this.boundingBox.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0; i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingBox.expandByPoint(_vertex); + } + } + /** + * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}. + * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting + * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed + * per frame in order to reflect the current animation state. + */ + computeBoundingSphere() { + const geometry = this.geometry; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + this.boundingSphere.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0; i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingSphere.expandByPoint(_vertex); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.bindMode = source.bindMode; + this.bindMatrix.copy(source.bindMatrix); + this.bindMatrixInverse.copy(source.bindMatrixInverse); + this.skeleton = source.skeleton; + if (source.boundingBox !== null) this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) this.boundingSphere = source.boundingSphere.clone(); + return this; + } + raycast(raycaster, intersects2) { + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === void 0) return; + if (this.boundingSphere === null) this.computeBoundingSphere(); + _sphere$5.copy(this.boundingSphere); + _sphere$5.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$5) === false) return; + _inverseMatrix$2.copy(matrixWorld).invert(); + _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); + if (this.boundingBox !== null) { + if (_ray$2.intersectsBox(this.boundingBox) === false) return; + } + this._computeIntersections(raycaster, intersects2, _ray$2); + } + getVertexPosition(index, target) { + super.getVertexPosition(index, target); + this.applyBoneTransform(index, target); + return target; + } + /** + * Binds the given skeleton to the skinned mesh. + * + * @param {Skeleton} skeleton - The skeleton to bind. + * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided, + * the skinned mesh's world matrix will be used instead. + */ + bind(skeleton, bindMatrix) { + this.skeleton = skeleton; + if (bindMatrix === void 0) { + this.updateMatrixWorld(true); + this.skeleton.calculateInverses(); + bindMatrix = this.matrixWorld; + } + this.bindMatrix.copy(bindMatrix); + this.bindMatrixInverse.copy(bindMatrix).invert(); + } + /** + * This method sets the skinned mesh in the rest pose). + */ + pose() { + this.skeleton.pose(); + } + /** + * Normalizes the skin weights which are defined as a buffer attribute + * in the skinned mesh's geometry. + */ + normalizeSkinWeights() { + const vector = new Vector4(); + const skinWeight = this.geometry.attributes.skinWeight; + for (let i = 0, l = skinWeight.count; i < l; i++) { + vector.fromBufferAttribute(skinWeight, i); + const scale = 1 / vector.manhattanLength(); + if (scale !== Infinity) { + vector.multiplyScalar(scale); + } else { + vector.set(1, 0, 0, 0); + } + skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); + } + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.bindMode === AttachedBindMode) { + this.bindMatrixInverse.copy(this.matrixWorld).invert(); + } else if (this.bindMode === DetachedBindMode) { + this.bindMatrixInverse.copy(this.bindMatrix).invert(); + } else { + warn("SkinnedMesh: Unrecognized bindMode: " + this.bindMode); + } + } + /** + * Applies the bone transform associated with the given index to the given + * vector. Can be used to transform positions or direction vectors by providing + * a Vector4 with 1 or 0 in the w component respectively. Returns the updated vector. + * + * @param {number} index - The vertex index. + * @param {Vector3|Vector4} target - The target object that is used to store the method's result. + * @return {Vector3|Vector4} The updated vertex attribute data. + */ + applyBoneTransform(index, target) { + const skeleton = this.skeleton; + const geometry = this.geometry; + _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index); + _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index); + if (target.isVector4) { + _baseVector.copy(target); + target.set(0, 0, 0, 0); + } else { + _baseVector.set(...target, 1); + target.set(0, 0, 0); + } + _baseVector.applyMatrix4(this.bindMatrix); + for (let i = 0; i < 4; i++) { + const weight = _skinWeight.getComponent(i); + if (weight !== 0) { + const boneIndex = _skinIndex.getComponent(i); + _matrix4.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); + target.addScaledVector(_vector4.copy(_baseVector).applyMatrix4(_matrix4), weight); + } + } + if (target.isVector4) { + target.w = _baseVector.w; + } + return target.applyMatrix4(this.bindMatrixInverse); + } + } + class Bone extends Object3D { + /** + * Constructs a new bone. + */ + constructor() { + super(); + this.isBone = true; + this.type = "Bone"; + } + } + class DataTexture extends Texture { + /** + * Constructs a new data texture. + * + * @param {?TypedArray} [data=null] - The buffer data. + * @param {number} [width=1] - The width of the texture. + * @param {number} [height=1] - The height of the texture. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=NearestFilter] - The mag filter value. + * @param {number} [minFilter=NearestFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space. + */ + constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isDataTexture = true; + this.image = { data, width, height }; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + } + const _offsetMatrix = /* @__PURE__ */ new Matrix4(); + const _identityMatrix = /* @__PURE__ */ new Matrix4(); + class Skeleton { + /** + * Constructs a new skeleton. + * + * @param {Array} [bones] - An array of bones. + * @param {Array} [boneInverses] - An array of bone inverse matrices. + * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}. + */ + constructor(bones = [], boneInverses = []) { + this.uuid = generateUUID(); + this.bones = bones.slice(0); + this.boneInverses = boneInverses; + this.boneMatrices = null; + this.previousBoneMatrices = null; + this.boneTexture = null; + this.init(); + } + /** + * Initializes the skeleton. This method gets automatically called by the constructor + * but depending on how the skeleton is created it might be necessary to call this method + * manually. + */ + init() { + const bones = this.bones; + const boneInverses = this.boneInverses; + this.boneMatrices = new Float32Array(bones.length * 16); + if (boneInverses.length === 0) { + this.calculateInverses(); + } else { + if (bones.length !== boneInverses.length) { + warn("Skeleton: Number of inverse bone matrices does not match amount of bones."); + this.boneInverses = []; + for (let i = 0, il = this.bones.length; i < il; i++) { + this.boneInverses.push(new Matrix4()); + } + } + } + } + /** + * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses} + * and fills it with new matrices. + */ + calculateInverses() { + this.boneInverses.length = 0; + for (let i = 0, il = this.bones.length; i < il; i++) { + const inverse = new Matrix4(); + if (this.bones[i]) { + inverse.copy(this.bones[i].matrixWorld).invert(); + } + this.boneInverses.push(inverse); + } + } + /** + * Resets the skeleton to the base pose. + */ + pose() { + for (let i = 0, il = this.bones.length; i < il; i++) { + const bone = this.bones[i]; + if (bone) { + bone.matrixWorld.copy(this.boneInverses[i]).invert(); + } + } + for (let i = 0, il = this.bones.length; i < il; i++) { + const bone = this.bones[i]; + if (bone) { + if (bone.parent && bone.parent.isBone) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(bone.matrixWorld); + } else { + bone.matrix.copy(bone.matrixWorld); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + } + } + } + /** + * Resets the skeleton to the base pose. + */ + update() { + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + for (let i = 0, il = bones.length; i < il; i++) { + const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix; + _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]); + _offsetMatrix.toArray(boneMatrices, i * 16); + } + if (boneTexture !== null) { + boneTexture.needsUpdate = true; + } + } + /** + * Returns a new skeleton with copied values from this instance. + * + * @return {Skeleton} A clone of this instance. + */ + clone() { + return new Skeleton(this.bones, this.boneInverses); + } + /** + * Computes a data texture for passing bone data to the vertex shader. + * + * @return {Skeleton} A reference of this instance. + */ + computeBoneTexture() { + let size = Math.sqrt(this.bones.length * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const boneMatrices = new Float32Array(size * size * 4); + boneMatrices.set(this.boneMatrices); + const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType); + boneTexture.needsUpdate = true; + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + return this; + } + /** + * Searches through the skeleton's bone array and returns the first with a + * matching name. + * + * @param {string} name - The name of the bone. + * @return {Bone|undefined} The found bone. `undefined` if no bone has been found. + */ + getBoneByName(name) { + for (let i = 0, il = this.bones.length; i < il; i++) { + const bone = this.bones[i]; + if (bone.name === name) { + return bone; + } + } + return void 0; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + if (this.boneTexture !== null) { + this.boneTexture.dispose(); + this.boneTexture = null; + } + } + /** + * Setups the skeleton by the given JSON and bones. + * + * @param {Object} json - The skeleton as serialized JSON. + * @param {Object} bones - An array of bones. + * @return {Skeleton} A reference of this instance. + */ + fromJSON(json, bones) { + this.uuid = json.uuid; + for (let i = 0, l = json.bones.length; i < l; i++) { + const uuid = json.bones[i]; + let bone = bones[uuid]; + if (bone === void 0) { + warn("Skeleton: No bone found with UUID:", uuid); + bone = new Bone(); + } + this.bones.push(bone); + this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i])); + } + this.init(); + return this; + } + /** + * Serializes the skeleton into JSON. + * + * @return {Object} A JSON object representing the serialized skeleton. + * @see {@link ObjectLoader#parse} + */ + toJSON() { + const data = { + metadata: { + version: 4.7, + type: "Skeleton", + generator: "Skeleton.toJSON" + }, + bones: [], + boneInverses: [] + }; + data.uuid = this.uuid; + const bones = this.bones; + const boneInverses = this.boneInverses; + for (let i = 0, l = bones.length; i < l; i++) { + const bone = bones[i]; + data.bones.push(bone.uuid); + const boneInverse = boneInverses[i]; + data.boneInverses.push(boneInverse.toArray()); + } + return data; + } + } + class InstancedBufferAttribute extends BufferAttribute { + /** + * Constructs a new instanced buffer attribute. + * + * @param {TypedArray} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated. + */ + constructor(array, itemSize, normalized, meshPerAttribute = 1) { + super(array, itemSize, normalized); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + toJSON() { + const data = super.toJSON(); + data.meshPerAttribute = this.meshPerAttribute; + data.isInstancedBufferAttribute = true; + return data; + } + } + const _instanceLocalMatrix = /* @__PURE__ */ new Matrix4(); + const _instanceWorldMatrix = /* @__PURE__ */ new Matrix4(); + const _instanceIntersects = []; + const _box3 = /* @__PURE__ */ new Box3(); + const _identity = /* @__PURE__ */ new Matrix4(); + const _mesh$1 = /* @__PURE__ */ new Mesh(); + const _sphere$4 = /* @__PURE__ */ new Sphere(); + class InstancedMesh extends Mesh { + /** + * Constructs a new instanced mesh. + * + * @param {BufferGeometry} [geometry] - The mesh geometry. + * @param {Material|Array} [material] - The mesh material. + * @param {number} count - The number of instances. + */ + constructor(geometry, material, count) { + super(geometry, material); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16); + this.previousInstanceMatrix = null; + this.instanceColor = null; + this.morphTexture = null; + this.count = count; + this.boundingBox = null; + this.boundingSphere = null; + for (let i = 0; i < count; i++) { + this.setMatrixAt(i, _identity); + } + } + /** + * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}. + * The bounding box is not automatically computed by the engine; this method must be called by your app. + * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}. + */ + computeBoundingBox() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + this.boundingBox.makeEmpty(); + for (let i = 0; i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _box3.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix); + this.boundingBox.union(_box3); + } + } + /** + * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere} + * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. + * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}. + */ + computeBoundingSphere() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + if (geometry.boundingSphere === null) { + geometry.computeBoundingSphere(); + } + this.boundingSphere.makeEmpty(); + for (let i = 0; i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _sphere$4.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix); + this.boundingSphere.union(_sphere$4); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.instanceMatrix.copy(source.instanceMatrix); + if (source.previousInstanceMatrix !== null) this.previousInstanceMatrix = source.previousInstanceMatrix.clone(); + if (source.morphTexture !== null) this.morphTexture = source.morphTexture.clone(); + if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone(); + this.count = source.count; + if (source.boundingBox !== null) this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) this.boundingSphere = source.boundingSphere.clone(); + return this; + } + /** + * Gets the color of the defined instance. + * + * @param {number} index - The instance index. + * @param {Color} color - The target object that is used to store the method's result. + * @return {Color} A reference to the target color. + */ + getColorAt(index, color) { + if (this.instanceColor === null) { + return color.setRGB(1, 1, 1); + } else { + return color.fromArray(this.instanceColor.array, index * 3); + } + } + /** + * Gets the local transformation matrix of the defined instance. + * + * @param {number} index - The instance index. + * @param {Matrix4} matrix - The target object that is used to store the method's result. + * @return {Matrix4} A reference to the target matrix. + */ + getMatrixAt(index, matrix) { + return matrix.fromArray(this.instanceMatrix.array, index * 16); + } + /** + * Gets the morph target weights of the defined instance. + * + * @param {number} index - The instance index. + * @param {Mesh} object - The target object that is used to store the method's result. + */ + getMorphAt(index, object) { + const objectInfluences = object.morphTargetInfluences; + const array = this.morphTexture.source.data.data; + const len = objectInfluences.length + 1; + const dataIndex = index * len + 1; + for (let i = 0; i < objectInfluences.length; i++) { + objectInfluences[i] = array[dataIndex + i]; + } + } + raycast(raycaster, intersects2) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + _mesh$1.geometry = this.geometry; + _mesh$1.material = this.material; + if (_mesh$1.material === void 0) return; + if (this.boundingSphere === null) this.computeBoundingSphere(); + _sphere$4.copy(this.boundingSphere); + _sphere$4.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$4) === false) return; + for (let instanceId = 0; instanceId < raycastTimes; instanceId++) { + this.getMatrixAt(instanceId, _instanceLocalMatrix); + _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); + _mesh$1.matrixWorld = _instanceWorldMatrix; + _mesh$1.raycast(raycaster, _instanceIntersects); + for (let i = 0, l = _instanceIntersects.length; i < l; i++) { + const intersect2 = _instanceIntersects[i]; + intersect2.instanceId = instanceId; + intersect2.object = this; + intersects2.push(intersect2); + } + _instanceIntersects.length = 0; + } + } + /** + * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of + * {@link InstancedMesh#instanceColor} to `true` after updating all the colors. + * + * @param {number} index - The instance index. + * @param {Color} color - The instance color. + * @return {InstancedMesh} A reference to this instanced mesh. + */ + setColorAt(index, color) { + if (this.instanceColor === null) { + this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3); + } + color.toArray(this.instanceColor.array, index * 3); + return this; + } + /** + * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of + * {@link InstancedMesh#instanceMatrix} to `true` after updating all the matrices. + * + * @param {number} index - The instance index. + * @param {Matrix4} matrix - The local transformation. + * @return {InstancedMesh} A reference to this instanced mesh. + */ + setMatrixAt(index, matrix) { + matrix.toArray(this.instanceMatrix.array, index * 16); + return this; + } + /** + * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of + * {@link InstancedMesh#morphTexture} to `true` after updating all the influences. + * + * @param {number} index - The instance index. + * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights + * of a single instance. + * @return {InstancedMesh} A reference to this instanced mesh. + */ + setMorphAt(index, object) { + const objectInfluences = object.morphTargetInfluences; + const len = objectInfluences.length + 1; + if (this.morphTexture === null) { + this.morphTexture = new DataTexture(new Float32Array(len * this.count), len, this.count, RedFormat, FloatType); + } + const array = this.morphTexture.source.data.data; + let morphInfluencesSum = 0; + for (let i = 0; i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const dataIndex = len * index; + array[dataIndex] = morphBaseInfluence; + array.set(objectInfluences, dataIndex + 1); + return this; + } + updateMorphTargets() { + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + if (this.morphTexture !== null) { + this.morphTexture.dispose(); + this.morphTexture = null; + } + } + } + const _vector1 = /* @__PURE__ */ new Vector3(); + const _vector2 = /* @__PURE__ */ new Vector3(); + const _normalMatrix = /* @__PURE__ */ new Matrix3(); + class Plane { + /** + * Constructs a new plane. + * + * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane. + * @param {number} [constant=0] - The signed distance from the origin to the plane. + */ + constructor(normal = new Vector3(1, 0, 0), constant = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant; + } + /** + * Sets the plane components by copying the given values. + * + * @param {Vector3} normal - The normal. + * @param {number} constant - The constant. + * @return {Plane} A reference to this plane. + */ + set(normal, constant) { + this.normal.copy(normal); + this.constant = constant; + return this; + } + /** + * Sets the plane components by defining `x`, `y`, `z` as the + * plane normal and `w` as the constant. + * + * @param {number} x - The value for the normal's x component. + * @param {number} y - The value for the normal's y component. + * @param {number} z - The value for the normal's z component. + * @param {number} w - The constant value. + * @return {Plane} A reference to this plane. + */ + setComponents(x, y, z, w) { + this.normal.set(x, y, z); + this.constant = w; + return this; + } + /** + * Sets the plane from the given normal and coplanar point (that is a point + * that lies onto the plane). + * + * @param {Vector3} normal - The normal. + * @param {Vector3} point - A coplanar point. + * @return {Plane} A reference to this plane. + */ + setFromNormalAndCoplanarPoint(normal, point2) { + this.normal.copy(normal); + this.constant = -point2.dot(this.normal); + return this; + } + /** + * Sets the plane from three coplanar points. The winding order is + * assumed to be counter-clockwise, and determines the direction of + * the plane normal. + * + * @param {Vector3} a - The first coplanar point. + * @param {Vector3} b - The second coplanar point. + * @param {Vector3} c - The third coplanar point. + * @return {Plane} A reference to this plane. + */ + setFromCoplanarPoints(a, b, c) { + const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a); + return this; + } + /** + * Copies the values of the given plane to this instance. + * + * @param {Plane} plane - The plane to copy. + * @return {Plane} A reference to this plane. + */ + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + /** + * Normalizes the plane normal and adjusts the constant accordingly. + * + * @return {Plane} A reference to this plane. + */ + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + /** + * Negates both the plane normal and the constant. + * + * @return {Plane} A reference to this plane. + */ + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + /** + * Returns the signed distance from the given point to this plane. + * + * @param {Vector3} point - The point to compute the distance for. + * @return {number} The signed distance. + */ + distanceToPoint(point2) { + return this.normal.dot(point2) + this.constant; + } + /** + * Returns the signed distance from the given sphere to this plane. + * + * @param {Sphere} sphere - The sphere to compute the distance for. + * @return {number} The signed distance. + */ + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + /** + * Projects a the given point onto the plane. + * + * @param {Vector3} point - The point to project. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The projected point on the plane. + */ + projectPoint(point2, target) { + return target.copy(point2).addScaledVector(this.normal, -this.distanceToPoint(point2)); + } + /** + * Returns the intersection point of the passed line and the plane. Returns + * `null` if the line does not intersect. Returns the line's starting point if + * the line is coplanar with the plane. + * + * @param {Line3} line - The line to compute the intersection for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @param {boolean} [clampToLine=true] - Whether to clamp the intersection to the line segment. + * @return {?Vector3} The intersection point. Returns `null` if no intersection is detected. + */ + intersectLine(line, target, clampToLine = true) { + const direction = line.delta(_vector1); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line.start) === 0) { + return target.copy(line.start); + } + return null; + } + const t = -(line.start.dot(this.normal) + this.constant) / denominator; + if (clampToLine === true && (t < 0 || t > 1)) { + return null; + } + return target.copy(line.start).addScaledVector(direction, t); + } + /** + * Returns `true` if the given line segment intersects with (passes through) the plane. + * + * @param {Line3} line - The line to test. + * @return {boolean} Whether the given line segment intersects with the plane or not. + */ + intersectsLine(line) { + const startSign = this.distanceToPoint(line.start); + const endSign = this.distanceToPoint(line.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + /** + * Returns `true` if the given bounding box intersects with the plane. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the given bounding box intersects with the plane or not. + */ + intersectsBox(box) { + return box.intersectsPlane(this); + } + /** + * Returns `true` if the given bounding sphere intersects with the plane. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the given bounding sphere intersects with the plane or not. + */ + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + /** + * Returns a coplanar vector to the plane, by calculating the + * projection of the normal at the origin onto the plane. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The coplanar point. + */ + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + /** + * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform. + * + * The optional normal matrix can be pre-computed like so: + * ```js + * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + * ``` + * + * @param {Matrix4} matrix - The transformation matrix. + * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix. + * @return {Plane} A reference to this plane. + */ + applyMatrix4(matrix, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix); + const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + /** + * Translates the plane by the distance defined by the given offset vector. + * Note that this only affects the plane constant and will not affect the normal vector. + * + * @param {Vector3} offset - The offset vector. + * @return {Plane} A reference to this plane. + */ + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + /** + * Returns `true` if this plane is equal with the given one. + * + * @param {Plane} plane - The plane to test for equality. + * @return {boolean} Whether this plane is equal with the given one. + */ + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + /** + * Returns a new plane with copied values from this instance. + * + * @return {Plane} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + } + const _sphere$3 = /* @__PURE__ */ new Sphere(); + const _defaultSpriteCenter = /* @__PURE__ */ new Vector2(0.5, 0.5); + const _vector$6 = /* @__PURE__ */ new Vector3(); + class Frustum { + /** + * Constructs a new frustum. + * + * @param {Plane} [p0] - The first plane that encloses the frustum. + * @param {Plane} [p1] - The second plane that encloses the frustum. + * @param {Plane} [p2] - The third plane that encloses the frustum. + * @param {Plane} [p3] - The fourth plane that encloses the frustum. + * @param {Plane} [p4] - The fifth plane that encloses the frustum. + * @param {Plane} [p5] - The sixth plane that encloses the frustum. + */ + constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) { + this.planes = [p0, p1, p2, p3, p4, p5]; + } + /** + * Sets the frustum planes by copying the given planes. + * + * @param {Plane} [p0] - The first plane that encloses the frustum. + * @param {Plane} [p1] - The second plane that encloses the frustum. + * @param {Plane} [p2] - The third plane that encloses the frustum. + * @param {Plane} [p3] - The fourth plane that encloses the frustum. + * @param {Plane} [p4] - The fifth plane that encloses the frustum. + * @param {Plane} [p5] - The sixth plane that encloses the frustum. + * @return {Frustum} A reference to this frustum. + */ + set(p0, p1, p2, p3, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p2); + planes[3].copy(p3); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + /** + * Copies the values of the given frustum to this instance. + * + * @param {Frustum} frustum - The frustum to copy. + * @return {Frustum} A reference to this frustum. + */ + copy(frustum) { + const planes = this.planes; + for (let i = 0; i < 6; i++) { + planes[i].copy(frustum.planes[i]); + } + return this; + } + /** + * Sets the frustum planes from the given projection matrix. + * + * @param {Matrix4} m - The projection matrix. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Frustum} A reference to this frustum. + */ + setFromProjectionMatrix(m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false) { + const planes = this.planes; + const me = m.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + if (reversedDepth) { + planes[4].setComponents(me2, me6, me10, me14).normalize(); + planes[5].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + } else { + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + } + return this; + } + /** + * Returns `true` if the 3D object's bounding sphere is intersecting this frustum. + * + * Note that the 3D object must have a geometry so that the bounding sphere can be calculated. + * + * @param {Object3D} object - The 3D object to test. + * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not. + */ + intersectsObject(object) { + if (object.boundingSphere !== void 0) { + if (object.boundingSphere === null) object.computeBoundingSphere(); + _sphere$3.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere$3.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$3); + } + /** + * Returns `true` if the given sprite is intersecting this frustum. + * + * @param {Sprite} sprite - The sprite to test. + * @return {boolean} Whether the sprite is intersecting this frustum or not. + */ + intersectsSprite(sprite) { + _sphere$3.center.set(0, 0, 0); + const offset = _defaultSpriteCenter.distanceTo(sprite.center); + _sphere$3.radius = 0.7071067811865476 + offset; + _sphere$3.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$3); + } + /** + * Returns `true` if the given bounding sphere is intersecting this frustum. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the bounding sphere is intersecting this frustum or not. + */ + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i = 0; i < 6; i++) { + const distance = planes[i].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + /** + * Returns `true` if the given bounding box is intersecting this frustum. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the bounding box is intersecting this frustum or not. + */ + intersectsBox(box) { + const planes = this.planes; + for (let i = 0; i < 6; i++) { + const plane = planes[i]; + _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$6) < 0) { + return false; + } + } + return true; + } + /** + * Returns `true` if the given point lies within the frustum. + * + * @param {Vector3} point - The point to test. + * @return {boolean} Whether the point lies within this frustum or not. + */ + containsPoint(point2) { + const planes = this.planes; + for (let i = 0; i < 6; i++) { + if (planes[i].distanceToPoint(point2) < 0) { + return false; + } + } + return true; + } + /** + * Returns a new frustum with copied values from this instance. + * + * @return {Frustum} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + } + const _projScreenMatrix$2 = /* @__PURE__ */ new Matrix4(); + const _frustum$1 = /* @__PURE__ */ new Frustum(); + class FrustumArray { + /** + * Constructs a new frustum array. + * + */ + constructor() { + this.coordinateSystem = WebGLCoordinateSystem; + } + /** + * Returns `true` if the 3D object's bounding sphere is intersecting any frustum + * from the camera array. + * + * @param {Object3D} object - The 3D object to test. + * @param {Object} cameraArray - An object with a cameras property containing an array of cameras. + * @return {boolean} Whether the 3D object is visible in any camera. + */ + intersectsObject(object, cameraArray) { + if (!cameraArray.isArrayCamera || cameraArray.cameras.length === 0) { + return false; + } + for (let i = 0; i < cameraArray.cameras.length; i++) { + const camera = cameraArray.cameras[i]; + _projScreenMatrix$2.multiplyMatrices( + camera.projectionMatrix, + camera.matrixWorldInverse + ); + _frustum$1.setFromProjectionMatrix( + _projScreenMatrix$2, + camera.coordinateSystem, + camera.reversedDepth + ); + if (_frustum$1.intersectsObject(object)) { + return true; + } + } + return false; + } + /** + * Returns `true` if the given sprite is intersecting any frustum + * from the camera array. + * + * @param {Sprite} sprite - The sprite to test. + * @param {Object} cameraArray - An object with a cameras property containing an array of cameras. + * @return {boolean} Whether the sprite is visible in any camera. + */ + intersectsSprite(sprite, cameraArray) { + if (!cameraArray || !cameraArray.cameras || cameraArray.cameras.length === 0) { + return false; + } + for (let i = 0; i < cameraArray.cameras.length; i++) { + const camera = cameraArray.cameras[i]; + _projScreenMatrix$2.multiplyMatrices( + camera.projectionMatrix, + camera.matrixWorldInverse + ); + _frustum$1.setFromProjectionMatrix( + _projScreenMatrix$2, + camera.coordinateSystem, + camera.reversedDepth + ); + if (_frustum$1.intersectsSprite(sprite)) { + return true; + } + } + return false; + } + /** + * Returns `true` if the given bounding sphere is intersecting any frustum + * from the camera array. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @param {Object} cameraArray - An object with a cameras property containing an array of cameras. + * @return {boolean} Whether the sphere is visible in any camera. + */ + intersectsSphere(sphere, cameraArray) { + if (!cameraArray || !cameraArray.cameras || cameraArray.cameras.length === 0) { + return false; + } + for (let i = 0; i < cameraArray.cameras.length; i++) { + const camera = cameraArray.cameras[i]; + _projScreenMatrix$2.multiplyMatrices( + camera.projectionMatrix, + camera.matrixWorldInverse + ); + _frustum$1.setFromProjectionMatrix( + _projScreenMatrix$2, + camera.coordinateSystem, + camera.reversedDepth + ); + if (_frustum$1.intersectsSphere(sphere)) { + return true; + } + } + return false; + } + /** + * Returns `true` if the given bounding box is intersecting any frustum + * from the camera array. + * + * @param {Box3} box - The bounding box to test. + * @param {Object} cameraArray - An object with a cameras property containing an array of cameras. + * @return {boolean} Whether the box is visible in any camera. + */ + intersectsBox(box, cameraArray) { + if (!cameraArray || !cameraArray.cameras || cameraArray.cameras.length === 0) { + return false; + } + for (let i = 0; i < cameraArray.cameras.length; i++) { + const camera = cameraArray.cameras[i]; + _projScreenMatrix$2.multiplyMatrices( + camera.projectionMatrix, + camera.matrixWorldInverse + ); + _frustum$1.setFromProjectionMatrix( + _projScreenMatrix$2, + camera.coordinateSystem, + camera.reversedDepth + ); + if (_frustum$1.intersectsBox(box)) { + return true; + } + } + return false; + } + /** + * Returns `true` if the given point lies within any frustum + * from the camera array. + * + * @param {Vector3} point - The point to test. + * @param {Object} cameraArray - An object with a cameras property containing an array of cameras. + * @return {boolean} Whether the point is visible in any camera. + */ + containsPoint(point2, cameraArray) { + if (!cameraArray || !cameraArray.cameras || cameraArray.cameras.length === 0) { + return false; + } + for (let i = 0; i < cameraArray.cameras.length; i++) { + const camera = cameraArray.cameras[i]; + _projScreenMatrix$2.multiplyMatrices( + camera.projectionMatrix, + camera.matrixWorldInverse + ); + _frustum$1.setFromProjectionMatrix( + _projScreenMatrix$2, + camera.coordinateSystem, + camera.reversedDepth + ); + if (_frustum$1.containsPoint(point2)) { + return true; + } + } + return false; + } + /** + * Returns a new frustum array with copied values from this instance. + * + * @return {FrustumArray} A clone of this instance. + */ + clone() { + return new FrustumArray(); + } + } + function ascIdSort(a, b) { + return a - b; + } + function sortOpaque(a, b) { + return a.z - b.z; + } + function sortTransparent(a, b) { + return b.z - a.z; + } + class MultiDrawRenderList { + constructor() { + this.index = 0; + this.pool = []; + this.list = []; + } + push(start, count, z, index) { + const pool = this.pool; + const list = this.list; + if (this.index >= pool.length) { + pool.push({ + start: -1, + count: -1, + z: -1, + index: -1 + }); + } + const item = pool[this.index]; + list.push(item); + this.index++; + item.start = start; + item.count = count; + item.z = z; + item.index = index; + } + reset() { + this.list.length = 0; + this.index = 0; + } + } + const _matrix$1 = /* @__PURE__ */ new Matrix4(); + const _whiteColor = /* @__PURE__ */ new Color(1, 1, 1); + const _frustum = /* @__PURE__ */ new Frustum(); + const _frustumArray = /* @__PURE__ */ new FrustumArray(); + const _box$1 = /* @__PURE__ */ new Box3(); + const _sphere$2 = /* @__PURE__ */ new Sphere(); + const _vector$5 = /* @__PURE__ */ new Vector3(); + const _forward$1 = /* @__PURE__ */ new Vector3(); + const _temp = /* @__PURE__ */ new Vector3(); + const _renderList = /* @__PURE__ */ new MultiDrawRenderList(); + const _mesh = /* @__PURE__ */ new Mesh(); + const _batchIntersects = []; + function copyAttributeData(src, target, targetOffset = 0) { + const itemSize = target.itemSize; + if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { + const vertexCount = src.count; + for (let i = 0; i < vertexCount; i++) { + for (let c = 0; c < itemSize; c++) { + target.setComponent(i + targetOffset, c, src.getComponent(i, c)); + } + } + } else { + target.array.set(src.array, targetOffset * itemSize); + } + target.needsUpdate = true; + } + function copyArrayContents(src, target) { + if (src.constructor !== target.constructor) { + const len = Math.min(src.length, target.length); + for (let i = 0; i < len; i++) { + target[i] = src[i]; + } + } else { + const len = Math.min(src.length, target.length); + target.set(new src.constructor(src.buffer, 0, len)); + } + } + class BatchedMesh extends Mesh { + /** + * Constructs a new batched mesh. + * + * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered. + * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries. + * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries + * @param {Material|Array} [material] - The mesh material. + */ + constructor(maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { + super(new BufferGeometry(), material); + this.isBatchedMesh = true; + this.perObjectFrustumCulled = true; + this.sortObjects = true; + this.boundingBox = null; + this.boundingSphere = null; + this.customSort = null; + this._instanceInfo = []; + this._geometryInfo = []; + this._availableInstanceIds = []; + this._availableGeometryIds = []; + this._nextIndexStart = 0; + this._nextVertexStart = 0; + this._geometryCount = 0; + this._visibilityChanged = true; + this._geometryInitialized = false; + this._maxInstanceCount = maxInstanceCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + this._multiDrawCounts = new Int32Array(maxInstanceCount); + this._multiDrawStarts = new Int32Array(maxInstanceCount); + this._multiDrawCount = 0; + this._matricesTexture = null; + this._indirectTexture = null; + this._colorsTexture = null; + this._initMatricesTexture(); + this._initIndirectTexture(); + } + /** + * The maximum number of individual instances that can be stored in the batch. + * + * @type {number} + * @readonly + */ + get maxInstanceCount() { + return this._maxInstanceCount; + } + /** + * The instance count. + * + * @type {number} + * @readonly + */ + get instanceCount() { + return this._instanceInfo.length - this._availableInstanceIds.length; + } + /** + * The number of unused vertices. + * + * @type {number} + * @readonly + */ + get unusedVertexCount() { + return this._maxVertexCount - this._nextVertexStart; + } + /** + * The number of unused indices. + * + * @type {number} + * @readonly + */ + get unusedIndexCount() { + return this._maxIndexCount - this._nextIndexStart; + } + _initMatricesTexture() { + let size = Math.sqrt(this._maxInstanceCount * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const matricesArray = new Float32Array(size * size * 4); + const matricesTexture = new DataTexture(matricesArray, size, size, RGBAFormat, FloatType); + this._matricesTexture = matricesTexture; + } + _initIndirectTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const indirectArray = new Uint32Array(size * size); + const indirectTexture = new DataTexture(indirectArray, size, size, RedIntegerFormat, UnsignedIntType); + this._indirectTexture = indirectTexture; + } + _initColorsTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const colorsArray = new Float32Array(size * size * 4).fill(1); + const colorsTexture = new DataTexture(colorsArray, size, size, RGBAFormat, FloatType); + colorsTexture.colorSpace = ColorManagement.workingColorSpace; + this._colorsTexture = colorsTexture; + } + _initializeGeometry(reference) { + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxIndexCount = this._maxIndexCount; + if (this._geometryInitialized === false) { + for (const attributeName in reference.attributes) { + const srcAttribute = reference.getAttribute(attributeName); + const { array, itemSize, normalized } = srcAttribute; + const dstArray = new array.constructor(maxVertexCount * itemSize); + const dstAttribute = new BufferAttribute(dstArray, itemSize, normalized); + geometry.setAttribute(attributeName, dstAttribute); + } + if (reference.getIndex() !== null) { + const indexArray = maxVertexCount > 65535 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); + geometry.setIndex(new BufferAttribute(indexArray, 1)); + } + this._geometryInitialized = true; + } + } + // Make sure the geometry is compatible with the existing combined geometry attributes + _validateGeometry(geometry) { + const batchGeometry = this.geometry; + if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) { + throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".'); + } + for (const attributeName in batchGeometry.attributes) { + if (!geometry.hasAttribute(attributeName)) { + throw new Error(`THREE.BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) { + throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value."); + } + } + } + /** + * Validates the instance defined by the given ID. + * + * @param {number} instanceId - The instance to validate. + */ + validateInstanceId(instanceId) { + const instanceInfo = this._instanceInfo; + if (instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[instanceId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.`); + } + } + /** + * Validates the geometry defined by the given ID. + * + * @param {number} geometryId - The geometry to validate. + */ + validateGeometryId(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.`); + } + } + /** + * Takes a sort a function that is run before render. The function takes a list of instances to + * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with. + * + * @param {Function} func - The custom sort function. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setCustomSort(func) { + this.customSort = func; + return this; + } + /** + * Computes the bounding box, updating {@link BatchedMesh#boundingBox}. + * Bounding boxes aren't computed by default. They need to be explicitly computed, + * otherwise they are `null`. + */ + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + const boundingBox = this.boundingBox; + const instanceInfo = this._instanceInfo; + boundingBox.makeEmpty(); + for (let i = 0, l = instanceInfo.length; i < l; i++) { + if (instanceInfo[i].active === false) continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingBoxAt(geometryId, _box$1).applyMatrix4(_matrix$1); + boundingBox.union(_box$1); + } + } + /** + * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}. + * Bounding spheres aren't computed by default. They need to be explicitly computed, + * otherwise they are `null`. + */ + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + const boundingSphere = this.boundingSphere; + const instanceInfo = this._instanceInfo; + boundingSphere.makeEmpty(); + for (let i = 0, l = instanceInfo.length; i < l; i++) { + if (instanceInfo[i].active === false) continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + boundingSphere.union(_sphere$2); + } + } + /** + * Adds a new instance to the batch using the geometry of the given ID and returns + * a new id referring to the new instance to be used by other functions. + * + * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}. + * @return {number} The instance ID. + */ + addInstance(geometryId) { + const atCapacity = this._instanceInfo.length >= this.maxInstanceCount; + if (atCapacity && this._availableInstanceIds.length === 0) { + throw new Error("THREE.BatchedMesh: Maximum item count reached."); + } + const instanceInfo = { + visible: true, + active: true, + geometryIndex: geometryId + }; + let drawId = null; + if (this._availableInstanceIds.length > 0) { + this._availableInstanceIds.sort(ascIdSort); + drawId = this._availableInstanceIds.shift(); + this._instanceInfo[drawId] = instanceInfo; + } else { + drawId = this._instanceInfo.length; + this._instanceInfo.push(instanceInfo); + } + const matricesTexture = this._matricesTexture; + _matrix$1.identity().toArray(matricesTexture.image.data, drawId * 16); + matricesTexture.needsUpdate = true; + const colorsTexture = this._colorsTexture; + if (colorsTexture) { + _whiteColor.toArray(colorsTexture.image.data, drawId * 4); + colorsTexture.needsUpdate = true; + } + this._visibilityChanged = true; + return drawId; + } + /** + * Adds the given geometry to the batch and returns the associated + * geometry id referring to it to be used in other functions. + * + * @param {BufferGeometry} geometry - The geometry to add. + * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of + * vertex buffer space to reserve for the added geometry. This is necessary if it is planned + * to set a new geometry at this index at a later time that is larger than the original geometry. + * Defaults to the length of the given geometry vertex buffer. + * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index + * buffer space to reserve for the added geometry. This is necessary if it is planned to set a + * new geometry at this index at a later time that is larger than the original geometry. Defaults to + * the length of the given geometry index buffer. + * @return {number} The geometry ID. + */ + addGeometry(geometry, reservedVertexCount = -1, reservedIndexCount = -1) { + this._initializeGeometry(geometry); + this._validateGeometry(geometry); + const geometryInfo = { + // geometry information + vertexStart: -1, + vertexCount: -1, + reservedVertexCount: -1, + indexStart: -1, + indexCount: -1, + reservedIndexCount: -1, + // draw range information + start: -1, + count: -1, + // state + boundingBox: null, + boundingSphere: null, + active: true + }; + const geometryInfoList = this._geometryInfo; + geometryInfo.vertexStart = this._nextVertexStart; + geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute("position").count : reservedVertexCount; + const index = geometry.getIndex(); + const hasIndex = index !== null; + if (hasIndex) { + geometryInfo.indexStart = this._nextIndexStart; + geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount; + } + if (geometryInfo.indexStart !== -1 && geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."); + } + let geometryId; + if (this._availableGeometryIds.length > 0) { + this._availableGeometryIds.sort(ascIdSort); + geometryId = this._availableGeometryIds.shift(); + geometryInfoList[geometryId] = geometryInfo; + } else { + geometryId = this._geometryCount; + this._geometryCount++; + geometryInfoList.push(geometryInfo); + } + this.setGeometryAt(geometryId, geometry); + this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + return geometryId; + } + /** + * Replaces the geometry at the given ID with the provided geometry. Throws an error if there + * is not enough space reserved for geometry. Calling this will change all instances that are + * rendering that geometry. + * + * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry. + * @param {BufferGeometry} geometry - The new geometry. + * @return {number} The geometry ID. + */ + setGeometryAt(geometryId, geometry) { + if (geometryId >= this._geometryCount) { + throw new Error("THREE.BatchedMesh: Maximum geometry count reached."); + } + this._validateGeometry(geometry); + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const geometryInfo = this._geometryInfo[geometryId]; + if (hasIndex && srcIndex.count > geometryInfo.reservedIndexCount || geometry.attributes.position.count > geometryInfo.reservedVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry."); + } + const vertexStart = geometryInfo.vertexStart; + const reservedVertexCount = geometryInfo.reservedVertexCount; + geometryInfo.vertexCount = geometry.getAttribute("position").count; + for (const attributeName in batchGeometry.attributes) { + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + copyAttributeData(srcAttribute, dstAttribute, vertexStart); + const itemSize = srcAttribute.itemSize; + for (let i = srcAttribute.count, l = reservedVertexCount; i < l; i++) { + const index = vertexStart + i; + for (let c = 0; c < itemSize; c++) { + dstAttribute.setComponent(index, c, 0); + } + } + dstAttribute.needsUpdate = true; + dstAttribute.addUpdateRange(vertexStart * itemSize, reservedVertexCount * itemSize); + } + if (hasIndex) { + const indexStart = geometryInfo.indexStart; + const reservedIndexCount = geometryInfo.reservedIndexCount; + geometryInfo.indexCount = geometry.getIndex().count; + for (let i = 0; i < srcIndex.count; i++) { + dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); + } + for (let i = srcIndex.count, l = reservedIndexCount; i < l; i++) { + dstIndex.setX(indexStart + i, vertexStart); + } + dstIndex.needsUpdate = true; + dstIndex.addUpdateRange(indexStart, geometryInfo.reservedIndexCount); + } + geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart; + geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount; + geometryInfo.boundingBox = null; + if (geometry.boundingBox !== null) { + geometryInfo.boundingBox = geometry.boundingBox.clone(); + } + geometryInfo.boundingSphere = null; + if (geometry.boundingSphere !== null) { + geometryInfo.boundingSphere = geometry.boundingSphere.clone(); + } + this._visibilityChanged = true; + return geometryId; + } + /** + * Deletes the geometry defined by the given ID from this batch. Any instances referencing + * this geometry will also be removed as a side effect. + * + * @param {number} geometryId - The ID of the geometry to remove from the batch. + * @return {BatchedMesh} A reference to this batched mesh. + */ + deleteGeometry(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + return this; + } + const instanceInfo = this._instanceInfo; + for (let i = 0, l = instanceInfo.length; i < l; i++) { + if (instanceInfo[i].active && instanceInfo[i].geometryIndex === geometryId) { + this.deleteInstance(i); + } + } + geometryInfoList[geometryId].active = false; + this._availableGeometryIds.push(geometryId); + this._visibilityChanged = true; + return this; + } + /** + * Deletes an existing instance from the batch using the given ID. + * + * @param {number} instanceId - The ID of the instance to remove from the batch. + * @return {BatchedMesh} A reference to this batched mesh. + */ + deleteInstance(instanceId) { + this.validateInstanceId(instanceId); + this._instanceInfo[instanceId].active = false; + this._availableInstanceIds.push(instanceId); + this._visibilityChanged = true; + return this; + } + /** + * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from + * previously deleted geometry, freeing up space to add new geometry. + * + * @return {BatchedMesh} A reference to this batched mesh. + */ + optimize() { + let nextVertexStart = 0; + let nextIndexStart = 0; + const geometryInfoList = this._geometryInfo; + const indices = geometryInfoList.map((e, i) => i).sort((a, b) => { + return geometryInfoList[a].vertexStart - geometryInfoList[b].vertexStart; + }); + const geometry = this.geometry; + for (let i = 0, l = geometryInfoList.length; i < l; i++) { + const index = indices[i]; + const geometryInfo = geometryInfoList[index]; + if (geometryInfo.active === false) { + continue; + } + if (geometry.index !== null) { + if (geometryInfo.indexStart !== nextIndexStart) { + const { indexStart, vertexStart, reservedIndexCount } = geometryInfo; + const index2 = geometry.index; + const array = index2.array; + const elementDelta = nextVertexStart - vertexStart; + for (let j = indexStart; j < indexStart + reservedIndexCount; j++) { + array[j] = array[j] + elementDelta; + } + index2.array.copyWithin(nextIndexStart, indexStart, indexStart + reservedIndexCount); + index2.addUpdateRange(nextIndexStart, reservedIndexCount); + index2.needsUpdate = true; + geometryInfo.indexStart = nextIndexStart; + } + nextIndexStart += geometryInfo.reservedIndexCount; + } + if (geometryInfo.vertexStart !== nextVertexStart) { + const { vertexStart, reservedVertexCount } = geometryInfo; + const attributes = geometry.attributes; + for (const key in attributes) { + const attribute = attributes[key]; + const { array, itemSize } = attribute; + array.copyWithin(nextVertexStart * itemSize, vertexStart * itemSize, (vertexStart + reservedVertexCount) * itemSize); + attribute.addUpdateRange(nextVertexStart * itemSize, reservedVertexCount * itemSize); + attribute.needsUpdate = true; + } + geometryInfo.vertexStart = nextVertexStart; + } + nextVertexStart += geometryInfo.reservedVertexCount; + geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart; + } + this._nextIndexStart = nextIndexStart; + this._nextVertexStart = nextVertexStart; + this._visibilityChanged = true; + return this; + } + /** + * Returns the bounding box for the given geometry. + * + * @param {number} geometryId - The ID of the geometry to return the bounding box for. + * @param {Box3} target - The target object that is used to store the method's result. + * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID. + */ + getBoundingBoxAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingBox === null) { + const box = new Box3(); + const index = geometry.index; + const position = geometry.attributes.position; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i++) { + let iv = i; + if (index) { + iv = index.getX(iv); + } + box.expandByPoint(_vector$5.fromBufferAttribute(position, iv)); + } + geometryInfo.boundingBox = box; + } + target.copy(geometryInfo.boundingBox); + return target; + } + /** + * Returns the bounding sphere for the given geometry. + * + * @param {number} geometryId - The ID of the geometry to return the bounding sphere for. + * @param {Sphere} target - The target object that is used to store the method's result. + * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID. + */ + getBoundingSphereAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingSphere === null) { + const sphere = new Sphere(); + this.getBoundingBoxAt(geometryId, _box$1); + _box$1.getCenter(sphere.center); + const index = geometry.index; + const position = geometry.attributes.position; + let maxRadiusSq = 0; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i++) { + let iv = i; + if (index) { + iv = index.getX(iv); + } + _vector$5.fromBufferAttribute(position, iv); + maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$5)); + } + sphere.radius = Math.sqrt(maxRadiusSq); + geometryInfo.boundingSphere = sphere; + } + target.copy(geometryInfo.boundingSphere); + return target; + } + /** + * Sets the given local transformation matrix to the defined instance. + * Negatively scaled matrices are not supported. + * + * @param {number} instanceId - The ID of an instance to set the matrix of. + * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + matrix.toArray(matricesArray, instanceId * 16); + matricesTexture.needsUpdate = true; + return this; + } + /** + * Returns the local transformation matrix of the defined instance. + * + * @param {number} instanceId - The ID of an instance to get the matrix of. + * @param {Matrix4} matrix - The target object that is used to store the method's result. + * @return {Matrix4} The instance's local transformation matrix. + */ + getMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + return matrix.fromArray(this._matricesTexture.image.data, instanceId * 16); + } + /** + * Sets the given color to the defined instance. + * + * @param {number} instanceId - The ID of an instance to set the color of. + * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + if (this._colorsTexture === null) { + this._initColorsTexture(); + } + color.toArray(this._colorsTexture.image.data, instanceId * 4); + this._colorsTexture.needsUpdate = true; + return this; + } + /** + * Returns the color of the defined instance. + * + * @param {number} instanceId - The ID of an instance to get the color of. + * @param {Color|Vector4} color - The target object that is used to store the method's result. + * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha. + */ + getColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + if (this._colorsTexture === null) { + if (color.isVector4) { + return color.set(1, 1, 1, 1); + } else { + return color.setRGB(1, 1, 1); + } + } else { + return color.fromArray(this._colorsTexture.image.data, instanceId * 4); + } + } + /** + * Sets the visibility of the instance. + * + * @param {number} instanceId - The id of the instance to set the visibility of. + * @param {boolean} visible - Whether the instance is visible or not. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setVisibleAt(instanceId, visible) { + this.validateInstanceId(instanceId); + if (this._instanceInfo[instanceId].visible === visible) { + return this; + } + this._instanceInfo[instanceId].visible = visible; + this._visibilityChanged = true; + return this; + } + /** + * Returns the visibility state of the defined instance. + * + * @param {number} instanceId - The ID of an instance to get the visibility state of. + * @return {boolean} Whether the instance is visible or not. + */ + getVisibleAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].visible; + } + /** + * Sets the geometry ID of the instance at the given index. + * + * @param {number} instanceId - The ID of the instance to set the geometry ID of. + * @param {number} geometryId - The geometry ID to be use by the instance. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setGeometryIdAt(instanceId, geometryId) { + this.validateInstanceId(instanceId); + this.validateGeometryId(geometryId); + this._instanceInfo[instanceId].geometryIndex = geometryId; + return this; + } + /** + * Returns the geometry ID of the defined instance. + * + * @param {number} instanceId - The ID of an instance to get the geometry ID of. + * @return {number} The instance's geometry ID. + */ + getGeometryIdAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].geometryIndex; + } + /** + * Get the range representing the subset of triangles related to the attached geometry, + * indicating the starting offset and count, or `null` if invalid. + * + * @param {number} geometryId - The id of the geometry to get the range of. + * @param {Object} [target] - The target object that is used to store the method's result. + * @return {{ + * vertexStart:number,vertexCount:number,reservedVertexCount:number, + * indexStart:number,indexCount:number,reservedIndexCount:number, + * start:number,count:number + * }} The result object with range data. + */ + getGeometryRangeAt(geometryId, target = {}) { + this.validateGeometryId(geometryId); + const geometryInfo = this._geometryInfo[geometryId]; + target.vertexStart = geometryInfo.vertexStart; + target.vertexCount = geometryInfo.vertexCount; + target.reservedVertexCount = geometryInfo.reservedVertexCount; + target.indexStart = geometryInfo.indexStart; + target.indexCount = geometryInfo.indexCount; + target.reservedIndexCount = geometryInfo.reservedIndexCount; + target.start = geometryInfo.start; + target.count = geometryInfo.count; + return target; + } + /** + * Resizes the necessary buffers to support the provided number of instances. + * If the provided arguments shrink the number of instances but there are not enough + * unused Ids at the end of the list then an error is thrown. + * + * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch. + */ + setInstanceCount(maxInstanceCount) { + const availableInstanceIds = this._availableInstanceIds; + const instanceInfo = this._instanceInfo; + availableInstanceIds.sort(ascIdSort); + while (availableInstanceIds[availableInstanceIds.length - 1] === instanceInfo.length - 1) { + instanceInfo.pop(); + availableInstanceIds.pop(); + } + if (maxInstanceCount < instanceInfo.length) { + throw new Error(`BatchedMesh: Instance ids outside the range ${maxInstanceCount} are being used. Cannot shrink instance count.`); + } + const multiDrawCounts = new Int32Array(maxInstanceCount); + const multiDrawStarts = new Int32Array(maxInstanceCount); + copyArrayContents(this._multiDrawCounts, multiDrawCounts); + copyArrayContents(this._multiDrawStarts, multiDrawStarts); + this._multiDrawCounts = multiDrawCounts; + this._multiDrawStarts = multiDrawStarts; + this._maxInstanceCount = maxInstanceCount; + const indirectTexture = this._indirectTexture; + const matricesTexture = this._matricesTexture; + const colorsTexture = this._colorsTexture; + indirectTexture.dispose(); + this._initIndirectTexture(); + copyArrayContents(indirectTexture.image.data, this._indirectTexture.image.data); + matricesTexture.dispose(); + this._initMatricesTexture(); + copyArrayContents(matricesTexture.image.data, this._matricesTexture.image.data); + if (colorsTexture) { + colorsTexture.dispose(); + this._initColorsTexture(); + copyArrayContents(colorsTexture.image.data, this._colorsTexture.image.data); + } + } + /** + * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes. + * If the provided arguments shrink the geometry buffers but there is not enough unused space at the + * end of the geometry attributes then an error is thrown. + * + * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to. + * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to. + */ + setGeometrySize(maxVertexCount, maxIndexCount) { + const validRanges = [...this._geometryInfo].filter((info) => info.active); + const requiredVertexLength = Math.max(...validRanges.map((range) => range.vertexStart + range.reservedVertexCount)); + if (requiredVertexLength > maxVertexCount) { + throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + if (this.geometry.index) { + const requiredIndexLength = Math.max(...validRanges.map((range) => range.indexStart + range.reservedIndexCount)); + if (requiredIndexLength > maxIndexCount) { + throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + } + const oldGeometry = this.geometry; + oldGeometry.dispose(); + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + if (this._geometryInitialized) { + this._geometryInitialized = false; + this.geometry = new BufferGeometry(); + this._initializeGeometry(oldGeometry); + } + const geometry = this.geometry; + if (oldGeometry.index) { + copyArrayContents(oldGeometry.index.array, geometry.index.array); + } + for (const key in oldGeometry.attributes) { + copyArrayContents(oldGeometry.attributes[key].array, geometry.attributes[key].array); + } + } + raycast(raycaster, intersects2) { + const instanceInfo = this._instanceInfo; + const geometryInfoList = this._geometryInfo; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + _mesh.material = this.material; + _mesh.geometry.index = batchGeometry.index; + _mesh.geometry.attributes = batchGeometry.attributes; + if (_mesh.geometry.boundingBox === null) { + _mesh.geometry.boundingBox = new Box3(); + } + if (_mesh.geometry.boundingSphere === null) { + _mesh.geometry.boundingSphere = new Sphere(); + } + for (let i = 0, l = instanceInfo.length; i < l; i++) { + if (!instanceInfo[i].visible || !instanceInfo[i].active) { + continue; + } + const geometryId = instanceInfo[i].geometryIndex; + const geometryInfo = geometryInfoList[geometryId]; + _mesh.geometry.setDrawRange(geometryInfo.start, geometryInfo.count); + this.getMatrixAt(i, _mesh.matrixWorld).premultiply(matrixWorld); + this.getBoundingBoxAt(geometryId, _mesh.geometry.boundingBox); + this.getBoundingSphereAt(geometryId, _mesh.geometry.boundingSphere); + _mesh.raycast(raycaster, _batchIntersects); + for (let j = 0, l2 = _batchIntersects.length; j < l2; j++) { + const intersect2 = _batchIntersects[j]; + intersect2.object = this; + intersect2.batchId = i; + intersects2.push(intersect2); + } + _batchIntersects.length = 0; + } + _mesh.material = null; + _mesh.geometry.index = null; + _mesh.geometry.attributes = {}; + _mesh.geometry.setDrawRange(0, Infinity); + } + copy(source) { + super.copy(source); + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + this._geometryInfo = source._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null, + boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null + })); + this._instanceInfo = source._instanceInfo.map((info) => ({ ...info })); + this._availableInstanceIds = source._availableInstanceIds.slice(); + this._availableGeometryIds = source._availableGeometryIds.slice(); + this._nextIndexStart = source._nextIndexStart; + this._nextVertexStart = source._nextVertexStart; + this._geometryCount = source._geometryCount; + this._maxInstanceCount = source._maxInstanceCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + this._geometryInitialized = source._geometryInitialized; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._indirectTexture = source._indirectTexture.clone(); + this._indirectTexture.image.data = this._indirectTexture.image.data.slice(); + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.data.slice(); + if (this._colorsTexture !== null) { + this._colorsTexture = source._colorsTexture.clone(); + this._colorsTexture.image.data = this._colorsTexture.image.data.slice(); + } + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this._matricesTexture.dispose(); + this._matricesTexture = null; + this._indirectTexture.dispose(); + this._indirectTexture = null; + if (this._colorsTexture !== null) { + this._colorsTexture.dispose(); + this._colorsTexture = null; + } + } + onBeforeRender(renderer, scene, camera, geometry, material) { + if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) { + return; + } + const index = geometry.getIndex(); + let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT; + let multiDrawMultiplier = 1; + if (material.wireframe) { + multiDrawMultiplier = 2; + bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2; + } + const instanceInfo = this._instanceInfo; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const geometryInfoList = this._geometryInfo; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + const indirectTexture = this._indirectTexture; + const indirectArray = indirectTexture.image.data; + const frustum = camera.isArrayCamera ? _frustumArray : _frustum; + if (perObjectFrustumCulled && !camera.isArrayCamera) { + _matrix$1.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld); + _frustum.setFromProjectionMatrix( + _matrix$1, + camera.coordinateSystem, + camera.reversedDepth + ); + } + let multiDrawCount = 0; + if (this.sortObjects) { + _matrix$1.copy(this.matrixWorld).invert(); + _vector$5.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_matrix$1); + _forward$1.set(0, 0, -1).transformDirection(camera.matrixWorld).transformDirection(_matrix$1); + for (let i = 0, l = instanceInfo.length; i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + let culled = false; + if (perObjectFrustumCulled) { + culled = !frustum.intersectsSphere(_sphere$2, camera); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + const z = _temp.subVectors(_sphere$2.center, _vector$5).dot(_forward$1); + _renderList.push(geometryInfo.start, geometryInfo.count, z, i); + } + } + } + const list = _renderList.list; + const customSort = this.customSort; + if (customSort === null) { + list.sort(material.transparent ? sortTransparent : sortOpaque); + } else { + customSort.call(this, list, camera); + } + for (let i = 0, l = list.length; i < l; i++) { + const item = list[i]; + multiDrawStarts[multiDrawCount] = item.start * bytesPerElement * multiDrawMultiplier; + multiDrawCounts[multiDrawCount] = item.count * multiDrawMultiplier; + indirectArray[multiDrawCount] = item.index; + multiDrawCount++; + } + _renderList.reset(); + } else { + for (let i = 0, l = instanceInfo.length; i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + let culled = false; + if (perObjectFrustumCulled) { + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + culled = !frustum.intersectsSphere(_sphere$2, camera); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + multiDrawStarts[multiDrawCount] = geometryInfo.start * bytesPerElement * multiDrawMultiplier; + multiDrawCounts[multiDrawCount] = geometryInfo.count * multiDrawMultiplier; + indirectArray[multiDrawCount] = i; + multiDrawCount++; + } + } + } + } + indirectTexture.needsUpdate = true; + this._multiDrawCount = multiDrawCount; + this._visibilityChanged = false; + } + onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial) { + this.onBeforeRender(renderer, null, shadowCamera, geometry, depthMaterial); + } + } + class LineBasicMaterial extends Material { + /** + * Constructs a new line basic material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isLineBasicMaterial = true; + this.type = "LineBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.linewidth = 1; + this.linecap = "round"; + this.linejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + this.fog = source.fog; + return this; + } + } + const _vStart = /* @__PURE__ */ new Vector3(); + const _vEnd = /* @__PURE__ */ new Vector3(); + const _inverseMatrix$1 = /* @__PURE__ */ new Matrix4(); + const _ray$1 = /* @__PURE__ */ new Ray(); + const _sphere$1 = /* @__PURE__ */ new Sphere(); + const _intersectPointOnRay = /* @__PURE__ */ new Vector3(); + const _intersectPointOnSegment = /* @__PURE__ */ new Vector3(); + class Line extends Object3D { + /** + * Constructs a new line. + * + * @param {BufferGeometry} [geometry] - The line geometry. + * @param {Material|Array} [material] - The line material. + */ + constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) { + super(); + this.isLine = true; + this.type = "Line"; + this.geometry = geometry; + this.material = material; + this.morphTargetDictionary = void 0; + this.morphTargetInfluences = void 0; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + /** + * Computes an array of distance values which are necessary for rendering dashed lines. + * For each vertex in the geometry, the method calculates the cumulative length from the + * current point to the very beginning of the line. + * + * @return {Line} A reference to this line. + */ + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [0]; + for (let i = 1, l = positionAttribute.count; i < l; i++) { + _vStart.fromBufferAttribute(positionAttribute, i - 1); + _vEnd.fromBufferAttribute(positionAttribute, i); + lineDistances[i] = lineDistances[i - 1]; + lineDistances[i] += _vStart.distanceTo(_vEnd); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + warn("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + /** + * Computes intersection points between a casted ray and this line. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast(raycaster, intersects2) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere$1.copy(geometry.boundingSphere); + _sphere$1.applyMatrix4(matrixWorld); + _sphere$1.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; + _inverseMatrix$1.copy(matrixWorld).invert(); + _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const step = this.isLineSegments ? 2 : 1; + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1; i < l; i += step) { + const a = index.getX(i); + const b = index.getX(i + 1); + const intersect2 = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, i); + if (intersect2) { + intersects2.push(intersect2); + } + } + if (this.isLineLoop) { + const a = index.getX(end - 1); + const b = index.getX(start); + const intersect2 = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, end - 1); + if (intersect2) { + intersects2.push(intersect2); + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1; i < l; i += step) { + const intersect2 = checkIntersection(this, raycaster, _ray$1, localThresholdSq, i, i + 1, i); + if (intersect2) { + intersects2.push(intersect2); + } + } + if (this.isLineLoop) { + const intersect2 = checkIntersection(this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1); + if (intersect2) { + intersects2.push(intersect2); + } + } + } + } + /** + * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences} + * to make sure existing morph targets can influence this 3D object. + */ + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys(morphAttributes); + if (keys.length > 0) { + const morphAttribute = morphAttributes[keys[0]]; + if (morphAttribute !== void 0) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length; m < ml; m++) { + const name = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name] = m; + } + } + } + } + } + function checkIntersection(object, raycaster, ray, thresholdSq, a, b, i) { + const positionAttribute = object.geometry.attributes.position; + _vStart.fromBufferAttribute(positionAttribute, a); + _vEnd.fromBufferAttribute(positionAttribute, b); + const distSq = ray.distanceSqToSegment(_vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment); + if (distSq > thresholdSq) return; + _intersectPointOnRay.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay); + if (distance < raycaster.near || distance > raycaster.far) return; + return { + distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: _intersectPointOnSegment.clone().applyMatrix4(object.matrixWorld), + index: i, + face: null, + faceIndex: null, + barycoord: null, + object + }; + } + const _start = /* @__PURE__ */ new Vector3(); + const _end = /* @__PURE__ */ new Vector3(); + class LineSegments extends Line { + /** + * Constructs a new line segments. + * + * @param {BufferGeometry} [geometry] - The line geometry. + * @param {Material|Array} [material] - The line material. + */ + constructor(geometry, material) { + super(geometry, material); + this.isLineSegments = true; + this.type = "LineSegments"; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + for (let i = 0, l = positionAttribute.count; i < l; i += 2) { + _start.fromBufferAttribute(positionAttribute, i); + _end.fromBufferAttribute(positionAttribute, i + 1); + lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; + lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + warn("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + } + class LineLoop extends Line { + /** + * Constructs a new line loop. + * + * @param {BufferGeometry} [geometry] - The line geometry. + * @param {Material|Array} [material] - The line material. + */ + constructor(geometry, material) { + super(geometry, material); + this.isLineLoop = true; + this.type = "LineLoop"; + } + } + class PointsMaterial extends Material { + /** + * Constructs a new points material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isPointsMaterial = true; + this.type = "PointsMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.size = 1; + this.sizeAttenuation = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + } + const _inverseMatrix = /* @__PURE__ */ new Matrix4(); + const _ray = /* @__PURE__ */ new Ray(); + const _sphere = /* @__PURE__ */ new Sphere(); + const _position$3 = /* @__PURE__ */ new Vector3(); + class Points extends Object3D { + /** + * Constructs a new point cloud. + * + * @param {BufferGeometry} [geometry] - The points geometry. + * @param {Material|Array} [material] - The points material. + */ + constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) { + super(); + this.isPoints = true; + this.type = "Points"; + this.geometry = geometry; + this.material = material; + this.morphTargetDictionary = void 0; + this.morphTargetInfluences = void 0; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + /** + * Computes intersection points between a casted ray and this point cloud. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast(raycaster, intersects2) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere.copy(geometry.boundingSphere); + _sphere.applyMatrix4(matrixWorld); + _sphere.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere) === false) return; + _inverseMatrix.copy(matrixWorld).invert(); + _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index.count, drawRange.start + drawRange.count); + for (let i = start, il = end; i < il; i++) { + const a = index.getX(i); + _position$3.fromBufferAttribute(positionAttribute, a); + testPoint(_position$3, a, localThresholdSq, matrixWorld, raycaster, intersects2, this); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end; i < l; i++) { + _position$3.fromBufferAttribute(positionAttribute, i); + testPoint(_position$3, i, localThresholdSq, matrixWorld, raycaster, intersects2, this); + } + } + } + /** + * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences} + * to make sure existing morph targets can influence this 3D object. + */ + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys(morphAttributes); + if (keys.length > 0) { + const morphAttribute = morphAttributes[keys[0]]; + if (morphAttribute !== void 0) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length; m < ml; m++) { + const name = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name] = m; + } + } + } + } + } + function testPoint(point2, index, localThresholdSq, matrixWorld, raycaster, intersects2, object) { + const rayPointDistanceSq = _ray.distanceSqToPoint(point2); + if (rayPointDistanceSq < localThresholdSq) { + const intersectPoint = new Vector3(); + _ray.closestPointToPoint(point2, intersectPoint); + intersectPoint.applyMatrix4(matrixWorld); + const distance = raycaster.ray.origin.distanceTo(intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) return; + intersects2.push({ + distance, + distanceToRay: Math.sqrt(rayPointDistanceSq), + point: intersectPoint, + index, + face: null, + faceIndex: null, + barycoord: null, + object + }); + } + } + class VideoTexture extends Texture { + /** + * Constructs a new video texture. + * + * @param {HTMLVideoElement} video - The video element to use as a data source for the texture. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + */ + constructor(video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy) { + super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoTexture = true; + this.generateMipmaps = false; + this._requestVideoFrameCallbackId = 0; + const scope = this; + function updateVideo() { + scope.needsUpdate = true; + scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback(updateVideo); + } + if ("requestVideoFrameCallback" in video) { + this._requestVideoFrameCallbackId = video.requestVideoFrameCallback(updateVideo); + } + } + clone() { + return new this.constructor(this.image).copy(this); + } + /** + * This method is called automatically by the renderer and sets {@link Texture#needsUpdate} + * to `true` every time a new frame is available. + * + * Only relevant if `requestVideoFrameCallback` is not supported in the browser. + */ + update() { + const video = this.image; + const hasVideoFrameCallback = "requestVideoFrameCallback" in video; + if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) { + this.needsUpdate = true; + } + } + dispose() { + if (this._requestVideoFrameCallbackId !== 0) { + this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId); + this._requestVideoFrameCallbackId = 0; + } + super.dispose(); + } + } + class VideoFrameTexture extends VideoTexture { + /** + * Constructs a new video frame texture. + * + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + */ + constructor(mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super({}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoFrameTexture = true; + } + /** + * This method overwritten with an empty implementation since + * this type of texture is updated via `setFrame()`. + */ + update() { + } + clone() { + return new this.constructor().copy(this); + } + /** + * Sets the current frame of the video. This will automatically update the texture + * so the data can be used for rendering. + * + * @param {VideoFrame} frame - The video frame. + */ + setFrame(frame) { + this.image = frame; + this.needsUpdate = true; + } + } + class FramebufferTexture extends Texture { + /** + * Constructs a new framebuffer texture. + * + * @param {number} [width] - The width of the texture. + * @param {number} [height] - The height of the texture. + */ + constructor(width, height) { + super({ width, height }); + this.isFramebufferTexture = true; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.generateMipmaps = false; + this.needsUpdate = true; + } + } + class CompressedTexture extends Texture { + /** + * Constructs a new compressed texture. + * + * @param {Array} mipmaps - This array holds for all mipmaps (including the bases mip) + * the data and dimensions. + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space. + */ + constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCompressedTexture = true; + this.image = { width, height }; + this.mipmaps = mipmaps; + this.flipY = false; + this.generateMipmaps = false; + } + } + class CompressedArrayTexture extends CompressedTexture { + /** + * Constructs a new compressed array texture. + * + * @param {Array} mipmaps - This array holds for all mipmaps (including the bases mip) + * the data and dimensions. + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} depth - The depth of the texture. + * @param {number} [format=RGBAFormat] - The min filter value. + * @param {number} [type=UnsignedByteType] - The min filter value. + */ + constructor(mipmaps, width, height, depth, format, type) { + super(mipmaps, width, height, format, type); + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping; + this.layerUpdates = /* @__PURE__ */ new Set(); + } + /** + * Describes that a specific layer of the texture needs to be updated. + * Normally when {@link Texture#needsUpdate} is set to `true`, the + * entire compressed texture array is sent to the GPU. Marking specific + * layers will only transmit subsets of all mipmaps associated with a + * specific depth in the array which is often much more performant. + * + * @param {number} layerIndex - The layer index that should be updated. + */ + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + /** + * Resets the layer updates registry. + */ + clearLayerUpdates() { + this.layerUpdates.clear(); + } + } + class CompressedCubeTexture extends CompressedTexture { + /** + * Constructs a new compressed texture. + * + * @param {Array} images - An array of compressed textures. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + */ + constructor(images, format, type) { + super(void 0, images[0].width, images[0].height, format, type, CubeReflectionMapping); + this.isCompressedCubeTexture = true; + this.isCubeTexture = true; + this.image = images; + } + } + class CubeTexture extends Texture { + /** + * Constructs a new cube texture. + * + * @param {Array} [images=[]] - An array holding a image for each side of a cube. + * @param {number} [mapping=CubeReflectionMapping] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space value. + */ + constructor(images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + /** + * Alias for {@link CubeTexture#image}. + * + * @type {Array} + */ + get images() { + return this.image; + } + set images(value) { + this.image = value; + } + } + class CanvasTexture extends Texture { + /** + * Constructs a new texture. + * + * @param {HTMLCanvasElement} [canvas] - The HTML canvas element. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + */ + constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isCanvasTexture = true; + this.needsUpdate = true; + } + } + class HTMLTexture extends Texture { + /** + * Constructs a new texture. + * + * @param {HTMLElement} [element] - The HTML element. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + */ + constructor(element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isHTMLTexture = true; + this.generateMipmaps = false; + this.needsUpdate = true; + const parent = element ? element.parentNode : null; + if (parent !== null && "requestPaint" in parent) { + parent.onpaint = () => { + this.needsUpdate = true; + }; + parent.requestPaint(); + } + } + dispose() { + const parent = this.image ? this.image.parentNode : null; + if (parent !== null && "onpaint" in parent) { + parent.onpaint = null; + } + super.dispose(); + } + } + class DepthTexture extends Texture { + /** + * Constructs a new depth texture. + * + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} [type=UnsignedIntType] - The texture type. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {number} [format=DepthFormat] - The texture format. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor(width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1) { + if (format !== DepthFormat && format !== DepthStencilFormat) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + const image = { width, height, depth }; + super(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.source = new Source(Object.assign({}, source.image)); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + if (this.compareFunction !== null) data.compareFunction = this.compareFunction; + return data; + } + } + class CubeDepthTexture extends DepthTexture { + /** + * Constructs a new cube depth texture. + * + * @param {number} size - The size (width and height) of each cube face. + * @param {number} [type=UnsignedIntType] - The texture type. + * @param {number} [mapping=CubeReflectionMapping] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=NearestFilter] - The mag filter value. + * @param {number} [minFilter=NearestFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {number} [format=DepthFormat] - The texture format. + */ + constructor(size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat) { + const image = { width: size, height: size, depth: 1 }; + const images = [image, image, image, image, image, image]; + super(size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format); + this.image = images; + this.isCubeDepthTexture = true; + this.isCubeTexture = true; + } + /** + * Alias for {@link CubeDepthTexture#image}. + * + * @type {Array} + */ + get images() { + return this.image; + } + set images(value) { + this.image = value; + } + } + class ExternalTexture extends Texture { + /** + * Creates a new raw texture. + * + * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture. + */ + constructor(sourceTexture = null) { + super(); + this.sourceTexture = sourceTexture; + this.isExternalTexture = true; + } + copy(source) { + super.copy(source); + this.sourceTexture = source.sourceTexture; + return this; + } + } + class BoxGeometry extends BufferGeometry { + /** + * Constructs a new box geometry. + * + * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis. + * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis. + * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis. + * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides. + * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides. + * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides. + */ + constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width, + height, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function buildPlane(u, v, w, udir, vdir, width2, height2, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width2 / gridX; + const segmentHeight = height2 / gridY; + const widthHalf = width2 / 2; + const heightHalf = height2 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector3(); + for (let iy = 0; iy < gridY1; iy++) { + const y = iy * segmentHeight - heightHalf; + for (let ix = 0; ix < gridX1; ix++) { + const x = ix * segmentWidth - widthHalf; + vector[u] = x * udir; + vector[v] = y * vdir; + vector[w] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u] = 0; + vector[v] = 0; + vector[w] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0; iy < gridY; iy++) { + for (let ix = 0; ix < gridX; ix++) { + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * (iy + 1); + const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {BoxGeometry} A new instance. + */ + static fromJSON(data) { + return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments); + } + } + class CapsuleGeometry extends BufferGeometry { + /** + * Constructs a new capsule geometry. + * + * @param {number} [radius=1] - Radius of the capsule. + * @param {number} [height=1] - Height of the middle section. + * @param {number} [capSegments=4] - Number of curve segments used to build each cap. + * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3. + * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1. + */ + constructor(radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1) { + super(); + this.type = "CapsuleGeometry"; + this.parameters = { + radius, + height, + capSegments, + radialSegments, + heightSegments + }; + height = Math.max(0, height); + capSegments = Math.max(1, Math.floor(capSegments)); + radialSegments = Math.max(3, Math.floor(radialSegments)); + heightSegments = Math.max(1, Math.floor(heightSegments)); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const halfHeight = height / 2; + const capArcLength = Math.PI / 2 * radius; + const cylinderPartLength = height; + const totalArcLength = 2 * capArcLength + cylinderPartLength; + const numVerticalSegments = capSegments * 2 + heightSegments; + const verticesPerRow = radialSegments + 1; + const normal = new Vector3(); + const vertex2 = new Vector3(); + for (let iy = 0; iy <= numVerticalSegments; iy++) { + let currentArcLength = 0; + let profileY = 0; + let profileRadius = 0; + let normalYComponent = 0; + if (iy <= capSegments) { + const segmentProgress = iy / capSegments; + const angle = segmentProgress * Math.PI / 2; + profileY = -halfHeight - radius * Math.cos(angle); + profileRadius = radius * Math.sin(angle); + normalYComponent = -radius * Math.cos(angle); + currentArcLength = segmentProgress * capArcLength; + } else if (iy <= capSegments + heightSegments) { + const segmentProgress = (iy - capSegments) / heightSegments; + profileY = -halfHeight + segmentProgress * height; + profileRadius = radius; + normalYComponent = 0; + currentArcLength = capArcLength + segmentProgress * cylinderPartLength; + } else { + const segmentProgress = (iy - capSegments - heightSegments) / capSegments; + const angle = segmentProgress * Math.PI / 2; + profileY = halfHeight + radius * Math.sin(angle); + profileRadius = radius * Math.cos(angle); + normalYComponent = radius * Math.sin(angle); + currentArcLength = capArcLength + cylinderPartLength + segmentProgress * capArcLength; + } + const v = Math.max(0, Math.min(1, currentArcLength / totalArcLength)); + let uOffset = 0; + if (iy === 0) { + uOffset = 0.5 / radialSegments; + } else if (iy === numVerticalSegments) { + uOffset = -0.5 / radialSegments; + } + for (let ix = 0; ix <= radialSegments; ix++) { + const u = ix / radialSegments; + const theta = u * Math.PI * 2; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex2.x = -profileRadius * cosTheta; + vertex2.y = profileY; + vertex2.z = profileRadius * sinTheta; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normal.set( + -profileRadius * cosTheta, + normalYComponent, + profileRadius * sinTheta + ); + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u + uOffset, v); + } + if (iy > 0) { + const prevIndexRow = (iy - 1) * verticesPerRow; + for (let ix = 0; ix < radialSegments; ix++) { + const i1 = prevIndexRow + ix; + const i2 = prevIndexRow + ix + 1; + const i3 = iy * verticesPerRow + ix; + const i4 = iy * verticesPerRow + ix + 1; + indices.push(i1, i2, i3); + indices.push(i2, i4, i3); + } + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {CapsuleGeometry} A new instance. + */ + static fromJSON(data) { + return new CapsuleGeometry(data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments); + } + } + class CircleGeometry extends BufferGeometry { + /** + * Constructs a new circle geometry. + * + * @param {number} [radius=1] - Radius of the circle. + * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`. + * @param {number} [thetaStart=0] - Start angle for first segment in radians. + * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, + * of the circular sector in radians. The default value results in a complete circle. + */ + constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CircleGeometry"; + this.parameters = { + radius, + segments, + thetaStart, + thetaLength + }; + segments = Math.max(3, segments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex2 = new Vector3(); + const uv = new Vector2(); + vertices.push(0, 0, 0); + normals.push(0, 0, 1); + uvs.push(0.5, 0.5); + for (let s = 0, i = 3; s <= segments; s++, i += 3) { + const segment = thetaStart + s / segments * thetaLength; + vertex2.x = radius * Math.cos(segment); + vertex2.y = radius * Math.sin(segment); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normals.push(0, 0, 1); + uv.x = (vertices[i] / radius + 1) / 2; + uv.y = (vertices[i + 1] / radius + 1) / 2; + uvs.push(uv.x, uv.y); + } + for (let i = 1; i <= segments; i++) { + indices.push(i, i + 1, 0); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {CircleGeometry} A new instance. + */ + static fromJSON(data) { + return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength); + } + } + class CylinderGeometry extends BufferGeometry { + /** + * Constructs a new cylinder geometry. + * + * @param {number} [radiusTop=1] - Radius of the cylinder at the top. + * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom. + * @param {number} [height=1] - Height of the cylinder. + * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder. + * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder. + * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped. + * @param {number} [thetaStart=0] - Start angle for first segment, in radians. + * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians. + * The default value results in a complete cylinder. + */ + constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CylinderGeometry"; + this.parameters = { + radiusTop, + radiusBottom, + height, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + const scope = this; + radialSegments = Math.floor(radialSegments); + heightSegments = Math.floor(heightSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index = 0; + const indexArray = []; + const halfHeight = height / 2; + let groupStart = 0; + generateTorso(); + if (openEnded === false) { + if (radiusTop > 0) generateCap(true); + if (radiusBottom > 0) generateCap(false); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateTorso() { + const normal = new Vector3(); + const vertex2 = new Vector3(); + let groupCount = 0; + const slope = (radiusBottom - radiusTop) / height; + for (let y = 0; y <= heightSegments; y++) { + const indexRow = []; + const v = y / heightSegments; + const radius = v * (radiusBottom - radiusTop) + radiusTop; + for (let x = 0; x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex2.x = radius * sinTheta; + vertex2.y = -v * height + halfHeight; + vertex2.z = radius * cosTheta; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u, 1 - v); + indexRow.push(index++); + } + indexArray.push(indexRow); + } + for (let x = 0; x < radialSegments; x++) { + for (let y = 0; y < heightSegments; y++) { + const a = indexArray[y][x]; + const b = indexArray[y + 1][x]; + const c = indexArray[y + 1][x + 1]; + const d = indexArray[y][x + 1]; + if (radiusTop > 0 || y !== 0) { + indices.push(a, b, d); + groupCount += 3; + } + if (radiusBottom > 0 || y !== heightSegments - 1) { + indices.push(b, c, d); + groupCount += 3; + } + } + } + scope.addGroup(groupStart, groupCount, 0); + groupStart += groupCount; + } + function generateCap(top) { + const centerIndexStart = index; + const uv = new Vector2(); + const vertex2 = new Vector3(); + let groupCount = 0; + const radius = top === true ? radiusTop : radiusBottom; + const sign2 = top === true ? 1 : -1; + for (let x = 1; x <= radialSegments; x++) { + vertices.push(0, halfHeight * sign2, 0); + normals.push(0, sign2, 0); + uvs.push(0.5, 0.5); + index++; + } + const centerIndexEnd = index; + for (let x = 0; x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + vertex2.x = radius * sinTheta; + vertex2.y = halfHeight * sign2; + vertex2.z = radius * cosTheta; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normals.push(0, sign2, 0); + uv.x = cosTheta * 0.5 + 0.5; + uv.y = sinTheta * 0.5 * sign2 + 0.5; + uvs.push(uv.x, uv.y); + index++; + } + for (let x = 0; x < radialSegments; x++) { + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + if (top === true) { + indices.push(i, i + 1, c); + } else { + indices.push(i + 1, i, c); + } + groupCount += 3; + } + scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + groupStart += groupCount; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {CylinderGeometry} A new instance. + */ + static fromJSON(data) { + return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength); + } + } + class ConeGeometry extends CylinderGeometry { + /** + * Constructs a new cone geometry. + * + * @param {number} [radius=1] - Radius of the cone base. + * @param {number} [height=1] - Height of the cone. + * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone. + * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone. + * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped. + * @param {number} [thetaStart=0] - Start angle for first segment, in radians. + * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians. + * The default value results in a complete cone. + */ + constructor(radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); + this.type = "ConeGeometry"; + this.parameters = { + radius, + height, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {ConeGeometry} A new instance. + */ + static fromJSON(data) { + return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength); + } + } + class PolyhedronGeometry extends BufferGeometry { + /** + * Constructs a new polyhedron geometry. + * + * @param {Array} [vertices] - A flat array of vertices describing the base shape. + * @param {Array} [indices] - A flat array of indices describing the base shape. + * @param {number} [radius=1] - The radius of the shape. + * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape. + */ + constructor(vertices = [], indices = [], radius = 1, detail = 0) { + super(); + this.type = "PolyhedronGeometry"; + this.parameters = { + vertices, + indices, + radius, + detail + }; + const vertexBuffer = []; + const uvBuffer = []; + subdivide(detail); + applyRadius(radius); + generateUVs(); + this.setAttribute("position", new Float32BufferAttribute(vertexBuffer, 3)); + this.setAttribute("normal", new Float32BufferAttribute(vertexBuffer.slice(), 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvBuffer, 2)); + if (detail === 0) { + this.computeVertexNormals(); + } else { + this.normalizeNormals(); + } + function subdivide(detail2) { + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + for (let i = 0; i < indices.length; i += 3) { + getVertexByIndex(indices[i + 0], a); + getVertexByIndex(indices[i + 1], b); + getVertexByIndex(indices[i + 2], c); + subdivideFace(a, b, c, detail2); + } + } + function subdivideFace(a, b, c, detail2) { + const cols = detail2 + 1; + const v = []; + for (let i = 0; i <= cols; i++) { + v[i] = []; + const aj = a.clone().lerp(c, i / cols); + const bj = b.clone().lerp(c, i / cols); + const rows2 = cols - i; + for (let j = 0; j <= rows2; j++) { + if (j === 0 && i === cols) { + v[i][j] = aj; + } else { + v[i][j] = aj.clone().lerp(bj, j / rows2); + } + } + } + for (let i = 0; i < cols; i++) { + for (let j = 0; j < 2 * (cols - i) - 1; j++) { + const k = Math.floor(j / 2); + if (j % 2 === 0) { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k]); + pushVertex(v[i][k]); + } else { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k + 1]); + pushVertex(v[i + 1][k]); + } + } + } + } + function applyRadius(radius2) { + const vertex2 = new Vector3(); + for (let i = 0; i < vertexBuffer.length; i += 3) { + vertex2.x = vertexBuffer[i + 0]; + vertex2.y = vertexBuffer[i + 1]; + vertex2.z = vertexBuffer[i + 2]; + vertex2.normalize().multiplyScalar(radius2); + vertexBuffer[i + 0] = vertex2.x; + vertexBuffer[i + 1] = vertex2.y; + vertexBuffer[i + 2] = vertex2.z; + } + } + function generateUVs() { + const vertex2 = new Vector3(); + for (let i = 0; i < vertexBuffer.length; i += 3) { + vertex2.x = vertexBuffer[i + 0]; + vertex2.y = vertexBuffer[i + 1]; + vertex2.z = vertexBuffer[i + 2]; + const u = azimuth(vertex2) / 2 / Math.PI + 0.5; + const v = inclination(vertex2) / Math.PI + 0.5; + uvBuffer.push(u, 1 - v); + } + correctUVs(); + correctSeam(); + } + function correctSeam() { + for (let i = 0; i < uvBuffer.length; i += 6) { + const x0 = uvBuffer[i + 0]; + const x1 = uvBuffer[i + 2]; + const x2 = uvBuffer[i + 4]; + const max = Math.max(x0, x1, x2); + const min = Math.min(x0, x1, x2); + if (max > 0.9 && min < 0.1) { + if (x0 < 0.2) uvBuffer[i + 0] += 1; + if (x1 < 0.2) uvBuffer[i + 2] += 1; + if (x2 < 0.2) uvBuffer[i + 4] += 1; + } + } + } + function pushVertex(vertex2) { + vertexBuffer.push(vertex2.x, vertex2.y, vertex2.z); + } + function getVertexByIndex(index, vertex2) { + const stride = index * 3; + vertex2.x = vertices[stride + 0]; + vertex2.y = vertices[stride + 1]; + vertex2.z = vertices[stride + 2]; + } + function correctUVs() { + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + const centroid = new Vector3(); + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); + for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) { + a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); + b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); + c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); + uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]); + uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]); + uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]); + centroid.copy(a).add(b).add(c).divideScalar(3); + const azi = azimuth(centroid); + correctUV(uvA, j + 0, a, azi); + correctUV(uvB, j + 2, b, azi); + correctUV(uvC, j + 4, c, azi); + } + } + function correctUV(uv, stride, vector, azimuth2) { + if (azimuth2 < 0 && uv.x === 1) { + uvBuffer[stride] = uv.x - 1; + } + if (vector.x === 0 && vector.z === 0) { + uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; + } + } + function azimuth(vector) { + return Math.atan2(vector.z, -vector.x); + } + function inclination(vector) { + return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {PolyhedronGeometry} A new instance. + */ + static fromJSON(data) { + return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.detail); + } + } + class DodecahedronGeometry extends PolyhedronGeometry { + /** + * Constructs a new dodecahedron geometry. + * + * @param {number} [radius=1] - Radius of the dodecahedron. + * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron. + */ + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const r = 1 / t; + const vertices = [ + // (±1, ±1, ±1) + -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, ±1/φ, ±φ) + 0, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + // (±1/φ, ±φ, 0) + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + 0, + // (±φ, 0, ±1/φ) + -t, + 0, + -r, + t, + 0, + -r, + -t, + 0, + r, + t, + 0, + r + ]; + const indices = [ + 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 + ]; + super(vertices, indices, radius, detail); + this.type = "DodecahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {DodecahedronGeometry} A new instance. + */ + static fromJSON(data) { + return new DodecahedronGeometry(data.radius, data.detail); + } + } + const _v0$1 = /* @__PURE__ */ new Vector3(); + const _v1$1 = /* @__PURE__ */ new Vector3(); + const _normal = /* @__PURE__ */ new Vector3(); + const _triangle = /* @__PURE__ */ new Triangle(); + class EdgesGeometry extends BufferGeometry { + /** + * Constructs a new edges geometry. + * + * @param {?BufferGeometry} [geometry=null] - The geometry. + * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees) + * between the face normals of the adjoining faces exceeds this value. + */ + constructor(geometry = null, thresholdAngle = 1) { + super(); + this.type = "EdgesGeometry"; + this.parameters = { + geometry, + thresholdAngle + }; + if (geometry !== null) { + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(DEG2RAD * thresholdAngle); + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + const indexArr = [0, 0, 0]; + const vertKeys = ["a", "b", "c"]; + const hashes = new Array(3); + const edgeData = {}; + const vertices = []; + for (let i = 0; i < indexCount; i += 3) { + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + const { a, b, c } = _triangle; + a.fromBufferAttribute(positionAttr, indexArr[0]); + b.fromBufferAttribute(positionAttr, indexArr[1]); + c.fromBufferAttribute(positionAttr, indexArr[2]); + _triangle.getNormal(_normal); + hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`; + hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`; + hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + for (let j = 0; j < 3; j++) { + const jNext = (j + 1) % 3; + const vecHash0 = hashes[j]; + const vecHash1 = hashes[jNext]; + const v0 = _triangle[vertKeys[j]]; + const v1 = _triangle[vertKeys[jNext]]; + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + if (reverseHash in edgeData && edgeData[reverseHash]) { + if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) { + vertices.push(v0.x, v0.y, v0.z); + vertices.push(v1.x, v1.y, v1.z); + } + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j], + index1: indexArr[jNext], + normal: _normal.clone() + }; + } + } + } + for (const key in edgeData) { + if (edgeData[key]) { + const { index0, index1 } = edgeData[key]; + _v0$1.fromBufferAttribute(positionAttr, index0); + _v1$1.fromBufferAttribute(positionAttr, index1); + vertices.push(_v0$1.x, _v0$1.y, _v0$1.z); + vertices.push(_v1$1.x, _v1$1.y, _v1$1.z); + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + } + class Curve { + /** + * Constructs a new curve. + */ + constructor() { + this.type = "Curve"; + this.arcLengthDivisions = 200; + this.needsUpdate = false; + this.cacheArcLengths = null; + } + /** + * This method returns a vector in 2D or 3D space (depending on the curve definition) + * for the given interpolation factor. + * + * @abstract + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition. + */ + getPoint() { + warn("Curve: .getPoint() not implemented."); + } + /** + * This method returns a vector in 2D or 3D space (depending on the curve definition) + * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length + * of the curve which equidistant samples. + * + * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition. + */ + getPointAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getPoint(t, optionalTarget); + } + /** + * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing + * the curve shape. + * + * @param {number} [divisions=5] - The number of divisions. + * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`. + */ + getPoints(divisions = 5) { + const points = []; + for (let d = 0; d <= divisions; d++) { + points.push(this.getPoint(d / divisions)); + } + return points; + } + // Get sequence of points using getPointAt( u ) + /** + * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing + * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire + * curve. + * + * @param {number} [divisions=5] - The number of divisions. + * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`. + */ + getSpacedPoints(divisions = 5) { + const points = []; + for (let d = 0; d <= divisions; d++) { + points.push(this.getPointAt(d / divisions)); + } + return points; + } + /** + * Returns the total arc length of the curve. + * + * @return {number} The length of the curve. + */ + getLength() { + const lengths = this.getLengths(); + return lengths[lengths.length - 1]; + } + /** + * Returns an array of cumulative segment lengths of the curve. + * + * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions. + * @return {Array} An array holding the cumulative segment lengths. + */ + getLengths(divisions = this.arcLengthDivisions) { + if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { + return this.cacheArcLengths; + } + this.needsUpdate = false; + const cache = []; + let current, last = this.getPoint(0); + let sum = 0; + cache.push(0); + for (let p = 1; p <= divisions; p++) { + current = this.getPoint(p / divisions); + sum += current.distanceTo(last); + cache.push(sum); + last = current; + } + this.cacheArcLengths = cache; + return cache; + } + /** + * Update the cumulative segment distance cache. The method must be called + * every time curve parameters are changed. If an updated curve is part of a + * composed curve like {@link CurvePath}, this method must be called on the + * composed curve, too. + */ + updateArcLengths() { + this.needsUpdate = true; + this.getLengths(); + } + /** + * Given an interpolation factor in the range `[0,1]`, this method returns an updated + * interpolation factor in the same range that can be ued to sample equidistant points + * from a curve. + * + * @param {number} u - The interpolation factor. + * @param {?number} distance - An optional distance on the curve. + * @return {number} The updated interpolation factor. + */ + getUtoTmapping(u, distance = null) { + const arcLengths = this.getLengths(); + let i = 0; + const il = arcLengths.length; + let targetArcLength; + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u * arcLengths[il - 1]; + } + let low = 0, high = il - 1, comparison; + while (low <= high) { + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + } else if (comparison > 0) { + high = i - 1; + } else { + high = i; + break; + } + } + i = high; + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + const segmentLength = lengthAfter - lengthBefore; + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + const t = (i + segmentFraction) / (il - 1); + return t; + } + /** + * Returns a unit vector tangent for the given interpolation factor. + * If the derived curve does not implement its tangent derivation, + * two points a small delta apart will be used to find its gradient + * which seems to give a reasonable approximation. + * + * @param {number} t - The interpolation factor. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {(Vector2|Vector3)} The tangent vector. + */ + getTangent(t, optionalTarget) { + const delta = 1e-4; + let t1 = t - delta; + let t2 = t + delta; + if (t1 < 0) t1 = 0; + if (t2 > 1) t2 = 1; + const pt1 = this.getPoint(t1); + const pt2 = this.getPoint(t2); + const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3()); + tangent.copy(pt2).sub(pt1).normalize(); + return tangent; + } + /** + * Same as {@link Curve#getTangent} but with equidistant samples. + * + * @param {number} u - The interpolation factor. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {(Vector2|Vector3)} The tangent vector. + * @see {@link Curve#getPointAt} + */ + getTangentAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getTangent(t, optionalTarget); + } + /** + * Generates the Frenet Frames. Requires a curve definition in 3D space. Used + * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}. + * + * @param {number} segments - The number of segments. + * @param {boolean} [closed=false] - Whether the curve is closed or not. + * @return {{tangents: Array, normals: Array, binormals: Array}} The Frenet Frames. + */ + computeFrenetFrames(segments, closed = false) { + const normal = new Vector3(); + const tangents = []; + const normals = []; + const binormals = []; + const vec = new Vector3(); + const mat = new Matrix4(); + for (let i = 0; i <= segments; i++) { + const u = i / segments; + tangents[i] = this.getTangentAt(u, new Vector3()); + } + normals[0] = new Vector3(); + binormals[0] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs(tangents[0].x); + const ty = Math.abs(tangents[0].y); + const tz = Math.abs(tangents[0].z); + if (tx <= min) { + min = tx; + normal.set(1, 0, 0); + } + if (ty <= min) { + min = ty; + normal.set(0, 1, 0); + } + if (tz <= min) { + normal.set(0, 0, 1); + } + vec.crossVectors(tangents[0], normal).normalize(); + normals[0].crossVectors(tangents[0], vec); + binormals[0].crossVectors(tangents[0], normals[0]); + for (let i = 1; i <= segments; i++) { + normals[i] = normals[i - 1].clone(); + binormals[i] = binormals[i - 1].clone(); + vec.crossVectors(tangents[i - 1], tangents[i]); + if (vec.length() > Number.EPSILON) { + vec.normalize(); + const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); + normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); + } + binormals[i].crossVectors(tangents[i], normals[i]); + } + if (closed === true) { + let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1)); + theta /= segments; + if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { + theta = -theta; + } + for (let i = 1; i <= segments; i++) { + normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); + binormals[i].crossVectors(tangents[i], normals[i]); + } + } + return { + tangents, + normals, + binormals + }; + } + /** + * Returns a new curve with copied values from this instance. + * + * @return {Curve} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given curve to this instance. + * + * @param {Curve} source - The curve to copy. + * @return {Curve} A reference to this curve. + */ + copy(source) { + this.arcLengthDivisions = source.arcLengthDivisions; + return this; + } + /** + * Serializes the curve into JSON. + * + * @return {Object} A JSON object representing the serialized curve. + * @see {@link ObjectLoader#parse} + */ + toJSON() { + const data = { + metadata: { + version: 4.7, + type: "Curve", + generator: "Curve.toJSON" + } + }; + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; + return data; + } + /** + * Deserializes the curve from the given JSON. + * + * @param {Object} json - The JSON holding the serialized curve. + * @return {Curve} A reference to this curve. + */ + fromJSON(json) { + this.arcLengthDivisions = json.arcLengthDivisions; + return this; + } + } + class EllipseCurve extends Curve { + /** + * Constructs a new ellipse curve. + * + * @param {number} [aX=0] - The X center of the ellipse. + * @param {number} [aY=0] - The Y center of the ellipse. + * @param {number} [xRadius=1] - The radius of the ellipse in the x direction. + * @param {number} [yRadius=1] - The radius of the ellipse in the y direction. + * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis. + * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis. + * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not. + * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. + */ + constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { + super(); + this.isEllipseCurve = true; + this.type = "EllipseCurve"; + this.aX = aX; + this.aY = aY; + this.xRadius = xRadius; + this.yRadius = yRadius; + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + this.aClockwise = aClockwise; + this.aRotation = aRotation; + } + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the curve. + */ + getPoint(t, optionalTarget = new Vector2()) { + const point2 = optionalTarget; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + while (deltaAngle < 0) deltaAngle += twoPi; + while (deltaAngle > twoPi) deltaAngle -= twoPi; + if (deltaAngle < Number.EPSILON) { + if (samePoints) { + deltaAngle = 0; + } else { + deltaAngle = twoPi; + } + } + if (this.aClockwise === true && !samePoints) { + if (deltaAngle === twoPi) { + deltaAngle = -twoPi; + } else { + deltaAngle = deltaAngle - twoPi; + } + } + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos(angle); + let y = this.aY + this.yRadius * Math.sin(angle); + if (this.aRotation !== 0) { + const cos = Math.cos(this.aRotation); + const sin = Math.sin(this.aRotation); + const tx = x - this.aX; + const ty = y - this.aY; + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + } + return point2.set(x, y); + } + copy(source) { + super.copy(source); + this.aX = source.aX; + this.aY = source.aY; + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + this.aClockwise = source.aClockwise; + this.aRotation = source.aRotation; + return this; + } + toJSON() { + const data = super.toJSON(); + data.aX = this.aX; + data.aY = this.aY; + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; + data.aClockwise = this.aClockwise; + data.aRotation = this.aRotation; + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.aX = json.aX; + this.aY = json.aY; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + this.aClockwise = json.aClockwise; + this.aRotation = json.aRotation; + return this; + } + } + class ArcCurve extends EllipseCurve { + /** + * Constructs a new arc curve. + * + * @param {number} [aX=0] - The X center of the ellipse. + * @param {number} [aY=0] - The Y center of the ellipse. + * @param {number} [aRadius=1] - The radius of the ellipse in the x direction. + * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis. + * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis. + * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not. + */ + constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + this.isArcCurve = true; + this.type = "ArcCurve"; + } + } + function CubicPoly() { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + function init(x0, x1, t0, t1) { + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + } + return { + initCatmullRom: function(x0, x1, x2, x3, tension) { + init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); + }, + initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) { + let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; + let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t2 *= dt1; + init(x1, x2, t1, t2); + }, + calc: function(t) { + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + } + }; + } + const tmp = /* @__PURE__ */ new Vector3(); + const tmp2 = /* @__PURE__ */ new Vector3(); + const px = /* @__PURE__ */ new CubicPoly(); + const py = /* @__PURE__ */ new CubicPoly(); + const pz = /* @__PURE__ */ new CubicPoly(); + class CatmullRomCurve3 extends Curve { + /** + * Constructs a new Catmull-Rom curve. + * + * @param {Array} [points] - An array of 3D points defining the curve. + * @param {boolean} [closed=false] - Whether the curve is closed or not. + * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type. + * @param {number} [tension=0.5] - Tension of the curve. + */ + constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { + super(); + this.isCatmullRomCurve3 = true; + this.type = "CatmullRomCurve3"; + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector3} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector3} The position on the curve. + */ + getPoint(t, optionalTarget = new Vector3()) { + const point2 = optionalTarget; + const points = this.points; + const l = points.length; + const p = (l - (this.closed ? 0 : 1)) * t; + let intPoint = Math.floor(p); + let weight = p - intPoint; + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; + } else if (weight === 0 && intPoint === l - 1) { + intPoint = l - 2; + weight = 1; + } + let p0, p3; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l]; + } else { + tmp2.subVectors(points[0], points[1]).add(points[0]); + p0 = tmp2; + } + const p1 = points[intPoint % l]; + const p2 = points[(intPoint + 1) % l]; + if (this.closed || intPoint + 2 < l) { + p3 = points[(intPoint + 2) % l]; + } else { + tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]); + p3 = tmp; + } + if (this.curveType === "centripetal" || this.curveType === "chordal") { + const pow = this.curveType === "chordal" ? 0.5 : 0.25; + let dt0 = Math.pow(p0.distanceToSquared(p1), pow); + let dt1 = Math.pow(p1.distanceToSquared(p2), pow); + let dt2 = Math.pow(p2.distanceToSquared(p3), pow); + if (dt1 < 1e-4) dt1 = 1; + if (dt0 < 1e-4) dt0 = dt1; + if (dt2 < 1e-4) dt2 = dt1; + px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); + py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); + pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); + } else if (this.curveType === "catmullrom") { + px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); + py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); + pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); + } + point2.set( + px.calc(weight), + py.calc(weight), + pz.calc(weight) + ); + return point2; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length; i < l; i++) { + const point2 = source.points[i]; + this.points.push(point2.clone()); + } + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + return this; + } + toJSON() { + const data = super.toJSON(); + data.points = []; + for (let i = 0, l = this.points.length; i < l; i++) { + const point2 = this.points[i]; + data.points.push(point2.toArray()); + } + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length; i < l; i++) { + const point2 = json.points[i]; + this.points.push(new Vector3().fromArray(point2)); + } + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + return this; + } + } + function CatmullRom(t, p0, p1, p2, p3) { + const v0 = (p2 - p0) * 0.5; + const v1 = (p3 - p1) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + } + function QuadraticBezierP0(t, p) { + const k = 1 - t; + return k * k * p; + } + function QuadraticBezierP1(t, p) { + return 2 * (1 - t) * t * p; + } + function QuadraticBezierP2(t, p) { + return t * t * p; + } + function QuadraticBezier(t, p0, p1, p2) { + return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2); + } + function CubicBezierP0(t, p) { + const k = 1 - t; + return k * k * k * p; + } + function CubicBezierP1(t, p) { + const k = 1 - t; + return 3 * k * k * t * p; + } + function CubicBezierP2(t, p) { + return 3 * (1 - t) * t * t * p; + } + function CubicBezierP3(t, p) { + return t * t * t * p; + } + function CubicBezier(t, p0, p1, p2, p3) { + return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3); + } + class CubicBezierCurve extends Curve { + /** + * Constructs a new Cubic Bezier curve. + * + * @param {Vector2} [v0] - The start point. + * @param {Vector2} [v1] - The first control point. + * @param {Vector2} [v2] - The second control point. + * @param {Vector2} [v3] - The end point. + */ + constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) { + super(); + this.isCubicBezierCurve = true; + this.type = "CubicBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the curve. + */ + getPoint(t, optionalTarget = new Vector2()) { + const point2 = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point2.set( + CubicBezier(t, v0.x, v1.x, v2.x, v3.x), + CubicBezier(t, v0.y, v1.y, v2.y, v3.y) + ); + return point2; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + } + class CubicBezierCurve3 extends Curve { + /** + * Constructs a new Cubic Bezier curve. + * + * @param {Vector3} [v0] - The start point. + * @param {Vector3} [v1] - The first control point. + * @param {Vector3} [v2] - The second control point. + * @param {Vector3} [v3] - The end point. + */ + constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) { + super(); + this.isCubicBezierCurve3 = true; + this.type = "CubicBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector3} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector3} The position on the curve. + */ + getPoint(t, optionalTarget = new Vector3()) { + const point2 = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point2.set( + CubicBezier(t, v0.x, v1.x, v2.x, v3.x), + CubicBezier(t, v0.y, v1.y, v2.y, v3.y), + CubicBezier(t, v0.z, v1.z, v2.z, v3.z) + ); + return point2; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + } + class LineCurve extends Curve { + /** + * Constructs a new line curve. + * + * @param {Vector2} [v1] - The start point. + * @param {Vector2} [v2] - The end point. + */ + constructor(v1 = new Vector2(), v2 = new Vector2()) { + super(); + this.isLineCurve = true; + this.type = "LineCurve"; + this.v1 = v1; + this.v2 = v2; + } + /** + * Returns a point on the line. + * + * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the line. + */ + getPoint(t, optionalTarget = new Vector2()) { + const point2 = optionalTarget; + if (t === 1) { + point2.copy(this.v2); + } else { + point2.copy(this.v2).sub(this.v1); + point2.multiplyScalar(t).add(this.v1); + } + return point2; + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector2()) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + class LineCurve3 extends Curve { + /** + * Constructs a new line curve. + * + * @param {Vector3} [v1] - The start point. + * @param {Vector3} [v2] - The end point. + */ + constructor(v1 = new Vector3(), v2 = new Vector3()) { + super(); + this.isLineCurve3 = true; + this.type = "LineCurve3"; + this.v1 = v1; + this.v2 = v2; + } + /** + * Returns a point on the line. + * + * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`. + * @param {Vector3} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector3} The position on the line. + */ + getPoint(t, optionalTarget = new Vector3()) { + const point2 = optionalTarget; + if (t === 1) { + point2.copy(this.v2); + } else { + point2.copy(this.v2).sub(this.v1); + point2.multiplyScalar(t).add(this.v1); + } + return point2; + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector3()) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + class QuadraticBezierCurve extends Curve { + /** + * Constructs a new Quadratic Bezier curve. + * + * @param {Vector2} [v0] - The start point. + * @param {Vector2} [v1] - The control point. + * @param {Vector2} [v2] - The end point. + */ + constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) { + super(); + this.isQuadraticBezierCurve = true; + this.type = "QuadraticBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the curve. + */ + getPoint(t, optionalTarget = new Vector2()) { + const point2 = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point2.set( + QuadraticBezier(t, v0.x, v1.x, v2.x), + QuadraticBezier(t, v0.y, v1.y, v2.y) + ); + return point2; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + class QuadraticBezierCurve3 extends Curve { + /** + * Constructs a new Quadratic Bezier curve. + * + * @param {Vector3} [v0] - The start point. + * @param {Vector3} [v1] - The control point. + * @param {Vector3} [v2] - The end point. + */ + constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) { + super(); + this.isQuadraticBezierCurve3 = true; + this.type = "QuadraticBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector3} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector3} The position on the curve. + */ + getPoint(t, optionalTarget = new Vector3()) { + const point2 = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point2.set( + QuadraticBezier(t, v0.x, v1.x, v2.x), + QuadraticBezier(t, v0.y, v1.y, v2.y), + QuadraticBezier(t, v0.z, v1.z, v2.z) + ); + return point2; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + class SplineCurve extends Curve { + /** + * Constructs a new 2D spline curve. + * + * @param {Array} [points] - An array of 2D points defining the curve. + */ + constructor(points = []) { + super(); + this.isSplineCurve = true; + this.type = "SplineCurve"; + this.points = points; + } + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the curve. + */ + getPoint(t, optionalTarget = new Vector2()) { + const point2 = optionalTarget; + const points = this.points; + const p = (points.length - 1) * t; + const intPoint = Math.floor(p); + const weight = p - intPoint; + const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; + const p1 = points[intPoint]; + const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; + const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; + point2.set( + CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), + CatmullRom(weight, p0.y, p1.y, p2.y, p3.y) + ); + return point2; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length; i < l; i++) { + const point2 = source.points[i]; + this.points.push(point2.clone()); + } + return this; + } + toJSON() { + const data = super.toJSON(); + data.points = []; + for (let i = 0, l = this.points.length; i < l; i++) { + const point2 = this.points[i]; + data.points.push(point2.toArray()); + } + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length; i < l; i++) { + const point2 = json.points[i]; + this.points.push(new Vector2().fromArray(point2)); + } + return this; + } + } + var Curves = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ArcCurve, + CatmullRomCurve3, + CubicBezierCurve, + CubicBezierCurve3, + EllipseCurve, + LineCurve, + LineCurve3, + QuadraticBezierCurve, + QuadraticBezierCurve3, + SplineCurve + }); + class CurvePath extends Curve { + /** + * Constructs a new curve path. + */ + constructor() { + super(); + this.type = "CurvePath"; + this.curves = []; + this.autoClose = false; + } + /** + * Adds a curve to this curve path. + * + * @param {Curve} curve - The curve to add. + */ + add(curve) { + this.curves.push(curve); + } + /** + * Adds a line curve to close the path. + * + * @return {CurvePath} A reference to this curve path. + */ + closePath() { + const startPoint = this.curves[0].getPoint(0); + const endPoint = this.curves[this.curves.length - 1].getPoint(1); + if (!startPoint.equals(endPoint)) { + const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3"; + this.curves.push(new Curves[lineType](endPoint, startPoint)); + } + return this; + } + /** + * This method returns a vector in 2D or 3D space (depending on the curve definitions) + * for the given interpolation factor. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition. + */ + getPoint(t, optionalTarget) { + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + while (i < curveLengths.length) { + if (curveLengths[i] >= d) { + const diff = curveLengths[i] - d; + const curve = this.curves[i]; + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + return curve.getPointAt(u, optionalTarget); + } + i++; + } + return null; + } + getLength() { + const lens = this.getCurveLengths(); + return lens[lens.length - 1]; + } + updateArcLengths() { + this.needsUpdate = true; + this.cacheLengths = null; + this.getCurveLengths(); + } + /** + * Returns list of cumulative curve lengths of the defined curves. + * + * @return {Array} The curve lengths. + */ + getCurveLengths() { + if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { + return this.cacheLengths; + } + const lengths = []; + let sums = 0; + for (let i = 0, l = this.curves.length; i < l; i++) { + sums += this.curves[i].getLength(); + lengths.push(sums); + } + this.cacheLengths = lengths; + return lengths; + } + getSpacedPoints(divisions = 40) { + const points = []; + for (let i = 0; i <= divisions; i++) { + points.push(this.getPoint(i / divisions)); + } + if (this.autoClose) { + points.push(points[0]); + } + return points; + } + getPoints(divisions = 12) { + const points = []; + let last; + for (let i = 0, curves = this.curves; i < curves.length; i++) { + const curve = curves[i]; + const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; + const pts = curve.getPoints(resolution); + for (let j = 0; j < pts.length; j++) { + const point2 = pts[j]; + if (last && last.equals(point2)) continue; + points.push(point2); + last = point2; + } + } + if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { + points.push(points[0]); + } + return points; + } + copy(source) { + super.copy(source); + this.curves = []; + for (let i = 0, l = source.curves.length; i < l; i++) { + const curve = source.curves[i]; + this.curves.push(curve.clone()); + } + this.autoClose = source.autoClose; + return this; + } + toJSON() { + const data = super.toJSON(); + data.autoClose = this.autoClose; + data.curves = []; + for (let i = 0, l = this.curves.length; i < l; i++) { + const curve = this.curves[i]; + data.curves.push(curve.toJSON()); + } + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.autoClose = json.autoClose; + this.curves = []; + for (let i = 0, l = json.curves.length; i < l; i++) { + const curve = json.curves[i]; + this.curves.push(new Curves[curve.type]().fromJSON(curve)); + } + return this; + } + } + class Path extends CurvePath { + /** + * Constructs a new path. + * + * @param {Array} [points] - An array of 2D points defining the path. + */ + constructor(points) { + super(); + this.type = "Path"; + this.currentPoint = new Vector2(); + if (points) { + this.setFromPoints(points); + } + } + /** + * Creates a path from the given list of points. The points are added + * to the path as instances of {@link LineCurve}. + * + * @param {Array} points - An array of 2D points. + * @return {Path} A reference to this path. + */ + setFromPoints(points) { + this.moveTo(points[0].x, points[0].y); + for (let i = 1, l = points.length; i < l; i++) { + this.lineTo(points[i].x, points[i].y); + } + return this; + } + /** + * Moves {@link Path#currentPoint} to the given point. + * + * @param {number} x - The x coordinate. + * @param {number} y - The y coordinate. + * @return {Path} A reference to this path. + */ + moveTo(x, y) { + this.currentPoint.set(x, y); + return this; + } + /** + * Adds an instance of {@link LineCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} x - The x coordinate of the end point. + * @param {number} y - The y coordinate of the end point. + * @return {Path} A reference to this path. + */ + lineTo(x, y) { + const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y)); + this.curves.push(curve); + this.currentPoint.set(x, y); + return this; + } + /** + * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} aCPx - The x coordinate of the control point. + * @param {number} aCPy - The y coordinate of the control point. + * @param {number} aX - The x coordinate of the end point. + * @param {number} aY - The y coordinate of the end point. + * @return {Path} A reference to this path. + */ + quadraticCurveTo(aCPx, aCPy, aX, aY) { + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2(aCPx, aCPy), + new Vector2(aX, aY) + ); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + /** + * Adds an instance of {@link CubicBezierCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} aCP1x - The x coordinate of the first control point. + * @param {number} aCP1y - The y coordinate of the first control point. + * @param {number} aCP2x - The x coordinate of the second control point. + * @param {number} aCP2y - The y coordinate of the second control point. + * @param {number} aX - The x coordinate of the end point. + * @param {number} aY - The y coordinate of the end point. + * @return {Path} A reference to this path. + */ + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + const curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2(aCP1x, aCP1y), + new Vector2(aCP2x, aCP2y), + new Vector2(aX, aY) + ); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + /** + * Adds an instance of {@link SplineCurve} to the path by connecting + * the current point with the given list of points. + * + * @param {Array} pts - An array of points in 2D space. + * @return {Path} A reference to this path. + */ + splineThru(pts) { + const npts = [this.currentPoint.clone()].concat(pts); + const curve = new SplineCurve(npts); + this.curves.push(curve); + this.currentPoint.copy(pts[pts.length - 1]); + return this; + } + /** + * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative + * to the current point. + * + * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve. + * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve. + * @param {number} [aRadius=1] - The radius of the arc. + * @param {number} [aStartAngle=0] - The start angle in radians. + * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians. + * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not. + * @return {Path} A reference to this path. + */ + arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absarc( + aX + x0, + aY + y0, + aRadius, + aStartAngle, + aEndAngle, + aClockwise + ); + return this; + } + /** + * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path. + * + * @param {number} [aX=0] - The x coordinate of the center of the arc. + * @param {number} [aY=0] - The y coordinate of the center of the arc. + * @param {number} [aRadius=1] - The radius of the arc. + * @param {number} [aStartAngle=0] - The start angle in radians. + * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians. + * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not. + * @return {Path} A reference to this path. + */ + absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + /** + * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative + * to the current point + * + * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve. + * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve. + * @param {number} [xRadius=1] - The radius of the ellipse in the x axis. + * @param {number} [yRadius=1] - The radius of the ellipse in the y axis. + * @param {number} [aStartAngle=0] - The start angle in radians. + * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians. + * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not. + * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. + * @return {Path} A reference to this path. + */ + ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + return this; + } + /** + * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path. + * + * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse. + * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse. + * @param {number} [xRadius=1] - The radius of the ellipse in the x axis. + * @param {number} [yRadius=1] - The radius of the ellipse in the y axis. + * @param {number} [aStartAngle=0] - The start angle in radians. + * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians. + * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not. + * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. + * @return {Path} A reference to this path. + */ + absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + if (this.curves.length > 0) { + const firstPoint = curve.getPoint(0); + if (!firstPoint.equals(this.currentPoint)) { + this.lineTo(firstPoint.x, firstPoint.y); + } + } + this.curves.push(curve); + const lastPoint = curve.getPoint(1); + this.currentPoint.copy(lastPoint); + return this; + } + copy(source) { + super.copy(source); + this.currentPoint.copy(source.currentPoint); + return this; + } + toJSON() { + const data = super.toJSON(); + data.currentPoint = this.currentPoint.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.currentPoint.fromArray(json.currentPoint); + return this; + } + } + class Shape extends Path { + /** + * Constructs a new shape. + * + * @param {Array} [points] - An array of 2D points defining the shape. + */ + constructor(points) { + super(points); + this.uuid = generateUUID(); + this.type = "Shape"; + this.holes = []; + } + /** + * Returns an array representing each contour of the holes + * as a list of 2D points. + * + * @param {number} divisions - The fineness of the result. + * @return {Array>} The holes as a series of 2D points. + */ + getPointsHoles(divisions) { + const holesPts = []; + for (let i = 0, l = this.holes.length; i < l; i++) { + holesPts[i] = this.holes[i].getPoints(divisions); + } + return holesPts; + } + // get points of shape and holes (keypoints based on segments parameter) + /** + * Returns an object that holds contour data for the shape and its holes as + * arrays of 2D points. + * + * @param {number} divisions - The fineness of the result. + * @return {{shape:Array,holes:Array>}} An object with contour data. + */ + extractPoints(divisions) { + return { + shape: this.getPoints(divisions), + holes: this.getPointsHoles(divisions) + }; + } + copy(source) { + super.copy(source); + this.holes = []; + for (let i = 0, l = source.holes.length; i < l; i++) { + const hole = source.holes[i]; + this.holes.push(hole.clone()); + } + return this; + } + toJSON() { + const data = super.toJSON(); + data.uuid = this.uuid; + data.holes = []; + for (let i = 0, l = this.holes.length; i < l; i++) { + const hole = this.holes[i]; + data.holes.push(hole.toJSON()); + } + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.uuid = json.uuid; + this.holes = []; + for (let i = 0, l = json.holes.length; i < l; i++) { + const hole = json.holes[i]; + this.holes.push(new Path().fromJSON(hole)); + } + return this; + } + } + function earcut(data, holeIndices, dim = 2) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + let outerNode = linkedList(data, 0, outerLen, dim, true); + const triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + let minX, minY, invSize; + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + if (data.length > 80 * dim) { + minX = data[0]; + minY = data[1]; + let maxX = minX; + let maxY = minY; + for (let i = dim; i < outerLen; i += dim) { + const x = data[i]; + const y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; + } + function linkedList(data, start, end, dim, clockwise) { + let last; + if (clockwise === signedArea(data, start, end, dim) > 0) { + for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } else { + for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + return last; + } + function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + let p = start, again; + do { + again = false; + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; + } + function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + let stop = ear; + while (ear.prev !== ear.next) { + const prev = ear.prev; + const next = ear.next; + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i, ear.i, next.i); + removeNode(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } + } + function isEar(ear) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = Math.min(ax, bx, cx), y0 = Math.min(ay, by, cy), x1 = Math.max(ax, bx, cx), y1 = Math.max(ay, by, cy); + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + return true; + } + function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = Math.min(ax, bx, cx), y0 = Math.min(ay, by, cy), x1 = Math.max(ax, bx, cx), y1 = Math.max(ay, by, cy); + const minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); + let p = ear.prevZ, n = ear.nextZ; + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + return true; + } + function cureLocalIntersections(start, triangles) { + let p = start; + do { + const a = p.prev, b = p.next.next; + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + triangles.push(a.i, p.i, b.i); + removeNode(p); + removeNode(p.next); + p = start = b; + } + p = p.next; + } while (p !== start); + return filterPoints(p); + } + function splitEarcut(start, triangles, dim, minX, minY, invSize) { + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + let c = splitPolygon(a, b); + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); + } + function eliminateHoles(data, holeIndices, outerNode, dim) { + const queue = []; + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + const list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + queue.sort(compareXYSlope); + for (let i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + return outerNode; + } + function compareXYSlope(a, b) { + let result = a.x - b.x; + if (result === 0) { + result = a.y - b.y; + if (result === 0) { + const aSlope = (a.next.y - a.y) / (a.next.x - a.x); + const bSlope = (b.next.y - b.y) / (b.next.x - b.x); + result = aSlope - bSlope; + } + } + return result; + } + function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = splitPolygon(bridge, hole); + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); + } + function findHoleBridge(hole, outerNode) { + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = -Infinity; + let m; + if (equals(hole, p)) return p; + do { + if (equals(hole, p.next)) return p.next; + else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) return null; + const stop = m; + const mx = m.x; + const my = m.y; + let tanMin = Infinity; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + const tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; + } + function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; + } + function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked(p); + } + function sortLinked(list) { + let numMerges; + let inSize = 1; + do { + let p = list; + let e; + list = null; + let tail = null; + numMerges = 0; + while (p) { + numMerges++; + let q = p; + let pSize = 0; + for (let i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + let qSize = inSize; + while (pSize > 0 || qSize > 0 && q) { + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + if (tail) tail.nextZ = e; + else list = e; + e.prevZ = tail; + tail = e; + } + p = q; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; + } + function zOrder(x, y, minX, minY, invSize) { + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + x = (x | x << 8) & 16711935; + x = (x | x << 4) & 252645135; + x = (x | x << 2) & 858993459; + x = (x | x << 1) & 1431655765; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x | y << 1; + } + function getLeftmost(start) { + let p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; + } + function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py2) { + return (cx - px2) * (ay - py2) >= (ax - px2) * (cy - py2) && (ax - px2) * (by - py2) >= (bx - px2) * (ay - py2) && (bx - px2) * (cy - py2) >= (cx - px2) * (by - py2); + } + function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px2, py2) { + return !(ax === px2 && ay === py2) && pointInTriangle(ax, ay, bx, by, cx, cy, px2, py2); + } + function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); + } + function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + } + function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } + function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) return true; + if (o1 === 0 && onSegment(p1, p2, q1)) return true; + if (o2 === 0 && onSegment(p1, q2, q1)) return true; + if (o3 === 0 && onSegment(p2, p1, q2)) return true; + if (o4 === 0 && onSegment(p2, q1, q2)) return true; + return false; + } + function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); + } + function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + return false; + } + function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; + } + function middleInside(a, b) { + let p = a; + let inside = false; + const px2 = (a.x + b.x) / 2; + const py2 = (a.y + b.y) / 2; + do { + if (p.y > py2 !== p.next.y > py2 && p.next.y !== p.y && px2 < (p.next.x - p.x) * (py2 - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a); + return inside; + } + function splitPolygon(a, b) { + const a2 = createNode(a.i, a.x, a.y), b2 = createNode(b.i, b.x, b.y), an = a.next, bp = b.prev; + a.next = b; + b.prev = a; + a2.next = an; + an.prev = a2; + b2.next = a2; + a2.prev = b2; + bp.next = b2; + b2.prev = bp; + return b2; + } + function insertNode(i, x, y, last) { + const p = createNode(i, x, y); + if (!last) { + p.prev = p; + p.next = p; + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; + } + function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; + } + function createNode(i, x, y) { + return { + i, + // vertex index in coordinates array + x, + y, + // vertex coordinates + prev: null, + // previous and next vertex nodes in a polygon ring + next: null, + z: 0, + // z-order curve value + prevZ: null, + // previous and next nodes in z-order + nextZ: null, + steiner: false + // indicates whether this is a steiner point + }; + } + function signedArea(data, start, end, dim) { + let sum = 0; + for (let i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; + } + class Earcut { + /** + * Triangulates the given shape definition by returning an array of triangles. + * + * @param {Array} data - An array with 2D points. + * @param {Array} holeIndices - An array with indices defining holes. + * @param {number} [dim=2] - The number of coordinates per vertex in the input array. + * @return {Array} An array representing the triangulated faces. Each face is defined by three consecutive numbers + * representing vertex indices. + */ + static triangulate(data, holeIndices, dim = 2) { + return earcut(data, holeIndices, dim); + } + } + class ShapeUtils { + /** + * Calculate area of a ( 2D ) contour polygon. + * + * @param {Array} contour - An array of 2D points. + * @return {number} The area. + */ + static area(contour) { + const n = contour.length; + let a = 0; + for (let p = n - 1, q = 0; q < n; p = q++) { + a += contour[p].x * contour[q].y - contour[q].x * contour[p].y; + } + return a * 0.5; + } + /** + * Returns `true` if the given contour uses a clockwise winding order. + * + * @param {Array} pts - An array of 2D points defining a polygon. + * @return {boolean} Whether the given contour uses a clockwise winding order or not. + */ + static isClockWise(pts) { + return ShapeUtils.area(pts) < 0; + } + /** + * Triangulates the given shape definition. + * + * @param {Array} contour - An array of 2D points defining the contour. + * @param {Array>} holes - An array that holds arrays of 2D points defining the holes. + * @return {Array>} An array that holds for each face definition an array with three indices. + */ + static triangulateShape(contour, holes) { + const vertices = []; + const holeIndices = []; + const faces = []; + removeDupEndPts(contour); + addContour(vertices, contour); + let holeIndex = contour.length; + holes.forEach(removeDupEndPts); + for (let i = 0; i < holes.length; i++) { + holeIndices.push(holeIndex); + holeIndex += holes[i].length; + addContour(vertices, holes[i]); + } + const triangles = Earcut.triangulate(vertices, holeIndices); + for (let i = 0; i < triangles.length; i += 3) { + faces.push(triangles.slice(i, i + 3)); + } + return faces; + } + } + function removeDupEndPts(points) { + const l = points.length; + if (l > 2 && points[l - 1].equals(points[0])) { + points.pop(); + } + } + function addContour(vertices, contour) { + for (let i = 0; i < contour.length; i++) { + vertices.push(contour[i].x); + vertices.push(contour[i].y); + } + } + class ExtrudeGeometry extends BufferGeometry { + /** + * Constructs a new extrude geometry. + * + * @param {Shape|Array} [shapes] - A shape or an array of shapes. + * @param {ExtrudeGeometry~Options} [options] - The extrude settings. + */ + constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) { + super(); + this.type = "ExtrudeGeometry"; + this.parameters = { + shapes, + options + }; + shapes = Array.isArray(shapes) ? shapes : [shapes]; + const scope = this; + const verticesArray = []; + const uvArray = []; + for (let i = 0, l = shapes.length; i < l; i++) { + const shape = shapes[i]; + addShape(shape); + } + this.setAttribute("position", new Float32BufferAttribute(verticesArray, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvArray, 2)); + this.computeVertexNormals(); + function addShape(shape) { + const placeholder = []; + const curveSegments = options.curveSegments !== void 0 ? options.curveSegments : 12; + const steps = options.steps !== void 0 ? options.steps : 1; + const depth = options.depth !== void 0 ? options.depth : 1; + let bevelEnabled = options.bevelEnabled !== void 0 ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== void 0 ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== void 0 ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== void 0 ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== void 0 ? options.bevelSegments : 3; + const extrudePath = options.extrudePath; + const uvgen = options.UVGenerator !== void 0 ? options.UVGenerator : WorldUVGenerator; + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + if (extrudePath) { + extrudePts = extrudePath.getSpacedPoints(steps); + extrudeByPath = true; + bevelEnabled = false; + const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false; + splineTube = extrudePath.computeFrenetFrames(steps, isClosed); + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + } + if (!bevelEnabled) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + } + const shapePoints = shape.extractPoints(curveSegments); + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + const reverse = !ShapeUtils.isClockWise(vertices); + if (reverse) { + vertices = vertices.reverse(); + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + if (ShapeUtils.isClockWise(ahole)) { + holes[h] = ahole.reverse(); + } + } + } + function mergeOverlappingPoints(points) { + const THRESHOLD = 1e-10; + const THRESHOLD_SQ = THRESHOLD * THRESHOLD; + let prevPos = points[0]; + for (let i = 1; i <= points.length; i++) { + const currentIndex = i % points.length; + const currentPos = points[currentIndex]; + const dx = currentPos.x - prevPos.x; + const dy = currentPos.y - prevPos.y; + const distSq = dx * dx + dy * dy; + const scalingFactorSqrt = Math.max( + Math.abs(currentPos.x), + Math.abs(currentPos.y), + Math.abs(prevPos.x), + Math.abs(prevPos.y) + ); + const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt; + if (distSq <= thresholdSqScaled) { + points.splice(currentIndex, 1); + i--; + continue; + } + prevPos = currentPos; + } + } + mergeOverlappingPoints(vertices); + holes.forEach(mergeOverlappingPoints); + const numHoles = holes.length; + const contour = vertices; + for (let h = 0; h < numHoles; h++) { + const ahole = holes[h]; + vertices = vertices.concat(ahole); + } + function scalePt2(pt, vec, size) { + if (!vec) error("ExtrudeGeometry: vec does not exist"); + return pt.clone().addScaledVector(vec, size); + } + const vlen = vertices.length; + function getBevelVec(inPt, inPrev, inNext) { + let v_trans_x, v_trans_y, shrink_by; + const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; + if (Math.abs(collinear0) > Number.EPSILON) { + const v_prev_len = Math.sqrt(v_prev_lensq); + const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; + const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; + const ptNextShift_x = inNext.x - v_next_y / v_next_len; + const ptNextShift_y = inNext.y + v_next_x / v_next_len; + const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; + v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; + if (v_trans_lensq <= 2) { + return new Vector2(v_trans_x, v_trans_y); + } else { + shrink_by = Math.sqrt(v_trans_lensq / 2); + } + } else { + let direction_eq = false; + if (v_prev_x > Number.EPSILON) { + if (v_next_x > Number.EPSILON) { + direction_eq = true; + } + } else { + if (v_prev_x < -Number.EPSILON) { + if (v_next_x < -Number.EPSILON) { + direction_eq = true; + } + } else { + if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { + direction_eq = true; + } + } + } + if (direction_eq) { + v_trans_x = -v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt(v_prev_lensq); + } else { + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt(v_prev_lensq / 2); + } + } + return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by); + } + const contourMovements = []; + for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) { + if (j === il) j = 0; + if (k === il) k = 0; + contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]); + } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + for (let h = 0, hl = numHoles; h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = []; + for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) { + if (j === il) j = 0; + if (k === il) k = 0; + oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]); + } + holesMovements.push(oneHoleMovements); + verticesMovements = verticesMovements.concat(oneHoleMovements); + } + let faces; + if (bevelSegments === 0) { + faces = ShapeUtils.triangulateShape(contour, holes); + } else { + const contractedContourVertices = []; + const expandedHoleVertices = []; + for (let b = 0; b < bevelSegments; b++) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length; i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, -z); + if (t === 0) contractedContourVertices.push(vert); + } + for (let h = 0, hl = numHoles; h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + const oneHoleVertices = []; + for (let i = 0, il = ahole.length; i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + v(vert.x, vert.y, -z); + if (t === 0) oneHoleVertices.push(vert); + } + if (t === 0) expandedHoleVertices.push(oneHoleVertices); + } + } + faces = ShapeUtils.triangulateShape(contractedContourVertices, expandedHoleVertices); + } + const flen = faces.length; + const bs = bevelSize + bevelOffset; + for (let i = 0; i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, 0); + } else { + normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); + position2.copy(extrudePts[0]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + for (let s = 1; s <= steps; s++) { + for (let i = 0; i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, depth / steps * s); + } else { + normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); + position2.copy(extrudePts[s]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + } + for (let b = bevelSegments - 1; b >= 0; b--) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length; i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, depth + z); + } + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length; i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + if (!extrudeByPath) { + v(vert.x, vert.y, depth + z); + } else { + v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); + } + } + } + } + buildLidFaces(); + buildSideFaces(); + function buildLidFaces() { + const start = verticesArray.length / 3; + if (bevelEnabled) { + let layer = 0; + let offset = vlen * layer; + for (let i = 0; i < flen; i++) { + const face2 = faces[i]; + f3(face2[2] + offset, face2[1] + offset, face2[0] + offset); + } + layer = steps + bevelSegments * 2; + offset = vlen * layer; + for (let i = 0; i < flen; i++) { + const face2 = faces[i]; + f3(face2[0] + offset, face2[1] + offset, face2[2] + offset); + } + } else { + for (let i = 0; i < flen; i++) { + const face2 = faces[i]; + f3(face2[2], face2[1], face2[0]); + } + for (let i = 0; i < flen; i++) { + const face2 = faces[i]; + f3(face2[0] + vlen * steps, face2[1] + vlen * steps, face2[2] + vlen * steps); + } + } + scope.addGroup(start, verticesArray.length / 3 - start, 0); + } + function buildSideFaces() { + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls(contour, layeroffset); + layeroffset += contour.length; + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + sidewalls(ahole, layeroffset); + layeroffset += ahole.length; + } + scope.addGroup(start, verticesArray.length / 3 - start, 1); + } + function sidewalls(contour2, layeroffset) { + let i = contour2.length; + while (--i >= 0) { + const j = i; + let k = i - 1; + if (k < 0) k = contour2.length - 1; + for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) { + const slen1 = vlen * s; + const slen2 = vlen * (s + 1); + const a = layeroffset + j + slen1, b = layeroffset + k + slen1, c = layeroffset + k + slen2, d = layeroffset + j + slen2; + f4(a, b, c, d); + } + } + } + function v(x, y, z) { + placeholder.push(x); + placeholder.push(y); + placeholder.push(z); + } + function f3(a, b, c) { + addVertex(a); + addVertex(b); + addVertex(c); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[2]); + } + function f4(a, b, c, d) { + addVertex(a); + addVertex(b); + addVertex(d); + addVertex(b); + addVertex(c); + addVertex(d); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[3]); + addUV(uvs[1]); + addUV(uvs[2]); + addUV(uvs[3]); + } + function addVertex(index) { + verticesArray.push(placeholder[index * 3 + 0]); + verticesArray.push(placeholder[index * 3 + 1]); + verticesArray.push(placeholder[index * 3 + 2]); + } + function addUV(vector2) { + uvArray.push(vector2.x); + uvArray.push(vector2.y); + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data = super.toJSON(); + const shapes = this.parameters.shapes; + const options = this.parameters.options; + return toJSON$1(shapes, options, data); + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @param {Array} shapes - An array of shapes. + * @return {ExtrudeGeometry} A new instance. + */ + static fromJSON(data, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data.shapes.length; j < jl; j++) { + const shape = shapes[data.shapes[j]]; + geometryShapes.push(shape); + } + const extrudePath = data.options.extrudePath; + if (extrudePath !== void 0) { + data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath); + } + return new ExtrudeGeometry(geometryShapes, data.options); + } + } + const WorldUVGenerator = { + generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + return [ + new Vector2(a_x, a_y), + new Vector2(b_x, b_y), + new Vector2(c_x, c_y) + ]; + }, + generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const a_z = vertices[indexA * 3 + 2]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const b_z = vertices[indexB * 3 + 2]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + const c_z = vertices[indexC * 3 + 2]; + const d_x = vertices[indexD * 3]; + const d_y = vertices[indexD * 3 + 1]; + const d_z = vertices[indexD * 3 + 2]; + if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { + return [ + new Vector2(a_x, 1 - a_z), + new Vector2(b_x, 1 - b_z), + new Vector2(c_x, 1 - c_z), + new Vector2(d_x, 1 - d_z) + ]; + } else { + return [ + new Vector2(a_y, 1 - a_z), + new Vector2(b_y, 1 - b_z), + new Vector2(c_y, 1 - c_z), + new Vector2(d_y, 1 - d_z) + ]; + } + } + }; + function toJSON$1(shapes, options, data) { + data.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length; i < l; i++) { + const shape = shapes[i]; + data.shapes.push(shape.uuid); + } + } else { + data.shapes.push(shapes.uuid); + } + data.options = Object.assign({}, options); + if (options.extrudePath !== void 0) data.options.extrudePath = options.extrudePath.toJSON(); + return data; + } + class IcosahedronGeometry extends PolyhedronGeometry { + /** + * Constructs a new icosahedron geometry. + * + * @param {number} [radius=1] - Radius of the icosahedron. + * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron. + */ + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const vertices = [ + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + 0, + 0, + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + t, + 0, + -1, + t, + 0, + 1, + -t, + 0, + -1, + -t, + 0, + 1 + ]; + const indices = [ + 0, + 11, + 5, + 0, + 5, + 1, + 0, + 1, + 7, + 0, + 7, + 10, + 0, + 10, + 11, + 1, + 5, + 9, + 5, + 11, + 4, + 11, + 10, + 2, + 10, + 7, + 6, + 7, + 1, + 8, + 3, + 9, + 4, + 3, + 4, + 2, + 3, + 2, + 6, + 3, + 6, + 8, + 3, + 8, + 9, + 4, + 9, + 5, + 2, + 4, + 11, + 6, + 2, + 10, + 8, + 6, + 7, + 9, + 8, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "IcosahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {IcosahedronGeometry} A new instance. + */ + static fromJSON(data) { + return new IcosahedronGeometry(data.radius, data.detail); + } + } + class LatheGeometry extends BufferGeometry { + /** + * Constructs a new lathe geometry. + * + * @param {Array} [points] - An array of points in 2D space. The x-coordinate of each point + * must be greater than zero. + * @param {number} [segments=12] - The number of circumference segments to generate. + * @param {number} [phiStart=0] - The starting angle in radians. + * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a + * closed lathe, less than 2PI is a portion. + */ + constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { + super(); + this.type = "LatheGeometry"; + this.parameters = { + points, + segments, + phiStart, + phiLength + }; + segments = Math.floor(segments); + phiLength = clamp(phiLength, 0, Math.PI * 2); + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + const inverseSegments = 1 / segments; + const vertex2 = new Vector3(); + const uv = new Vector2(); + const normal = new Vector3(); + const curNormal = new Vector3(); + const prevNormal = new Vector3(); + let dx = 0; + let dy = 0; + for (let j = 0; j <= points.length - 1; j++) { + switch (j) { + case 0: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + prevNormal.copy(normal); + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + break; + case points.length - 1: + initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); + break; + default: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + curNormal.copy(normal); + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + prevNormal.copy(curNormal); + } + } + for (let i = 0; i <= segments; i++) { + const phi = phiStart + i * inverseSegments * phiLength; + const sin = Math.sin(phi); + const cos = Math.cos(phi); + for (let j = 0; j <= points.length - 1; j++) { + vertex2.x = points[j].x * sin; + vertex2.y = points[j].y; + vertex2.z = points[j].x * cos; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + uv.x = i / segments; + uv.y = j / (points.length - 1); + uvs.push(uv.x, uv.y); + const x = initNormals[3 * j + 0] * sin; + const y = initNormals[3 * j + 1]; + const z = initNormals[3 * j + 0] * cos; + normals.push(x, y, z); + } + } + for (let i = 0; i < segments; i++) { + for (let j = 0; j < points.length - 1; j++) { + const base = j + i * points.length; + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + indices.push(a, b, d); + indices.push(c, d, b); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {LatheGeometry} A new instance. + */ + static fromJSON(data) { + return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength); + } + } + class OctahedronGeometry extends PolyhedronGeometry { + /** + * Constructs a new octahedron geometry. + * + * @param {number} [radius=1] - Radius of the octahedron. + * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron. + */ + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1 + ]; + const indices = [ + 0, + 2, + 4, + 0, + 4, + 3, + 0, + 3, + 5, + 0, + 5, + 2, + 1, + 2, + 5, + 1, + 5, + 3, + 1, + 3, + 4, + 1, + 4, + 2 + ]; + super(vertices, indices, radius, detail); + this.type = "OctahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {OctahedronGeometry} A new instance. + */ + static fromJSON(data) { + return new OctahedronGeometry(data.radius, data.detail); + } + } + class PlaneGeometry extends BufferGeometry { + /** + * Constructs a new plane geometry. + * + * @param {number} [width=1] - The width along the X axis. + * @param {number} [height=1] - The height along the Y axis + * @param {number} [widthSegments=1] - The number of segments along the X axis. + * @param {number} [heightSegments=1] - The number of segments along the Y axis. + */ + constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width, + height, + widthSegments, + heightSegments + }; + const width_half = width / 2; + const height_half = height / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width / gridX; + const segment_height = height / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0; iy < gridY1; iy++) { + const y = iy * segment_height - height_half; + for (let ix = 0; ix < gridX1; ix++) { + const x = ix * segment_width - width_half; + vertices.push(x, -y, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0; iy < gridY; iy++) { + for (let ix = 0; ix < gridX; ix++) { + const a = ix + gridX1 * iy; + const b = ix + gridX1 * (iy + 1); + const c = ix + 1 + gridX1 * (iy + 1); + const d = ix + 1 + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {PlaneGeometry} A new instance. + */ + static fromJSON(data) { + return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments); + } + } + class RingGeometry extends BufferGeometry { + /** + * Constructs a new ring geometry. + * + * @param {number} [innerRadius=0.5] - The inner radius of the ring. + * @param {number} [outerRadius=1] - The outer radius of the ring. + * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`. + * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`. + * @param {number} [thetaStart=0] - Starting angle in radians. + * @param {number} [thetaLength=Math.PI*2] - Central angle in radians. + */ + constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "RingGeometry"; + this.parameters = { + innerRadius, + outerRadius, + thetaSegments, + phiSegments, + thetaStart, + thetaLength + }; + thetaSegments = Math.max(3, thetaSegments); + phiSegments = Math.max(1, phiSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let radius = innerRadius; + const radiusStep = (outerRadius - innerRadius) / phiSegments; + const vertex2 = new Vector3(); + const uv = new Vector2(); + for (let j = 0; j <= phiSegments; j++) { + for (let i = 0; i <= thetaSegments; i++) { + const segment = thetaStart + i / thetaSegments * thetaLength; + vertex2.x = radius * Math.cos(segment); + vertex2.y = radius * Math.sin(segment); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normals.push(0, 0, 1); + uv.x = (vertex2.x / outerRadius + 1) / 2; + uv.y = (vertex2.y / outerRadius + 1) / 2; + uvs.push(uv.x, uv.y); + } + radius += radiusStep; + } + for (let j = 0; j < phiSegments; j++) { + const thetaSegmentLevel = j * (thetaSegments + 1); + for (let i = 0; i < thetaSegments; i++) { + const segment = i + thetaSegmentLevel; + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {RingGeometry} A new instance. + */ + static fromJSON(data) { + return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength); + } + } + class ShapeGeometry extends BufferGeometry { + /** + * Constructs a new shape geometry. + * + * @param {Shape|Array} [shapes] - A shape or an array of shapes. + * @param {number} [curveSegments=12] - Number of segments per shape. + */ + constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) { + super(); + this.type = "ShapeGeometry"; + this.parameters = { + shapes, + curveSegments + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let groupStart = 0; + let groupCount = 0; + if (Array.isArray(shapes) === false) { + addShape(shapes); + } else { + for (let i = 0; i < shapes.length; i++) { + addShape(shapes[i]); + this.addGroup(groupStart, groupCount, i); + groupStart += groupCount; + groupCount = 0; + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function addShape(shape) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints(curveSegments); + let shapeVertices = points.shape; + const shapeHoles = points.holes; + if (ShapeUtils.isClockWise(shapeVertices) === false) { + shapeVertices = shapeVertices.reverse(); + } + for (let i = 0, l = shapeHoles.length; i < l; i++) { + const shapeHole = shapeHoles[i]; + if (ShapeUtils.isClockWise(shapeHole) === true) { + shapeHoles[i] = shapeHole.reverse(); + } + } + const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); + for (let i = 0, l = shapeHoles.length; i < l; i++) { + const shapeHole = shapeHoles[i]; + shapeVertices = shapeVertices.concat(shapeHole); + } + for (let i = 0, l = shapeVertices.length; i < l; i++) { + const vertex2 = shapeVertices[i]; + vertices.push(vertex2.x, vertex2.y, 0); + normals.push(0, 0, 1); + uvs.push(vertex2.x, vertex2.y); + } + for (let i = 0, l = faces.length; i < l; i++) { + const face2 = faces[i]; + const a = face2[0] + indexOffset; + const b = face2[1] + indexOffset; + const c = face2[2] + indexOffset; + indices.push(a, b, c); + groupCount += 3; + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data = super.toJSON(); + const shapes = this.parameters.shapes; + return toJSON(shapes, data); + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @param {Array} shapes - An array of shapes. + * @return {ShapeGeometry} A new instance. + */ + static fromJSON(data, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data.shapes.length; j < jl; j++) { + const shape = shapes[data.shapes[j]]; + geometryShapes.push(shape); + } + return new ShapeGeometry(geometryShapes, data.curveSegments); + } + } + function toJSON(shapes, data) { + data.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length; i < l; i++) { + const shape = shapes[i]; + data.shapes.push(shape.uuid); + } + } else { + data.shapes.push(shapes.uuid); + } + return data; + } + class SphereGeometry extends BufferGeometry { + /** + * Constructs a new sphere geometry. + * + * @param {number} [radius=1] - The sphere radius. + * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`. + * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`. + * @param {number} [phiStart=0] - The horizontal starting angle in radians. + * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size. + * @param {number} [thetaStart=0] - The vertical starting angle in radians. + * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size. + */ + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index = 0; + const grid = []; + const vertex2 = new Vector3(); + const normal = new Vector3(); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0; iy <= heightSegments; iy++) { + const verticesRow = []; + const v = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0; ix <= widthSegments; ix++) { + const u = ix / widthSegments; + vertex2.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertex2.y = radius * Math.cos(thetaStart + v * thetaLength); + vertex2.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normal.copy(vertex2).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u + uOffset, 1 - v); + verticesRow.push(index++); + } + grid.push(verticesRow); + } + for (let iy = 0; iy < heightSegments; iy++) { + for (let ix = 0; ix < widthSegments; ix++) { + const a = grid[iy][ix + 1]; + const b = grid[iy][ix]; + const c = grid[iy + 1][ix]; + const d = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) indices.push(a, b, d); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {SphereGeometry} A new instance. + */ + static fromJSON(data) { + return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength); + } + } + class TetrahedronGeometry extends PolyhedronGeometry { + /** + * Constructs a new tetrahedron geometry. + * + * @param {number} [radius=1] - Radius of the tetrahedron. + * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron. + */ + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + -1, + 1, + -1, + -1 + ]; + const indices = [ + 2, + 1, + 0, + 0, + 3, + 2, + 1, + 3, + 0, + 2, + 3, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "TetrahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {TetrahedronGeometry} A new instance. + */ + static fromJSON(data) { + return new TetrahedronGeometry(data.radius, data.detail); + } + } + class TorusGeometry extends BufferGeometry { + /** + * Constructs a new torus geometry. + * + * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube. + * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`. + * @param {number} [radialSegments=12] - The number of radial segments. + * @param {number} [tubularSegments=48] - The number of tubular segments. + * @param {number} [arc=Math.PI*2] - Central angle in radians. + * @param {number} [thetaStart=0] - Start of the tubular sweep in radians. + * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians. + */ + constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "TorusGeometry"; + this.parameters = { + radius, + tube, + radialSegments, + tubularSegments, + arc, + thetaStart, + thetaLength + }; + radialSegments = Math.floor(radialSegments); + tubularSegments = Math.floor(tubularSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const center = new Vector3(); + const vertex2 = new Vector3(); + const normal = new Vector3(); + for (let j = 0; j <= radialSegments; j++) { + const v = thetaStart + j / radialSegments * thetaLength; + for (let i = 0; i <= tubularSegments; i++) { + const u = i / tubularSegments * arc; + vertex2.x = (radius + tube * Math.cos(v)) * Math.cos(u); + vertex2.y = (radius + tube * Math.cos(v)) * Math.sin(u); + vertex2.z = tube * Math.sin(v); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + center.x = radius * Math.cos(u); + center.y = radius * Math.sin(u); + normal.subVectors(vertex2, center).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1; j <= radialSegments; j++) { + for (let i = 1; i <= tubularSegments; i++) { + const a = (tubularSegments + 1) * j + i - 1; + const b = (tubularSegments + 1) * (j - 1) + i - 1; + const c = (tubularSegments + 1) * (j - 1) + i; + const d = (tubularSegments + 1) * j + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {TorusGeometry} A new instance. + */ + static fromJSON(data) { + return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc); + } + } + class TorusKnotGeometry extends BufferGeometry { + /** + * Constructs a new torus knot geometry. + * + * @param {number} [radius=1] - Radius of the torus knot. + * @param {number} [tube=0.4] - Radius of the tube. + * @param {number} [tubularSegments=64] - The number of tubular segments. + * @param {number} [radialSegments=8] - The number of radial segments. + * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry. + * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus. + */ + constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) { + super(); + this.type = "TorusKnotGeometry"; + this.parameters = { + radius, + tube, + tubularSegments, + radialSegments, + p, + q + }; + tubularSegments = Math.floor(tubularSegments); + radialSegments = Math.floor(radialSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex2 = new Vector3(); + const normal = new Vector3(); + const P1 = new Vector3(); + const P2 = new Vector3(); + const B = new Vector3(); + const T = new Vector3(); + const N2 = new Vector3(); + for (let i = 0; i <= tubularSegments; ++i) { + const u = i / tubularSegments * p * Math.PI * 2; + calculatePositionOnCurve(u, p, q, radius, P1); + calculatePositionOnCurve(u + 0.01, p, q, radius, P2); + T.subVectors(P2, P1); + N2.addVectors(P2, P1); + B.crossVectors(T, N2); + N2.crossVectors(B, T); + B.normalize(); + N2.normalize(); + for (let j = 0; j <= radialSegments; ++j) { + const v = j / radialSegments * Math.PI * 2; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + vertex2.x = P1.x + (cx * N2.x + cy * B.x); + vertex2.y = P1.y + (cx * N2.y + cy * B.y); + vertex2.z = P1.z + (cx * N2.z + cy * B.z); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normal.subVectors(vertex2, P1).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1; j <= tubularSegments; j++) { + for (let i = 1; i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function calculatePositionOnCurve(u, p2, q2, radius2, position) { + const cu = Math.cos(u); + const su = Math.sin(u); + const quOverP = q2 / p2 * u; + const cs = Math.cos(quOverP); + position.x = radius2 * (2 + cs) * 0.5 * cu; + position.y = radius2 * (2 + cs) * su * 0.5; + position.z = radius2 * Math.sin(quOverP) * 0.5; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {TorusKnotGeometry} A new instance. + */ + static fromJSON(data) { + return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q); + } + } + class TubeGeometry extends BufferGeometry { + /** + * Constructs a new tube geometry. + * + * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube. + * @param {number} [tubularSegments=64] - The number of segments that make up the tube. + * @param {number} [radius=1] -The radius of the tube. + * @param {number} [radialSegments=8] - The number of segments that make up the cross-section. + * @param {boolean} [closed=false] - Whether the tube is closed or not. + */ + constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { + super(); + this.type = "TubeGeometry"; + this.parameters = { + path, + tubularSegments, + radius, + radialSegments, + closed + }; + const frames = path.computeFrenetFrames(tubularSegments, closed); + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; + const vertex2 = new Vector3(); + const normal = new Vector3(); + const uv = new Vector2(); + let P = new Vector3(); + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + generateBufferData(); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateBufferData() { + for (let i = 0; i < tubularSegments; i++) { + generateSegment(i); + } + generateSegment(closed === false ? tubularSegments : 0); + generateUVs(); + generateIndices(); + } + function generateSegment(i) { + P = path.getPointAt(i / tubularSegments, P); + const N2 = frames.normals[i]; + const B = frames.binormals[i]; + for (let j = 0; j <= radialSegments; j++) { + const v = j / radialSegments * Math.PI * 2; + const sin = Math.sin(v); + const cos = -Math.cos(v); + normal.x = cos * N2.x + sin * B.x; + normal.y = cos * N2.y + sin * B.y; + normal.z = cos * N2.z + sin * B.z; + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + vertex2.x = P.x + radius * normal.x; + vertex2.y = P.y + radius * normal.y; + vertex2.z = P.z + radius * normal.z; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + } + } + function generateIndices() { + for (let j = 1; j <= tubularSegments; j++) { + for (let i = 1; i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + } + function generateUVs() { + for (let i = 0; i <= tubularSegments; i++) { + for (let j = 0; j <= radialSegments; j++) { + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.push(uv.x, uv.y); + } + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data = super.toJSON(); + data.path = this.parameters.path.toJSON(); + return data; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {TubeGeometry} A new instance. + */ + static fromJSON(data) { + return new TubeGeometry( + new Curves[data.path.type]().fromJSON(data.path), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); + } + } + class WireframeGeometry extends BufferGeometry { + /** + * Constructs a new wireframe geometry. + * + * @param {?BufferGeometry} [geometry=null] - The geometry. + */ + constructor(geometry = null) { + super(); + this.type = "WireframeGeometry"; + this.parameters = { + geometry + }; + if (geometry !== null) { + const vertices = []; + const edges = /* @__PURE__ */ new Set(); + const start = new Vector3(); + const end = new Vector3(); + if (geometry.index !== null) { + const position = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + if (groups.length === 0) { + groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; + } + for (let o = 0, ol = groups.length; o < ol; ++o) { + const group = groups[o]; + const groupStart = group.start; + const groupCount = group.count; + for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) { + for (let j = 0; j < 3; j++) { + const index1 = indices.getX(i + j); + const index2 = indices.getX(i + (j + 1) % 3); + start.fromBufferAttribute(position, index1); + end.fromBufferAttribute(position, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + } else { + const position = geometry.attributes.position; + for (let i = 0, l = position.count / 3; i < l; i++) { + for (let j = 0; j < 3; j++) { + const index1 = 3 * i + j; + const index2 = 3 * i + (j + 1) % 3; + start.fromBufferAttribute(position, index1); + end.fromBufferAttribute(position, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + } + function isUniqueEdge(start, end, edges) { + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; + if (edges.has(hash1) === true || edges.has(hash2) === true) { + return false; + } else { + edges.add(hash1); + edges.add(hash2); + return true; + } + } + var Geometries = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BoxGeometry, + CapsuleGeometry, + CircleGeometry, + ConeGeometry, + CylinderGeometry, + DodecahedronGeometry, + EdgesGeometry, + ExtrudeGeometry, + IcosahedronGeometry, + LatheGeometry, + OctahedronGeometry, + PlaneGeometry, + PolyhedronGeometry, + RingGeometry, + ShapeGeometry, + SphereGeometry, + TetrahedronGeometry, + TorusGeometry, + TorusKnotGeometry, + TubeGeometry, + WireframeGeometry + }); + class ShadowMaterial extends Material { + /** + * Constructs a new shadow material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isShadowMaterial = true; + this.type = "ShadowMaterial"; + this.color = new Color(0); + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.fog = source.fog; + return this; + } + } + function cloneUniforms(src) { + const dst = {}; + for (const u in src) { + dst[u] = {}; + for (const p in src[u]) { + const property = src[u][p]; + if (isThreeObject(property)) { + if (property.isRenderTargetTexture) { + warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u][p] = null; + } else { + dst[u][p] = property.clone(); + } + } else if (Array.isArray(property)) { + if (isThreeObject(property[0])) { + const clonedProperty = []; + for (let i = 0, l = property.length; i < l; i++) { + clonedProperty[i] = property[i].clone(); + } + dst[u][p] = clonedProperty; + } else { + dst[u][p] = property.slice(); + } + } else { + dst[u][p] = property; + } + } + } + return dst; + } + function mergeUniforms(uniforms) { + const merged = {}; + for (let u = 0; u < uniforms.length; u++) { + const tmp3 = cloneUniforms(uniforms[u]); + for (const p in tmp3) { + merged[p] = tmp3[p]; + } + } + return merged; + } + function isThreeObject(property) { + return property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion); + } + function cloneUniformsGroups(src) { + const dst = []; + for (let u = 0; u < src.length; u++) { + dst.push(src[u].clone()); + } + return dst; + } + function getUnlitUniformColorSpace(renderer) { + const currentRenderTarget = renderer.getRenderTarget(); + if (currentRenderTarget === null) { + return renderer.outputColorSpace; + } + if (currentRenderTarget.isXRRenderTarget === true) { + return currentRenderTarget.texture.colorSpace; + } + return ColorManagement.workingColorSpace; + } + const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + var default_vertex = "void main() {\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + var default_fragment = "void main() {\n gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + class ShaderMaterial extends Material { + /** + * Constructs a new shader material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + clipCullDistance: false, + // set to use vertex shader clipping + multiDraw: false + // set to use vertex shader multi_draw / enable gl_DrawID + }; + this.defaultAttributeValues = { + "color": [1, 1, 1], + "uv": [0, 0], + "uv1": [0, 0] + }; + this.index0AttributeName = void 0; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== void 0) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms(source.uniforms); + this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + this.defaultAttributeValues = Object.assign({}, source.defaultAttributeValues); + this.index0AttributeName = source.index0AttributeName; + this.uniformsNeedUpdate = source.uniformsNeedUpdate; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.glslVersion = this.glslVersion; + data.uniforms = {}; + for (const name in this.uniforms) { + const uniform = this.uniforms[name]; + const value = uniform.value; + if (value && value.isTexture) { + data.uniforms[name] = { + type: "t", + value: value.toJSON(meta).uuid + }; + } else if (value && value.isColor) { + data.uniforms[name] = { + type: "c", + value: value.getHex() + }; + } else if (value && value.isVector2) { + data.uniforms[name] = { + type: "v2", + value: value.toArray() + }; + } else if (value && value.isVector3) { + data.uniforms[name] = { + type: "v3", + value: value.toArray() + }; + } else if (value && value.isVector4) { + data.uniforms[name] = { + type: "v4", + value: value.toArray() + }; + } else if (value && value.isMatrix3) { + data.uniforms[name] = { + type: "m3", + value: value.toArray() + }; + } else if (value && value.isMatrix4) { + data.uniforms[name] = { + type: "m4", + value: value.toArray() + }; + } else { + data.uniforms[name] = { + value + }; + } + } + if (Object.keys(this.defines).length > 0) data.defines = this.defines; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + data.lights = this.lights; + data.clipping = this.clipping; + const extensions = {}; + for (const key in this.extensions) { + if (this.extensions[key] === true) extensions[key] = true; + } + if (Object.keys(extensions).length > 0) data.extensions = extensions; + return data; + } + } + class RawShaderMaterial extends ShaderMaterial { + /** + * Constructs a new raw shader material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(parameters); + this.isRawShaderMaterial = true; + this.type = "RawShaderMaterial"; + } + } + class MeshStandardMaterial extends Material { + /** + * Constructs a new mesh standard material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshStandardMaterial = true; + this.type = "MeshStandardMaterial"; + this.defines = { "STANDARD": "" }; + this.color = new Color(16777215); + this.roughness = 1; + this.metalness = 0; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.roughnessMap = null; + this.metalnessMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler(); + this.envMapIntensity = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { "STANDARD": "" }; + this.color.copy(source.color); + this.roughness = source.roughness; + this.metalness = source.metalness; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.roughnessMap = source.roughnessMap; + this.metalnessMap = source.metalnessMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.envMapIntensity = source.envMapIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + class MeshPhysicalMaterial extends MeshStandardMaterial { + /** + * Constructs a new mesh physical material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshPhysicalMaterial = true; + this.defines = { + "STANDARD": "", + "PHYSICAL": "" + }; + this.type = "MeshPhysicalMaterial"; + this.anisotropyRotation = 0; + this.anisotropyMap = null; + this.clearcoatMap = null; + this.clearcoatRoughness = 0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2(1, 1); + this.clearcoatNormalMap = null; + this.ior = 1.5; + Object.defineProperty(this, "reflectivity", { + get: function() { + return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); + }, + set: function(reflectivity) { + this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); + } + }); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [100, 400]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color(0); + this.sheenColorMap = null; + this.sheenRoughness = 1; + this.sheenRoughnessMap = null; + this.transmissionMap = null; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color(1, 1, 1); + this.specularIntensity = 1; + this.specularIntensityMap = null; + this.specularColor = new Color(1, 1, 1); + this.specularColorMap = null; + this._anisotropy = 0; + this._clearcoat = 0; + this._dispersion = 0; + this._iridescence = 0; + this._sheen = 0; + this._transmission = 0; + this.setValues(parameters); + } + /** + * The anisotropy strength, from `0.0` to `1.0`. + * + * @type {number} + * @default 0 + */ + get anisotropy() { + return this._anisotropy; + } + set anisotropy(value) { + if (this._anisotropy > 0 !== value > 0) { + this.version++; + } + this._anisotropy = value; + } + /** + * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use + * clear coat related properties to enable multilayer materials that have a + * thin translucent layer over the base layer. + * + * @type {number} + * @default 0 + */ + get clearcoat() { + return this._clearcoat; + } + set clearcoat(value) { + if (this._clearcoat > 0 !== value > 0) { + this.version++; + } + this._clearcoat = value; + } + /** + * The intensity of the iridescence layer, simulating RGB color shift based on the angle between + * the surface and the viewer, from `0.0` to `1.0`. + * + * @type {number} + * @default 0 + */ + get iridescence() { + return this._iridescence; + } + set iridescence(value) { + if (this._iridescence > 0 !== value > 0) { + this.version++; + } + this._iridescence = value; + } + /** + * Defines the strength of the angular separation of colors (chromatic aberration) transmitting + * through a relatively clear volume. Any value zero or larger is valid, the typical range of + * realistic values is `[0, 1]`. This property can be only be used with transmissive objects. + * + * @type {number} + * @default 0 + */ + get dispersion() { + return this._dispersion; + } + set dispersion(value) { + if (this._dispersion > 0 !== value > 0) { + this.version++; + } + this._dispersion = value; + } + /** + * The intensity of the sheen layer, from `0.0` to `1.0`. + * + * @type {number} + * @default 0 + */ + get sheen() { + return this._sheen; + } + set sheen(value) { + if (this._sheen > 0 !== value > 0) { + this.version++; + } + this._sheen = value; + } + /** + * Degree of transmission (or optical transparency), from `0.0` to `1.0`. + * + * Thin, transparent or semitransparent, plastic or glass materials remain + * largely reflective even if they are fully transmissive. The transmission + * property can be used to model these materials. + * + * When transmission is non-zero, `opacity` should be set to `1`. + * + * @type {number} + * @default 0 + */ + get transmission() { + return this._transmission; + } + set transmission(value) { + if (this._transmission > 0 !== value > 0) { + this.version++; + } + this._transmission = value; + } + copy(source) { + super.copy(source); + this.defines = { + "STANDARD": "", + "PHYSICAL": "" + }; + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy(source.clearcoatNormalScale); + this.dispersion = source.dispersion; + this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; + this.sheenColor.copy(source.sheenColor); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy(source.attenuationColor); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy(source.specularColor); + this.specularColorMap = source.specularColorMap; + return this; + } + } + class MeshPhongMaterial extends Material { + /** + * Constructs a new mesh phong material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshPhongMaterial = true; + this.type = "MeshPhongMaterial"; + this.color = new Color(16777215); + this.specular = new Color(1118481); + this.shininess = 30; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler(); + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.envMapIntensity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.specular.copy(source.specular); + this.shininess = source.shininess; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.envMapIntensity = source.envMapIntensity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + class MeshToonMaterial extends Material { + /** + * Constructs a new mesh toon material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshToonMaterial = true; + this.defines = { "TOON": "" }; + this.type = "MeshToonMaterial"; + this.color = new Color(16777215); + this.map = null; + this.gradientMap = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.gradientMap = source.gradientMap; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + } + class MeshNormalMaterial extends Material { + /** + * Constructs a new mesh normal material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshNormalMaterial = true; + this.type = "MeshNormalMaterial"; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + return this; + } + } + class MeshLambertMaterial extends Material { + /** + * Constructs a new mesh lambert material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshLambertMaterial = true; + this.type = "MeshLambertMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler(); + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.envMapIntensity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.envMapIntensity = source.envMapIntensity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + class MeshDepthMaterial extends Material { + /** + * Constructs a new mesh depth material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } + } + class MeshDistanceMaterial extends Material { + /** + * Constructs a new mesh distance material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } + } + class MeshMatcapMaterial extends Material { + /** + * Constructs a new mesh matcap material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshMatcapMaterial = true; + this.defines = { "MATCAP": "" }; + this.type = "MeshMatcapMaterial"; + this.color = new Color(16777215); + this.matcap = null; + this.map = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { "MATCAP": "" }; + this.color.copy(source.color); + this.matcap = source.matcap; + this.map = source.map; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + class LineDashedMaterial extends LineBasicMaterial { + /** + * Constructs a new line dashed material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isLineDashedMaterial = true; + this.type = "LineDashedMaterial"; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + return this; + } + } + function convertArray(array, type) { + if (!array || array.constructor === type) return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); + } + function getKeyframeOrder(times) { + function compareTime(i, j) { + return times[i] - times[j]; + } + const n = times.length; + const result = new Array(n); + for (let i = 0; i !== n; ++i) result[i] = i; + result.sort(compareTime); + return result; + } + function sortedArray(values, stride, order) { + const nValues = values.length; + const result = new values.constructor(nValues); + for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) { + const srcOffset = order[i] * stride; + for (let j = 0; j !== stride; ++j) { + result[dstOffset++] = values[srcOffset + j]; + } + } + return result; + } + function flattenJSON(jsonKeys, times, values, valuePropertyName) { + let i = 1, key = jsonKeys[0]; + while (key !== void 0 && key[valuePropertyName] === void 0) { + key = jsonKeys[i++]; + } + if (key === void 0) return; + let value = key[valuePropertyName]; + if (value === void 0) return; + if (Array.isArray(value)) { + do { + value = key[valuePropertyName]; + if (value !== void 0) { + times.push(key.time); + values.push(...value); + } + key = jsonKeys[i++]; + } while (key !== void 0); + } else if (value.toArray !== void 0) { + do { + value = key[valuePropertyName]; + if (value !== void 0) { + times.push(key.time); + value.toArray(values, values.length); + } + key = jsonKeys[i++]; + } while (key !== void 0); + } else { + do { + value = key[valuePropertyName]; + if (value !== void 0) { + times.push(key.time); + values.push(value); + } + key = jsonKeys[i++]; + } while (key !== void 0); + } + } + function subclip(sourceClip, name, startFrame, endFrame, fps = 30) { + const clip = sourceClip.clone(); + clip.name = name; + const tracks = []; + for (let i = 0; i < clip.tracks.length; ++i) { + const track = clip.tracks[i]; + const valueSize = track.getValueSize(); + const times = []; + const values = []; + for (let j = 0; j < track.times.length; ++j) { + const frame = track.times[j] * fps; + if (frame < startFrame || frame >= endFrame) continue; + times.push(track.times[j]); + for (let k = 0; k < valueSize; ++k) { + values.push(track.values[j * valueSize + k]); + } + } + if (times.length === 0) continue; + track.times = convertArray(times, track.times.constructor); + track.values = convertArray(values, track.values.constructor); + tracks.push(track); + } + clip.tracks = tracks; + let minStartTime = Infinity; + for (let i = 0; i < clip.tracks.length; ++i) { + if (minStartTime > clip.tracks[i].times[0]) { + minStartTime = clip.tracks[i].times[0]; + } + } + for (let i = 0; i < clip.tracks.length; ++i) { + clip.tracks[i].shift(-1 * minStartTime); + } + clip.resetDuration(); + return clip; + } + function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + if (fps <= 0) fps = 30; + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + for (let i = 0; i < numTracks; ++i) { + const referenceTrack = referenceClip.tracks[i]; + const referenceTrackType = referenceTrack.ValueTypeName; + if (referenceTrackType === "bool" || referenceTrackType === "string") continue; + const targetTrack = targetClip.tracks.find(function(track) { + return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; + }); + if (targetTrack === void 0) continue; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + referenceOffset = referenceValueSize / 3; + } + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + targetOffset = targetValueSize / 3; + } + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + if (referenceTime <= referenceTrack.times[0]) { + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else if (referenceTime >= referenceTrack.times[lastIndex]) { + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else { + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate(referenceTime); + referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex); + } + if (referenceTrackType === "quaternion") { + const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate(); + referenceQuat.toArray(referenceValue); + } + const numTimes = targetTrack.times.length; + for (let j = 0; j < numTimes; ++j) { + const valueStart = j * targetValueSize + targetOffset; + if (referenceTrackType === "quaternion") { + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); + } else { + const valueEnd = targetValueSize - targetOffset * 2; + for (let k = 0; k < valueEnd; ++k) { + targetTrack.values[valueStart + k] -= referenceValue[k]; + } + } + } + } + targetClip.blendMode = AdditiveAnimationBlendMode; + return targetClip; + } + class AnimationUtils { + /** + * Converts an array to a specific type + * + * @static + * @param {TypedArray|Array} array - The array to convert. + * @param {TypedArray.constructor} type - The constructor of a type array. + * @return {TypedArray} The converted array + */ + static convertArray(array, type) { + return convertArray(array, type); + } + /** + * Returns `true` if the given object is a typed array. + * + * @static + * @param {any} object - The object to check. + * @return {boolean} Whether the given object is a typed array. + */ + static isTypedArray(object) { + return isTypedArray(object); + } + /** + * Returns an array by which times and values can be sorted. + * + * @static + * @param {Array} times - The keyframe time values. + * @return {Array} The array. + */ + static getKeyframeOrder(times) { + return getKeyframeOrder(times); + } + /** + * Sorts the given array by the previously computed order via `getKeyframeOrder()`. + * + * @static + * @param {Array} values - The values to sort. + * @param {number} stride - The stride. + * @param {Array} order - The sort order. + * @return {Array} The sorted values. + */ + static sortedArray(values, stride, order) { + return sortedArray(values, stride, order); + } + /** + * Used for parsing AOS keyframe formats. + * + * @static + * @param {Array} jsonKeys - A list of JSON keyframes. + * @param {Array} times - This array will be filled with keyframe times by this method. + * @param {Array} values - This array will be filled with keyframe values by this method. + * @param {string} valuePropertyName - The name of the property to use. + */ + static flattenJSON(jsonKeys, times, values, valuePropertyName) { + flattenJSON(jsonKeys, times, values, valuePropertyName); + } + /** + * Creates a new clip, containing only the segment of the original clip between the given frames. + * + * @static + * @param {AnimationClip} sourceClip - The values to sort. + * @param {string} name - The name of the clip. + * @param {number} startFrame - The start frame. + * @param {number} endFrame - The end frame. + * @param {number} [fps=30] - The FPS. + * @return {AnimationClip} The new sub clip. + */ + static subclip(sourceClip, name, startFrame, endFrame, fps = 30) { + return subclip(sourceClip, name, startFrame, endFrame, fps); + } + /** + * Converts the keyframes of the given animation clip to an additive format. + * + * @static + * @param {AnimationClip} targetClip - The clip to make additive. + * @param {number} [referenceFrame=0] - The reference frame. + * @param {AnimationClip} [referenceClip=targetClip] - The reference clip. + * @param {number} [fps=30] - The FPS. + * @return {AnimationClip} The updated clip which is now additive. + */ + static makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + return makeClipAdditive(targetClip, referenceFrame, referenceClip, fps); + } + } + class Interpolant { + /** + * Constructs a new interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== void 0 ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + /** + * Evaluate the interpolant at position `t`. + * + * @param {number} t - The interpolation factor. + * @return {TypedArray} The result buffer. + */ + evaluate(t) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: if (!(t < t1)) { + for (let giveUpAt = i1 + 2; ; ) { + if (t1 === void 0) { + if (t < t0) break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) break; + t0 = t1; + t1 = pp[++i1]; + if (t < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t >= t0)) { + const t1global = pp[1]; + if (t < t1global) { + i1 = 2; + t0 = t1global; + } + for (let giveUpAt = i1 - 2; ; ) { + if (t0 === void 0) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) break; + t1 = t0; + t0 = pp[--i1 - 1]; + if (t >= t0) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t0 = pp[i1 - 1]; + if (t0 === void 0) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === void 0) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t0, t1); + } + return this.interpolate_(i1, t0, t, t1); + } + /** + * Returns the interpolation settings. + * + * @return {Object} The interpolation settings. + */ + getSettings_() { + return this.settings || this.DefaultSettings_; + } + /** + * Copies a sample value to the result buffer. + * + * @param {number} index - An index into the sample value buffer. + * @return {TypedArray} The result buffer. + */ + copySampleValue_(index) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset = index * stride; + for (let i = 0; i !== stride; ++i) { + result[i] = values[offset + i]; + } + return result; + } + /** + * Copies a sample value to the result buffer. + * + * @abstract + * @param {number} i1 - An index into the sample value buffer. + * @param {number} t0 - The previous interpolation factor. + * @param {number} t - The current interpolation factor. + * @param {number} t1 - The next interpolation factor. + * @return {TypedArray} The result buffer. + */ + interpolate_() { + throw new Error("call to abstract method"); + } + /** + * Optional method that is executed when the interval has changed. + * + * @param {number} i1 - An index into the sample value buffer. + * @param {number} t0 - The previous interpolation factor. + * @param {number} t - The current interpolation factor. + */ + intervalChanged_() { + } + } + class CubicInterpolant extends Interpolant { + /** + * Constructs a new cubic interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + } + intervalChanged_(i1, t0, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === void 0) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding: + iPrev = i1; + tPrev = 2 * t0 - t1; + break; + case WrapAroundEnding: + iPrev = pp.length - 2; + tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === void 0) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding: + iNext = i1; + tNext = 2 * t1 - t0; + break; + case WrapAroundEnding: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t0; + } + } + const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t0 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t - t0) / (t1 - t0), pp = p * p, ppp = pp * p; + const sP = -wP * ppp + 2 * wP * pp - wP * p; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + for (let i = 0; i !== stride; ++i) { + result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i]; + } + return result; + } + } + class LinearInterpolant extends Interpolant { + /** + * Constructs a new linear interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t - t0) / (t1 - t0), weight0 = 1 - weight1; + for (let i = 0; i !== stride; ++i) { + result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1; + } + return result; + } + } + class DiscreteInterpolant extends Interpolant { + /** + * Constructs a new discrete interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } + } + class BezierInterpolant extends Interpolant { + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer; + const values = this.sampleValues; + const stride = this.valueSize; + const offset1 = i1 * stride; + const offset0 = offset1 - stride; + const settings = this.settings || this.DefaultSettings_; + const inTangents = settings.inTangents; + const outTangents = settings.outTangents; + if (!inTangents || !outTangents) { + const weight1 = (t - t0) / (t1 - t0); + const weight0 = 1 - weight1; + for (let i = 0; i !== stride; ++i) { + result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1; + } + return result; + } + const tangentStride = stride * 2; + const i0 = i1 - 1; + for (let i = 0; i !== stride; ++i) { + const v0 = values[offset0 + i]; + const v1 = values[offset1 + i]; + const outTangentOffset = i0 * tangentStride + i * 2; + const c0x = outTangents[outTangentOffset]; + const c0y = outTangents[outTangentOffset + 1]; + const inTangentOffset = i1 * tangentStride + i * 2; + const c1x = inTangents[inTangentOffset]; + const c1y = inTangents[inTangentOffset + 1]; + let s = (t - t0) / (t1 - t0); + let s2, s3, oneMinusS, oneMinusS2, oneMinusS3; + for (let iter = 0; iter < 8; iter++) { + s2 = s * s; + s3 = s2 * s; + oneMinusS = 1 - s; + oneMinusS2 = oneMinusS * oneMinusS; + oneMinusS3 = oneMinusS2 * oneMinusS; + const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1; + const error2 = bx - t; + if (Math.abs(error2) < 1e-10) break; + const dbx = 3 * oneMinusS2 * (c0x - t0) + 6 * oneMinusS * s * (c1x - c0x) + 3 * s2 * (t1 - c1x); + if (Math.abs(dbx) < 1e-10) break; + s = s - error2 / dbx; + s = Math.max(0, Math.min(1, s)); + } + result[i] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1; + } + return result; + } + } + class KeyframeTrack { + /** + * Constructs a new keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + if (name === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === void 0 || times.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name); + this.name = name; + this.times = convertArray(times, this.TimeBufferType); + this.values = convertArray(values, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + /** + * Converts the keyframe track to JSON. + * + * @static + * @param {KeyframeTrack} track - The keyframe track to serialize. + * @return {Object} The serialized keyframe track as JSON. + */ + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + "name": track.name, + "times": convertArray(track.times, Array), + "values": convertArray(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + /** + * Factory method for creating a new discrete interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {DiscreteInterpolant} The new interpolant. + */ + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result); + } + /** + * Factory method for creating a new linear interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {LinearInterpolant} The new interpolant. + */ + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant(this.times, this.values, this.getValueSize(), result); + } + /** + * Factory method for creating a new smooth interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {CubicInterpolant} The new interpolant. + */ + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant(this.times, this.values, this.getValueSize(), result); + } + /** + * Factory method for creating a new Bezier interpolant. + * + * The Bezier interpolant requires tangent data to be set via the `settings` property + * on the track before creating the interpolant. The settings should contain: + * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component + * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {BezierInterpolant} The new interpolant. + */ + InterpolantFactoryMethodBezier(result) { + const interpolant = new BezierInterpolant(this.times, this.values, this.getValueSize(), result); + if (this.settings) { + interpolant.settings = this.settings; + } + return interpolant; + } + /** + * Defines the interpolation factor method for this keyframe track. + * + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + case InterpolateBezier: + factoryMethod = this.InterpolantFactoryMethodBezier; + break; + } + if (factoryMethod === void 0) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === void 0) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + warn("KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + /** + * Returns the current interpolation type. + * + * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type. + */ + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth; + case this.InterpolantFactoryMethodBezier: + return InterpolateBezier; + } + } + /** + * Returns the value size. + * + * @return {number} The value size. + */ + getValueSize() { + return this.values.length / this.times.length; + } + /** + * Moves all keyframes either forward or backward in time. + * + * @param {number} timeOffset - The offset to move the time values. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i = 0, n = times.length; i !== n; ++i) { + times[i] += timeOffset; + } + } + return this; + } + /** + * Scale all keyframe times by a factor (useful for frame - seconds conversions). + * + * @param {number} timeScale - The time scale. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i = 0, n = times.length; i !== n; ++i) { + times[i] *= timeScale; + } + } + return this; + } + /** + * Removes keyframes before and after animation without changing any values within the defined time range. + * + * Note: The method does not shift around keys to the start of the track time, because for interpolated + * keys this will change their values + * + * @param {number} startTime - The start time. + * @param {number} endTime - The end time. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + /** + * Performs minimal validation on the keyframe track. Returns `true` if the values + * are valid. + * + * @return {boolean} Whether the keyframes are valid or not. + */ + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + error("KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values = this.values, nKeys = times.length; + if (nKeys === 0) { + error("KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i = 0; i !== nKeys; i++) { + const currTime = times[i]; + if (typeof currTime === "number" && isNaN(currTime)) { + error("KeyframeTrack: Time is not a valid number.", this, i, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + error("KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values !== void 0) { + if (isTypedArray(values)) { + for (let i = 0, n = values.length; i !== n; ++i) { + const value = values[i]; + if (isNaN(value)) { + error("KeyframeTrack: Value is not a valid number.", this, i, value); + valid = false; + break; + } + } + } + } + return valid; + } + /** + * Optimizes this keyframe track by removing equivalent sequential keys (which are + * common in morph target sequences). + * + * @return {KeyframeTrack} A reference to this keyframe track. + */ + optimize() { + const times = this.times.slice(), values = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i = 1; i < lastIndex; ++i) { + let keep = false; + const time = times[i]; + const timeNext = times[i + 1]; + if (time !== timeNext && (i !== 1 || time !== times[0])) { + if (!smoothInterpolation) { + const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j = 0; j !== stride; ++j) { + const value = values[offset + j]; + if (value !== values[offsetP + j] || value !== values[offsetN + j]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i !== writeIndex) { + times[writeIndex] = times[i]; + const readOffset = i * stride, writeOffset = writeIndex * stride; + for (let j = 0; j !== stride; ++j) { + values[writeOffset + j] = values[readOffset + j]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) { + values[writeOffset + j] = values[readOffset + j]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values; + } + return this; + } + /** + * Returns a new keyframe track with copied values from this instance. + * + * @return {KeyframeTrack} A clone of this instance. + */ + clone() { + const times = this.times.slice(); + const values = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values); + track.createInterpolant = this.createInterpolant; + return track; + } + } + KeyframeTrack.prototype.ValueTypeName = ""; + KeyframeTrack.prototype.TimeBufferType = Float32Array; + KeyframeTrack.prototype.ValueBufferType = Float32Array; + KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + class BooleanKeyframeTrack extends KeyframeTrack { + /** + * Constructs a new boolean keyframe track. + * + * This keyframe track type has no `interpolation` parameter because the + * interpolation is always discrete. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + */ + constructor(name, times, values) { + super(name, times, values); + } + } + BooleanKeyframeTrack.prototype.ValueTypeName = "bool"; + BooleanKeyframeTrack.prototype.ValueBufferType = Array; + BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; + BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0; + BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; + class ColorKeyframeTrack extends KeyframeTrack { + /** + * Constructs a new color keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + super(name, times, values, interpolation); + } + } + ColorKeyframeTrack.prototype.ValueTypeName = "color"; + class NumberKeyframeTrack extends KeyframeTrack { + /** + * Constructs a new number keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + super(name, times, values, interpolation); + } + } + NumberKeyframeTrack.prototype.ValueTypeName = "number"; + class QuaternionLinearInterpolant extends Interpolant { + /** + * Constructs a new SLERP interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, alpha = (t - t0) / (t1 - t0); + let offset = i1 * stride; + for (let end = offset + stride; offset !== end; offset += 4) { + Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha); + } + return result; + } + } + class QuaternionKeyframeTrack extends KeyframeTrack { + /** + * Constructs a new Quaternion keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + super(name, times, values, interpolation); + } + /** + * Overwritten so the method returns Quaternion based interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {QuaternionLinearInterpolant} The new interpolant. + */ + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result); + } + } + QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion"; + QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; + class StringKeyframeTrack extends KeyframeTrack { + /** + * Constructs a new string keyframe track. + * + * This keyframe track type has no `interpolation` parameter because the + * interpolation is always discrete. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + */ + constructor(name, times, values) { + super(name, times, values); + } + } + StringKeyframeTrack.prototype.ValueTypeName = "string"; + StringKeyframeTrack.prototype.ValueBufferType = Array; + StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; + StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0; + StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; + class VectorKeyframeTrack extends KeyframeTrack { + /** + * Constructs a new vector keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + super(name, times, values, interpolation); + } + } + VectorKeyframeTrack.prototype.ValueTypeName = "vector"; + class AnimationClip { + /** + * Constructs a new animation clip. + * + * Note: Instead of instantiating an AnimationClip directly with the constructor, you can + * use the static interface of this class for creating clips. In most cases though, animation clips + * will automatically be created by loaders when importing animated 3D assets. + * + * @param {string} [name=''] - The clip's name. + * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed, + * the duration will be calculated from the passed keyframes. + * @param {Array} tracks - An array of keyframe tracks. + * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation + * is blended/combined when two or more animations are simultaneously played. + */ + constructor(name = "", duration = -1, tracks = [], blendMode = NormalAnimationBlendMode) { + this.name = name; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + this.uuid = generateUUID(); + this.userData = {}; + if (this.duration < 0) { + this.resetDuration(); + } + } + /** + * Factory method for creating an animation clip from the given JSON. + * + * @static + * @param {Object} json - The serialized animation clip. + * @return {AnimationClip} The new animation clip. + */ + static parse(json) { + const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); + for (let i = 0, n = jsonTracks.length; i !== n; ++i) { + tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime)); + } + const clip = new this(json.name, json.duration, tracks, json.blendMode); + clip.uuid = json.uuid; + clip.userData = JSON.parse(json.userData || "{}"); + return clip; + } + /** + * Serializes the given animation clip into JSON. + * + * @static + * @param {AnimationClip} clip - The animation clip to serialize. + * @return {Object} The JSON object. + */ + static toJSON(clip) { + const tracks = [], clipTracks = clip.tracks; + const json = { + "name": clip.name, + "duration": clip.duration, + "tracks": tracks, + "uuid": clip.uuid, + "blendMode": clip.blendMode, + "userData": JSON.stringify(clip.userData) + }; + for (let i = 0, n = clipTracks.length; i !== n; ++i) { + tracks.push(KeyframeTrack.toJSON(clipTracks[i])); + } + return json; + } + /** + * Returns a new animation clip from the passed morph targets array of a + * geometry, taking a name and the number of frames per second. + * + * Note: The fps parameter is required, but the animation speed can be + * overridden via {@link AnimationAction#setDuration}. + * + * @static + * @param {string} name - The name of the animation clip. + * @param {Array} morphTargetSequence - A sequence of morph targets. + * @param {number} fps - The Frames-Per-Second value. + * @param {boolean} noLoop - Whether the clip should be no loop or not. + * @return {AnimationClip} The new animation clip. + */ + static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + for (let i = 0; i < numMorphTargets; i++) { + let times = []; + let values = []; + times.push( + (i + numMorphTargets - 1) % numMorphTargets, + i, + (i + 1) % numMorphTargets + ); + values.push(0, 1, 0); + const order = getKeyframeOrder(times); + times = sortedArray(times, 1, order); + values = sortedArray(values, 1, order); + if (!noLoop && times[0] === 0) { + times.push(numMorphTargets); + values.push(values[0]); + } + tracks.push( + new NumberKeyframeTrack( + ".morphTargetInfluences[" + morphTargetSequence[i].name + "]", + times, + values + ).scale(1 / fps) + ); + } + return new this(name, -1, tracks); + } + /** + * Searches for an animation clip by name, taking as its first parameter + * either an array of clips, or a mesh or geometry that contains an + * array named "animations" property. + * + * @static + * @param {(Array|Object3D)} objectOrClipArray - The array or object to search through. + * @param {string} name - The name to search for. + * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found. + */ + static findByName(objectOrClipArray, name) { + let clipArray = objectOrClipArray; + if (!Array.isArray(objectOrClipArray)) { + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + } + for (let i = 0; i < clipArray.length; i++) { + if (clipArray[i].name === name) { + return clipArray[i]; + } + } + return null; + } + /** + * Returns an array of new AnimationClips created from the morph target + * sequences of a geometry, trying to sort morph target names into + * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...". + * + * See {@link MD2Loader#parse} as an example for how the method should be used. + * + * @static + * @param {Array} morphTargets - A sequence of morph targets. + * @param {number} fps - The Frames-Per-Second value. + * @param {boolean} noLoop - Whether the clip should be no loop or not. + * @return {Array} An array of new animation clips. + */ + static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { + const animationToMorphTargets = {}; + const pattern = /^([\w-]*?)([\d]+)$/; + for (let i = 0, il = morphTargets.length; i < il; i++) { + const morphTarget = morphTargets[i]; + const parts = morphTarget.name.match(pattern); + if (parts && parts.length > 1) { + const name = parts[1]; + let animationMorphTargets = animationToMorphTargets[name]; + if (!animationMorphTargets) { + animationToMorphTargets[name] = animationMorphTargets = []; + } + animationMorphTargets.push(morphTarget); + } + } + const clips = []; + for (const name in animationToMorphTargets) { + clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop)); + } + return clips; + } + /** + * Parses the `animation.hierarchy` format and returns a new animation clip. + * + * @static + * @deprecated since r175. + * @param {Object} animation - A serialized animation clip as JSON. + * @param {Array} bones - An array of bones. + * @return {?AnimationClip} The new animation clip. + */ + static parseAnimation(animation, bones) { + warn("AnimationClip: parseAnimation() is deprecated and will be removed with r185"); + if (!animation) { + error("AnimationClip: No animation in JSONLoader data."); + return null; + } + const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { + if (animationKeys.length !== 0) { + const times = []; + const values = []; + flattenJSON(animationKeys, times, values, propertyName); + if (times.length !== 0) { + destTracks.push(new trackType(trackName, times, values)); + } + } + }; + const tracks = []; + const clipName = animation.name || "default"; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + let duration = animation.length || -1; + const hierarchyTracks = animation.hierarchy || []; + for (let h = 0; h < hierarchyTracks.length; h++) { + const animationKeys = hierarchyTracks[h].keys; + if (!animationKeys || animationKeys.length === 0) continue; + if (animationKeys[0].morphTargets) { + const morphTargetNames = {}; + let k; + for (k = 0; k < animationKeys.length; k++) { + if (animationKeys[k].morphTargets) { + for (let m = 0; m < animationKeys[k].morphTargets.length; m++) { + morphTargetNames[animationKeys[k].morphTargets[m]] = -1; + } + } + } + for (const morphTargetName in morphTargetNames) { + const times = []; + const values = []; + for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) { + const animationKey = animationKeys[k]; + times.push(animationKey.time); + values.push(animationKey.morphTarget === morphTargetName ? 1 : 0); + } + tracks.push(new NumberKeyframeTrack(".morphTargetInfluence[" + morphTargetName + "]", times, values)); + } + duration = morphTargetNames.length * fps; + } else { + const boneName = ".bones[" + bones[h].name + "]"; + addNonemptyTrack( + VectorKeyframeTrack, + boneName + ".position", + animationKeys, + "pos", + tracks + ); + addNonemptyTrack( + QuaternionKeyframeTrack, + boneName + ".quaternion", + animationKeys, + "rot", + tracks + ); + addNonemptyTrack( + VectorKeyframeTrack, + boneName + ".scale", + animationKeys, + "scl", + tracks + ); + } + } + if (tracks.length === 0) { + return null; + } + const clip = new this(clipName, duration, tracks, blendMode); + return clip; + } + /** + * Sets the duration of this clip to the duration of its longest keyframe track. + * + * @return {AnimationClip} A reference to this animation clip. + */ + resetDuration() { + const tracks = this.tracks; + let duration = 0; + for (let i = 0, n = tracks.length; i !== n; ++i) { + const track = this.tracks[i]; + duration = Math.max(duration, track.times[track.times.length - 1]); + } + this.duration = duration; + return this; + } + /** + * Trims all tracks to the clip's duration. + * + * @return {AnimationClip} A reference to this animation clip. + */ + trim() { + for (let i = 0; i < this.tracks.length; i++) { + this.tracks[i].trim(0, this.duration); + } + return this; + } + /** + * Performs minimal validation on each track in the clip. Returns `true` if all + * tracks are valid. + * + * @return {boolean} Whether the clip's keyframes are valid or not. + */ + validate() { + let valid = true; + for (let i = 0; i < this.tracks.length; i++) { + valid = valid && this.tracks[i].validate(); + } + return valid; + } + /** + * Optimizes each track by removing equivalent sequential keys (which are + * common in morph target sequences). + * + * @return {AnimationClip} A reference to this animation clip. + */ + optimize() { + for (let i = 0; i < this.tracks.length; i++) { + this.tracks[i].optimize(); + } + return this; + } + /** + * Returns a new animation clip with copied values from this instance. + * + * @return {AnimationClip} A clone of this instance. + */ + clone() { + const tracks = []; + for (let i = 0; i < this.tracks.length; i++) { + tracks.push(this.tracks[i].clone()); + } + const clip = new this.constructor(this.name, this.duration, tracks, this.blendMode); + clip.userData = JSON.parse(JSON.stringify(this.userData)); + return clip; + } + /** + * Serializes this animation clip into JSON. + * + * @return {Object} The JSON object. + */ + toJSON() { + return this.constructor.toJSON(this); + } + } + function getTrackTypeForValueTypeName(typeName) { + switch (typeName.toLowerCase()) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": + return NumberKeyframeTrack; + case "vector": + case "vector2": + case "vector3": + case "vector4": + return VectorKeyframeTrack; + case "color": + return ColorKeyframeTrack; + case "quaternion": + return QuaternionKeyframeTrack; + case "bool": + case "boolean": + return BooleanKeyframeTrack; + case "string": + return StringKeyframeTrack; + } + throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); + } + function parseKeyframeTrack(json) { + if (json.type === void 0) { + throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); + } + const trackType = getTrackTypeForValueTypeName(json.type); + if (json.times === void 0) { + const times = [], values = []; + flattenJSON(json.keys, times, values, "value"); + json.times = times; + json.values = values; + } + if (trackType.parse !== void 0) { + return trackType.parse(json); + } else { + return new trackType(json.name, json.times, json.values, json.interpolation); + } + } + const Cache = { + /** + * Whether caching is enabled or not. + * + * @static + * @type {boolean} + * @default false + */ + enabled: false, + /** + * A dictionary that holds cached files. + * + * @static + * @type {Object} + */ + files: {}, + /** + * Adds a cache entry with a key to reference the file. If this key already + * holds a file, it is overwritten. + * + * @static + * @param {string} key - The key to reference the cached file. + * @param {Object} file - The file to be cached. + */ + add: function(key, file) { + if (this.enabled === false) return; + if (isBlobURL(key)) return; + this.files[key] = file; + }, + /** + * Gets the cached value for the given key. + * + * @static + * @param {string} key - The key to reference the cached file. + * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned. + */ + get: function(key) { + if (this.enabled === false) return; + if (isBlobURL(key)) return; + return this.files[key]; + }, + /** + * Removes the cached file associated with the given key. + * + * @static + * @param {string} key - The key to reference the cached file. + */ + remove: function(key) { + delete this.files[key]; + }, + /** + * Remove all values from the cache. + * + * @static + */ + clear: function() { + this.files = {}; + } + }; + function isBlobURL(key) { + try { + const urlString = key.slice(key.indexOf(":") + 1); + const url = new URL(urlString); + return url.protocol === "blob:"; + } catch (e) { + return false; + } + } + class LoadingManager { + /** + * Constructs a new loading manager. + * + * @param {Function} [onLoad] - Executes when all items have been loaded. + * @param {Function} [onProgress] - Executes when single items have been loaded. + * @param {Function} [onError] - Executes when an error occurs. + */ + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = void 0; + const handlers = []; + this.onStart = void 0; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this._abortController = null; + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== void 0) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== void 0) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== void 0) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== void 0) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform) { + urlModifier = transform; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index = handlers.indexOf(regex); + if (index !== -1) { + handlers.splice(index, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i = 0, l = handlers.length; i < l; i += 2) { + const regex = handlers[i]; + const loader = handlers[i + 1]; + if (regex.global) regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + this.abort = function() { + this.abortController.abort(); + this._abortController = null; + return this; + }; + } + // TODO: Revert this back to a single member variable once this issue has been fixed + // https://github.com/cloudflare/workerd/issues/3657 + /** + * Used for aborting ongoing requests in loaders using this manager. + * + * @type {AbortController} + */ + get abortController() { + if (!this._abortController) { + this._abortController = new AbortController(); + } + return this._abortController; + } + } + const DefaultLoadingManager = /* @__PURE__ */ new LoadingManager(); + class Loader { + /** + * Constructs a new loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + this.manager = manager !== void 0 ? manager : DefaultLoadingManager; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + /** + * This method needs to be implemented by all concrete loaders. It holds the + * logic for loading assets from the backend. + * + * @abstract + * @param {string} url - The path/URL of the file to be loaded. + * @param {Function} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. + * @param {onErrorCallback} [onError] - Executed when errors occur. + */ + load() { + } + /** + * A async version of {@link Loader#load}. + * + * @param {string} url - The path/URL of the file to be loaded. + * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. + * @return {Promise} A Promise that resolves when the asset has been loaded. + */ + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject) { + scope.load(url, resolve, onProgress, reject); + }); + } + /** + * This method needs to be implemented by all concrete loaders. It holds the + * logic for parsing the asset into three.js entities. + * + * @abstract + * @param {any} data - The data to parse. + */ + parse() { + } + /** + * Sets the `crossOrigin` String to implement CORS for loading the URL + * from a different domain that allows CORS. + * + * @param {string} crossOrigin - The `crossOrigin` value. + * @return {Loader} A reference to this instance. + */ + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + /** + * Whether the XMLHttpRequest uses credentials such as cookies, authorization + * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials). + * + * Note: This setting has no effect if you are loading files locally or from the same domain. + * + * @param {boolean} value - The `withCredentials` value. + * @return {Loader} A reference to this instance. + */ + setWithCredentials(value) { + this.withCredentials = value; + return this; + } + /** + * Sets the base path for the asset. + * + * @param {string} path - The base path. + * @return {Loader} A reference to this instance. + */ + setPath(path) { + this.path = path; + return this; + } + /** + * Sets the base path for dependent resources like textures. + * + * @param {string} resourcePath - The resource path. + * @return {Loader} A reference to this instance. + */ + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + /** + * Sets the given request header. + * + * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) + * for configuring the HTTP request. + * @return {Loader} A reference to this instance. + */ + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } + /** + * This method can be implemented in loaders for aborting ongoing requests. + * + * @abstract + * @return {Loader} A reference to this instance. + */ + abort() { + return this; + } + } + Loader.DEFAULT_MATERIAL_NAME = "__DEFAULT"; + const loading = {}; + class HttpError extends Error { + constructor(message, response) { + super(message); + this.response = response; + } + } + class FileLoader extends Loader { + /** + * Constructs a new file loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + this.mimeType = ""; + this.responseType = ""; + this._abortController = new AbortController(); + } + /** + * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(any)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. + * @param {onErrorCallback} [onError] - Executed when errors occur. + */ + load(url, onLoad, onProgress, onError) { + if (url === void 0) url = ""; + if (this.path !== void 0) url = this.path + url; + url = this.manager.resolveURL(url); + const cached = Cache.get(`file:${url}`); + if (cached !== void 0) { + this.manager.itemStart(url); + setTimeout(() => { + if (onLoad) onLoad(cached); + this.manager.itemEnd(url); + }, 0); + return; + } + if (loading[url] !== void 0) { + loading[url].push({ + onLoad, + onProgress, + onError + }); + return; + } + loading[url] = []; + loading[url].push({ + onLoad, + onProgress, + onError + }); + const req = new Request(url, { + headers: new Headers(this.requestHeader), + credentials: this.withCredentials ? "include" : "same-origin", + signal: typeof AbortSignal.any === "function" ? AbortSignal.any([this._abortController.signal, this.manager.abortController.signal]) : this._abortController.signal + }); + const mimeType = this.mimeType; + const responseType = this.responseType; + fetch(req).then((response) => { + if (response.status === 200 || response.status === 0) { + if (response.status === 0) { + warn("FileLoader: HTTP Status 0 received."); + } + if (typeof ReadableStream === "undefined" || response.body === void 0 || response.body.getReader === void 0) { + return response; + } + const callbacks = loading[url]; + const reader = response.body.getReader(); + const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length"); + const total = contentLength ? parseInt(contentLength) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + const stream = new ReadableStream({ + start(controller) { + readData(); + function readData() { + reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + } else { + loaded += value.byteLength; + const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); + for (let i = 0, il = callbacks.length; i < il; i++) { + const callback = callbacks[i]; + if (callback.onProgress) callback.onProgress(event); + } + controller.enqueue(value); + readData(); + } + }, (e) => { + controller.error(e); + }); + } + } + }); + return new Response(stream); + } else { + throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); + } + }).then((response) => { + switch (responseType) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "document": + return response.text().then((text) => { + const parser = new DOMParser(); + return parser.parseFromString(text, mimeType); + }); + case "json": + return response.json(); + default: + if (mimeType === "") { + return response.text(); + } else { + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec(mimeType); + const label = exec && exec[1] ? exec[1].toLowerCase() : void 0; + const decoder = new TextDecoder(label); + return response.arrayBuffer().then((ab) => decoder.decode(ab)); + } + } + }).then((data) => { + Cache.add(`file:${url}`, data); + const callbacks = loading[url]; + delete loading[url]; + for (let i = 0, il = callbacks.length; i < il; i++) { + const callback = callbacks[i]; + if (callback.onLoad) callback.onLoad(data); + } + }).catch((err) => { + const callbacks = loading[url]; + if (callbacks === void 0) { + this.manager.itemError(url); + throw err; + } + delete loading[url]; + for (let i = 0, il = callbacks.length; i < il; i++) { + const callback = callbacks[i]; + if (callback.onError) callback.onError(err); + } + this.manager.itemError(url); + }).finally(() => { + this.manager.itemEnd(url); + }); + this.manager.itemStart(url); + } + /** + * Sets the expected response type. + * + * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type. + * @return {FileLoader} A reference to this file loader. + */ + setResponseType(value) { + this.responseType = value; + return this; + } + /** + * Sets the expected mime type of the loaded file. + * + * @param {string} value - The mime type. + * @return {FileLoader} A reference to this file loader. + */ + setMimeType(value) { + this.mimeType = value; + return this; + } + /** + * Aborts ongoing fetch requests. + * + * @return {FileLoader} A reference to this instance. + */ + abort() { + this._abortController.abort(); + this._abortController = new AbortController(); + return this; + } + } + class AnimationLoader extends Loader { + /** + * Constructs a new animation loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and pass the loaded animations as an array + * holding instances of {@link AnimationClip} to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Array)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text) { + try { + onLoad(scope.parse(JSON.parse(text))); + } catch (e) { + if (onError) { + onError(e); + } else { + error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + /** + * Parses the given JSON object and returns an array of animation clips. + * + * @param {Object} json - The serialized animation clips. + * @return {Array} The parsed animation clips. + */ + parse(json) { + const animations = []; + for (let i = 0; i < json.length; i++) { + const clip = AnimationClip.parse(json[i]); + animations.push(clip); + } + return animations; + } + } + class CompressedTextureLoader extends Loader { + /** + * Constructs a new compressed texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and passes the loaded compressed texture + * to the `onLoad()` callback. The method also returns a new texture object which can + * directly be used for material creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {CompressedTexture} The compressed texture. + */ + load(url, onLoad, onProgress, onError) { + const scope = this; + const images = []; + const texture = new CompressedTexture(); + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(scope.withCredentials); + let loaded = 0; + function loadTexture(i) { + loader.load(url[i], function(buffer) { + const texDatas = scope.parse(buffer, true); + images[i] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + loaded += 1; + if (loaded === 6) { + if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter; + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) onLoad(texture); + } + }, onProgress, onError); + } + if (Array.isArray(url)) { + for (let i = 0, il = url.length; i < il; ++i) { + loadTexture(i); + } + } else { + loader.load(url, function(buffer) { + const texDatas = scope.parse(buffer, true); + if (texDatas.isCubemap) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + for (let f = 0; f < faces; f++) { + images[f] = { mipmaps: [] }; + for (let i = 0; i < texDatas.mipmapCount; i++) { + images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]); + images[f].format = texDatas.format; + images[f].width = texDatas.width; + images[f].height = texDatas.height; + } + } + texture.image = images; + } else { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + } + if (texDatas.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) onLoad(texture); + }, onProgress, onError); + } + return texture; + } + } + const _loading = /* @__PURE__ */ new WeakMap(); + class ImageLoader extends Loader { + /** + * Constructs a new image loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and passes the loaded image + * to the `onLoad()` callback. The method also returns a new `Image` object which can + * directly be used for texture creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Image)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {Image} The image. + */ + load(url, onLoad, onProgress, onError) { + if (this.path !== void 0) url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(`image:${url}`); + if (cached !== void 0) { + if (cached.complete === true) { + scope.manager.itemStart(url); + setTimeout(function() { + if (onLoad) onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + } else { + let arr = _loading.get(cached); + if (arr === void 0) { + arr = []; + _loading.set(cached, arr); + } + arr.push({ onLoad, onError }); + } + return cached; + } + const image = createElementNS("img"); + function onImageLoad() { + removeEventListeners(); + if (onLoad) onLoad(this); + const callbacks = _loading.get(this) || []; + for (let i = 0; i < callbacks.length; i++) { + const callback = callbacks[i]; + if (callback.onLoad) callback.onLoad(this); + } + _loading.delete(this); + scope.manager.itemEnd(url); + } + function onImageError(event) { + removeEventListeners(); + if (onError) onError(event); + Cache.remove(`image:${url}`); + const callbacks = _loading.get(this) || []; + for (let i = 0; i < callbacks.length; i++) { + const callback = callbacks[i]; + if (callback.onError) callback.onError(event); + } + _loading.delete(this); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } + function removeEventListeners() { + image.removeEventListener("load", onImageLoad, false); + image.removeEventListener("error", onImageError, false); + } + image.addEventListener("load", onImageLoad, false); + image.addEventListener("error", onImageError, false); + if (url.slice(0, 5) !== "data:") { + if (this.crossOrigin !== void 0) image.crossOrigin = this.crossOrigin; + } + Cache.add(`image:${url}`, image); + scope.manager.itemStart(url); + image.src = url; + return image; + } + } + class CubeTextureLoader extends Loader { + /** + * Constructs a new cube texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and pass the fully loaded cube texture + * to the `onLoad()` callback. The method also returns a new cube texture object which can + * directly be used for material creation. If you do it this way, the cube texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {Array} urls - Array of 6 URLs to images, one for each side of the + * cube texture. The urls should be specified in the following order: pos-x, + * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well. + * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {CubeTexture} The cube texture. + */ + load(urls, onLoad, onProgress, onError) { + const texture = new CubeTexture(); + texture.colorSpace = SRGBColorSpace; + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + let loaded = 0; + function loadTexture(i) { + loader.load(urls[i], function(image) { + texture.images[i] = image; + loaded++; + if (loaded === 6) { + texture.needsUpdate = true; + if (onLoad) onLoad(texture); + } + }, void 0, onError); + } + for (let i = 0; i < urls.length; ++i) { + loadTexture(i); + } + return texture; + } + } + class DataTextureLoader extends Loader { + /** + * Constructs a new data texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and passes the loaded data texture + * to the `onLoad()` callback. The method also returns a new texture object which can + * directly be used for material creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {DataTexture} The data texture. + */ + load(url, onLoad, onProgress, onError) { + const scope = this; + const texture = new DataTexture(); + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setPath(this.path); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + let texData; + try { + texData = scope.parse(buffer); + } catch (e) { + if (onError !== void 0) { + onError(e); + } else { + error(e); + } + return; + } + if (texData.image !== void 0) { + texture.image = texData.image; + } else if (texData.data !== void 0) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + } + texture.wrapS = texData.wrapS !== void 0 ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== void 0 ? texData.wrapT : ClampToEdgeWrapping; + texture.magFilter = texData.magFilter !== void 0 ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== void 0 ? texData.minFilter : LinearFilter; + texture.anisotropy = texData.anisotropy !== void 0 ? texData.anisotropy : 1; + if (texData.colorSpace !== void 0) { + texture.colorSpace = texData.colorSpace; + } + if (texData.flipY !== void 0) { + texture.flipY = texData.flipY; + } + if (texData.format !== void 0) { + texture.format = texData.format; + } + if (texData.type !== void 0) { + texture.type = texData.type; + } + if (texData.mipmaps !== void 0) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; + } + if (texData.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + if (texData.generateMipmaps !== void 0) { + texture.generateMipmaps = texData.generateMipmaps; + } + texture.needsUpdate = true; + if (onLoad) onLoad(texture, texData); + }, onProgress, onError); + return texture; + } + } + class TextureLoader extends Loader { + /** + * Constructs a new texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and pass the fully loaded texture + * to the `onLoad()` callback. The method also returns a new texture object which can + * directly be used for material creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Texture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {Texture} The texture. + */ + load(url, onLoad, onProgress, onError) { + const texture = new Texture(); + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + loader.load(url, function(image) { + texture.image = image; + texture.needsUpdate = true; + if (onLoad !== void 0) { + onLoad(texture); + } + }, onProgress, onError); + return texture; + } + } + class Light extends Object3D { + /** + * Constructs a new light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor(color, intensity = 1) { + super(); + this.isLight = true; + this.type = "Light"; + this.color = new Color(color); + this.intensity = intensity; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + copy(source, recursive) { + super.copy(source, recursive); + this.color.copy(source.color); + this.intensity = source.intensity; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; + return data; + } + } + class HemisphereLight extends Light { + /** + * Constructs a new hemisphere light. + * + * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color. + * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor(skyColor, groundColor, intensity) { + super(skyColor, intensity); + this.isHemisphereLight = true; + this.type = "HemisphereLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.groundColor = new Color(groundColor); + } + copy(source, recursive) { + super.copy(source, recursive); + this.groundColor.copy(source.groundColor); + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.groundColor = this.groundColor.getHex(); + return data; + } + } + const _projScreenMatrix$1 = /* @__PURE__ */ new Matrix4(); + const _lightPositionWorld$1 = /* @__PURE__ */ new Vector3(); + const _lookTarget$1 = /* @__PURE__ */ new Vector3(); + class LightShadow { + /** + * Constructs a new light shadow. + * + * @param {Camera} camera - The light's view of the world. + */ + constructor(camera) { + this.camera = camera; + this.intensity = 1; + this.bias = 0; + this.biasNode = null; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + this.mapSize = new Vector2(512, 512); + this.mapType = UnsignedByteType; + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); + this.autoUpdate = true; + this.needsUpdate = false; + this._frustum = new Frustum(); + this._frameExtents = new Vector2(1, 1); + this._viewportCount = 1; + this._viewports = [ + new Vector4(0, 0, 1, 1) + ]; + } + /** + * Used internally by the renderer to get the number of viewports that need + * to be rendered for this shadow. + * + * @return {number} The viewport count. + */ + getViewportCount() { + return this._viewportCount; + } + /** + * Gets the shadow cameras frustum. Used internally by the renderer to cull objects. + * + * @return {Frustum} The shadow camera frustum. + */ + getFrustum() { + return this._frustum; + } + /** + * Update the matrices for the camera and shadow, used internally by the renderer. + * + * @param {Light} light - The light for which the shadow is being rendered. + */ + updateMatrices(light) { + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld); + shadowCamera.position.copy(_lightPositionWorld$1); + _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld); + shadowCamera.lookAt(_lookTarget$1); + shadowCamera.updateMatrixWorld(); + _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth); + if (shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth) { + shadowMatrix.set( + 0.5, + 0, + 0, + 0.5, + 0, + 0.5, + 0, + 0.5, + 0, + 0, + 1, + 0, + // Identity Z (preserving the correct [0, 1] range from the projection matrix) + 0, + 0, + 0, + 1 + ); + } else { + shadowMatrix.set( + 0.5, + 0, + 0, + 0.5, + 0, + 0.5, + 0, + 0.5, + 0, + 0, + 0.5, + 0.5, + 0, + 0, + 0, + 1 + ); + } + shadowMatrix.multiply(_projScreenMatrix$1); + } + /** + * Returns a viewport definition for the given viewport index. + * + * @param {number} viewportIndex - The viewport index. + * @return {Vector4} The viewport. + */ + getViewport(viewportIndex) { + return this._viewports[viewportIndex]; + } + /** + * Returns the frame extends. + * + * @return {Vector2} The frame extends. + */ + getFrameExtents() { + return this._frameExtents; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + if (this.map) { + this.map.dispose(); + } + if (this.mapPass) { + this.mapPass.dispose(); + } + } + /** + * Copies the values of the given light shadow instance to this instance. + * + * @param {LightShadow} source - The light shadow to copy. + * @return {LightShadow} A reference to this light shadow instance. + */ + copy(source) { + this.camera = source.camera.clone(); + this.intensity = source.intensity; + this.bias = source.bias; + this.radius = source.radius; + this.autoUpdate = source.autoUpdate; + this.needsUpdate = source.needsUpdate; + this.normalBias = source.normalBias; + this.blurSamples = source.blurSamples; + this.mapSize.copy(source.mapSize); + this.biasNode = source.biasNode; + return this; + } + /** + * Returns a new light shadow instance with copied values from this instance. + * + * @return {LightShadow} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Serializes the light shadow into JSON. + * + * @return {Object} A JSON object representing the serialized light shadow. + * @see {@link ObjectLoader#parse} + */ + toJSON() { + const object = {}; + if (this.intensity !== 1) object.intensity = this.intensity; + if (this.bias !== 0) object.bias = this.bias; + if (this.normalBias !== 0) object.normalBias = this.normalBias; + if (this.radius !== 1) object.radius = this.radius; + if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray(); + object.camera = this.camera.toJSON(false).object; + delete object.camera.matrix; + return object; + } + } + const _position$2 = /* @__PURE__ */ new Vector3(); + const _quaternion$2 = /* @__PURE__ */ new Quaternion(); + const _scale$2 = /* @__PURE__ */ new Vector3(); + class Camera extends Object3D { + /** + * Constructs a new camera. + */ + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); + this.coordinateSystem = WebGLCoordinateSystem; + this._reversedDepth = false; + } + /** + * The flag that indicates whether the camera uses a reversed depth buffer. + * + * @type {boolean} + * @default false + */ + get reversedDepth() { + return this._reversedDepth; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + /** + * Returns a vector representing the ("look") direction of the 3D object in world space. + * + * This method is overwritten since cameras have a different forward vector compared to other + * 3D objects. A camera looks down its local, negative z-axis by default. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's direction in world space. + */ + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorld.decompose(_position$2, _quaternion$2, _scale$2); + if (_scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1) { + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } else { + this.matrixWorldInverse.compose(_position$2, _quaternion$2, _scale$2.set(1, 1, 1)).invert(); + } + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorld.decompose(_position$2, _quaternion$2, _scale$2); + if (_scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1) { + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } else { + this.matrixWorldInverse.compose(_position$2, _quaternion$2, _scale$2.set(1, 1, 1)).invert(); + } + } + clone() { + return new this.constructor().copy(this); + } + } + const _v3$1 = /* @__PURE__ */ new Vector3(); + const _minTarget = /* @__PURE__ */ new Vector2(); + const _maxTarget = /* @__PURE__ */ new Vector2(); + class PerspectiveCamera extends Camera { + /** + * Constructs a new perspective camera. + * + * @param {number} [fov=50] - The vertical field of view. + * @param {number} [aspect=1] - The aspect ratio. + * @param {number} [near=0.1] - The camera's near plane. + * @param {number} [far=2000] - The camera's far plane. + */ + constructor(fov2 = 50, aspect2 = 1, near = 0.1, far = 2e3) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov2; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect2; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + /** + * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * @param {number} focalLength - Values for focal length and film gauge must have the same unit. + */ + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + /** + * Returns the focal length from the current {@link PerspectiveCamera#fov} and + * {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The computed focal length. + */ + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + /** + * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}. + * + * @return {number} The effective FOV. + */ + getEffectiveFOV() { + return RAD2DEG * 2 * Math.atan( + Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom + ); + } + /** + * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or + * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The film width. + */ + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + /** + * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or + * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The film width. + */ + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + /** + * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. + * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle. + * + * @param {number} distance - The viewing distance. + * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector. + * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector. + */ + getViewBounds(distance, minTarget, maxTarget) { + _v3$1.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse); + minTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + _v3$1.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse); + maxTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + } + /** + * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. + * + * @param {number} distance - The viewing distance. + * @param {Vector2} target - The target vector that is used to store result where x is width and y is height. + * @returns {Vector2} The view size. + */ + getViewSize(distance, target) { + this.getViewBounds(distance, _minTarget, _maxTarget); + return target.subVectors(_maxTarget, _minTarget); + } + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + *``` + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + *``` + * then for each monitor you would call it like this: + *```js + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * // --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * // --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * // --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * // --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * // --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * // --F-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * ``` + * + * Note there is no reason monitors have to be the same size or in a grid. + * + * @param {number} fullWidth - The full width of multiview setup. + * @param {number} fullHeight - The full height of multiview setup. + * @param {number} x - The horizontal offset of the subcamera. + * @param {number} y - The vertical offset of the subcamera. + * @param {number} width - The width of subcamera. + * @param {number} height - The height of subcamera. + */ + setViewOffset(fullWidth, fullHeight, x, y, width, height) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + this.updateProjectionMatrix(); + } + /** + * Removes the view offset from the projection matrix. + */ + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + /** + * Updates the camera's projection matrix. Must be called after any change of + * camera properties. + */ + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom; + let height = 2 * top; + let width = this.aspect * height; + let left = -0.5 * width; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const fullWidth = view.fullWidth, fullHeight = view.fullHeight; + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.fov = this.fov; + data.object.zoom = this.zoom; + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; + data.object.aspect = this.aspect; + if (this.view !== null) data.object.view = Object.assign({}, this.view); + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; + return data; + } + } + class SpotLightShadow extends LightShadow { + /** + * Constructs a new spot light shadow. + */ + constructor() { + super(new PerspectiveCamera(50, 1, 0.5, 500)); + this.isSpotLightShadow = true; + this.focus = 1; + this.aspect = 1; + } + updateMatrices(light) { + const camera = this.camera; + const fov2 = RAD2DEG * 2 * light.angle * this.focus; + const aspect2 = this.mapSize.width / this.mapSize.height * this.aspect; + const far = light.distance || camera.far; + if (fov2 !== camera.fov || aspect2 !== camera.aspect || far !== camera.far) { + camera.fov = fov2; + camera.aspect = aspect2; + camera.far = far; + camera.updateProjectionMatrix(); + } + super.updateMatrices(light); + } + copy(source) { + super.copy(source); + this.focus = source.focus; + return this; + } + } + class SpotLight extends Light { + /** + * Constructs a new spot light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd). + * @param {number} [distance=0] - Maximum range of the light. `0` means no limit. + * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`. + * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`. + * @param {number} [decay=2] - The amount the light dims along the distance of the light. + */ + constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) { + super(color, intensity); + this.isSpotLight = true; + this.type = "SpotLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D(); + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + this.map = null; + this.shadow = new SpotLightShadow(); + } + /** + * The light's power. Power is the luminous power of the light measured in lumens (lm). + * Changing the power will also change the light's intensity. + * + * @type {number} + */ + get power() { + return this.intensity * Math.PI; + } + set power(power) { + this.intensity = power / Math.PI; + } + dispose() { + super.dispose(); + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + this.target = source.target.clone(); + this.map = source.map; + this.shadow = source.shadow.clone(); + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.distance = this.distance; + data.object.angle = this.angle; + data.object.decay = this.decay; + data.object.penumbra = this.penumbra; + data.object.target = this.target.uuid; + if (this.map && this.map.isTexture) data.object.map = this.map.toJSON(meta).uuid; + data.object.shadow = this.shadow.toJSON(); + return data; + } + } + class PointLightShadow extends LightShadow { + /** + * Constructs a new point light shadow. + */ + constructor() { + super(new PerspectiveCamera(90, 1, 0.5, 500)); + this.isPointLightShadow = true; + } + } + class PointLight extends Light { + /** + * Constructs a new point light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd). + * @param {number} [distance=0] - Maximum range of the light. `0` means no limit. + * @param {number} [decay=2] - The amount the light dims along the distance of the light. + */ + constructor(color, intensity, distance = 0, decay = 2) { + super(color, intensity); + this.isPointLight = true; + this.type = "PointLight"; + this.distance = distance; + this.decay = decay; + this.shadow = new PointLightShadow(); + } + /** + * The light's power. Power is the luminous power of the light measured in lumens (lm). + * Changing the power will also change the light's intensity. + * + * @type {number} + */ + get power() { + return this.intensity * 4 * Math.PI; + } + set power(power) { + this.intensity = power / (4 * Math.PI); + } + dispose() { + super.dispose(); + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.decay = source.decay; + this.shadow = source.shadow.clone(); + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.distance = this.distance; + data.object.decay = this.decay; + data.object.shadow = this.shadow.toJSON(); + return data; + } + } + class OrthographicCamera extends Camera { + /** + * Constructs a new orthographic camera. + * + * @param {number} [left=-1] - The left plane of the camera's frustum. + * @param {number} [right=1] - The right plane of the camera's frustum. + * @param {number} [top=1] - The top plane of the camera's frustum. + * @param {number} [bottom=-1] - The bottom plane of the camera's frustum. + * @param {number} [near=0.1] - The camera's near plane. + * @param {number} [far=2000] - The camera's far plane. + */ + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2e3) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * @param {number} fullWidth - The full width of multiview setup. + * @param {number} fullHeight - The full height of multiview setup. + * @param {number} x - The horizontal offset of the subcamera. + * @param {number} y - The vertical offset of the subcamera. + * @param {number} width - The width of subcamera. + * @param {number} height - The height of subcamera. + * @see {@link PerspectiveCamera#setViewOffset} + */ + setViewOffset(fullWidth, fullHeight, x, y, width, height) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + this.updateProjectionMatrix(); + } + /** + * Removes the view offset from the projection matrix. + */ + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + /** + * Updates the camera's projection matrix. Must be called after any change of + * camera properties. + */ + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; + if (this.view !== null) data.object.view = Object.assign({}, this.view); + return data; + } + } + class DirectionalLightShadow extends LightShadow { + /** + * Constructs a new directional light shadow. + */ + constructor() { + super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500)); + this.isDirectionalLightShadow = true; + } + } + class DirectionalLight extends Light { + /** + * Constructs a new directional light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor(color, intensity) { + super(color, intensity); + this.isDirectionalLight = true; + this.type = "DirectionalLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D(); + this.shadow = new DirectionalLightShadow(); + } + dispose() { + super.dispose(); + this.shadow.dispose(); + } + copy(source) { + super.copy(source); + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.shadow = this.shadow.toJSON(); + data.object.target = this.target.uuid; + return data; + } + } + class AmbientLight extends Light { + /** + * Constructs a new ambient light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor(color, intensity) { + super(color, intensity); + this.isAmbientLight = true; + this.type = "AmbientLight"; + } + } + class RectAreaLight extends Light { + /** + * Constructs a new area light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + * @param {number} [width=10] - The width of the light. + * @param {number} [height=10] - The height of the light. + */ + constructor(color, intensity, width = 10, height = 10) { + super(color, intensity); + this.isRectAreaLight = true; + this.type = "RectAreaLight"; + this.width = width; + this.height = height; + } + /** + * The light's power. Power is the luminous power of the light measured in lumens (lm). + * Changing the power will also change the light's intensity. + * + * @type {number} + */ + get power() { + return this.intensity * this.width * this.height * Math.PI; + } + set power(power) { + this.intensity = power / (this.width * this.height * Math.PI); + } + copy(source) { + super.copy(source); + this.width = source.width; + this.height = source.height; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.width = this.width; + data.object.height = this.height; + return data; + } + } + class SphericalHarmonics3 { + /** + * Constructs a new spherical harmonics. + */ + constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; + for (let i = 0; i < 9; i++) { + this.coefficients.push(new Vector3()); + } + } + /** + * Sets the given SH coefficients to this instance by copying + * the values. + * + * @param {Array} coefficients - The SH coefficients. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + set(coefficients) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].copy(coefficients[i]); + } + return this; + } + /** + * Sets all SH coefficients to `0`. + * + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + zero() { + for (let i = 0; i < 9; i++) { + this.coefficients[i].set(0, 0, 0); + } + return this; + } + /** + * Returns the radiance in the direction of the given normal. + * + * @param {Vector3} normal - The normal vector (assumed to be unit length) + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The radiance. + */ + getAt(normal, target) { + const x = normal.x, y = normal.y, z = normal.z; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.282095); + target.addScaledVector(coeff[1], 0.488603 * y); + target.addScaledVector(coeff[2], 0.488603 * z); + target.addScaledVector(coeff[3], 0.488603 * x); + target.addScaledVector(coeff[4], 1.092548 * (x * y)); + target.addScaledVector(coeff[5], 1.092548 * (y * z)); + target.addScaledVector(coeff[6], 0.315392 * (3 * z * z - 1)); + target.addScaledVector(coeff[7], 1.092548 * (x * z)); + target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y)); + return target; + } + /** + * Returns the irradiance (radiance convolved with cosine lobe) in the + * direction of the given normal. + * + * @param {Vector3} normal - The normal vector (assumed to be unit length) + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The irradiance. + */ + getIrradianceAt(normal, target) { + const x = normal.x, y = normal.y, z = normal.z; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.886227); + target.addScaledVector(coeff[1], 2 * 0.511664 * y); + target.addScaledVector(coeff[2], 2 * 0.511664 * z); + target.addScaledVector(coeff[3], 2 * 0.511664 * x); + target.addScaledVector(coeff[4], 2 * 0.429043 * x * y); + target.addScaledVector(coeff[5], 2 * 0.429043 * y * z); + target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); + target.addScaledVector(coeff[7], 2 * 0.429043 * x * z); + target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); + return target; + } + /** + * Adds the given SH to this instance. + * + * @param {SphericalHarmonics3} sh - The SH to add. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + add(sh) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].add(sh.coefficients[i]); + } + return this; + } + /** + * A convenience method for performing {@link SphericalHarmonics3#add} and + * {@link SphericalHarmonics3#scale} at once. + * + * @param {SphericalHarmonics3} sh - The SH to add. + * @param {number} s - The scale factor. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + addScaledSH(sh, s) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].addScaledVector(sh.coefficients[i], s); + } + return this; + } + /** + * Scales this SH by the given scale factor. + * + * @param {number} s - The scale factor. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + scale(s) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].multiplyScalar(s); + } + return this; + } + /** + * Linear interpolates between the given SH and this instance by the given + * alpha factor. + * + * @param {SphericalHarmonics3} sh - The SH to interpolate with. + * @param {number} alpha - The alpha factor. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + lerp(sh, alpha) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].lerp(sh.coefficients[i], alpha); + } + return this; + } + /** + * Returns `true` if this spherical harmonics is equal with the given one. + * + * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality. + * @return {boolean} Whether this spherical harmonics is equal with the given one. + */ + equals(sh) { + for (let i = 0; i < 9; i++) { + if (!this.coefficients[i].equals(sh.coefficients[i])) { + return false; + } + } + return true; + } + /** + * Copies the values of the given spherical harmonics to this instance. + * + * @param {SphericalHarmonics3} sh - The spherical harmonics to copy. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + copy(sh) { + return this.set(sh.coefficients); + } + /** + * Returns a new spherical harmonics with copied values from this instance. + * + * @return {SphericalHarmonics3} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Sets the SH coefficients of this instance from the given array. + * + * @param {Array} array - An array holding the SH coefficients. + * @param {number} [offset=0] - The array offset where to start copying. + * @return {SphericalHarmonics3} A clone of this instance. + */ + fromArray(array, offset = 0) { + const coefficients = this.coefficients; + for (let i = 0; i < 9; i++) { + coefficients[i].fromArray(array, offset + i * 3); + } + return this; + } + /** + * Returns an array with the SH coefficients, or copies them into the provided + * array. The coefficients are represented as numbers. + * + * @param {Array} [array=[]] - The target array. + * @param {number} [offset=0] - The array offset where to start copying. + * @return {Array} An array with flat SH coefficients. + */ + toArray(array = [], offset = 0) { + const coefficients = this.coefficients; + for (let i = 0; i < 9; i++) { + coefficients[i].toArray(array, offset + i * 3); + } + return array; + } + /** + * Computes the SH basis for the given normal vector. + * + * @param {Vector3} normal - The normal. + * @param {Array} shBasis - The target array holding the SH basis. + */ + static getBasisAt(normal, shBasis) { + const x = normal.x, y = normal.y, z = normal.z; + shBasis[0] = 0.282095; + shBasis[1] = 0.488603 * y; + shBasis[2] = 0.488603 * z; + shBasis[3] = 0.488603 * x; + shBasis[4] = 1.092548 * x * y; + shBasis[5] = 1.092548 * y * z; + shBasis[6] = 0.315392 * (3 * z * z - 1); + shBasis[7] = 1.092548 * x * z; + shBasis[8] = 0.546274 * (x * x - y * y); + } + } + class LightProbe extends Light { + /** + * Constructs a new light probe. + * + * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor(sh = new SphericalHarmonics3(), intensity = 1) { + super(void 0, intensity); + this.isLightProbe = true; + this.sh = sh; + } + copy(source) { + super.copy(source); + this.sh.copy(source.sh); + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.sh = this.sh.toArray(); + return data; + } + } + class MaterialLoader extends Loader { + /** + * Constructs a new material loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + this.textures = {}; + } + /** + * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Material)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text) { + try { + onLoad(scope.parse(JSON.parse(text))); + } catch (e) { + if (onError) { + onError(e); + } else { + error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + /** + * Parses the given JSON object and returns a material. + * + * @param {Object} json - The serialized material. + * @return {Material} The parsed material. + */ + parse(json) { + const textures = this.textures; + function getTexture(name) { + if (textures[name] === void 0) { + warn("MaterialLoader: Undefined texture", name); + } + return textures[name]; + } + const material = this.createMaterialFromType(json.type); + if (json.uuid !== void 0) material.uuid = json.uuid; + if (json.name !== void 0) material.name = json.name; + if (json.color !== void 0 && material.color !== void 0) material.color.setHex(json.color); + if (json.roughness !== void 0) material.roughness = json.roughness; + if (json.metalness !== void 0) material.metalness = json.metalness; + if (json.sheen !== void 0) material.sheen = json.sheen; + if (json.sheenColor !== void 0) material.sheenColor = new Color().setHex(json.sheenColor); + if (json.sheenRoughness !== void 0) material.sheenRoughness = json.sheenRoughness; + if (json.emissive !== void 0 && material.emissive !== void 0) material.emissive.setHex(json.emissive); + if (json.specular !== void 0 && material.specular !== void 0) material.specular.setHex(json.specular); + if (json.specularIntensity !== void 0) material.specularIntensity = json.specularIntensity; + if (json.specularColor !== void 0 && material.specularColor !== void 0) material.specularColor.setHex(json.specularColor); + if (json.shininess !== void 0) material.shininess = json.shininess; + if (json.clearcoat !== void 0) material.clearcoat = json.clearcoat; + if (json.clearcoatRoughness !== void 0) material.clearcoatRoughness = json.clearcoatRoughness; + if (json.dispersion !== void 0) material.dispersion = json.dispersion; + if (json.iridescence !== void 0) material.iridescence = json.iridescence; + if (json.iridescenceIOR !== void 0) material.iridescenceIOR = json.iridescenceIOR; + if (json.iridescenceThicknessRange !== void 0) material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if (json.transmission !== void 0) material.transmission = json.transmission; + if (json.thickness !== void 0) material.thickness = json.thickness; + if (json.attenuationDistance !== void 0) material.attenuationDistance = json.attenuationDistance; + if (json.attenuationColor !== void 0 && material.attenuationColor !== void 0) material.attenuationColor.setHex(json.attenuationColor); + if (json.anisotropy !== void 0) material.anisotropy = json.anisotropy; + if (json.anisotropyRotation !== void 0) material.anisotropyRotation = json.anisotropyRotation; + if (json.fog !== void 0) material.fog = json.fog; + if (json.flatShading !== void 0) material.flatShading = json.flatShading; + if (json.blending !== void 0) material.blending = json.blending; + if (json.combine !== void 0) material.combine = json.combine; + if (json.side !== void 0) material.side = json.side; + if (json.shadowSide !== void 0) material.shadowSide = json.shadowSide; + if (json.opacity !== void 0) material.opacity = json.opacity; + if (json.transparent !== void 0) material.transparent = json.transparent; + if (json.alphaTest !== void 0) material.alphaTest = json.alphaTest; + if (json.alphaHash !== void 0) material.alphaHash = json.alphaHash; + if (json.depthFunc !== void 0) material.depthFunc = json.depthFunc; + if (json.depthTest !== void 0) material.depthTest = json.depthTest; + if (json.depthWrite !== void 0) material.depthWrite = json.depthWrite; + if (json.colorWrite !== void 0) material.colorWrite = json.colorWrite; + if (json.blendSrc !== void 0) material.blendSrc = json.blendSrc; + if (json.blendDst !== void 0) material.blendDst = json.blendDst; + if (json.blendEquation !== void 0) material.blendEquation = json.blendEquation; + if (json.blendSrcAlpha !== void 0) material.blendSrcAlpha = json.blendSrcAlpha; + if (json.blendDstAlpha !== void 0) material.blendDstAlpha = json.blendDstAlpha; + if (json.blendEquationAlpha !== void 0) material.blendEquationAlpha = json.blendEquationAlpha; + if (json.blendColor !== void 0 && material.blendColor !== void 0) material.blendColor.setHex(json.blendColor); + if (json.blendAlpha !== void 0) material.blendAlpha = json.blendAlpha; + if (json.stencilWriteMask !== void 0) material.stencilWriteMask = json.stencilWriteMask; + if (json.stencilFunc !== void 0) material.stencilFunc = json.stencilFunc; + if (json.stencilRef !== void 0) material.stencilRef = json.stencilRef; + if (json.stencilFuncMask !== void 0) material.stencilFuncMask = json.stencilFuncMask; + if (json.stencilFail !== void 0) material.stencilFail = json.stencilFail; + if (json.stencilZFail !== void 0) material.stencilZFail = json.stencilZFail; + if (json.stencilZPass !== void 0) material.stencilZPass = json.stencilZPass; + if (json.stencilWrite !== void 0) material.stencilWrite = json.stencilWrite; + if (json.wireframe !== void 0) material.wireframe = json.wireframe; + if (json.wireframeLinewidth !== void 0) material.wireframeLinewidth = json.wireframeLinewidth; + if (json.wireframeLinecap !== void 0) material.wireframeLinecap = json.wireframeLinecap; + if (json.wireframeLinejoin !== void 0) material.wireframeLinejoin = json.wireframeLinejoin; + if (json.rotation !== void 0) material.rotation = json.rotation; + if (json.linewidth !== void 0) material.linewidth = json.linewidth; + if (json.dashSize !== void 0) material.dashSize = json.dashSize; + if (json.gapSize !== void 0) material.gapSize = json.gapSize; + if (json.scale !== void 0) material.scale = json.scale; + if (json.polygonOffset !== void 0) material.polygonOffset = json.polygonOffset; + if (json.polygonOffsetFactor !== void 0) material.polygonOffsetFactor = json.polygonOffsetFactor; + if (json.polygonOffsetUnits !== void 0) material.polygonOffsetUnits = json.polygonOffsetUnits; + if (json.dithering !== void 0) material.dithering = json.dithering; + if (json.alphaToCoverage !== void 0) material.alphaToCoverage = json.alphaToCoverage; + if (json.premultipliedAlpha !== void 0) material.premultipliedAlpha = json.premultipliedAlpha; + if (json.forceSinglePass !== void 0) material.forceSinglePass = json.forceSinglePass; + if (json.allowOverride !== void 0) material.allowOverride = json.allowOverride; + if (json.visible !== void 0) material.visible = json.visible; + if (json.toneMapped !== void 0) material.toneMapped = json.toneMapped; + if (json.userData !== void 0) material.userData = json.userData; + if (json.vertexColors !== void 0) { + if (typeof json.vertexColors === "number") { + material.vertexColors = json.vertexColors > 0; + } else { + material.vertexColors = json.vertexColors; + } + } + if (json.uniforms !== void 0) { + for (const name in json.uniforms) { + const uniform = json.uniforms[name]; + material.uniforms[name] = {}; + switch (uniform.type) { + case "t": + material.uniforms[name].value = getTexture(uniform.value); + break; + case "c": + material.uniforms[name].value = new Color().setHex(uniform.value); + break; + case "v2": + material.uniforms[name].value = new Vector2().fromArray(uniform.value); + break; + case "v3": + material.uniforms[name].value = new Vector3().fromArray(uniform.value); + break; + case "v4": + material.uniforms[name].value = new Vector4().fromArray(uniform.value); + break; + case "m3": + material.uniforms[name].value = new Matrix3().fromArray(uniform.value); + break; + case "m4": + material.uniforms[name].value = new Matrix4().fromArray(uniform.value); + break; + default: + material.uniforms[name].value = uniform.value; + } + } + } + if (json.defines !== void 0) material.defines = json.defines; + if (json.vertexShader !== void 0) material.vertexShader = json.vertexShader; + if (json.fragmentShader !== void 0) material.fragmentShader = json.fragmentShader; + if (json.glslVersion !== void 0) material.glslVersion = json.glslVersion; + if (json.extensions !== void 0) { + for (const key in json.extensions) { + material.extensions[key] = json.extensions[key]; + } + } + if (json.lights !== void 0) material.lights = json.lights; + if (json.clipping !== void 0) material.clipping = json.clipping; + if (json.size !== void 0) material.size = json.size; + if (json.sizeAttenuation !== void 0) material.sizeAttenuation = json.sizeAttenuation; + if (json.map !== void 0) material.map = getTexture(json.map); + if (json.matcap !== void 0) material.matcap = getTexture(json.matcap); + if (json.alphaMap !== void 0) material.alphaMap = getTexture(json.alphaMap); + if (json.bumpMap !== void 0) material.bumpMap = getTexture(json.bumpMap); + if (json.bumpScale !== void 0) material.bumpScale = json.bumpScale; + if (json.normalMap !== void 0) material.normalMap = getTexture(json.normalMap); + if (json.normalMapType !== void 0) material.normalMapType = json.normalMapType; + if (json.normalScale !== void 0) { + let normalScale = json.normalScale; + if (Array.isArray(normalScale) === false) { + normalScale = [normalScale, normalScale]; + } + material.normalScale = new Vector2().fromArray(normalScale); + } + if (json.displacementMap !== void 0) material.displacementMap = getTexture(json.displacementMap); + if (json.displacementScale !== void 0) material.displacementScale = json.displacementScale; + if (json.displacementBias !== void 0) material.displacementBias = json.displacementBias; + if (json.roughnessMap !== void 0) material.roughnessMap = getTexture(json.roughnessMap); + if (json.metalnessMap !== void 0) material.metalnessMap = getTexture(json.metalnessMap); + if (json.emissiveMap !== void 0) material.emissiveMap = getTexture(json.emissiveMap); + if (json.emissiveIntensity !== void 0) material.emissiveIntensity = json.emissiveIntensity; + if (json.specularMap !== void 0) material.specularMap = getTexture(json.specularMap); + if (json.specularIntensityMap !== void 0) material.specularIntensityMap = getTexture(json.specularIntensityMap); + if (json.specularColorMap !== void 0) material.specularColorMap = getTexture(json.specularColorMap); + if (json.envMap !== void 0) material.envMap = getTexture(json.envMap); + if (json.envMapRotation !== void 0) material.envMapRotation.fromArray(json.envMapRotation); + if (json.envMapIntensity !== void 0) material.envMapIntensity = json.envMapIntensity; + if (json.reflectivity !== void 0) material.reflectivity = json.reflectivity; + if (json.refractionRatio !== void 0) material.refractionRatio = json.refractionRatio; + if (json.lightMap !== void 0) material.lightMap = getTexture(json.lightMap); + if (json.lightMapIntensity !== void 0) material.lightMapIntensity = json.lightMapIntensity; + if (json.aoMap !== void 0) material.aoMap = getTexture(json.aoMap); + if (json.aoMapIntensity !== void 0) material.aoMapIntensity = json.aoMapIntensity; + if (json.gradientMap !== void 0) material.gradientMap = getTexture(json.gradientMap); + if (json.clearcoatMap !== void 0) material.clearcoatMap = getTexture(json.clearcoatMap); + if (json.clearcoatRoughnessMap !== void 0) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap); + if (json.clearcoatNormalMap !== void 0) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap); + if (json.clearcoatNormalScale !== void 0) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale); + if (json.iridescenceMap !== void 0) material.iridescenceMap = getTexture(json.iridescenceMap); + if (json.iridescenceThicknessMap !== void 0) material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap); + if (json.transmissionMap !== void 0) material.transmissionMap = getTexture(json.transmissionMap); + if (json.thicknessMap !== void 0) material.thicknessMap = getTexture(json.thicknessMap); + if (json.anisotropyMap !== void 0) material.anisotropyMap = getTexture(json.anisotropyMap); + if (json.sheenColorMap !== void 0) material.sheenColorMap = getTexture(json.sheenColorMap); + if (json.sheenRoughnessMap !== void 0) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap); + return material; + } + /** + * Textures are not embedded in the material JSON so they have + * to be injected before the loading process starts. + * + * @param {Object} value - A dictionary holding textures for material properties. + * @return {MaterialLoader} A reference to this material loader. + */ + setTextures(value) { + this.textures = value; + return this; + } + /** + * Creates a material for the given type. + * + * @param {string} type - The material type. + * @return {Material} The new material. + */ + createMaterialFromType(type) { + return MaterialLoader.createMaterialFromType(type); + } + /** + * Creates a material for the given type. + * + * @static + * @param {string} type - The material type. + * @return {Material} The new material. + */ + static createMaterialFromType(type) { + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + return new materialLib[type](); + } + } + class LoaderUtils { + /** + * Extracts the base URL from the given URL. + * + * @param {string} url -The URL to extract the base URL from. + * @return {string} The extracted base URL. + */ + static extractUrlBase(url) { + const index = url.lastIndexOf("/"); + if (index === -1) return "./"; + return url.slice(0, index + 1); + } + /** + * Resolves relative URLs against the given path. Absolute paths, data urls, + * and blob URLs will be returned as is. Invalid URLs will return an empty + * string. + * + * @param {string} url -The URL to resolve. + * @param {string} path - The base path for relative URLs to be resolved against. + * @return {string} The resolved URL. + */ + static resolveURL(url, path) { + if (typeof url !== "string" || url === "") return ""; + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); + } + if (/^(https?:)?\/\//i.test(url)) return url; + if (/^data:.*,.*$/i.test(url)) return url; + if (/^blob:.*$/i.test(url)) return url; + return path + url; + } + } + class InstancedBufferGeometry extends BufferGeometry { + /** + * Constructs a new instanced buffer geometry. + */ + constructor() { + super(); + this.isInstancedBufferGeometry = true; + this.type = "InstancedBufferGeometry"; + this.instanceCount = Infinity; + } + copy(source) { + super.copy(source); + this.instanceCount = source.instanceCount; + return this; + } + toJSON() { + const data = super.toJSON(); + data.instanceCount = this.instanceCount; + data.isInstancedBufferGeometry = true; + return data; + } + } + class BufferGeometryLoader extends Loader { + /** + * Constructs a new geometry loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text) { + try { + onLoad(scope.parse(JSON.parse(text))); + } catch (e) { + if (onError) { + onError(e); + } else { + error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + /** + * Parses the given JSON object and returns a geometry. + * + * @param {Object} json - The serialized geometry. + * @return {BufferGeometry} The parsed geometry. + */ + parse(json) { + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + function getInterleavedBuffer(json2, uuid) { + if (interleavedBufferMap[uuid] !== void 0) return interleavedBufferMap[uuid]; + const interleavedBuffers = json2.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[uuid]; + const buffer = getArrayBuffer(json2, interleavedBuffer.buffer); + const array = getTypedArray(interleavedBuffer.type, buffer); + const ib = new InterleavedBuffer(array, interleavedBuffer.stride); + ib.uuid = interleavedBuffer.uuid; + interleavedBufferMap[uuid] = ib; + return ib; + } + function getArrayBuffer(json2, uuid) { + if (arrayBufferMap[uuid] !== void 0) return arrayBufferMap[uuid]; + const arrayBuffers = json2.arrayBuffers; + const arrayBuffer = arrayBuffers[uuid]; + const ab = new Uint32Array(arrayBuffer).buffer; + arrayBufferMap[uuid] = ab; + return ab; + } + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + const index = json.data.index; + if (index !== void 0) { + const typedArray = getTypedArray(index.type, index.array); + geometry.setIndex(new BufferAttribute(typedArray, 1)); + } + const attributes = json.data.attributes; + for (const key in attributes) { + const attribute = attributes[key]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== void 0) bufferAttribute.name = attribute.name; + if (attribute.usage !== void 0) bufferAttribute.setUsage(attribute.usage); + geometry.setAttribute(key, bufferAttribute); + } + const morphAttributes = json.data.morphAttributes; + if (morphAttributes) { + for (const key in morphAttributes) { + const attributeArray = morphAttributes[key]; + const array = []; + for (let i = 0, il = attributeArray.length; i < il; i++) { + const attribute = attributeArray[i]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== void 0) bufferAttribute.name = attribute.name; + array.push(bufferAttribute); + } + geometry.morphAttributes[key] = array; + } + } + const morphTargetsRelative = json.data.morphTargetsRelative; + if (morphTargetsRelative) { + geometry.morphTargetsRelative = true; + } + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if (groups !== void 0) { + for (let i = 0, n = groups.length; i !== n; ++i) { + const group = groups[i]; + geometry.addGroup(group.start, group.count, group.materialIndex); + } + } + const boundingSphere = json.data.boundingSphere; + if (boundingSphere !== void 0) { + geometry.boundingSphere = new Sphere().fromJSON(boundingSphere); + } + if (json.name) geometry.name = json.name; + if (json.userData) geometry.userData = json.userData; + return geometry; + } + } + const _customGeometries = {}; + class ObjectLoader extends Loader { + /** + * Constructs a new object loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Object3D)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text) { + let json = null; + try { + json = JSON.parse(text); + } catch (e) { + if (onError !== void 0) onError(e); + error("ObjectLoader: Can't parse " + url + ".", e.message); + return; + } + const metadata = json.metadata; + if (metadata === void 0 || metadata.type === void 0 || metadata.type.toLowerCase() === "geometry") { + if (onError !== void 0) onError(new Error("THREE.ObjectLoader: Can't load " + url)); + error("ObjectLoader: Can't load " + url); + return; + } + scope.parse(json, onLoad); + }, onProgress, onError); + } + /** + * Async version of {@link ObjectLoader#load}. + * + * @async + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @return {Promise} A Promise that resolves with the loaded 3D object. + */ + async loadAsync(url, onProgress) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + const text = await loader.loadAsync(url, onProgress); + let json; + try { + json = JSON.parse(text); + } catch (e) { + throw new Error("ObjectLoader: Can't parse " + url + ". " + e.message); + } + const metadata = json.metadata; + if (metadata === void 0 || metadata.type === void 0 || metadata.type.toLowerCase() === "geometry") { + throw new Error("THREE.ObjectLoader: Can't load " + url); + } + return await scope.parseAsync(json); + } + /** + * Parses the given JSON. This is used internally by {@link ObjectLoader#load} + * but can also be used directly to parse a previously loaded JSON structure. + * + * @param {Object} json - The serialized 3D object. + * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded. + * @return {Object3D} The parsed 3D object. + */ + parse(json, onLoad) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = this.parseImages(json.images, function() { + if (onLoad !== void 0) onLoad(object); + }); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + if (onLoad !== void 0) { + let hasImages = false; + for (const uuid in images) { + if (images[uuid].data instanceof HTMLImageElement) { + hasImages = true; + break; + } + } + if (hasImages === false) onLoad(object); + } + return object; + } + /** + * Async version of {@link ObjectLoader#parse}. + * + * @param {Object} json - The serialized 3D object. + * @return {Promise} A Promise that resolves with the parsed 3D object. + */ + async parseAsync(json) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = await this.parseImagesAsync(json.images); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + return object; + } + /** + * Registers the given geometry at the internal + * geometry library. + * + * @static + * @param {string} type - The geometry type. + * @param {BufferGeometry.constructor} geometryClass - The geometry class. + */ + static registerGeometry(type, geometryClass) { + _customGeometries[type] = geometryClass; + } + // internals + parseShapes(json) { + const shapes = {}; + if (json !== void 0) { + for (let i = 0, l = json.length; i < l; i++) { + const shape = new Shape().fromJSON(json[i]); + shapes[shape.uuid] = shape; + } + } + return shapes; + } + parseSkeletons(json, object) { + const skeletons = {}; + const bones = {}; + object.traverse(function(child) { + if (child.isBone) bones[child.uuid] = child; + }); + if (json !== void 0) { + for (let i = 0, l = json.length; i < l; i++) { + const skeleton = new Skeleton().fromJSON(json[i], bones); + skeletons[skeleton.uuid] = skeleton; + } + } + return skeletons; + } + parseGeometries(json, shapes) { + const geometries = {}; + if (json !== void 0) { + const bufferGeometryLoader = new BufferGeometryLoader(); + for (let i = 0, l = json.length; i < l; i++) { + let geometry; + const data = json[i]; + switch (data.type) { + case "BufferGeometry": + case "InstancedBufferGeometry": + geometry = bufferGeometryLoader.parse(data); + break; + default: + if (data.type in Geometries) { + geometry = Geometries[data.type].fromJSON(data, shapes); + } else if (data.type in _customGeometries) { + geometry = _customGeometries[data.type].fromJSON(data, shapes); + } else { + warn(`ObjectLoader: Unknown geometry type "${data.type}". Use .registerGeometry() before starting the deserialization process.`); + } + } + geometry.uuid = data.uuid; + if (data.name !== void 0) geometry.name = data.name; + if (data.userData !== void 0) geometry.userData = data.userData; + geometries[data.uuid] = geometry; + } + } + return geometries; + } + parseMaterials(json, textures) { + const cache = {}; + const materials = {}; + if (json !== void 0) { + const loader = new MaterialLoader(); + loader.setTextures(textures); + for (let i = 0, l = json.length; i < l; i++) { + const data = json[i]; + if (cache[data.uuid] === void 0) { + cache[data.uuid] = loader.parse(data); + } + materials[data.uuid] = cache[data.uuid]; + } + } + return materials; + } + parseAnimations(json) { + const animations = {}; + if (json !== void 0) { + for (let i = 0; i < json.length; i++) { + const data = json[i]; + const clip = AnimationClip.parse(data); + animations[clip.uuid] = clip; + } + } + return animations; + } + parseImages(json, onLoad) { + const scope = this; + const images = {}; + let loader; + function loadImage(url) { + scope.manager.itemStart(url); + return loader.load(url, function() { + scope.manager.itemEnd(url); + }, void 0, function() { + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + } + function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return loadImage(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== void 0 && json.length > 0) { + const manager = new LoadingManager(onLoad); + loader = new ImageLoader(manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length; i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length; j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + async parseImagesAsync(json) { + const scope = this; + const images = {}; + let loader; + async function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return await loader.loadAsync(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== void 0 && json.length > 0) { + loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length; i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length; j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = await deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = await deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + parseTextures(json, images) { + function parseConstant(value, type) { + if (typeof value === "number") return value; + warn("ObjectLoader.parseTexture: Constant should be in numeric form.", value); + return type[value]; + } + const textures = {}; + if (json !== void 0) { + for (let i = 0, l = json.length; i < l; i++) { + const data = json[i]; + if (data.image === void 0) { + warn('ObjectLoader: No "image" specified for', data.uuid); + } + if (images[data.image] === void 0) { + warn("ObjectLoader: Undefined image", data.image); + } + const source = images[data.image]; + const image = source.data; + let texture; + if (Array.isArray(image)) { + texture = new CubeTexture(); + if (image.length === 6) texture.needsUpdate = true; + } else { + if (image && image.data) { + texture = new DataTexture(); + } else { + texture = new Texture(); + } + if (image) texture.needsUpdate = true; + } + texture.source = source; + texture.uuid = data.uuid; + if (data.name !== void 0) texture.name = data.name; + if (data.mapping !== void 0) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING); + if (data.channel !== void 0) texture.channel = data.channel; + if (data.offset !== void 0) texture.offset.fromArray(data.offset); + if (data.repeat !== void 0) texture.repeat.fromArray(data.repeat); + if (data.center !== void 0) texture.center.fromArray(data.center); + if (data.rotation !== void 0) texture.rotation = data.rotation; + if (data.wrap !== void 0) { + texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING); + texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING); + } + if (data.format !== void 0) texture.format = data.format; + if (data.internalFormat !== void 0) texture.internalFormat = data.internalFormat; + if (data.type !== void 0) texture.type = data.type; + if (data.colorSpace !== void 0) texture.colorSpace = data.colorSpace; + if (data.minFilter !== void 0) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER); + if (data.magFilter !== void 0) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER); + if (data.anisotropy !== void 0) texture.anisotropy = data.anisotropy; + if (data.flipY !== void 0) texture.flipY = data.flipY; + if (data.generateMipmaps !== void 0) texture.generateMipmaps = data.generateMipmaps; + if (data.premultiplyAlpha !== void 0) texture.premultiplyAlpha = data.premultiplyAlpha; + if (data.unpackAlignment !== void 0) texture.unpackAlignment = data.unpackAlignment; + if (data.compareFunction !== void 0) texture.compareFunction = data.compareFunction; + if (data.normalized !== void 0) texture.normalized = data.normalized; + if (data.userData !== void 0) texture.userData = data.userData; + textures[data.uuid] = texture; + } + } + return textures; + } + parseObject(data, geometries, materials, textures, animations) { + let object; + function getGeometry(name) { + if (geometries[name] === void 0) { + warn("ObjectLoader: Undefined geometry", name); + } + return geometries[name]; + } + function getMaterial(name) { + if (name === void 0) return void 0; + if (Array.isArray(name)) { + const array = []; + for (let i = 0, l = name.length; i < l; i++) { + const uuid = name[i]; + if (materials[uuid] === void 0) { + warn("ObjectLoader: Undefined material", uuid); + } + array.push(materials[uuid]); + } + return array; + } + if (materials[name] === void 0) { + warn("ObjectLoader: Undefined material", name); + } + return materials[name]; + } + function getTexture(uuid) { + if (textures[uuid] === void 0) { + warn("ObjectLoader: Undefined texture", uuid); + } + return textures[uuid]; + } + let geometry, material; + switch (data.type) { + case "Scene": + object = new Scene(); + if (data.background !== void 0) { + if (Number.isInteger(data.background)) { + object.background = new Color(data.background); + } else { + object.background = getTexture(data.background); + } + } + if (data.environment !== void 0) { + object.environment = getTexture(data.environment); + } + if (data.fog !== void 0) { + if (data.fog.type === "Fog") { + object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far); + } else if (data.fog.type === "FogExp2") { + object.fog = new FogExp2(data.fog.color, data.fog.density); + } + if (data.fog.name !== "") { + object.fog.name = data.fog.name; + } + } + if (data.backgroundBlurriness !== void 0) object.backgroundBlurriness = data.backgroundBlurriness; + if (data.backgroundIntensity !== void 0) object.backgroundIntensity = data.backgroundIntensity; + if (data.backgroundRotation !== void 0) object.backgroundRotation.fromArray(data.backgroundRotation); + if (data.environmentIntensity !== void 0) object.environmentIntensity = data.environmentIntensity; + if (data.environmentRotation !== void 0) object.environmentRotation.fromArray(data.environmentRotation); + break; + case "PerspectiveCamera": + object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far); + if (data.focus !== void 0) object.focus = data.focus; + if (data.zoom !== void 0) object.zoom = data.zoom; + if (data.filmGauge !== void 0) object.filmGauge = data.filmGauge; + if (data.filmOffset !== void 0) object.filmOffset = data.filmOffset; + if (data.view !== void 0) object.view = Object.assign({}, data.view); + break; + case "OrthographicCamera": + object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far); + if (data.zoom !== void 0) object.zoom = data.zoom; + if (data.view !== void 0) object.view = Object.assign({}, data.view); + break; + case "AmbientLight": + object = new AmbientLight(data.color, data.intensity); + break; + case "DirectionalLight": + object = new DirectionalLight(data.color, data.intensity); + object.target = data.target || ""; + break; + case "PointLight": + object = new PointLight(data.color, data.intensity, data.distance, data.decay); + break; + case "RectAreaLight": + object = new RectAreaLight(data.color, data.intensity, data.width, data.height); + break; + case "SpotLight": + object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay); + object.target = data.target || ""; + break; + case "HemisphereLight": + object = new HemisphereLight(data.color, data.groundColor, data.intensity); + break; + case "LightProbe": + const sh = new SphericalHarmonics3().fromArray(data.sh); + object = new LightProbe(sh, data.intensity); + break; + case "SkinnedMesh": + geometry = getGeometry(data.geometry); + material = getMaterial(data.material); + object = new SkinnedMesh(geometry, material); + if (data.bindMode !== void 0) object.bindMode = data.bindMode; + if (data.bindMatrix !== void 0) object.bindMatrix.fromArray(data.bindMatrix); + if (data.skeleton !== void 0) object.skeleton = data.skeleton; + break; + case "Mesh": + geometry = getGeometry(data.geometry); + material = getMaterial(data.material); + object = new Mesh(geometry, material); + break; + case "InstancedMesh": + geometry = getGeometry(data.geometry); + material = getMaterial(data.material); + const count = data.count; + const instanceMatrix = data.instanceMatrix; + const instanceColor = data.instanceColor; + object = new InstancedMesh(geometry, material, count); + object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16); + if (instanceColor !== void 0) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize); + break; + case "BatchedMesh": + geometry = getGeometry(data.geometry); + material = getMaterial(data.material); + object = new BatchedMesh(data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material); + object.geometry = geometry; + object.perObjectFrustumCulled = data.perObjectFrustumCulled; + object.sortObjects = data.sortObjects; + object._drawRanges = data.drawRanges; + object._reservedRanges = data.reservedRanges; + object._geometryInfo = data.geometryInfo.map((info) => { + let box = null; + let sphere = null; + if (info.boundingBox !== void 0) { + box = new Box3().fromJSON(info.boundingBox); + } + if (info.boundingSphere !== void 0) { + sphere = new Sphere().fromJSON(info.boundingSphere); + } + return { + ...info, + boundingBox: box, + boundingSphere: sphere + }; + }); + object._instanceInfo = data.instanceInfo; + object._availableInstanceIds = data._availableInstanceIds; + object._availableGeometryIds = data._availableGeometryIds; + object._nextIndexStart = data.nextIndexStart; + object._nextVertexStart = data.nextVertexStart; + object._geometryCount = data.geometryCount; + object._maxInstanceCount = data.maxInstanceCount; + object._maxVertexCount = data.maxVertexCount; + object._maxIndexCount = data.maxIndexCount; + object._geometryInitialized = data.geometryInitialized; + object._matricesTexture = getTexture(data.matricesTexture.uuid); + object._indirectTexture = getTexture(data.indirectTexture.uuid); + if (data.colorsTexture !== void 0) { + object._colorsTexture = getTexture(data.colorsTexture.uuid); + } + if (data.boundingSphere !== void 0) { + object.boundingSphere = new Sphere().fromJSON(data.boundingSphere); + } + if (data.boundingBox !== void 0) { + object.boundingBox = new Box3().fromJSON(data.boundingBox); + } + break; + case "LOD": + object = new LOD(); + break; + case "Line": + object = new Line(getGeometry(data.geometry), getMaterial(data.material)); + break; + case "LineLoop": + object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material)); + break; + case "LineSegments": + object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material)); + break; + case "PointCloud": + case "Points": + object = new Points(getGeometry(data.geometry), getMaterial(data.material)); + break; + case "Sprite": + object = new Sprite(getMaterial(data.material)); + break; + case "Group": + object = new Group(); + break; + case "Bone": + object = new Bone(); + break; + default: + object = new Object3D(); + } + object.uuid = data.uuid; + if (data.name !== void 0) object.name = data.name; + if (data.matrix !== void 0) { + object.matrix.fromArray(data.matrix); + if (data.matrixAutoUpdate !== void 0) object.matrixAutoUpdate = data.matrixAutoUpdate; + if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale); + } else { + if (data.position !== void 0) object.position.fromArray(data.position); + if (data.rotation !== void 0) object.rotation.fromArray(data.rotation); + if (data.quaternion !== void 0) object.quaternion.fromArray(data.quaternion); + if (data.scale !== void 0) object.scale.fromArray(data.scale); + } + if (data.up !== void 0) object.up.fromArray(data.up); + if (data.pivot !== void 0) object.pivot = new Vector3().fromArray(data.pivot); + if (data.morphTargetDictionary !== void 0) object.morphTargetDictionary = Object.assign({}, data.morphTargetDictionary); + if (data.morphTargetInfluences !== void 0) object.morphTargetInfluences = data.morphTargetInfluences.slice(); + if (data.castShadow !== void 0) object.castShadow = data.castShadow; + if (data.receiveShadow !== void 0) object.receiveShadow = data.receiveShadow; + if (data.shadow) { + if (data.shadow.intensity !== void 0) object.shadow.intensity = data.shadow.intensity; + if (data.shadow.bias !== void 0) object.shadow.bias = data.shadow.bias; + if (data.shadow.normalBias !== void 0) object.shadow.normalBias = data.shadow.normalBias; + if (data.shadow.radius !== void 0) object.shadow.radius = data.shadow.radius; + if (data.shadow.mapSize !== void 0) object.shadow.mapSize.fromArray(data.shadow.mapSize); + if (data.shadow.camera !== void 0) object.shadow.camera = this.parseObject(data.shadow.camera); + } + if (data.visible !== void 0) object.visible = data.visible; + if (data.frustumCulled !== void 0) object.frustumCulled = data.frustumCulled; + if (data.renderOrder !== void 0) object.renderOrder = data.renderOrder; + if (data.static !== void 0) object.static = data.static; + if (data.userData !== void 0) object.userData = data.userData; + if (data.layers !== void 0) object.layers.mask = data.layers; + if (data.children !== void 0) { + const children = data.children; + for (let i = 0; i < children.length; i++) { + object.add(this.parseObject(children[i], geometries, materials, textures, animations)); + } + } + if (data.animations !== void 0) { + const objectAnimations = data.animations; + for (let i = 0; i < objectAnimations.length; i++) { + const uuid = objectAnimations[i]; + object.animations.push(animations[uuid]); + } + } + if (data.type === "LOD") { + if (data.autoUpdate !== void 0) object.autoUpdate = data.autoUpdate; + const levels = data.levels; + for (let l = 0; l < levels.length; l++) { + const level = levels[l]; + const child = object.getObjectByProperty("uuid", level.object); + if (child !== void 0) { + object.addLevel(child, level.distance, level.hysteresis); + } + } + } + return object; + } + bindSkeletons(object, skeletons) { + if (Object.keys(skeletons).length === 0) return; + object.traverse(function(child) { + if (child.isSkinnedMesh === true && child.skeleton !== void 0) { + const skeleton = skeletons[child.skeleton]; + if (skeleton === void 0) { + warn("ObjectLoader: No skeleton found with UUID:", child.skeleton); + } else { + child.bind(skeleton, child.bindMatrix); + } + } + }); + } + bindLightTargets(object) { + object.traverse(function(child) { + if (child.isDirectionalLight || child.isSpotLight) { + const uuid = child.target; + const target = object.getObjectByProperty("uuid", uuid); + if (target !== void 0) { + child.target = target; + } else { + child.target = new Object3D(); + } + } + }); + } + } + const TEXTURE_MAPPING = { + UVMapping, + CubeReflectionMapping, + CubeRefractionMapping, + EquirectangularReflectionMapping, + EquirectangularRefractionMapping, + CubeUVReflectionMapping + }; + const TEXTURE_WRAPPING = { + RepeatWrapping, + ClampToEdgeWrapping, + MirroredRepeatWrapping + }; + const TEXTURE_FILTER = { + NearestFilter, + NearestMipmapNearestFilter, + NearestMipmapLinearFilter, + LinearFilter, + LinearMipmapNearestFilter, + LinearMipmapLinearFilter + }; + const _errorMap = /* @__PURE__ */ new WeakMap(); + class ImageBitmapLoader extends Loader { + /** + * Constructs a new image bitmap loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + this.isImageBitmapLoader = true; + if (typeof createImageBitmap === "undefined") { + warn("ImageBitmapLoader: createImageBitmap() not supported."); + } + if (typeof fetch === "undefined") { + warn("ImageBitmapLoader: fetch() not supported."); + } + this.options = { premultiplyAlpha: "none" }; + this._abortController = new AbortController(); + } + /** + * Sets the given loader options. The structure of the object must match the `options` parameter of + * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap). + * + * Note: When caching is enabled, the cache key is based on the URL only. Loading the same URL with + * different options will return the cached result of the first request. + * + * @param {Object} options - The loader options to set. + * @return {ImageBitmapLoader} A reference to this image bitmap loader. + */ + setOptions(options) { + this.options = options; + return this; + } + /** + * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load(url, onLoad, onProgress, onError) { + if (url === void 0) url = ""; + if (this.path !== void 0) url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(`image-bitmap:${url}`); + if (cached !== void 0) { + scope.manager.itemStart(url); + if (cached.then) { + cached.then((imageBitmap) => { + if (_errorMap.has(cached) === true) { + if (onError) onError(_errorMap.get(cached)); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } else { + if (onLoad) onLoad(imageBitmap); + scope.manager.itemEnd(url); + } + }); + return; + } + setTimeout(function() { + if (onLoad) onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return; + } + const fetchOptions = {}; + fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; + fetchOptions.headers = this.requestHeader; + fetchOptions.signal = typeof AbortSignal.any === "function" ? AbortSignal.any([this._abortController.signal, this.manager.abortController.signal]) : this._abortController.signal; + const promise = fetch(url, fetchOptions).then(function(res) { + return res.blob(); + }).then(function(blob) { + return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); + }).then(function(imageBitmap) { + Cache.add(`image-bitmap:${url}`, imageBitmap); + if (onLoad) onLoad(imageBitmap); + scope.manager.itemEnd(url); + }).catch(function(e) { + if (onError) onError(e); + _errorMap.set(promise, e); + Cache.remove(`image-bitmap:${url}`); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + Cache.add(`image-bitmap:${url}`, promise); + scope.manager.itemStart(url); + } + /** + * Aborts ongoing fetch requests. + * + * @return {ImageBitmapLoader} A reference to this instance. + */ + abort() { + this._abortController.abort(); + this._abortController = new AbortController(); + return this; + } + } + let _context; + class AudioContext { + /** + * Returns the global native audio context. + * + * @return {Window.AudioContext} The native audio context. + */ + static getContext() { + if (_context === void 0) { + _context = new (window.AudioContext || window.webkitAudioContext)(); + } + return _context; + } + /** + * Allows to set the global native audio context from outside. + * + * @param {Window.AudioContext} value - The native context to set. + */ + static setContext(value) { + _context = value; + } + } + class AudioLoader extends Loader { + /** + * Constructs a new audio loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + super(manager); + } + /** + * Starts loading from the given URL and passes the loaded audio buffer + * to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(buffer) { + try { + const bufferCopy = buffer.slice(0); + const context = AudioContext.getContext(); + const decodeUrl = url + "#decode"; + scope.manager.itemStart(decodeUrl); + context.decodeAudioData(bufferCopy, function(audioBuffer) { + onLoad(audioBuffer); + scope.manager.itemEnd(decodeUrl); + }).catch(function(e) { + handleError(e); + scope.manager.itemEnd(decodeUrl); + }); + } catch (e) { + handleError(e); + } + }, onProgress, onError); + function handleError(e) { + if (onError) { + onError(e); + } else { + error(e); + } + scope.manager.itemError(url); + } + } + } + const _eyeRight = /* @__PURE__ */ new Matrix4(); + const _eyeLeft = /* @__PURE__ */ new Matrix4(); + const _projectionMatrix = /* @__PURE__ */ new Matrix4(); + class StereoCamera { + /** + * Constructs a new stereo camera. + */ + constructor() { + this.type = "StereoCamera"; + this.aspect = 1; + this.eyeSep = 0.064; + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable(1); + this.cameraL.matrixAutoUpdate = false; + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable(2); + this.cameraR.matrixAutoUpdate = false; + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + } + /** + * Updates the stereo camera based on the given perspective camera. + * + * @param {PerspectiveCamera} camera - The perspective camera. + */ + update(camera) { + const cache = this._cache; + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + if (needsUpdate) { + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + _projectionMatrix.copy(camera.projectionMatrix); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom; + let xmin, xmax; + _eyeLeft.elements[12] = -eyeSepHalf; + _eyeRight.elements[12] = eyeSepHalf; + xmin = -ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraL.projectionMatrix.copy(_projectionMatrix); + xmin = -ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraR.projectionMatrix.copy(_projectionMatrix); + } + this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft); + this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight); + } + } + const fov = -90; + const aspect = 1; + class CubeCamera extends Object3D { + /** + * Constructs a new cube camera. + * + * @param {number} near - The camera's near plane. + * @param {number} far - The camera's far plane. + * @param {WebGLCubeRenderTarget} renderTarget - The cube render target. + */ + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera(fov, aspect, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera(fov, aspect, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera(fov, aspect, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera(fov, aspect, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera(fov, aspect, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera(fov, aspect, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + /** + * Must be called when the coordinate system of the cube camera is changed. + */ + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + /** + * Calling this method will render the given scene with the given renderer + * into the cube render target of the camera. + * + * @param {(Renderer|WebGLRenderer)} renderer - The renderer. + * @param {Scene} scene - The scene to render. + */ + update(renderer, scene) { + if (this.parent === null) this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer.coordinateSystem) { + this.coordinateSystem = renderer.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer.getRenderTarget(); + const currentActiveCubeFace = renderer.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer.getActiveMipmapLevel(); + const currentXrEnabled = renderer.xr.enabled; + renderer.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + let reversedDepthBuffer = false; + if (renderer.isWebGLRenderer === true) { + reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + } else { + reversedDepthBuffer = renderer.reversedDepthBuffer; + } + renderer.setRenderTarget(renderTarget, 0, activeMipmapLevel); + if (reversedDepthBuffer && renderer.autoClear === false) renderer.clearDepth(); + renderer.render(scene, cameraPX); + renderer.setRenderTarget(renderTarget, 1, activeMipmapLevel); + if (reversedDepthBuffer && renderer.autoClear === false) renderer.clearDepth(); + renderer.render(scene, cameraNX); + renderer.setRenderTarget(renderTarget, 2, activeMipmapLevel); + if (reversedDepthBuffer && renderer.autoClear === false) renderer.clearDepth(); + renderer.render(scene, cameraPY); + renderer.setRenderTarget(renderTarget, 3, activeMipmapLevel); + if (reversedDepthBuffer && renderer.autoClear === false) renderer.clearDepth(); + renderer.render(scene, cameraNY); + renderer.setRenderTarget(renderTarget, 4, activeMipmapLevel); + if (reversedDepthBuffer && renderer.autoClear === false) renderer.clearDepth(); + renderer.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer.setRenderTarget(renderTarget, 5, activeMipmapLevel); + if (reversedDepthBuffer && renderer.autoClear === false) renderer.clearDepth(); + renderer.render(scene, cameraNZ); + renderer.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } + } + class ArrayCamera extends PerspectiveCamera { + /** + * Constructs a new array camera. + * + * @param {Array} [array=[]] - An array of perspective sub cameras. + */ + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.isMultiViewCamera = false; + this.cameras = array; + } + } + class Timer { + /** + * Constructs a new timer. + */ + constructor() { + this._previousTime = 0; + this._currentTime = 0; + this._startTime = performance.now(); + this._delta = 0; + this._elapsed = 0; + this._timescale = 1; + this._document = null; + this._pageVisibilityHandler = null; + } + /** + * Connect the timer to the given document.Calling this method is not mandatory to + * use the timer but enables the usage of the Page Visibility API to avoid large time + * delta values. + * + * @param {Document} document - The document. + */ + connect(document2) { + this._document = document2; + if (document2.hidden !== void 0) { + this._pageVisibilityHandler = handleVisibilityChange.bind(this); + document2.addEventListener("visibilitychange", this._pageVisibilityHandler, false); + } + } + /** + * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API. + */ + disconnect() { + if (this._pageVisibilityHandler !== null) { + this._document.removeEventListener("visibilitychange", this._pageVisibilityHandler); + this._pageVisibilityHandler = null; + } + this._document = null; + } + /** + * Returns the time delta in seconds. + * + * @return {number} The time delta in second. + */ + getDelta() { + return this._delta / 1e3; + } + /** + * Returns the elapsed time in seconds. + * + * @return {number} The elapsed time in second. + */ + getElapsed() { + return this._elapsed / 1e3; + } + /** + * Returns the timescale. + * + * @return {number} The timescale. + */ + getTimescale() { + return this._timescale; + } + /** + * Sets the given timescale which scale the time delta computation + * in `update()`. + * + * @param {number} timescale - The timescale to set. + * @return {Timer} A reference to this timer. + */ + setTimescale(timescale) { + this._timescale = timescale; + return this; + } + /** + * Resets the time computation for the current simulation step. + * + * @return {Timer} A reference to this timer. + */ + reset() { + this._currentTime = performance.now() - this._startTime; + return this; + } + /** + * Can be used to free all internal resources. Usually called when + * the timer instance isn't required anymore. + */ + dispose() { + this.disconnect(); + } + /** + * Updates the internal state of the timer. This method should be called + * once per simulation step and before you perform queries against the timer + * (e.g. via `getDelta()`). + * + * @param {number} timestamp - The current time in milliseconds. Can be obtained + * from the `requestAnimationFrame` callback argument. If not provided, the current + * time will be determined with `performance.now`. + * @return {Timer} A reference to this timer. + */ + update(timestamp) { + if (this._pageVisibilityHandler !== null && this._document.hidden === true) { + this._delta = 0; + } else { + this._previousTime = this._currentTime; + this._currentTime = (timestamp !== void 0 ? timestamp : performance.now()) - this._startTime; + this._delta = (this._currentTime - this._previousTime) * this._timescale; + this._elapsed += this._delta; + } + return this; + } + } + function handleVisibilityChange() { + if (this._document.hidden === false) this.reset(); + } + const _position$1 = /* @__PURE__ */ new Vector3(); + const _quaternion$1 = /* @__PURE__ */ new Quaternion(); + const _scale$1 = /* @__PURE__ */ new Vector3(); + const _forward = /* @__PURE__ */ new Vector3(); + const _up = /* @__PURE__ */ new Vector3(); + class AudioListener extends Object3D { + /** + * Constructs a new audio listener. + */ + constructor() { + super(); + this.type = "AudioListener"; + this.context = AudioContext.getContext(); + this.gain = this.context.createGain(); + this.gain.connect(this.context.destination); + this.filter = null; + this.timeDelta = 0; + this._timer = new Timer(); + } + /** + * Returns the listener's input node. + * + * This method is used by other audio nodes to connect to this listener. + * + * @return {GainNode} The input node. + */ + getInput() { + return this.gain; + } + /** + * Removes the current filter from this listener. + * + * @return {AudioListener} A reference to this listener. + */ + removeFilter() { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + this.gain.connect(this.context.destination); + this.filter = null; + } + return this; + } + /** + * Returns the current set filter. + * + * @return {?AudioNode} The filter. + */ + getFilter() { + return this.filter; + } + /** + * Sets the given filter to this listener. + * + * @param {AudioNode} value - The filter to set. + * @return {AudioListener} A reference to this listener. + */ + setFilter(value) { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + } else { + this.gain.disconnect(this.context.destination); + } + this.filter = value; + this.gain.connect(this.filter); + this.filter.connect(this.context.destination); + return this; + } + /** + * Returns the applications master volume. + * + * @return {number} The master volume. + */ + getMasterVolume() { + return this.gain.gain.value; + } + /** + * Sets the applications master volume. This volume setting affects + * all audio nodes in the scene. + * + * @param {number} value - The master volume to set. + * @return {AudioListener} A reference to this listener. + */ + setMasterVolume(value) { + this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01); + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this._timer.update(); + const listener = this.context.listener; + this.timeDelta = this._timer.getDelta(); + this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1); + _forward.set(0, 0, -1).applyQuaternion(_quaternion$1); + _up.set(0, 1, 0).applyQuaternion(_quaternion$1); + if (listener.positionX) { + const endTime = this.context.currentTime + this.timeDelta; + listener.positionX.linearRampToValueAtTime(_position$1.x, endTime); + listener.positionY.linearRampToValueAtTime(_position$1.y, endTime); + listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime); + listener.forwardX.linearRampToValueAtTime(_forward.x, endTime); + listener.forwardY.linearRampToValueAtTime(_forward.y, endTime); + listener.forwardZ.linearRampToValueAtTime(_forward.z, endTime); + listener.upX.linearRampToValueAtTime(_up.x, endTime); + listener.upY.linearRampToValueAtTime(_up.y, endTime); + listener.upZ.linearRampToValueAtTime(_up.z, endTime); + } else { + listener.setPosition(_position$1.x, _position$1.y, _position$1.z); + listener.setOrientation(_forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z); + } + } + } + class Audio extends Object3D { + /** + * Constructs a new audio. + * + * @param {AudioListener} listener - The global audio listener. + */ + constructor(listener) { + super(); + this.type = "Audio"; + this.listener = listener; + this.context = listener.context; + this.gain = this.context.createGain(); + this.gain.connect(listener.getInput()); + this.autoplay = false; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = void 0; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = "empty"; + this._startedAt = 0; + this._progress = 0; + this._connected = false; + this.filters = []; + } + /** + * Returns the output audio node. + * + * @return {GainNode} The output node. + */ + getOutput() { + return this.gain; + } + /** + * Sets the given audio node as the source of this instance. + * + * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`. + * + * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`. + * @return {Audio} A reference to this instance. + */ + setNodeSource(audioNode) { + this.hasPlaybackControl = false; + this.sourceType = "audioNode"; + this.source = audioNode; + this.connect(); + return this; + } + /** + * Sets the given media element as the source of this instance. + * + * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`. + * + * @param {HTMLMediaElement} mediaElement - The media element. + * @return {Audio} A reference to this instance. + */ + setMediaElementSource(mediaElement) { + this.hasPlaybackControl = false; + this.sourceType = "mediaNode"; + this.source = this.context.createMediaElementSource(mediaElement); + this.connect(); + return this; + } + /** + * Sets the given media stream as the source of this instance. + * + * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`. + * + * @param {MediaStream} mediaStream - The media stream. + * @return {Audio} A reference to this instance. + */ + setMediaStreamSource(mediaStream) { + this.hasPlaybackControl = false; + this.sourceType = "mediaStreamNode"; + this.source = this.context.createMediaStreamSource(mediaStream); + this.connect(); + return this; + } + /** + * Sets the given audio buffer as the source of this instance. + * + * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`. + * + * @param {AudioBuffer} audioBuffer - The audio buffer. + * @return {Audio} A reference to this instance. + */ + setBuffer(audioBuffer) { + this.buffer = audioBuffer; + this.sourceType = "buffer"; + if (this.autoplay) this.play(); + return this; + } + /** + * Starts the playback of the audio. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing. + * @return {Audio|undefined} A reference to this instance. + */ + play(delay = 0) { + if (this.isPlaying === true) { + warn("Audio: Audio is already playing."); + return; + } + if (this.hasPlaybackControl === false) { + warn("Audio: this Audio has no playback control."); + return; + } + this._startedAt = this.context.currentTime + delay; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind(this); + source.start(this._startedAt, this._progress + this.offset, this.duration); + this.isPlaying = true; + this.source = source; + this.setDetune(this.detune); + this.setPlaybackRate(this.playbackRate); + return this.connect(); + } + /** + * Pauses the playback of the audio. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @return {Audio|undefined} A reference to this instance. + */ + pause() { + if (this.hasPlaybackControl === false) { + warn("Audio: this Audio has no playback control."); + return; + } + if (this.isPlaying === true) { + this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate; + if (this.loop === true) { + this._progress = this._progress % (this.duration || this.buffer.duration); + } + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + } + return this; + } + /** + * Stops the playback of the audio. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing. + * @return {Audio|undefined} A reference to this instance. + */ + stop(delay = 0) { + if (this.hasPlaybackControl === false) { + warn("Audio: this Audio has no playback control."); + return; + } + this._progress = 0; + if (this.source !== null) { + this.source.stop(this.context.currentTime + delay); + this.source.onended = null; + } + this.isPlaying = false; + return this; + } + /** + * Connects to the audio source. This is used internally on + * initialisation and when setting / removing filters. + * + * @return {Audio} A reference to this instance. + */ + connect() { + if (this.filters.length > 0) { + this.source.connect(this.filters[0]); + for (let i = 1, l = this.filters.length; i < l; i++) { + this.filters[i - 1].connect(this.filters[i]); + } + this.filters[this.filters.length - 1].connect(this.getOutput()); + } else { + this.source.connect(this.getOutput()); + } + this._connected = true; + return this; + } + /** + * Disconnects to the audio source. This is used internally on + * initialisation and when setting / removing filters. + * + * @return {Audio|undefined} A reference to this instance. + */ + disconnect() { + if (this._connected === false) { + return; + } + if (this.filters.length > 0) { + this.source.disconnect(this.filters[0]); + for (let i = 1, l = this.filters.length; i < l; i++) { + this.filters[i - 1].disconnect(this.filters[i]); + } + this.filters[this.filters.length - 1].disconnect(this.getOutput()); + } else { + this.source.disconnect(this.getOutput()); + } + this._connected = false; + return this; + } + /** + * Returns the current set filters. + * + * @return {Array} The list of filters. + */ + getFilters() { + return this.filters; + } + /** + * Sets an array of filters and connects them with the audio source. + * + * @param {Array} [value] - A list of filters. + * @return {Audio} A reference to this instance. + */ + setFilters(value) { + if (!value) value = []; + if (this._connected === true) { + this.disconnect(); + this.filters = value.slice(); + this.connect(); + } else { + this.filters = value.slice(); + } + return this; + } + /** + * Defines the detuning of oscillation in cents. + * + * @param {number} value - The detuning of oscillation in cents. + * @return {Audio} A reference to this instance. + */ + setDetune(value) { + this.detune = value; + if (this.isPlaying === true && this.source.detune !== void 0) { + this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01); + } + return this; + } + /** + * Returns the detuning of oscillation in cents. + * + * @return {number} The detuning of oscillation in cents. + */ + getDetune() { + return this.detune; + } + /** + * Returns the first filter in the list of filters. + * + * @return {AudioNode|undefined} The first filter in the list of filters. + */ + getFilter() { + return this.getFilters()[0]; + } + /** + * Applies a single filter node to the audio. + * + * @param {AudioNode} [filter] - The filter to set. + * @return {Audio} A reference to this instance. + */ + setFilter(filter) { + return this.setFilters(filter ? [filter] : []); + } + /** + * Sets the playback rate. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @param {number} [value] - The playback rate to set. + * @return {Audio|undefined} A reference to this instance. + */ + setPlaybackRate(value) { + if (this.hasPlaybackControl === false) { + warn("Audio: this Audio has no playback control."); + return; + } + this.playbackRate = value; + if (this.isPlaying === true) { + this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01); + } + return this; + } + /** + * Returns the current playback rate. + + * @return {number} The playback rate. + */ + getPlaybackRate() { + return this.playbackRate; + } + /** + * Automatically called when playback finished. + */ + onEnded() { + this.isPlaying = false; + this._progress = 0; + } + /** + * Returns the loop flag. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @return {boolean} Whether the audio should loop or not. + */ + getLoop() { + if (this.hasPlaybackControl === false) { + warn("Audio: this Audio has no playback control."); + return false; + } + return this.loop; + } + /** + * Sets the loop flag. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @param {boolean} value - Whether the audio should loop or not. + * @return {Audio|undefined} A reference to this instance. + */ + setLoop(value) { + if (this.hasPlaybackControl === false) { + warn("Audio: this Audio has no playback control."); + return; + } + this.loop = value; + if (this.isPlaying === true) { + this.source.loop = this.loop; + } + return this; + } + /** + * Sets the loop start value which defines where in the audio buffer the replay should + * start, in seconds. + * + * @param {number} value - The loop start value. + * @return {Audio} A reference to this instance. + */ + setLoopStart(value) { + this.loopStart = value; + return this; + } + /** + * Sets the loop end value which defines where in the audio buffer the replay should + * stop, in seconds. + * + * @param {number} value - The loop end value. + * @return {Audio} A reference to this instance. + */ + setLoopEnd(value) { + this.loopEnd = value; + return this; + } + /** + * Returns the volume. + * + * @return {number} The volume. + */ + getVolume() { + return this.gain.gain.value; + } + /** + * Sets the volume. + * + * @param {number} value - The volume to set. + * @return {Audio} A reference to this instance. + */ + setVolume(value) { + this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.sourceType !== "buffer") { + warn("Audio: Audio source type cannot be copied."); + return this; + } + this.autoplay = source.autoplay; + this.buffer = source.buffer; + this.detune = source.detune; + this.loop = source.loop; + this.loopStart = source.loopStart; + this.loopEnd = source.loopEnd; + this.offset = source.offset; + this.duration = source.duration; + this.playbackRate = source.playbackRate; + this.hasPlaybackControl = source.hasPlaybackControl; + this.sourceType = source.sourceType; + this.filters = source.filters.slice(); + return this; + } + clone(recursive) { + return new this.constructor(this.listener).copy(this, recursive); + } + } + const _position = /* @__PURE__ */ new Vector3(); + const _quaternion = /* @__PURE__ */ new Quaternion(); + const _scale = /* @__PURE__ */ new Vector3(); + const _orientation = /* @__PURE__ */ new Vector3(); + class PositionalAudio extends Audio { + /** + * Constructs a positional audio. + * + * @param {AudioListener} listener - The global audio listener. + */ + constructor(listener) { + super(listener); + this.panner = this.context.createPanner(); + this.panner.panningModel = "HRTF"; + this.panner.connect(this.gain); + } + connect() { + super.connect(); + this.panner.connect(this.gain); + return this; + } + disconnect() { + super.disconnect(); + this.panner.disconnect(this.gain); + return this; + } + getOutput() { + return this.panner; + } + /** + * Returns the current reference distance. + * + * @return {number} The reference distance. + */ + getRefDistance() { + return this.panner.refDistance; + } + /** + * Defines the reference distance for reducing volume as the audio source moves + * further from the listener – i.e. the distance at which the volume reduction + * starts taking effect. + * + * @param {number} value - The reference distance to set. + * @return {PositionalAudio} A reference to this instance. + */ + setRefDistance(value) { + this.panner.refDistance = value; + return this; + } + /** + * Returns the current rolloff factor. + * + * @return {number} The rolloff factor. + */ + getRolloffFactor() { + return this.panner.rolloffFactor; + } + /** + * Defines how quickly the volume is reduced as the source moves away from the listener. + * + * @param {number} value - The rolloff factor. + * @return {PositionalAudio} A reference to this instance. + */ + setRolloffFactor(value) { + this.panner.rolloffFactor = value; + return this; + } + /** + * Returns the current distance model. + * + * @return {('linear'|'inverse'|'exponential')} The distance model. + */ + getDistanceModel() { + return this.panner.distanceModel; + } + /** + * Defines which algorithm to use to reduce the volume of the audio source + * as it moves away from the listener. + * + * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype) + * for more details. + * + * @param {('linear'|'inverse'|'exponential')} value - The distance model to set. + * @return {PositionalAudio} A reference to this instance. + */ + setDistanceModel(value) { + this.panner.distanceModel = value; + return this; + } + /** + * Returns the current max distance. + * + * @return {number} The max distance. + */ + getMaxDistance() { + return this.panner.maxDistance; + } + /** + * Defines the maximum distance between the audio source and the listener, + * after which the volume is not reduced any further. + * + * This value is used only by the `linear` distance model. + * + * @param {number} value - The max distance. + * @return {PositionalAudio} A reference to this instance. + */ + setMaxDistance(value) { + this.panner.maxDistance = value; + return this; + } + /** + * Sets the directional cone in which the audio can be listened. + * + * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction. + * @param {number} coneOuterAngle - An angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` parameter. + * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard. + * @return {PositionalAudio} A reference to this instance. + */ + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.hasPlaybackControl === true && this.isPlaying === false) return; + this.matrixWorld.decompose(_position, _quaternion, _scale); + _orientation.set(0, 0, 1).applyQuaternion(_quaternion); + const panner = this.panner; + if (panner.positionX) { + const endTime = this.context.currentTime + this.listener.timeDelta; + panner.positionX.linearRampToValueAtTime(_position.x, endTime); + panner.positionY.linearRampToValueAtTime(_position.y, endTime); + panner.positionZ.linearRampToValueAtTime(_position.z, endTime); + panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime); + panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime); + panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime); + } else { + panner.setPosition(_position.x, _position.y, _position.z); + panner.setOrientation(_orientation.x, _orientation.y, _orientation.z); + } + } + } + class AudioAnalyser { + /** + * Constructs a new audio analyzer. + * + * @param {Audio} audio - The audio to analyze. + * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data. + */ + constructor(audio, fftSize = 2048) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + this.data = new Uint8Array(this.analyser.frequencyBinCount); + audio.getOutput().connect(this.analyser); + } + /** + * Returns an array with frequency data of the audio. + * + * Each item in the array represents the decibel value for a specific frequency. + * The frequencies are spread linearly from 0 to 1/2 of the sample rate. + * For example, for 48000 sample rate, the last item of the array will represent + * the decibel value for 24000 Hz. + * + * @return {Uint8Array} The frequency data. + */ + getFrequencyData() { + this.analyser.getByteFrequencyData(this.data); + return this.data; + } + /** + * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}. + * + * @return {number} The average frequency. + */ + getAverageFrequency() { + let value = 0; + const data = this.getFrequencyData(); + for (let i = 0; i < data.length; i++) { + value += data[i]; + } + return value / data.length; + } + } + class PropertyMixer { + /** + * Constructs a new property mixer. + * + * @param {PropertyBinding} binding - The property binding. + * @param {string} typeName - The keyframe track type name. + * @param {number} valueSize - The keyframe track value size. + */ + constructor(binding, typeName, valueSize) { + this.binding = binding; + this.valueSize = valueSize; + let mixFunction, mixFunctionAdditive, setIdentity; + switch (typeName) { + case "quaternion": + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + this.buffer = new Float64Array(valueSize * 6); + this._workIndex = 5; + break; + case "string": + case "bool": + mixFunction = this._select; + mixFunctionAdditive = this._select; + setIdentity = this._setAdditiveIdentityOther; + this.buffer = new Array(valueSize * 5); + break; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + this.buffer = new Float64Array(valueSize * 5); + } + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + this.useCount = 0; + this.referenceCount = 0; + } + /** + * Accumulates data in the `incoming` region into `accu`. + * + * @param {number} accuIndex - The accumulation index. + * @param {number} weight - The weight. + */ + accumulate(accuIndex, weight) { + const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; + let currentWeight = this.cumulativeWeight; + if (currentWeight === 0) { + for (let i = 0; i !== stride; ++i) { + buffer[offset + i] = buffer[i]; + } + currentWeight = weight; + } else { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion(buffer, offset, 0, mix, stride); + } + this.cumulativeWeight = currentWeight; + } + /** + * Accumulates data in the `incoming` region into `add`. + * + * @param {number} weight - The weight. + */ + accumulateAdditive(weight) { + const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; + if (this.cumulativeWeightAdditive === 0) { + this._setIdentity(); + } + this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); + this.cumulativeWeightAdditive += weight; + } + /** + * Applies the state of `accu` to the binding when accus differ. + * + * @param {number} accuIndex - The accumulation index. + */ + apply(accuIndex) { + const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + if (weight < 1) { + const originalValueOffset = stride * this._origIndex; + this._mixBufferRegion( + buffer, + offset, + originalValueOffset, + 1 - weight, + stride + ); + } + if (weightAdditive > 0) { + this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); + } + for (let i = stride, e = stride + stride; i !== e; ++i) { + if (buffer[i] !== buffer[i + stride]) { + binding.setValue(buffer, offset); + break; + } + } + } + /** + * Remembers the state of the bound property and copy it to both accus. + */ + saveOriginalState() { + const binding = this.binding; + const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; + binding.getValue(buffer, originalValueOffset); + for (let i = stride, e = originalValueOffset; i !== e; ++i) { + buffer[i] = buffer[originalValueOffset + i % stride]; + } + this._setIdentity(); + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + } + /** + * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding. + */ + restoreOriginalState() { + const originalValueOffset = this.valueSize * 3; + this.binding.setValue(this.buffer, originalValueOffset); + } + // internals + _setAdditiveIdentityNumeric() { + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + for (let i = startIndex; i < endIndex; i++) { + this.buffer[i] = 0; + } + } + _setAdditiveIdentityQuaternion() { + this._setAdditiveIdentityNumeric(); + this.buffer[this._addIndex * this.valueSize + 3] = 1; + } + _setAdditiveIdentityOther() { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + for (let i = 0; i < this.valueSize; i++) { + this.buffer[targetIndex + i] = this.buffer[startIndex + i]; + } + } + // mix functions + _select(buffer, dstOffset, srcOffset, t, stride) { + if (t >= 0.5) { + for (let i = 0; i !== stride; ++i) { + buffer[dstOffset + i] = buffer[srcOffset + i]; + } + } + } + _slerp(buffer, dstOffset, srcOffset, t) { + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t); + } + _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + const workOffset = this._workIndex * stride; + Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t); + } + _lerp(buffer, dstOffset, srcOffset, t, stride) { + const s = 1 - t; + for (let i = 0; i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t; + } + } + _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + for (let i = 0; i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] + buffer[srcOffset + i] * t; + } + } + } + const _RESERVED_CHARS_RE = "\\[\\]\\.:\\/"; + const _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g"); + const _wordChar = "[^" + _RESERVED_CHARS_RE + "]"; + const _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]"; + const _directoryRe = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar); + const _nodeRe = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot); + const _objectRe = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar); + const _propertyRe = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar); + const _trackRe = new RegExp( + "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$" + ); + const _supportedObjectNames = ["material", "materials", "bones", "map"]; + class Composite { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== void 0) binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) { + bindings[i].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) { + bindings[i].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) { + bindings[i].unbind(); + } + } + } + class PropertyBinding { + /** + * Constructs a new property binding. + * + * @param {Object} rootNode - The root node. + * @param {string} path - The path. + * @param {?Object} [parsedPath] - The parsed path. + */ + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path); + this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + /** + * Factory method for creating a property binding from the given parameters. + * + * @static + * @param {Object} root - The root node. + * @param {string} path - The path. + * @param {?Object} [parsedPath] - The parsed path. + * @return {PropertyBinding|Composite} The created property binding or composite. + */ + static create(root, path, parsedPath) { + if (!(root && root.isAnimationObjectGroup)) { + return new PropertyBinding(root, path, parsedPath); + } else { + return new PropertyBinding.Composite(root, path, parsedPath); + } + } + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name - Node name to be sanitized. + * @return {string} The sanitized node name. + */ + static sanitizeNodeName(name) { + return name.replace(/\s/g, "_").replace(_reservedRe, ""); + } + /** + * Parses the given track name (an object path to an animated property) and + * returns an object with information about the path. Matches strings in the following forms: + * + * - nodeName.property + * - nodeName.property[accessor] + * - nodeName.material.property[accessor] + * - uuid.property[accessor] + * - uuid.objectName[objectIndex].propertyName[propertyIndex] + * - parentName/nodeName.property + * - parentName/parentName/nodeName.property[index] + * - .bone[Armature.DEF_cog].position + * - scene:helium_balloon_model:helium_balloon_model.position + * + * @static + * @param {string} trackName - The track name to parse. + * @return {Object} The parsed track name as an object. + */ + static parseTrackName(trackName) { + const matches = _trackRe.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + // required + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== void 0 && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + /** + * Searches for a node in the hierarchy of the given root object by the given + * node name. + * + * @static + * @param {Object} root - The root object. + * @param {string|number} nodeName - The name of the node. + * @return {?Object} The found node. Returns `null` if no object was found. + */ + static findNode(root, nodeName) { + if (nodeName === void 0 || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) { + return root; + } + if (root.skeleton) { + const bone = root.skeleton.getBoneByName(nodeName); + if (bone !== void 0) { + return bone; + } + } + if (root.children) { + const searchNodeSubtree = function(children) { + for (let i = 0; i < children.length; i++) { + const childNode = children[i]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + // these are used to "bind" a nonexistent property + _getValue_unavailable() { + } + _setValue_unavailable() { + } + // Getters + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i = 0, n = source.length; i !== n; ++i) { + buffer[offset++] = source[i]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + // Direct + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + // EntireArray + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length; i !== n; ++i) { + dest[i] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length; i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length; i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + // ArrayElement + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + // HasToFromArray + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + /** + * Creates a getter / setter pair for the property tracked by this binding. + */ + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + warn("PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + error("PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + error("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + error("PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i = 0; i < targetObject.length; i++) { + if (targetObject[i].name === objectIndex) { + objectIndex = i; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + error("PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + error("PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === void 0) { + error("PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== void 0) { + if (targetObject[objectIndex] === void 0) { + error("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === void 0) { + const nodeName = parsedPath.nodeName; + error("PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.isMaterial === true) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.isObject3D === true) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== void 0) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + error("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + error("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== void 0) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== void 0 && nodeProperty.toArray !== void 0) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + /** + * Unbinds the property. + */ + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + } + PropertyBinding.Composite = Composite; + PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }; + PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }; + PropertyBinding.prototype.GetterByBindingType = [ + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray + ]; + PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + // EntireArray + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] + ]; + class AnimationObjectGroup { + /** + * Constructs a new animation group. + * + * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state. + */ + constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID(); + this._objects = Array.prototype.slice.call(arguments); + this.nCachedObjects_ = 0; + const indices = {}; + this._indicesByUUID = indices; + for (let i = 0, n = arguments.length; i !== n; ++i) { + indices[arguments[i].uuid] = i; + } + this._paths = []; + this._parsedPaths = []; + this._bindings = []; + this._bindingsIndicesByPath = {}; + const scope = this; + this.stats = { + objects: { + get total() { + return scope._objects.length; + }, + get inUse() { + return this.total - scope.nCachedObjects_; + } + }, + get bindingsPerObject() { + return scope._bindings.length; + } + }; + } + /** + * Adds an arbitrary number of objects to this animation group. + * + * @param {...Object3D} arguments - The 3D objects to add. + */ + add() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length; + let knownObject = void 0, nObjects = objects.length, nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length; i !== n; ++i) { + const object = arguments[i], uuid = object.uuid; + let index = indicesByUUID[uuid]; + if (index === void 0) { + index = nObjects++; + indicesByUUID[uuid] = index; + objects.push(object); + for (let j = 0, m = nBindings; j !== m; ++j) { + bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j])); + } + } else if (index < nCachedObjects) { + knownObject = objects[index]; + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex]; + indicesByUUID[lastCachedObject.uuid] = index; + objects[index] = lastCachedObject; + indicesByUUID[uuid] = firstActiveIndex; + objects[firstActiveIndex] = object; + for (let j = 0, m = nBindings; j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex]; + let binding = bindingsForPath[index]; + bindingsForPath[index] = lastCached; + if (binding === void 0) { + binding = new PropertyBinding(object, paths[j], parsedPaths[j]); + } + bindingsForPath[firstActiveIndex] = binding; + } + } else if (objects[index] !== knownObject) { + error("AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes."); + } + } + this.nCachedObjects_ = nCachedObjects; + } + /** + * Removes an arbitrary number of objects to this animation group + * + * @param {...Object3D} arguments - The 3D objects to remove. + */ + remove() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length; i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index = indicesByUUID[uuid]; + if (index !== void 0 && index >= nCachedObjects) { + const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex]; + indicesByUUID[firstActiveObject.uuid] = index; + objects[index] = firstActiveObject; + indicesByUUID[uuid] = lastCachedIndex; + objects[lastCachedIndex] = object; + for (let j = 0, m = nBindings; j !== m; ++j) { + const bindingsForPath = bindings[j], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index]; + bindingsForPath[index] = firstActive; + bindingsForPath[lastCachedIndex] = binding; + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + /** + * Deallocates all memory resources for the passed 3D objects of this animation group. + * + * @param {...Object3D} arguments - The 3D objects to uncache. + */ + uncache() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_, nObjects = objects.length; + for (let i = 0, n = arguments.length; i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index = indicesByUUID[uuid]; + if (index !== void 0) { + delete indicesByUUID[uuid]; + if (index < nCachedObjects) { + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex]; + indicesByUUID[lastCachedObject.uuid] = index; + objects[index] = lastCachedObject; + indicesByUUID[lastObject.uuid] = firstActiveIndex; + objects[firstActiveIndex] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings; j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex], last = bindingsForPath[lastIndex]; + bindingsForPath[index] = lastCached; + bindingsForPath[firstActiveIndex] = last; + bindingsForPath.pop(); + } + } else { + const lastIndex = --nObjects, lastObject = objects[lastIndex]; + if (lastIndex > 0) { + indicesByUUID[lastObject.uuid] = index; + } + objects[index] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings; j !== m; ++j) { + const bindingsForPath = bindings[j]; + bindingsForPath[index] = bindingsForPath[lastIndex]; + bindingsForPath.pop(); + } + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + // Internal interface used by befriended PropertyBinding.Composite: + subscribe_(path, parsedPath) { + const indicesByPath = this._bindingsIndicesByPath; + let index = indicesByPath[path]; + const bindings = this._bindings; + if (index !== void 0) return bindings[index]; + const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects); + index = bindings.length; + indicesByPath[path] = index; + paths.push(path); + parsedPaths.push(parsedPath); + bindings.push(bindingsForPath); + for (let i = nCachedObjects, n = objects.length; i !== n; ++i) { + const object = objects[i]; + bindingsForPath[i] = new PropertyBinding(object, path, parsedPath); + } + return bindingsForPath; + } + unsubscribe_(path) { + const indicesByPath = this._bindingsIndicesByPath, index = indicesByPath[path]; + if (index !== void 0) { + const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex]; + indicesByPath[lastBindingsPath] = index; + bindings[index] = lastBindings; + bindings.pop(); + parsedPaths[index] = parsedPaths[lastBindingsIndex]; + parsedPaths.pop(); + paths[index] = paths[lastBindingsIndex]; + paths.pop(); + } + } + } + class AnimationAction { + /** + * Constructs a new animation action. + * + * @param {AnimationMixer} mixer - The mixer that is controlled by this action. + * @param {AnimationClip} clip - The animation clip that holds the actual keyframes. + * @param {?Object3D} [localRoot=null] - The root object on which this action is performed. + * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode. + */ + constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + for (let i = 0; i !== nTracks; ++i) { + const interpolant = tracks[i].createInterpolant(null); + interpolants[i] = interpolant; + if (interpolant.settings) { + Object.assign(interpolantSettings, interpolant.settings); + } + interpolant.settings = interpolantSettings; + } + this._interpolantSettings = interpolantSettings; + this._interpolants = interpolants; + this._propertyBindings = new Array(nTracks); + this._cacheIndex = null; + this._byClipCacheIndex = null; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + this.loop = LoopRepeat; + this._loopCount = -1; + this._startTime = null; + this.time = 0; + this.timeScale = 1; + this._effectiveTimeScale = 1; + this.weight = 1; + this._effectiveWeight = 1; + this.repetitions = Infinity; + this.paused = false; + this.enabled = true; + this.clampWhenFinished = false; + this.zeroSlopeAtStart = true; + this.zeroSlopeAtEnd = true; + } + /** + * Starts the playback of the animation. + * + * @return {AnimationAction} A reference to this animation action. + */ + play() { + this._mixer._activateAction(this); + return this; + } + /** + * Stops the playback of the animation. + * + * @return {AnimationAction} A reference to this animation action. + */ + stop() { + this._mixer._deactivateAction(this); + return this.reset(); + } + /** + * Resets the playback of the animation. + * + * @return {AnimationAction} A reference to this animation action. + */ + reset() { + this.paused = false; + this.enabled = true; + this.time = 0; + this._loopCount = -1; + this._startTime = null; + return this.stopFading().stopWarping(); + } + /** + * Returns `true` if the animation is running. + * + * @return {boolean} Whether the animation is running or not. + */ + isRunning() { + return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); + } + /** + * Returns `true` when {@link AnimationAction#play} has been called. + * + * @return {boolean} Whether the animation is scheduled or not. + */ + isScheduled() { + return this._mixer._isActiveAction(this); + } + /** + * Defines the time when the animation should start. + * + * @param {number} time - The start time in seconds. + * @return {AnimationAction} A reference to this animation action. + */ + startAt(time) { + this._startTime = time; + return this; + } + /** + * Configures the loop settings for this action. + * + * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode. + * @param {number} repetitions - The number of repetitions. + * @return {AnimationAction} A reference to this animation action. + */ + setLoop(mode, repetitions) { + this.loop = mode; + this.repetitions = repetitions; + return this; + } + /** + * Sets the effective weight of this action. + * + * An action has no effect and thus an effective weight of zero when the + * action is disabled. + * + * @param {number} weight - The weight to set. + * @return {AnimationAction} A reference to this animation action. + */ + setEffectiveWeight(weight) { + this.weight = weight; + this._effectiveWeight = this.enabled ? weight : 0; + return this.stopFading(); + } + /** + * Returns the effective weight of this action. + * + * @return {number} The effective weight. + */ + getEffectiveWeight() { + return this._effectiveWeight; + } + /** + * Fades the animation in by increasing its weight gradually from `0` to `1`, + * within the passed time interval. + * + * @param {number} duration - The duration of the fade. + * @return {AnimationAction} A reference to this animation action. + */ + fadeIn(duration) { + return this._scheduleFading(duration, 0, 1); + } + /** + * Fades the animation out by decreasing its weight gradually from `1` to `0`, + * within the passed time interval. + * + * @param {number} duration - The duration of the fade. + * @return {AnimationAction} A reference to this animation action. + */ + fadeOut(duration) { + return this._scheduleFading(duration, 1, 0); + } + /** + * Causes this action to fade in and the given action to fade out, + * within the passed time interval. + * + * @param {AnimationAction} fadeOutAction - The animation action to fade out. + * @param {number} duration - The duration of the fade. + * @param {boolean} [warp=false] - Whether warping should be used or not. + * @return {AnimationAction} A reference to this animation action. + */ + crossFadeFrom(fadeOutAction, duration, warp = false) { + fadeOutAction.fadeOut(duration); + this.fadeIn(duration); + if (warp === true) { + const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; + fadeOutAction.warp(1, startEndRatio, duration); + this.warp(endStartRatio, 1, duration); + } + return this; + } + /** + * Causes this action to fade out and the given action to fade in, + * within the passed time interval. + * + * @param {AnimationAction} fadeInAction - The animation action to fade in. + * @param {number} duration - The duration of the fade. + * @param {boolean} [warp=false] - Whether warping should be used or not. + * @return {AnimationAction} A reference to this animation action. + */ + crossFadeTo(fadeInAction, duration, warp = false) { + return fadeInAction.crossFadeFrom(this, duration, warp); + } + /** + * Stops any fading which is applied to this action. + * + * @return {AnimationAction} A reference to this animation action. + */ + stopFading() { + const weightInterpolant = this._weightInterpolant; + if (weightInterpolant !== null) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant(weightInterpolant); + } + return this; + } + /** + * Sets the effective time scale of this action. + * + * An action has no effect and thus an effective time scale of zero when the + * action is paused. + * + * @param {number} timeScale - The time scale to set. + * @return {AnimationAction} A reference to this animation action. + */ + setEffectiveTimeScale(timeScale) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + return this.stopWarping(); + } + /** + * Returns the effective time scale of this action. + * + * @return {number} The effective time scale. + */ + getEffectiveTimeScale() { + return this._effectiveTimeScale; + } + /** + * Sets the duration for a single loop of this action. + * + * @param {number} duration - The duration to set. + * @return {AnimationAction} A reference to this animation action. + */ + setDuration(duration) { + this.timeScale = this._clip.duration / duration; + return this.stopWarping(); + } + /** + * Synchronizes this action with the passed other action. + * + * @param {AnimationAction} action - The action to sync with. + * @return {AnimationAction} A reference to this animation action. + */ + syncWith(action) { + this.time = action.time; + this.timeScale = action.timeScale; + return this.stopWarping(); + } + /** + * Decelerates this animation's speed to `0` within the passed time interval. + * + * @param {number} duration - The duration. + * @return {AnimationAction} A reference to this animation action. + */ + halt(duration) { + return this.warp(this._effectiveTimeScale, 0, duration); + } + /** + * Changes the playback speed, within the passed time interval, by modifying + * {@link AnimationAction#timeScale} gradually from `startTimeScale` to + * `endTimeScale`. + * + * @param {number} startTimeScale - The start time scale. + * @param {number} endTimeScale - The end time scale. + * @param {number} duration - The duration. + * @return {AnimationAction} A reference to this animation action. + */ + warp(startTimeScale, endTimeScale, duration) { + const mixer = this._mixer, now = mixer.time, timeScale = this.timeScale; + let interpolant = this._timeScaleInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + } + const times = interpolant.parameterPositions, values = interpolant.sampleValues; + times[0] = now; + times[1] = now + duration; + values[0] = startTimeScale / timeScale; + values[1] = endTimeScale / timeScale; + return this; + } + /** + * Stops any scheduled warping which is applied to this action. + * + * @return {AnimationAction} A reference to this animation action. + */ + stopWarping() { + const timeScaleInterpolant = this._timeScaleInterpolant; + if (timeScaleInterpolant !== null) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant(timeScaleInterpolant); + } + return this; + } + /** + * Returns the animation mixer of this animation action. + * + * @return {AnimationMixer} The animation mixer. + */ + getMixer() { + return this._mixer; + } + /** + * Returns the animation clip of this animation action. + * + * @return {AnimationClip} The animation clip. + */ + getClip() { + return this._clip; + } + /** + * Returns the root object of this animation action. + * + * @return {Object3D} The root object. + */ + getRoot() { + return this._localRoot || this._mixer._root; + } + // Internal + _update(time, deltaTime, timeDirection, accuIndex) { + if (!this.enabled) { + this._updateWeight(time); + return; + } + const startTime = this._startTime; + if (startTime !== null) { + const timeRunning = (time - startTime) * timeDirection; + if (timeRunning < 0 || timeDirection === 0) { + deltaTime = 0; + } else { + this._startTime = null; + deltaTime = timeDirection * timeRunning; + } + } + deltaTime *= this._updateTimeScale(time); + const clipTime = this._updateTime(deltaTime); + const weight = this._updateWeight(time); + if (weight > 0) { + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + switch (this.blendMode) { + case AdditiveAnimationBlendMode: + for (let j = 0, m = interpolants.length; j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulateAdditive(weight); + } + break; + case NormalAnimationBlendMode: + default: + for (let j = 0, m = interpolants.length; j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulate(accuIndex, weight); + } + } + } + } + _updateWeight(time) { + let weight = 0; + if (this.enabled) { + weight = this.weight; + const interpolant = this._weightInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time)[0]; + weight *= interpolantValue; + if (time > interpolant.parameterPositions[1]) { + this.stopFading(); + if (interpolantValue === 0) { + this.enabled = false; + } + } + } + } + this._effectiveWeight = weight; + return weight; + } + _updateTimeScale(time) { + let timeScale = 0; + if (!this.paused) { + timeScale = this.timeScale; + const interpolant = this._timeScaleInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time)[0]; + timeScale *= interpolantValue; + if (time > interpolant.parameterPositions[1]) { + this.stopWarping(); + if (timeScale === 0) { + this.paused = true; + } else { + this.timeScale = timeScale; + } + } + } + } + this._effectiveTimeScale = timeScale; + return timeScale; + } + _updateTime(deltaTime) { + const duration = this._clip.duration; + const loop = this.loop; + let time = this.time + deltaTime; + let loopCount = this._loopCount; + const pingPong = loop === LoopPingPong; + if (deltaTime === 0) { + if (loopCount === -1) return time; + return pingPong && (loopCount & 1) === 1 ? duration - time : time; + } + if (loop === LoopOnce) { + if (loopCount === -1) { + this._loopCount = 0; + this._setEndings(true, true, false); + } + handle_stop: { + if (time >= duration) { + time = duration; + } else if (time < 0) { + time = 0; + } else { + this.time = time; + break handle_stop; + } + if (this.clampWhenFinished) this.paused = true; + else this.enabled = false; + this.time = time; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime < 0 ? -1 : 1 + }); + } + } else { + if (loopCount === -1) { + if (deltaTime >= 0) { + loopCount = 0; + this._setEndings(true, this.repetitions === 0, pingPong); + } else { + this._setEndings(this.repetitions === 0, true, pingPong); + } + } + if (time >= duration || time < 0) { + const loopDelta = Math.floor(time / duration); + time -= duration * loopDelta; + loopCount += Math.abs(loopDelta); + const pending = this.repetitions - loopCount; + if (pending <= 0) { + if (this.clampWhenFinished) this.paused = true; + else this.enabled = false; + time = deltaTime > 0 ? duration : 0; + this.time = time; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime > 0 ? 1 : -1 + }); + } else { + if (pending === 1) { + const atStart = deltaTime < 0; + this._setEndings(atStart, !atStart, pingPong); + } else { + this._setEndings(false, false, pingPong); + } + this._loopCount = loopCount; + this.time = time; + this._mixer.dispatchEvent({ + type: "loop", + action: this, + loopDelta + }); + } + } else { + this._loopCount = loopCount; + this.time = time; + } + if (pingPong && (loopCount & 1) === 1) { + return duration - time; + } + } + return time; + } + _setEndings(atStart, atEnd, pingPong) { + const settings = this._interpolantSettings; + if (pingPong) { + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + } else { + if (atStart) { + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingStart = WrapAroundEnding; + } + if (atEnd) { + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingEnd = WrapAroundEnding; + } + } + } + _scheduleFading(duration, weightNow, weightThen) { + const mixer = this._mixer, now = mixer.time; + let interpolant = this._weightInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + } + const times = interpolant.parameterPositions, values = interpolant.sampleValues; + times[0] = now; + values[0] = weightNow; + times[1] = now + duration; + values[1] = weightThen; + return this; + } + } + const _controlInterpolantsResultBuffer = new Float32Array(1); + class AnimationMixer extends EventDispatcher { + /** + * Constructs a new animation mixer. + * + * @param {Object3D} root - The object whose animations shall be played by this mixer. + */ + constructor(root) { + super(); + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + _bindAction(action, prototypeAction) { + const root = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName; + let bindingsByName = bindingsByRoot[rootUuid]; + if (bindingsByName === void 0) { + bindingsByName = {}; + bindingsByRoot[rootUuid] = bindingsByName; + } + for (let i = 0; i !== nTracks; ++i) { + const track = tracks[i], trackName = track.name; + let binding = bindingsByName[trackName]; + if (binding !== void 0) { + ++binding.referenceCount; + bindings[i] = binding; + } else { + binding = bindings[i]; + if (binding !== void 0) { + if (binding._cacheIndex === null) { + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + } + continue; + } + const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; + binding = new PropertyMixer( + PropertyBinding.create(root, trackName, path), + track.ValueTypeName, + track.getValueSize() + ); + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + bindings[i] = binding; + } + interpolants[i].resultBuffer = binding.buffer; + } + } + _activateAction(action) { + if (!this._isActiveAction(action)) { + if (action._cacheIndex === null) { + const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; + this._bindAction( + action, + actionsForClip && actionsForClip.knownActions[0] + ); + this._addInactiveAction(action, clipUuid, rootUuid); + } + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length; i !== n; ++i) { + const binding = bindings[i]; + if (binding.useCount++ === 0) { + this._lendBinding(binding); + binding.saveOriginalState(); + } + } + this._lendAction(action); + } + } + _deactivateAction(action) { + if (this._isActiveAction(action)) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length; i !== n; ++i) { + const binding = bindings[i]; + if (--binding.useCount === 0) { + binding.restoreOriginalState(); + this._takeBackBinding(binding); + } + } + this._takeBackAction(action); + } + } + // Memory manager + _initMemoryManager() { + this._actions = []; + this._nActiveActions = 0; + this._actionsByClip = {}; + this._bindings = []; + this._nActiveBindings = 0; + this._bindingsByRootAndName = {}; + this._controlInterpolants = []; + this._nActiveControlInterpolants = 0; + const scope = this; + this.stats = { + actions: { + get total() { + return scope._actions.length; + }, + get inUse() { + return scope._nActiveActions; + } + }, + bindings: { + get total() { + return scope._bindings.length; + }, + get inUse() { + return scope._nActiveBindings; + } + }, + controlInterpolants: { + get total() { + return scope._controlInterpolants.length; + }, + get inUse() { + return scope._nActiveControlInterpolants; + } + } + }; + } + // Memory management for AnimationAction objects + _isActiveAction(action) { + const index = action._cacheIndex; + return index !== null && index < this._nActiveActions; + } + _addInactiveAction(action, clipUuid, rootUuid) { + const actions = this._actions, actionsByClip = this._actionsByClip; + let actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip === void 0) { + actionsForClip = { + knownActions: [action], + actionByRoot: {} + }; + action._byClipCacheIndex = 0; + actionsByClip[clipUuid] = actionsForClip; + } else { + const knownActions = actionsForClip.knownActions; + action._byClipCacheIndex = knownActions.length; + knownActions.push(action); + } + action._cacheIndex = actions.length; + actions.push(action); + actionsForClip.actionByRoot[rootUuid] = action; + } + _removeInactiveAction(action) { + const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + action._cacheIndex = null; + const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[byClipCacheIndex] = lastKnownAction; + knownActionsForClip.pop(); + action._byClipCacheIndex = null; + const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; + delete actionByRoot[rootUuid]; + if (knownActionsForClip.length === 0) { + delete actionsByClip[clipUuid]; + } + this._removeInactiveBindingsForAction(action); + } + _removeInactiveBindingsForAction(action) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length; i !== n; ++i) { + const binding = bindings[i]; + if (--binding.referenceCount === 0) { + this._removeInactiveBinding(binding); + } + } + } + _lendAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; + action._cacheIndex = lastActiveIndex; + actions[lastActiveIndex] = action; + firstInactiveAction._cacheIndex = prevIndex; + actions[prevIndex] = firstInactiveAction; + } + _takeBackAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; + action._cacheIndex = firstInactiveIndex; + actions[firstInactiveIndex] = action; + lastActiveAction._cacheIndex = prevIndex; + actions[prevIndex] = lastActiveAction; + } + // Memory management for PropertyMixer objects + _addInactiveBinding(binding, rootUuid, trackName) { + const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; + let bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName === void 0) { + bindingByName = {}; + bindingsByRoot[rootUuid] = bindingByName; + } + bindingByName[trackName] = binding; + binding._cacheIndex = bindings.length; + bindings.push(binding); + } + _removeInactiveBinding(binding) { + const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[cacheIndex] = lastInactiveBinding; + bindings.pop(); + delete bindingByName[trackName]; + if (Object.keys(bindingByName).length === 0) { + delete bindingsByRoot[rootUuid]; + } + } + _lendBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; + binding._cacheIndex = lastActiveIndex; + bindings[lastActiveIndex] = binding; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = firstInactiveBinding; + } + _takeBackBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; + binding._cacheIndex = firstInactiveIndex; + bindings[firstInactiveIndex] = binding; + lastActiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = lastActiveBinding; + } + // Memory management of Interpolants for weight and time scale + _lendControlInterpolant() { + const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; + let interpolant = interpolants[lastActiveIndex]; + if (interpolant === void 0) { + interpolant = new LinearInterpolant( + new Float32Array(2), + new Float32Array(2), + 1, + _controlInterpolantsResultBuffer + ); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[lastActiveIndex] = interpolant; + } + return interpolant; + } + _takeBackControlInterpolant(interpolant) { + const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[firstInactiveIndex] = interpolant; + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[prevIndex] = lastActiveInterpolant; + } + /** + * Returns an instance of {@link AnimationAction} for the passed clip. + * + * If an action fitting the clip and root parameters doesn't yet exist, it + * will be created by this method. Calling this method several times with the + * same clip and root parameters always returns the same action. + * + * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip. + * @param {Object3D} [optionalRoot] - An alternative root object. + * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode. + * @return {?AnimationAction} The animation action. + */ + clipAction(clip, optionalRoot, blendMode) { + const root = optionalRoot || this._root, rootUuid = root.uuid; + let clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip; + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + const actionsForClip = this._actionsByClip[clipUuid]; + let prototypeAction = null; + if (blendMode === void 0) { + if (clipObject !== null) { + blendMode = clipObject.blendMode; + } else { + blendMode = NormalAnimationBlendMode; + } + } + if (actionsForClip !== void 0) { + const existingAction = actionsForClip.actionByRoot[rootUuid]; + if (existingAction !== void 0 && existingAction.blendMode === blendMode) { + return existingAction; + } + prototypeAction = actionsForClip.knownActions[0]; + if (clipObject === null) + clipObject = prototypeAction._clip; + } + if (clipObject === null) return null; + const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode); + this._bindAction(newAction, prototypeAction); + this._addInactiveAction(newAction, clipUuid, rootUuid); + return newAction; + } + /** + * Returns an existing animation action for the passed clip. + * + * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip. + * @param {Object3D} [optionalRoot] - An alternative root object. + * @return {?AnimationAction} The animation action. Returns `null` if no action was found. + */ + existingAction(clip, optionalRoot) { + const root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; + if (actionsForClip !== void 0) { + return actionsForClip.actionByRoot[rootUuid] || null; + } + return null; + } + /** + * Deactivates all previously scheduled actions on this mixer. + * + * @return {AnimationMixer} A reference to this animation mixer. + */ + stopAllAction() { + const actions = this._actions, nActions = this._nActiveActions; + for (let i = nActions - 1; i >= 0; --i) { + actions[i].stop(); + } + return this; + } + /** + * Advances the global mixer time and updates the animation. + * + * This is usually done in the render loop by passing the delta + * time from {@link Clock} or {@link Timer}. + * + * @param {number} deltaTime - The delta time in seconds. + * @return {AnimationMixer} A reference to this animation mixer. + */ + update(deltaTime) { + deltaTime *= this.timeScale; + const actions = this._actions, nActions = this._nActiveActions, time = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; + for (let i = 0; i !== nActions; ++i) { + const action = actions[i]; + action._update(time, deltaTime, timeDirection, accuIndex); + } + const bindings = this._bindings, nBindings = this._nActiveBindings; + for (let i = 0; i !== nBindings; ++i) { + bindings[i].apply(accuIndex); + } + return this; + } + /** + * Sets the global mixer to a specific time and updates the animation accordingly. + * + * This is useful when you need to jump to an exact time in an animation. The + * input parameter will be scaled by {@link AnimationMixer#timeScale} + * + * @param {number} time - The time to set in seconds. + * @return {AnimationMixer} A reference to this animation mixer. + */ + setTime(time) { + this.time = 0; + for (let i = 0; i < this._actions.length; i++) { + this._actions[i].time = 0; + } + return this.update(time); + } + /** + * Returns this mixer's root object. + * + * @return {Object3D} The mixer's root object. + */ + getRoot() { + return this._root; + } + /** + * Deallocates all memory resources for a clip. Before using this method make + * sure to call {@link AnimationAction#stop} for all related actions. + * + * @param {AnimationClip} clip - The clip to uncache. + */ + uncacheClip(clip) { + const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip !== void 0) { + const actionsToRemove = actionsForClip.knownActions; + for (let i = 0, n = actionsToRemove.length; i !== n; ++i) { + const action = actionsToRemove[i]; + this._deactivateAction(action); + const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; + action._cacheIndex = null; + action._byClipCacheIndex = null; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + this._removeInactiveBindingsForAction(action); + } + delete actionsByClip[clipUuid]; + } + } + /** + * Deallocates all memory resources for a root object. Before using this + * method make sure to call {@link AnimationAction#stop} for all related + * actions or alternatively {@link AnimationMixer#stopAllAction} when the + * mixer operates on a single root. + * + * @param {Object3D} root - The root object to uncache. + */ + uncacheRoot(root) { + const rootUuid = root.uuid, actionsByClip = this._actionsByClip; + for (const clipUuid in actionsByClip) { + const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; + if (action !== void 0) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName !== void 0) { + for (const trackName in bindingByName) { + const binding = bindingByName[trackName]; + binding.restoreOriginalState(); + this._removeInactiveBinding(binding); + } + } + } + /** + * Deallocates all memory resources for an action. The action is identified by the + * given clip and an optional root object. Before using this method make + * sure to call {@link AnimationAction#stop} to deactivate the action. + * + * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip. + * @param {Object3D} [optionalRoot] - An alternative root object. + */ + uncacheAction(clip, optionalRoot) { + const action = this.existingAction(clip, optionalRoot); + if (action !== null) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + } + class RenderTarget3D extends RenderTarget { + /** + * Constructs a new 3D render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {number} [depth=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(width = 1, height = 1, depth = 1, options = {}) { + super(width, height, options); + this.isRenderTarget3D = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width, height, depth); + this._setTextureOptions(options); + this.texture.isRenderTargetTexture = true; + } + } + class Uniform { + /** + * Constructs a new uniform. + * + * @param {any} value - The uniform value. + */ + constructor(value) { + this.value = value; + } + /** + * Returns a new uniform with copied values from this instance. + * If the value has a `clone()` method, the value is cloned as well. + * + * @return {Uniform} A clone of this instance. + */ + clone() { + return new Uniform(this.value.clone === void 0 ? this.value : this.value.clone()); + } + } + let _id$1 = 0; + class UniformsGroup extends EventDispatcher { + /** + * Constructs a new uniforms group. + */ + constructor() { + super(); + this.isUniformsGroup = true; + Object.defineProperty(this, "id", { value: _id$1++ }); + this.name = ""; + this.usage = StaticDrawUsage; + this.uniforms = []; + } + /** + * Adds the given uniform to this uniforms group. + * + * @param {Uniform} uniform - The uniform to add. + * @return {UniformsGroup} A reference to this uniforms group. + */ + add(uniform) { + this.uniforms.push(uniform); + return this; + } + /** + * Removes the given uniform from this uniforms group. + * + * @param {Uniform} uniform - The uniform to remove. + * @return {UniformsGroup} A reference to this uniforms group. + */ + remove(uniform) { + const index = this.uniforms.indexOf(uniform); + if (index !== -1) this.uniforms.splice(index, 1); + return this; + } + /** + * Sets the name of this uniforms group. + * + * @param {string} name - The name to set. + * @return {UniformsGroup} A reference to this uniforms group. + */ + setName(name) { + this.name = name; + return this; + } + /** + * Sets the usage of this uniforms group. + * + * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. + * @return {UniformsGroup} A reference to this uniforms group. + */ + setUsage(value) { + this.usage = value; + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires Texture#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + /** + * Copies the values of the given uniforms group to this instance. + * + * @param {UniformsGroup} source - The uniforms group to copy. + * @return {UniformsGroup} A reference to this uniforms group. + */ + copy(source) { + this.name = source.name; + this.usage = source.usage; + const uniformsSource = source.uniforms; + this.uniforms.length = 0; + for (let i = 0, l = uniformsSource.length; i < l; i++) { + const uniforms = Array.isArray(uniformsSource[i]) ? uniformsSource[i] : [uniformsSource[i]]; + for (let j = 0; j < uniforms.length; j++) { + this.uniforms.push(uniforms[j].clone()); + } + } + return this; + } + /** + * Returns a new uniforms group with copied values from this instance. + * + * @return {UniformsGroup} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + } + class InstancedInterleavedBuffer extends InterleavedBuffer { + /** + * Constructs a new instanced interleaved buffer. + * + * @param {TypedArray} array - A typed array with a shared buffer storing attribute data. + * @param {number} stride - The number of typed-array elements per vertex. + * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated. + */ + constructor(array, stride, meshPerAttribute = 1) { + super(array, stride); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + clone(data) { + const ib = super.clone(data); + ib.meshPerAttribute = this.meshPerAttribute; + return ib; + } + toJSON(data) { + const json = super.toJSON(data); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + return json; + } + } + class GLBufferAttribute { + /** + * Constructs a new GL buffer attribute. + * + * @param {WebGLBuffer} buffer - The native WebGL buffer. + * @param {number} type - The native data type (e.g. `gl.FLOAT`). + * @param {number} itemSize - The item size. + * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter. + * @param {number} count - The expected number of vertices in VBO. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(buffer, type, itemSize, elementSize, count, normalized = false) { + this.isGLBufferAttribute = true; + this.name = ""; + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + this.normalized = normalized; + this.version = 0; + } + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) this.version++; + } + /** + * Sets the given native WebGL buffer. + * + * @param {WebGLBuffer} buffer - The buffer to set. + * @return {BufferAttribute} A reference to this instance. + */ + setBuffer(buffer) { + this.buffer = buffer; + return this; + } + /** + * Sets the given native data type and element size. + * + * @param {number} type - The native data type (e.g. `gl.FLOAT`). + * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter. + * @return {BufferAttribute} A reference to this instance. + */ + setType(type, elementSize) { + this.type = type; + this.elementSize = elementSize; + return this; + } + /** + * Sets the item size. + * + * @param {number} itemSize - The item size. + * @return {BufferAttribute} A reference to this instance. + */ + setItemSize(itemSize) { + this.itemSize = itemSize; + return this; + } + /** + * Sets the count (the expected number of vertices in VBO). + * + * @param {number} count - The count. + * @return {BufferAttribute} A reference to this instance. + */ + setCount(count) { + this.count = count; + return this; + } + } + const _matrix = /* @__PURE__ */ new Matrix4(); + class Raycaster { + /** + * Constructs a new raycaster. + * + * @param {Vector3} origin - The origin vector where the ray casts from. + * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray. + * @param {number} [near=0] - All results returned are further away than near. Near can't be negative. + * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near. + */ + constructor(origin, direction, near = 0, far = Infinity) { + this.ray = new Ray(origin, direction); + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers(); + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + } + /** + * Updates the ray with a new origin and direction by copying the values from the arguments. + * + * @param {Vector3} origin - The origin vector where the ray casts from. + * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray. + */ + set(origin, direction) { + this.ray.set(origin, direction); + } + /** + * Uses the given coordinates and camera to compute a new origin and direction for the internal ray. + * + * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC). + * X and Y components should be between `-1` and `1`. + * @param {Camera} camera - The camera from which the ray should originate. + */ + setFromCamera(coords, camera) { + if (camera.isPerspectiveCamera) { + this.ray.origin.setFromMatrixPosition(camera.matrixWorld); + this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); + this.camera = camera; + } else if (camera.isOrthographicCamera) { + this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); + this.camera = camera; + } else { + error("Raycaster: Unsupported camera type: " + camera.type); + } + } + /** + * Uses the given WebXR controller to compute a new origin and direction for the internal ray. + * + * @param {WebXRController} controller - The controller to copy the position and direction from. + * @return {Raycaster} A reference to this raycaster. + */ + setFromXRController(controller) { + _matrix.identity().extractRotation(controller.matrixWorld); + this.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.ray.direction.set(0, 0, -1).applyMatrix4(_matrix); + return this; + } + /** + * The intersection point of a raycaster intersection test. + * @typedef {Object} Raycaster~Intersection + * @property {number} distance - The distance from the ray's origin to the intersection point. + * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the + * intersection to the nearest point on the ray. For other objects it will be `undefined`. + * @property {Vector3} point - The intersection point, in world coordinates. + * @property {Object} face - The face that has been intersected. + * @property {number} faceIndex - The face index. + * @property {Object3D} object - The 3D object that has been intersected. + * @property {Vector2} uv - U,V coordinates at point of intersection. + * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection. + * @property {Vector3} normal - Interpolated normal vector at point of intersection. + * @property {number} instanceId - The index number of the instance where the ray + * intersects the {@link InstancedMesh}. + */ + /** + * Checks all intersection between the ray and the object with or without the + * descendants. Intersections are returned sorted by distance, closest first. + * + * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when + * evaluating whether the ray intersects the object or not. This allows meshes to respond + * differently to ray casting than lines or points. + * + * Note that for meshes, faces must be pointed towards the origin of the ray in order + * to be detected; intersections of the ray passing through the back of a face will not + * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side} + * to `THREE.DoubleSide`. + * + * @param {Object3D} object - The 3D object to check for intersection with the ray. + * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants. + * Otherwise it only checks intersection with the object. + * @param {Array} [intersects=[]] The target array that holds the result of the method. + * @return {Array} An array holding the intersection points. + */ + intersectObject(object, recursive = true, intersects2 = []) { + intersect(object, this, intersects2, recursive); + intersects2.sort(ascSort); + return intersects2; + } + /** + * Checks all intersection between the ray and the objects with or without + * the descendants. Intersections are returned sorted by distance, closest first. + * + * @param {Array} objects - The 3D objects to check for intersection with the ray. + * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants. + * Otherwise it only checks intersection with the object. + * @param {Array} [intersects=[]] The target array that holds the result of the method. + * @return {Array} An array holding the intersection points. + */ + intersectObjects(objects, recursive = true, intersects2 = []) { + for (let i = 0, l = objects.length; i < l; i++) { + intersect(objects[i], this, intersects2, recursive); + } + intersects2.sort(ascSort); + return intersects2; + } + } + function ascSort(a, b) { + return a.distance - b.distance; + } + function intersect(object, raycaster, intersects2, recursive) { + let propagate = true; + if (object.layers.test(raycaster.layers)) { + const result = object.raycast(raycaster, intersects2); + if (result === false) propagate = false; + } + if (propagate === true && recursive === true) { + const children = object.children; + for (let i = 0, l = children.length; i < l; i++) { + intersect(children[i], raycaster, intersects2, true); + } + } + } + class Clock { + /** + * Constructs a new clock. + * + * @deprecated since 183. + * @param {boolean} [autoStart=true] - Whether to automatically start the clock when + * `getDelta()` is called for the first time. + */ + constructor(autoStart = true) { + this.autoStart = autoStart; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + this.running = false; + warn("Clock: This module has been deprecated. Please use THREE.Timer instead."); + } + /** + * Starts the clock. When `autoStart` is set to `true`, the method is automatically + * called by the class. + */ + start() { + this.startTime = performance.now(); + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } + /** + * Stops the clock. + */ + stop() { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } + /** + * Returns the elapsed time in seconds. + * + * @return {number} The elapsed time. + */ + getElapsedTime() { + this.getDelta(); + return this.elapsedTime; + } + /** + * Returns the delta time in seconds. + * + * @return {number} The delta time. + */ + getDelta() { + let diff = 0; + if (this.autoStart && !this.running) { + this.start(); + return 0; + } + if (this.running) { + const newTime = performance.now(); + diff = (newTime - this.oldTime) / 1e3; + this.oldTime = newTime; + this.elapsedTime += diff; + } + return diff; + } + } + class Spherical { + /** + * Constructs a new spherical. + * + * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin. + * @param {number} [phi=0] - The polar angle in radians from the y (up) axis. + * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis. + */ + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + } + /** + * Sets the spherical components by copying the given values. + * + * @param {number} radius - The radius. + * @param {number} phi - The polar angle. + * @param {number} theta - The azimuthal angle. + * @return {Spherical} A reference to this spherical. + */ + set(radius, phi, theta) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + /** + * Copies the values of the given spherical to this instance. + * + * @param {Spherical} other - The spherical to copy. + * @return {Spherical} A reference to this spherical. + */ + copy(other) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + return this; + } + /** + * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi - + * `0.000001`. + * + * @return {Spherical} A reference to this spherical. + */ + makeSafe() { + const EPS = 1e-6; + this.phi = clamp(this.phi, EPS, Math.PI - EPS); + return this; + } + /** + * Sets the spherical components from the given vector which is assumed to hold + * Cartesian coordinates. + * + * @param {Vector3} v - The vector to set. + * @return {Spherical} A reference to this spherical. + */ + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + /** + * Sets the spherical components from the given Cartesian coordinates. + * + * @param {number} x - The x value. + * @param {number} y - The y value. + * @param {number} z - The z value. + * @return {Spherical} A reference to this spherical. + */ + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + y * y + z * z); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x, z); + this.phi = Math.acos(clamp(y / this.radius, -1, 1)); + } + return this; + } + /** + * Returns a new spherical with copied values from this instance. + * + * @return {Spherical} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + } + class Cylindrical { + /** + * Constructs a new cylindrical. + * + * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane. + * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis. + * @param {number} [y=0] - The height above the x-z plane. + */ + constructor(radius = 1, theta = 0, y = 0) { + this.radius = radius; + this.theta = theta; + this.y = y; + } + /** + * Sets the cylindrical components by copying the given values. + * + * @param {number} radius - The radius. + * @param {number} theta - The theta angle. + * @param {number} y - The height value. + * @return {Cylindrical} A reference to this cylindrical. + */ + set(radius, theta, y) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + /** + * Copies the values of the given cylindrical to this instance. + * + * @param {Cylindrical} other - The cylindrical to copy. + * @return {Cylindrical} A reference to this cylindrical. + */ + copy(other) { + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + return this; + } + /** + * Sets the cylindrical components from the given vector which is assumed to hold + * Cartesian coordinates. + * + * @param {Vector3} v - The vector to set. + * @return {Cylindrical} A reference to this cylindrical. + */ + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + /** + * Sets the cylindrical components from the given Cartesian coordinates. + * + * @param {number} x - The x value. + * @param {number} y - The x value. + * @param {number} z - The x value. + * @return {Cylindrical} A reference to this cylindrical. + */ + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + z * z); + this.theta = Math.atan2(x, z); + this.y = y; + return this; + } + /** + * Returns a new cylindrical with copied values from this instance. + * + * @return {Cylindrical} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + } + const _Matrix2 = class _Matrix2 { + /** + * Constructs a new 2x2 matrix. The arguments are supposed to be + * in row-major order. If no arguments are provided, the constructor + * initializes the matrix as an identity matrix. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + */ + constructor(n11, n12, n21, n22) { + this.elements = [ + 1, + 0, + 0, + 1 + ]; + if (n11 !== void 0) { + this.set(n11, n12, n21, n22); + } + } + /** + * Sets this matrix to the 2x2 identity matrix. + * + * @return {Matrix2} A reference to this matrix. + */ + identity() { + this.set( + 1, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} array - The matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Matrix2} A reference to this matrix. + */ + fromArray(array, offset = 0) { + for (let i = 0; i < 4; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + /** + * Sets the elements of the matrix.The arguments are supposed to be + * in row-major order. + * + * @param {number} n11 - 1-1 matrix element. + * @param {number} n12 - 1-2 matrix element. + * @param {number} n21 - 2-1 matrix element. + * @param {number} n22 - 2-2 matrix element. + * @return {Matrix2} A reference to this matrix. + */ + set(n11, n12, n21, n22) { + const te = this.elements; + te[0] = n11; + te[2] = n12; + te[1] = n21; + te[3] = n22; + return this; + } + }; + _Matrix2.prototype.isMatrix2 = true; + let Matrix2 = _Matrix2; + const _vector$4 = /* @__PURE__ */ new Vector2(); + class Box2 { + /** + * Constructs a new bounding box. + * + * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box. + * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box. + */ + constructor(min = new Vector2(Infinity, Infinity), max = new Vector2(-Infinity, -Infinity)) { + this.isBox2 = true; + this.min = min; + this.max = max; + } + /** + * Sets the lower and upper boundaries of this box. + * Please note that this method only copies the values from the given objects. + * + * @param {Vector2} min - The lower boundary of the box. + * @param {Vector2} max - The upper boundary of the box. + * @return {Box2} A reference to this bounding box. + */ + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} points - An array holding 2D position data as instances of {@link Vector2}. + * @return {Box2} A reference to this bounding box. + */ + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length; i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + /** + * Centers this box on the given center vector and sets this box's width, height and + * depth to the given size values. + * + * @param {Vector2} center - The center of the box. + * @param {Vector2} size - The x and y dimensions of the box. + * @return {Box2} A reference to this bounding box. + */ + setFromCenterAndSize(center, size) { + const halfSize = _vector$4.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + /** + * Returns a new box with copied values from this instance. + * + * @return {Box2} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given box to this instance. + * + * @param {Box2} box - The box to copy. + * @return {Box2} A reference to this bounding box. + */ + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + /** + * Makes this box empty which means in encloses a zero space in 2D. + * + * @return {Box2} A reference to this bounding box. + */ + makeEmpty() { + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = -Infinity; + return this; + } + /** + * Returns true if this box includes zero points within its bounds. + * Note that a box with equal lower and upper bounds still includes one + * point, the one both bounds share. + * + * @return {boolean} Whether this box is empty or not. + */ + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + /** + * Returns the center point of this box. + * + * @param {Vector2} target - The target vector that is used to store the method's result. + * @return {Vector2} The center point. + */ + getCenter(target) { + return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + /** + * Returns the dimensions of this box. + * + * @param {Vector2} target - The target vector that is used to store the method's result. + * @return {Vector2} The size. + */ + getSize(target) { + return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); + } + /** + * Expands the boundaries of this box to include the given point. + * + * @param {Vector2} point - The point that should be included by the bounding box. + * @return {Box2} A reference to this bounding box. + */ + expandByPoint(point2) { + this.min.min(point2); + this.max.max(point2); + return this; + } + /** + * Expands this box equilaterally by the given vector. The width of this + * box will be expanded by the x component of the vector in both + * directions. The height of this box will be expanded by the y component of + * the vector in both directions. + * + * @param {Vector2} vector - The vector that should expand the bounding box. + * @return {Box2} A reference to this bounding box. + */ + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + /** + * Expands each dimension of the box by the given scalar. If negative, the + * dimensions of the box will be contracted. + * + * @param {number} scalar - The scalar value that should expand the bounding box. + * @return {Box2} A reference to this bounding box. + */ + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + /** + * Returns `true` if the given point lies within or on the boundaries of this box. + * + * @param {Vector2} point - The point to test. + * @return {boolean} Whether the bounding box contains the given point or not. + */ + containsPoint(point2) { + return point2.x >= this.min.x && point2.x <= this.max.x && point2.y >= this.min.y && point2.y <= this.max.y; + } + /** + * Returns `true` if this bounding box includes the entirety of the given bounding box. + * If this box and the given one are identical, this function also returns `true`. + * + * @param {Box2} box - The bounding box to test. + * @return {boolean} Whether the bounding box contains the given bounding box or not. + */ + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + /** + * Returns a point as a proportion of this box's width and height. + * + * @param {Vector2} point - A point in 2D space. + * @param {Vector2} target - The target vector that is used to store the method's result. + * @return {Vector2} A point as a proportion of this box's width and height. + */ + getParameter(point2, target) { + return target.set( + (point2.x - this.min.x) / (this.max.x - this.min.x), + (point2.y - this.min.y) / (this.max.y - this.min.y) + ); + } + /** + * Returns `true` if the given bounding box intersects with this bounding box. + * + * @param {Box2} box - The bounding box to test. + * @return {boolean} Whether the given bounding box intersects with this bounding box. + */ + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y; + } + /** + * Clamps the given point within the bounds of this box. + * + * @param {Vector2} point - The point to clamp. + * @param {Vector2} target - The target vector that is used to store the method's result. + * @return {Vector2} The clamped point. + */ + clampPoint(point2, target) { + return target.copy(point2).clamp(this.min, this.max); + } + /** + * Returns the euclidean distance from any edge of this box to the specified point. If + * the given point lies inside of this box, the distance will be `0`. + * + * @param {Vector2} point - The point to compute the distance to. + * @return {number} The euclidean distance. + */ + distanceToPoint(point2) { + return this.clampPoint(point2, _vector$4).distanceTo(point2); + } + /** + * Computes the intersection of this bounding box and the given one, setting the upper + * bound of this box to the lesser of the two boxes' upper bounds and the + * lower bound of this box to the greater of the two boxes' lower bounds. If + * there's no overlap, makes this box empty. + * + * @param {Box2} box - The bounding box to intersect with. + * @return {Box2} A reference to this bounding box. + */ + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) this.makeEmpty(); + return this; + } + /** + * Computes the union of this box and another and the given one, setting the upper + * bound of this box to the greater of the two boxes' upper bounds and the + * lower bound of this box to the lesser of the two boxes' lower bounds. + * + * @param {Box2} box - The bounding box that will be unioned with this instance. + * @return {Box2} A reference to this bounding box. + */ + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + /** + * Adds the given offset to both the upper and lower bounds of this bounding box, + * effectively moving it in 2D space. + * + * @param {Vector2} offset - The offset that should be used to translate the bounding box. + * @return {Box2} A reference to this bounding box. + */ + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + /** + * Returns `true` if this bounding box is equal with the given one. + * + * @param {Box2} box - The box to test for equality. + * @return {boolean} Whether this bounding box is equal with the given one. + */ + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + } + const _startP = /* @__PURE__ */ new Vector3(); + const _startEnd = /* @__PURE__ */ new Vector3(); + const _d1 = /* @__PURE__ */ new Vector3(); + const _d2 = /* @__PURE__ */ new Vector3(); + const _r = /* @__PURE__ */ new Vector3(); + const _c1 = /* @__PURE__ */ new Vector3(); + const _c2 = /* @__PURE__ */ new Vector3(); + class Line3 { + /** + * Constructs a new line segment. + * + * @param {Vector3} [start=(0,0,0)] - Start of the line segment. + * @param {Vector3} [end=(0,0,0)] - End of the line segment. + */ + constructor(start = new Vector3(), end = new Vector3()) { + this.start = start; + this.end = end; + } + /** + * Sets the start and end values by copying the given vectors. + * + * @param {Vector3} start - The start point. + * @param {Vector3} end - The end point. + * @return {Line3} A reference to this line segment. + */ + set(start, end) { + this.start.copy(start); + this.end.copy(end); + return this; + } + /** + * Copies the values of the given line segment to this instance. + * + * @param {Line3} line - The line segment to copy. + * @return {Line3} A reference to this line segment. + */ + copy(line) { + this.start.copy(line.start); + this.end.copy(line.end); + return this; + } + /** + * Returns the center of the line segment. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The center point. + */ + getCenter(target) { + return target.addVectors(this.start, this.end).multiplyScalar(0.5); + } + /** + * Returns the delta vector of the line segment's start and end point. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The delta vector. + */ + delta(target) { + return target.subVectors(this.end, this.start); + } + /** + * Returns the squared Euclidean distance between the line' start and end point. + * + * @return {number} The squared Euclidean distance. + */ + distanceSq() { + return this.start.distanceToSquared(this.end); + } + /** + * Returns the Euclidean distance between the line' start and end point. + * + * @return {number} The Euclidean distance. + */ + distance() { + return this.start.distanceTo(this.end); + } + /** + * Returns a vector at a certain position along the line segment. + * + * @param {number} t - A value between `[0,1]` to represent a position along the line segment. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The delta vector. + */ + at(t, target) { + return this.delta(target).multiplyScalar(t).add(this.start); + } + /** + * Returns a point parameter based on the closest point as projected on the line segment. + * + * @param {Vector3} point - The point for which to return a point parameter. + * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not. + * @return {number} The point parameter. + */ + closestPointToPointParameter(point2, clampToLine) { + _startP.subVectors(point2, this.start); + _startEnd.subVectors(this.end, this.start); + const startEnd2 = _startEnd.dot(_startEnd); + if (startEnd2 === 0) return 0; + const startEnd_startP = _startEnd.dot(_startP); + let t = startEnd_startP / startEnd2; + if (clampToLine) { + t = clamp(t, 0, 1); + } + return t; + } + /** + * Returns the closest point on the line for a given point. + * + * @param {Vector3} point - The point to compute the closest point on the line for. + * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The closest point on the line. + */ + closestPointToPoint(point2, clampToLine, target) { + const t = this.closestPointToPointParameter(point2, clampToLine); + return this.delta(target).multiplyScalar(t).add(this.start); + } + /** + * Returns the closest squared distance between this line segment and the given one. + * + * @param {Line3} line - The line segment to compute the closest squared distance to. + * @param {Vector3} [c1] - The closest point on this line segment. + * @param {Vector3} [c2] - The closest point on the given line segment. + * @return {number} The squared distance between this line segment and the given one. + */ + distanceSqToLine3(line, c1 = _c1, c2 = _c2) { + const EPSILON = 1e-8 * 1e-8; + let s, t; + const p1 = this.start; + const p2 = line.start; + const q1 = this.end; + const q2 = line.end; + _d1.subVectors(q1, p1); + _d2.subVectors(q2, p2); + _r.subVectors(p1, p2); + const a = _d1.dot(_d1); + const e = _d2.dot(_d2); + const f = _d2.dot(_r); + if (a <= EPSILON && e <= EPSILON) { + c1.copy(p1); + c2.copy(p2); + c1.sub(c2); + return c1.dot(c1); + } + if (a <= EPSILON) { + s = 0; + t = f / e; + t = clamp(t, 0, 1); + } else { + const c = _d1.dot(_r); + if (e <= EPSILON) { + t = 0; + s = clamp(-c / a, 0, 1); + } else { + const b = _d1.dot(_d2); + const denom = a * e - b * b; + if (denom !== 0) { + s = clamp((b * f - c * e) / denom, 0, 1); + } else { + s = 0; + } + t = (b * s + f) / e; + if (t < 0) { + t = 0; + s = clamp(-c / a, 0, 1); + } else if (t > 1) { + t = 1; + s = clamp((b - c) / a, 0, 1); + } + } + } + c1.copy(p1).addScaledVector(_d1, s); + c2.copy(p2).addScaledVector(_d2, t); + return c1.distanceToSquared(c2); + } + /** + * Applies a 4x4 transformation matrix to this line segment. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Line3} A reference to this line segment. + */ + applyMatrix4(matrix) { + this.start.applyMatrix4(matrix); + this.end.applyMatrix4(matrix); + return this; + } + /** + * Returns `true` if this line segment is equal with the given one. + * + * @param {Line3} line - The line segment to test for equality. + * @return {boolean} Whether this line segment is equal with the given one. + */ + equals(line) { + return line.start.equals(this.start) && line.end.equals(this.end); + } + /** + * Returns a new line segment with copied values from this instance. + * + * @return {Line3} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + } + const _vector$3 = /* @__PURE__ */ new Vector3(); + class SpotLightHelper extends Object3D { + /** + * Constructs a new spot light helper. + * + * @param {HemisphereLight} light - The light to be visualized. + * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take + * the color of the light. + */ + constructor(light, color) { + super(); + this.light = light; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "SpotLightHelper"; + const geometry = new BufferGeometry(); + const positions = [ + 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 (let i = 0, j = 1, l = 32; i < l; i++, j++) { + const p1 = i / l * Math.PI * 2; + const p2 = j / l * Math.PI * 2; + positions.push( + Math.cos(p1), + Math.sin(p1), + 1, + Math.cos(p2), + Math.sin(p2), + 1 + ); + } + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.cone = new LineSegments(geometry, material); + this.add(this.cone); + this.update(); + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + /** + * Updates the helper to match the position and direction of the + * light being visualized. + */ + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + if (this.parent) { + this.parent.updateWorldMatrix(true); + this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld); + } else { + this.matrix.copy(this.light.matrixWorld); + } + this.matrixWorld.copy(this.light.matrixWorld); + const coneLength = this.light.distance ? this.light.distance : 1e3; + const coneWidth = coneLength * Math.tan(this.light.angle); + this.cone.scale.set(coneWidth, coneWidth, coneLength); + _vector$3.setFromMatrixPosition(this.light.target.matrixWorld); + this.cone.lookAt(_vector$3); + if (this.color !== void 0) { + this.cone.material.color.set(this.color); + } else { + this.cone.material.color.copy(this.light.color); + } + } + } + const _vector$2 = /* @__PURE__ */ new Vector3(); + const _boneMatrix = /* @__PURE__ */ new Matrix4(); + const _matrixWorldInv = /* @__PURE__ */ new Matrix4(); + class SkeletonHelper extends LineSegments { + /** + * Constructs a new skeleton helper. + * + * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object + * can be used if it represents a hierarchy of bones (see {@link Bone}). + */ + constructor(object) { + const bones = getBoneList(object); + const geometry = new BufferGeometry(); + const vertices = []; + const colors = []; + for (let i = 0; i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + vertices.push(0, 0, 0); + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + colors.push(0, 0, 0); + } + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true }); + super(geometry, material); + this.isSkeletonHelper = true; + this.type = "SkeletonHelper"; + this.root = object; + this.bones = bones; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + const color1 = new Color(255); + const color2 = new Color(65280); + this.setColors(color1, color2); + } + updateMatrixWorld(force) { + const bones = this.bones; + const geometry = this.geometry; + const position = geometry.getAttribute("position"); + _matrixWorldInv.copy(this.root.matrixWorld).invert(); + for (let i = 0, j = 0; i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z); + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z); + j += 2; + } + } + geometry.getAttribute("position").needsUpdate = true; + super.updateMatrixWorld(force); + } + /** + * Defines the colors of the helper. + * + * @param {Color} color1 - The first line color for each bone. + * @param {Color} color2 - The second line color for each bone. + * @return {SkeletonHelper} A reference to this helper. + */ + setColors(color1, color2) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + for (let i = 0; i < colorAttribute.count; i += 2) { + colorAttribute.setXYZ(i, color1.r, color1.g, color1.b); + colorAttribute.setXYZ(i + 1, color2.r, color2.g, color2.b); + } + colorAttribute.needsUpdate = true; + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + function getBoneList(object) { + const boneList = []; + if (object.isBone === true) { + boneList.push(object); + } + for (let i = 0; i < object.children.length; i++) { + boneList.push(...getBoneList(object.children[i])); + } + return boneList; + } + class PointLightHelper extends Mesh { + /** + * Constructs a new point light helper. + * + * @param {PointLight} light - The light to be visualized. + * @param {number} [sphereSize=1] - The size of the sphere helper. + * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take + * the color of the light. + */ + constructor(light, sphereSize, color) { + const geometry = new SphereGeometry(sphereSize, 4, 2); + const material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + super(geometry, material); + this.light = light; + this.color = color; + this.type = "PointLightHelper"; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + this.update(); + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + /** + * Updates the helper to match the position of the + * light being visualized. + */ + update() { + this.light.updateWorldMatrix(true, false); + if (this.color !== void 0) { + this.material.color.set(this.color); + } else { + this.material.color.copy(this.light.color); + } + } + } + const _vector$1 = /* @__PURE__ */ new Vector3(); + const _color1 = /* @__PURE__ */ new Color(); + const _color2 = /* @__PURE__ */ new Color(); + class HemisphereLightHelper extends Object3D { + /** + * Constructs a new hemisphere light helper. + * + * @param {HemisphereLight} light - The light to be visualized. + * @param {number} [size=1] - The size of the mesh used to visualize the light. + * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take + * the color of the light. + */ + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "HemisphereLightHelper"; + const geometry = new OctahedronGeometry(size); + geometry.rotateY(Math.PI * 0.5); + this.material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + if (this.color === void 0) this.material.vertexColors = true; + const position = geometry.getAttribute("position"); + const colors = new Float32Array(position.count * 3); + geometry.setAttribute("color", new BufferAttribute(colors, 3)); + this.add(new Mesh(geometry, this.material)); + this.update(); + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + /** + * Updates the helper to match the position and direction of the + * light being visualized. + */ + update() { + const mesh = this.children[0]; + if (this.color !== void 0) { + this.material.color.set(this.color); + } else { + const colors = mesh.geometry.getAttribute("color"); + _color1.copy(this.light.color); + _color2.copy(this.light.groundColor); + for (let i = 0, l = colors.count; i < l; i++) { + const color = i < l / 2 ? _color1 : _color2; + colors.setXYZ(i, color.r, color.g, color.b); + } + colors.needsUpdate = true; + } + this.light.updateWorldMatrix(true, false); + mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate()); + } + } + class GridHelper extends LineSegments { + /** + * Constructs a new grid helper. + * + * @param {number} [size=10] - The size of the grid. + * @param {number} [divisions=10] - The number of divisions across the grid. + * @param {number|Color|string} [color1=0x444444] - The color of the center line. + * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid. + */ + constructor(size = 10, divisions = 10, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + const vertices = [], colors = []; + for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) { + vertices.push(-halfSize, 0, k, halfSize, 0, k); + vertices.push(k, 0, -halfSize, k, 0, halfSize); + const color = i === center ? color1 : color2; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + } + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "GridHelper"; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + class PolarGridHelper extends LineSegments { + /** + * Constructs a new polar grid helper. + * + * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number. + * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer. + * @param {number} [rings=16] - The number of rings. This can be any positive integer. + * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer. + * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements. + * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements. + */ + constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const vertices = []; + const colors = []; + if (sectors > 1) { + for (let i = 0; i < sectors; i++) { + const v = i / sectors * (Math.PI * 2); + const x = Math.sin(v) * radius; + const z = Math.cos(v) * radius; + vertices.push(0, 0, 0); + vertices.push(x, 0, z); + const color = i & 1 ? color1 : color2; + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + for (let i = 0; i < rings; i++) { + const color = i & 1 ? color1 : color2; + const r = radius - radius / rings * i; + for (let j = 0; j < divisions; j++) { + let v = j / divisions * (Math.PI * 2); + let x = Math.sin(v) * r; + let z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + v = (j + 1) / divisions * (Math.PI * 2); + x = Math.sin(v) * r; + z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + } + } + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "PolarGridHelper"; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + const _v1 = /* @__PURE__ */ new Vector3(); + const _v2 = /* @__PURE__ */ new Vector3(); + const _v3 = /* @__PURE__ */ new Vector3(); + class DirectionalLightHelper extends Object3D { + /** + * Constructs a new directional light helper. + * + * @param {DirectionalLight} light - The light to be visualized. + * @param {number} [size=1] - The dimensions of the plane. + * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take + * the color of the light. + */ + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "DirectionalLightHelper"; + if (size === void 0) size = 1; + let geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute([ + -size, + size, + 0, + size, + size, + 0, + size, + -size, + 0, + -size, + -size, + 0, + -size, + size, + 0 + ], 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.lightPlane = new Line(geometry, material); + this.add(this.lightPlane); + geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3)); + this.targetLine = new Line(geometry, material); + this.add(this.targetLine); + this.update(); + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + } + /** + * Updates the helper to match the position and direction of the + * light being visualized. + */ + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + _v1.setFromMatrixPosition(this.light.matrixWorld); + _v2.setFromMatrixPosition(this.light.target.matrixWorld); + _v3.subVectors(_v2, _v1); + this.lightPlane.lookAt(_v2); + if (this.color !== void 0) { + this.lightPlane.material.color.set(this.color); + this.targetLine.material.color.set(this.color); + } else { + this.lightPlane.material.color.copy(this.light.color); + this.targetLine.material.color.copy(this.light.color); + } + this.targetLine.lookAt(_v2); + this.targetLine.scale.z = _v3.length(); + } + } + const _vector = /* @__PURE__ */ new Vector3(); + const _camera = /* @__PURE__ */ new Camera(); + class CameraHelper extends LineSegments { + /** + * Constructs a new arrow helper. + * + * @param {Camera} camera - The camera to visualize. + */ + constructor(camera) { + const geometry = new BufferGeometry(); + const material = new LineBasicMaterial({ color: 16777215, vertexColors: true, toneMapped: false }); + const vertices = []; + const colors = []; + const pointMap = {}; + addLine("n1", "n2"); + addLine("n2", "n4"); + addLine("n4", "n3"); + addLine("n3", "n1"); + addLine("f1", "f2"); + addLine("f2", "f4"); + addLine("f4", "f3"); + addLine("f3", "f1"); + addLine("n1", "f1"); + addLine("n2", "f2"); + addLine("n3", "f3"); + addLine("n4", "f4"); + addLine("p", "n1"); + addLine("p", "n2"); + addLine("p", "n3"); + addLine("p", "n4"); + addLine("u1", "u2"); + addLine("u2", "u3"); + addLine("u3", "u1"); + addLine("c", "t"); + addLine("p", "c"); + addLine("cn1", "cn2"); + addLine("cn3", "cn4"); + addLine("cf1", "cf2"); + addLine("cf3", "cf4"); + function addLine(a, b) { + addPoint(a); + addPoint(b); + } + function addPoint(id) { + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + if (pointMap[id] === void 0) { + pointMap[id] = []; + } + pointMap[id].push(vertices.length / 3 - 1); + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + super(geometry, material); + this.type = "CameraHelper"; + this.camera = camera; + if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix(); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + this.pointMap = pointMap; + this.update(); + const colorFrustum = new Color(16755200); + const colorCone = new Color(16711680); + const colorUp = new Color(43775); + const colorTarget = new Color(16777215); + const colorCross = new Color(3355443); + this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross); + } + /** + * Defines the colors of the helper. + * + * @param {Color} frustum - The frustum line color. + * @param {Color} cone - The cone line color. + * @param {Color} up - The up line color. + * @param {Color} target - The target line color. + * @param {Color} cross - The cross line color. + * @return {CameraHelper} A reference to this helper. + */ + setColors(frustum, cone, up, target, cross) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(24, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(26, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(28, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(30, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(32, up.r, up.g, up.b); + colorAttribute.setXYZ(33, up.r, up.g, up.b); + colorAttribute.setXYZ(34, up.r, up.g, up.b); + colorAttribute.setXYZ(35, up.r, up.g, up.b); + colorAttribute.setXYZ(36, up.r, up.g, up.b); + colorAttribute.setXYZ(37, up.r, up.g, up.b); + colorAttribute.setXYZ(38, target.r, target.g, target.b); + colorAttribute.setXYZ(39, target.r, target.g, target.b); + colorAttribute.setXYZ(40, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(42, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(44, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(46, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(48, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); + colorAttribute.needsUpdate = true; + return this; + } + /** + * Updates the helper based on the projection matrix of the camera. + */ + update() { + const geometry = this.geometry; + const pointMap = this.pointMap; + const w = 1, h = 1; + let nearZ, farZ; + _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); + if (this.camera.reversedDepth === true) { + nearZ = 1; + farZ = 0; + } else { + if (this.camera.coordinateSystem === WebGLCoordinateSystem) { + nearZ = -1; + farZ = 1; + } else if (this.camera.coordinateSystem === WebGPUCoordinateSystem) { + nearZ = 0; + farZ = 1; + } else { + throw new Error("THREE.CameraHelper.update(): Invalid coordinate system: " + this.camera.coordinateSystem); + } + } + setPoint("c", pointMap, geometry, _camera, 0, 0, nearZ); + setPoint("t", pointMap, geometry, _camera, 0, 0, farZ); + setPoint("n1", pointMap, geometry, _camera, -w, -h, nearZ); + setPoint("n2", pointMap, geometry, _camera, w, -h, nearZ); + setPoint("n3", pointMap, geometry, _camera, -w, h, nearZ); + setPoint("n4", pointMap, geometry, _camera, w, h, nearZ); + setPoint("f1", pointMap, geometry, _camera, -w, -h, farZ); + setPoint("f2", pointMap, geometry, _camera, w, -h, farZ); + setPoint("f3", pointMap, geometry, _camera, -w, h, farZ); + setPoint("f4", pointMap, geometry, _camera, w, h, farZ); + setPoint("u1", pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ); + setPoint("u2", pointMap, geometry, _camera, -w * 0.7, h * 1.1, nearZ); + setPoint("u3", pointMap, geometry, _camera, 0, h * 2, nearZ); + setPoint("cf1", pointMap, geometry, _camera, -w, 0, farZ); + setPoint("cf2", pointMap, geometry, _camera, w, 0, farZ); + setPoint("cf3", pointMap, geometry, _camera, 0, -h, farZ); + setPoint("cf4", pointMap, geometry, _camera, 0, h, farZ); + setPoint("cn1", pointMap, geometry, _camera, -w, 0, nearZ); + setPoint("cn2", pointMap, geometry, _camera, w, 0, nearZ); + setPoint("cn3", pointMap, geometry, _camera, 0, -h, nearZ); + setPoint("cn4", pointMap, geometry, _camera, 0, h, nearZ); + geometry.getAttribute("position").needsUpdate = true; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + function setPoint(point2, pointMap, geometry, camera, x, y, z) { + _vector.set(x, y, z).unproject(camera); + const points = pointMap[point2]; + if (points !== void 0) { + const position = geometry.getAttribute("position"); + for (let i = 0, l = points.length; i < l; i++) { + position.setXYZ(points[i], _vector.x, _vector.y, _vector.z); + } + } + } + const _box = /* @__PURE__ */ new Box3(); + class BoxHelper extends LineSegments { + /** + * Constructs a new box helper. + * + * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box. + * @param {number|Color|string} [color=0xffff00] - The box's color. + */ + constructor(object, color = 16776960) { + const indices = 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]); + const positions = new Float32Array(8 * 3); + const geometry = new BufferGeometry(); + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.object = object; + this.type = "BoxHelper"; + this.matrixAutoUpdate = false; + this.update(); + } + /** + * Updates the helper's geometry to match the dimensions of the object, + * including any children. + */ + update() { + if (this.object !== void 0) { + _box.setFromObject(this.object); + } + if (_box.isEmpty()) return; + const min = _box.min; + const max = _box.max; + const position = this.geometry.attributes.position; + const array = position.array; + array[0] = max.x; + array[1] = max.y; + array[2] = max.z; + array[3] = min.x; + array[4] = max.y; + array[5] = max.z; + array[6] = min.x; + array[7] = min.y; + array[8] = max.z; + array[9] = max.x; + array[10] = min.y; + array[11] = max.z; + array[12] = max.x; + array[13] = max.y; + array[14] = min.z; + array[15] = min.x; + array[16] = max.y; + array[17] = min.z; + array[18] = min.x; + array[19] = min.y; + array[20] = min.z; + array[21] = max.x; + array[22] = min.y; + array[23] = min.z; + position.needsUpdate = true; + this.geometry.computeBoundingSphere(); + } + /** + * Updates the wireframe box for the passed object. + * + * @param {Object3D} object - The 3D object to create the helper for. + * @return {BoxHelper} A reference to this instance. + */ + setFromObject(object) { + this.object = object; + this.update(); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + this.object = source.object; + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + class Box3Helper extends LineSegments { + /** + * Constructs a new box3 helper. + * + * @param {Box3} box - The box to visualize. + * @param {number|Color|string} [color=0xffff00] - The box's color. + */ + constructor(box, color = 16776960) { + const indices = 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]); + const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1]; + const geometry = new BufferGeometry(); + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.box = box; + this.type = "Box3Helper"; + this.geometry.computeBoundingSphere(); + } + updateMatrixWorld(force) { + const box = this.box; + if (box.isEmpty()) return; + box.getCenter(this.position); + box.getSize(this.scale); + this.scale.multiplyScalar(0.5); + super.updateMatrixWorld(force); + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + class PlaneHelper extends Line { + /** + * Constructs a new plane helper. + * + * @param {Plane} plane - The plane to be visualized. + * @param {number} [size=1] - The side length of plane helper. + * @param {number|Color|string} [hex=0xffff00] - The helper's color. + */ + constructor(plane, size = 1, hex = 16776960) { + const color = hex; + const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0]; + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + geometry.computeBoundingSphere(); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.type = "PlaneHelper"; + this.plane = plane; + this.size = size; + const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]; + const geometry2 = new BufferGeometry(); + geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3)); + geometry2.computeBoundingSphere(); + this.add(new Mesh(geometry2, new MeshBasicMaterial({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false }))); + } + updateMatrixWorld(force) { + this.position.set(0, 0, 0); + this.scale.set(0.5 * this.size, 0.5 * this.size, 1); + this.lookAt(this.plane.normal); + this.translateZ(-this.plane.constant); + super.updateMatrixWorld(force); + } + /** + * Updates the helper to match the position and direction of the + * light being visualized. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + } + const _axis = /* @__PURE__ */ new Vector3(); + let _lineGeometry, _coneGeometry; + class ArrowHelper extends Object3D { + /** + * Constructs a new arrow helper. + * + * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector. + * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts. + * @param {number} [length=1] - Length of the arrow in world units. + * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow. + * @param {number} [headLength=length*0.2] - The length of the head of the arrow. + * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow. + */ + constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length = 1, color = 16776960, headLength = length * 0.2, headWidth = headLength * 0.2) { + super(); + this.type = "ArrowHelper"; + if (_lineGeometry === void 0) { + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3)); + _coneGeometry = new ConeGeometry(0.5, 1, 5, 1); + _coneGeometry.translate(0, -0.5, 0); + } + this.position.copy(origin); + this.line = new Line(_lineGeometry, new LineBasicMaterial({ color, toneMapped: false })); + this.line.matrixAutoUpdate = false; + this.add(this.line); + this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({ color, toneMapped: false })); + this.cone.matrixAutoUpdate = false; + this.add(this.cone); + this.setDirection(dir); + this.setLength(length, headLength, headWidth); + } + /** + * Sets the direction of the helper. + * + * @param {Vector3} dir - The normalized direction vector. + */ + setDirection(dir) { + if (dir.y > 0.99999) { + this.quaternion.set(0, 0, 0, 1); + } else if (dir.y < -0.99999) { + this.quaternion.set(1, 0, 0, 0); + } else { + _axis.set(dir.z, 0, -dir.x).normalize(); + const radians = Math.acos(dir.y); + this.quaternion.setFromAxisAngle(_axis, radians); + } + } + /** + * Sets the length of the helper. + * + * @param {number} length - Length of the arrow in world units. + * @param {number} [headLength=length*0.2] - The length of the head of the arrow. + * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow. + */ + setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) { + this.line.scale.set(1, Math.max(1e-4, length - headLength), 1); + this.line.updateMatrix(); + this.cone.scale.set(headWidth, headLength, headWidth); + this.cone.position.y = length; + this.cone.updateMatrix(); + } + /** + * Sets the color of the helper. + * + * @param {number|Color|string} color - The color to set. + */ + setColor(color) { + this.line.material.color.set(color); + this.cone.material.color.set(color); + } + copy(source) { + super.copy(source, false); + this.line.copy(source.line); + this.cone.copy(source.cone); + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + } + class AxesHelper extends LineSegments { + /** + * Constructs a new axes helper. + * + * @param {number} [size=1] - Size of the lines representing the axes. + */ + constructor(size = 1) { + const vertices = [ + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size + ]; + const colors = [ + 1, + 0, + 0, + 1, + 0.6, + 0, + 0, + 1, + 0, + 0.6, + 1, + 0, + 0, + 0, + 1, + 0, + 0.6, + 1 + ]; + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "AxesHelper"; + } + /** + * Defines the colors of the axes helper. + * + * @param {number|Color|string} xAxisColor - The color for the x axis. + * @param {number|Color|string} yAxisColor - The color for the y axis. + * @param {number|Color|string} zAxisColor - The color for the z axis. + * @return {AxesHelper} A reference to this axes helper. + */ + setColors(xAxisColor, yAxisColor, zAxisColor) { + const color = new Color(); + const array = this.geometry.attributes.color.array; + color.set(xAxisColor); + color.toArray(array, 0); + color.toArray(array, 3); + color.set(yAxisColor); + color.toArray(array, 6); + color.toArray(array, 9); + color.set(zAxisColor); + color.toArray(array, 12); + color.toArray(array, 15); + this.geometry.attributes.color.needsUpdate = true; + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + class ShapePath { + /** + * Constructs a new shape path. + */ + constructor() { + this.type = "ShapePath"; + this.color = new Color(); + this.subPaths = []; + this.currentPath = null; + } + /** + * Creates a new path and moves it current point to the given one. + * + * @param {number} x - The x coordinate. + * @param {number} y - The y coordinate. + * @return {ShapePath} A reference to this shape path. + */ + moveTo(x, y) { + this.currentPath = new Path(); + this.subPaths.push(this.currentPath); + this.currentPath.moveTo(x, y); + return this; + } + /** + * Adds an instance of {@link LineCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} x - The x coordinate of the end point. + * @param {number} y - The y coordinate of the end point. + * @return {ShapePath} A reference to this shape path. + */ + lineTo(x, y) { + this.currentPath.lineTo(x, y); + return this; + } + /** + * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} aCPx - The x coordinate of the control point. + * @param {number} aCPy - The y coordinate of the control point. + * @param {number} aX - The x coordinate of the end point. + * @param {number} aY - The y coordinate of the end point. + * @return {ShapePath} A reference to this shape path. + */ + quadraticCurveTo(aCPx, aCPy, aX, aY) { + this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); + return this; + } + /** + * Adds an instance of {@link CubicBezierCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} aCP1x - The x coordinate of the first control point. + * @param {number} aCP1y - The y coordinate of the first control point. + * @param {number} aCP2x - The x coordinate of the second control point. + * @param {number} aCP2y - The y coordinate of the second control point. + * @param {number} aX - The x coordinate of the end point. + * @param {number} aY - The y coordinate of the end point. + * @return {ShapePath} A reference to this shape path. + */ + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); + return this; + } + /** + * Adds an instance of {@link SplineCurve} to the path by connecting + * the current point with the given list of points. + * + * @param {Array} pts - An array of points in 2D space. + * @return {ShapePath} A reference to this shape path. + */ + splineThru(pts) { + this.currentPath.splineThru(pts); + return this; + } + /** + * Converts the paths into an array of shapes. + * + * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW). + * If this flag is set to `true`, then those are flipped. + * @return {Array} An array of shapes. + */ + toShapes(isCCW) { + function toShapesNoHoles(inSubpaths) { + const shapes2 = []; + for (let i = 0, l = inSubpaths.length; i < l; i++) { + const tmpPath2 = inSubpaths[i]; + const tmpShape2 = new Shape(); + tmpShape2.curves = tmpPath2.curves; + shapes2.push(tmpShape2); + } + return shapes2; + } + function isPointInsidePolygon(inPt, inPolygon) { + const polyLen = inPolygon.length; + let inside = false; + for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) { + let edgeLowPt = inPolygon[p]; + let edgeHighPt = inPolygon[q]; + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + if (edgeDy < 0) { + edgeLowPt = inPolygon[q]; + edgeDx = -edgeDx; + edgeHighPt = inPolygon[p]; + edgeDy = -edgeDy; + } + if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue; + if (inPt.y === edgeLowPt.y) { + if (inPt.x === edgeLowPt.x) return true; + } else { + const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if (perpEdge === 0) return true; + if (perpEdge < 0) continue; + inside = !inside; + } + } else { + if (inPt.y !== edgeLowPt.y) continue; + if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; + } + } + return inside; + } + const isClockWise = ShapeUtils.isClockWise; + const subPaths = this.subPaths; + if (subPaths.length === 0) return []; + let solid, tmpPath, tmpShape; + const shapes = []; + if (subPaths.length === 1) { + tmpPath = subPaths[0]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push(tmpShape); + return shapes; + } + let holesFirst = !isClockWise(subPaths[0].getPoints()); + holesFirst = isCCW ? !holesFirst : holesFirst; + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + newShapes[mainIdx] = void 0; + newShapeHoles[mainIdx] = []; + for (let i = 0, l = subPaths.length; i < l; i++) { + tmpPath = subPaths[i]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise(tmpPoints); + solid = isCCW ? !solid : solid; + if (solid) { + if (!holesFirst && newShapes[mainIdx]) mainIdx++; + newShapes[mainIdx] = { s: new Shape(), p: tmpPoints }; + newShapes[mainIdx].s.curves = tmpPath.curves; + if (holesFirst) mainIdx++; + newShapeHoles[mainIdx] = []; + } else { + newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] }); + } + } + if (!newShapes[0]) return toShapesNoHoles(subPaths); + if (newShapes.length > 1) { + let ambiguous = false; + let toChange = 0; + for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) { + betterShapeHoles[sIdx] = []; + } + for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) { + const sho = newShapeHoles[sIdx]; + for (let hIdx = 0; hIdx < sho.length; hIdx++) { + const ho = sho[hIdx]; + let hole_unassigned = true; + for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) { + if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { + if (sIdx !== s2Idx) toChange++; + if (hole_unassigned) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push(ho); + } else { + ambiguous = true; + } + } + } + if (hole_unassigned) { + betterShapeHoles[sIdx].push(ho); + } + } + } + if (toChange > 0 && ambiguous === false) { + newShapeHoles = betterShapeHoles; + } + } + let tmpHoles; + for (let i = 0, il = newShapes.length; i < il; i++) { + tmpShape = newShapes[i].s; + shapes.push(tmpShape); + tmpHoles = newShapeHoles[i]; + for (let j = 0, jl = tmpHoles.length; j < jl; j++) { + tmpShape.holes.push(tmpHoles[j].h); + } + } + return shapes; + } + } + class Controls extends EventDispatcher { + /** + * Constructs a new controls instance. + * + * @param {Object3D} object - The object that is managed by the controls. + * @param {?HTMLElement} domElement - The HTML element used for event listeners. + */ + constructor(object, domElement = null) { + super(); + this.object = object; + this.domElement = domElement; + this.enabled = true; + this.state = -1; + this.keys = {}; + this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; + this.touches = { ONE: null, TWO: null }; + } + /** + * Connects the controls to the DOM. This method has so called "side effects" since + * it adds the module's event listeners to the DOM. + * + * @param {HTMLElement} element - The DOM element to connect to. + */ + connect(element) { + if (element === void 0) { + warn("Controls: connect() now requires an element."); + return; + } + if (this.domElement !== null) this.disconnect(); + this.domElement = element; + } + /** + * Disconnects the controls from the DOM. + */ + disconnect() { + } + /** + * Call this method if you no longer want use to the controls. It frees all internal + * resources and removes all event listeners. + */ + dispose() { + } + /** + * Controls should implement this method if they have to update their internal state + * per simulation step. + * + * @param {number} [delta] - The time delta in seconds. + */ + update() { + } + } + function contain(texture, aspect2) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect2) { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect2; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } else { + texture.repeat.x = aspect2 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } + return texture; + } + function cover(texture, aspect2) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect2) { + texture.repeat.x = aspect2 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } else { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect2; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } + return texture; + } + function fill(texture) { + texture.repeat.x = 1; + texture.repeat.y = 1; + texture.offset.x = 0; + texture.offset.y = 0; + return texture; + } + function getByteLength(width, height, format, type) { + const typeByteLength = getTextureTypeByteLength(type); + switch (format) { + // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml + case AlphaFormat: + return width * height; + case RedFormat: + return width * height / typeByteLength.components * typeByteLength.byteLength; + case RedIntegerFormat: + return width * height / typeByteLength.components * typeByteLength.byteLength; + case RGFormat: + return width * height * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGIntegerFormat: + return width * height * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGBFormat: + return width * height * 3 / typeByteLength.components * typeByteLength.byteLength; + case RGBAFormat: + return width * height * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGBAIntegerFormat: + return width * height * 4 / typeByteLength.components * typeByteLength.byteLength; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/ + case RGB_S3TC_DXT1_Format: + case RGBA_S3TC_DXT1_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8; + case RGBA_S3TC_DXT3_Format: + case RGBA_S3TC_DXT5_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/ + case RGB_PVRTC_2BPPV1_Format: + case RGBA_PVRTC_2BPPV1_Format: + return Math.max(width, 16) * Math.max(height, 8) / 4; + case RGB_PVRTC_4BPPV1_Format: + case RGBA_PVRTC_4BPPV1_Format: + return Math.max(width, 8) * Math.max(height, 8) / 2; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/ + case RGB_ETC1_Format: + case RGB_ETC2_Format: + case R11_EAC_Format: + case SIGNED_R11_EAC_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8; + case RGBA_ETC2_EAC_Format: + case RG11_EAC_Format: + case SIGNED_RG11_EAC_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/ + case RGBA_ASTC_4x4_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16; + case RGBA_ASTC_5x4_Format: + return Math.floor((width + 4) / 5) * Math.floor((height + 3) / 4) * 16; + case RGBA_ASTC_5x5_Format: + return Math.floor((width + 4) / 5) * Math.floor((height + 4) / 5) * 16; + case RGBA_ASTC_6x5_Format: + return Math.floor((width + 5) / 6) * Math.floor((height + 4) / 5) * 16; + case RGBA_ASTC_6x6_Format: + return Math.floor((width + 5) / 6) * Math.floor((height + 5) / 6) * 16; + case RGBA_ASTC_8x5_Format: + return Math.floor((width + 7) / 8) * Math.floor((height + 4) / 5) * 16; + case RGBA_ASTC_8x6_Format: + return Math.floor((width + 7) / 8) * Math.floor((height + 5) / 6) * 16; + case RGBA_ASTC_8x8_Format: + return Math.floor((width + 7) / 8) * Math.floor((height + 7) / 8) * 16; + case RGBA_ASTC_10x5_Format: + return Math.floor((width + 9) / 10) * Math.floor((height + 4) / 5) * 16; + case RGBA_ASTC_10x6_Format: + return Math.floor((width + 9) / 10) * Math.floor((height + 5) / 6) * 16; + case RGBA_ASTC_10x8_Format: + return Math.floor((width + 9) / 10) * Math.floor((height + 7) / 8) * 16; + case RGBA_ASTC_10x10_Format: + return Math.floor((width + 9) / 10) * Math.floor((height + 9) / 10) * 16; + case RGBA_ASTC_12x10_Format: + return Math.floor((width + 11) / 12) * Math.floor((height + 9) / 10) * 16; + case RGBA_ASTC_12x12_Format: + return Math.floor((width + 11) / 12) * Math.floor((height + 11) / 12) * 16; + // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/ + case RGBA_BPTC_Format: + case RGB_BPTC_SIGNED_Format: + case RGB_BPTC_UNSIGNED_Format: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16; + // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/ + case RED_RGTC1_Format: + case SIGNED_RED_RGTC1_Format: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8; + case RED_GREEN_RGTC2_Format: + case SIGNED_RED_GREEN_RGTC2_Format: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16; + } + throw new Error( + `Unable to determine texture byte length for ${format} format.` + ); + } + function getTextureTypeByteLength(type) { + switch (type) { + case UnsignedByteType: + case ByteType: + return { byteLength: 1, components: 1 }; + case UnsignedShortType: + case ShortType: + case HalfFloatType: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type: + case UnsignedShort5551Type: + return { byteLength: 2, components: 4 }; + case UnsignedIntType: + case IntType: + case FloatType: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type: + case UnsignedInt101111Type: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${type}.`); + } + class TextureUtils { + /** + * Scales the texture as large as possible within its surface without cropping + * or stretching the texture. The method preserves the original aspect ratio of + * the texture. Akin to CSS `object-fit: contain` + * + * @param {Texture} texture - The texture. + * @param {number} aspect - The texture's aspect ratio. + * @return {Texture} The updated texture. + */ + static contain(texture, aspect2) { + return contain(texture, aspect2); + } + /** + * Scales the texture to the smallest possible size to fill the surface, leaving + * no empty space. The method preserves the original aspect ratio of the texture. + * Akin to CSS `object-fit: cover`. + * + * @param {Texture} texture - The texture. + * @param {number} aspect - The texture's aspect ratio. + * @return {Texture} The updated texture. + */ + static cover(texture, aspect2) { + return cover(texture, aspect2); + } + /** + * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`. + * + * @param {Texture} texture - The texture. + * @return {Texture} The updated texture. + */ + static fill(texture) { + return fill(texture); + } + /** + * Determines how many bytes must be used to represent the texture. + * + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} format - The texture's format. + * @param {number} type - The texture's type. + * @return {number} The byte length. + */ + static getByteLength(width, height, format, type) { + return getByteLength(width, height, format, type); + } + } + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION + } })); + } + if (typeof window !== "undefined") { + if (window.__THREE__) { + warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION; + } + } + function WebGLAnimation() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time, frame) { + animationLoop(time, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) return; + if (animationLoop === null) return; + if (context === null) return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + if (context !== null) context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value) { + context = value; + } + }; + } + function WebGLAttributes(gl) { + const buffers = /* @__PURE__ */ new WeakMap(); + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (typeof Float16Array !== "undefined" && array instanceof Float16Array) { + type = gl.HALF_FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + type = gl.HALF_FLOAT; + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } else { + updateRanges.sort((a, b) => a.start - b.start); + let mergeIndex = 0; + for (let i = 1; i < updateRanges.length; i++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i]; + if (range.start <= previousRange.start + previousRange.count + 1) { + previousRange.count = Math.max( + previousRange.count, + range.start + range.count - previousRange.start + ); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + for (let i = 0, l = updateRanges.length; i < l; i++) { + const range = updateRanges[i]; + gl.bufferSubData( + bufferType, + range.start * array.BYTES_PER_ELEMENT, + array, + range.start, + range.count + ); + } + attribute.clearUpdateRanges(); + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + const data = buffers.get(attribute); + if (data) { + gl.deleteBuffer(data.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + const data = buffers.get(attribute); + if (data === void 0) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data.version < attribute.version) { + if (data.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data.buffer, attribute, bufferType); + data.version = attribute.version; + } + } + return { + get, + remove, + update + }; + } + var alphahash_fragment = "#ifdef USE_ALPHAHASH\n if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif"; + var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n const float ALPHA_HASH_SCALE = 0.05;\n float hash2D( vec2 value ) {\n return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n }\n float hash3D( vec3 value ) {\n return hash2D( vec2( hash2D( value.xy ), value.z ) );\n }\n float getAlphaHashThreshold( vec3 position ) {\n float maxDeriv = max(\n length( dFdx( position.xyz ) ),\n length( dFdy( position.xyz ) )\n );\n float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n vec2 pixScales = vec2(\n exp2( floor( log2( pixScale ) ) ),\n exp2( ceil( log2( pixScale ) ) )\n );\n vec2 alpha = vec2(\n hash3D( floor( pixScales.x * position.xyz ) ),\n hash3D( floor( pixScales.y * position.xyz ) )\n );\n float lerpFactor = fract( log2( pixScale ) );\n float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n float a = min( lerpFactor, 1.0 - lerpFactor );\n vec3 cases = vec3(\n x * x / ( 2.0 * a * ( 1.0 - a ) ),\n ( x - 0.5 * a ) / ( 1.0 - a ),\n 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n );\n float threshold = ( x < ( 1.0 - a ) )\n ? ( ( x < a ) ? cases.x : cases.y )\n : cases.z;\n return clamp( threshold , 1.0e-6, 1.0 );\n }\n#endif"; + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif"; + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif"; + var alphatest_fragment = "#ifdef USE_ALPHATEST\n #ifdef ALPHA_TO_COVERAGE\n diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n if ( diffuseColor.a == 0.0 ) discard;\n #else\n if ( diffuseColor.a < alphaTest ) discard;\n #endif\n#endif"; + var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n uniform float alphaTest;\n#endif"; + var aomap_fragment = "#ifdef USE_AOMAP\n float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n #if defined( USE_CLEARCOAT ) \n clearcoatSpecularIndirect *= ambientOcclusion;\n #endif\n #if defined( USE_SHEEN ) \n sheenSpecularIndirect *= ambientOcclusion;\n #endif\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n #endif\n#endif"; + var aomap_pars_fragment = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif"; + var batching_pars_vertex = "#ifdef USE_BATCHING\n #if ! defined( GL_ANGLE_multi_draw )\n #define gl_DrawID _gl_DrawID\n uniform int _gl_DrawID;\n #endif\n uniform highp sampler2D batchingTexture;\n uniform highp usampler2D batchingIdTexture;\n mat4 getBatchingMatrix( const in float i ) {\n int size = textureSize( batchingTexture, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n float getIndirectIndex( const in int i ) {\n int size = textureSize( batchingIdTexture, 0 ).x;\n int x = i % size;\n int y = i / size;\n return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n }\n#endif\n#ifdef USE_BATCHING_COLOR\n uniform sampler2D batchingColorTexture;\n vec4 getBatchingColor( const in float i ) {\n int size = textureSize( batchingColorTexture, 0 ).x;\n int j = int( i );\n int x = j % size;\n int y = j / size;\n return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );\n }\n#endif"; + var batching_vertex = "#ifdef USE_BATCHING\n mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif"; + var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n vPosition = vec3( position );\n#endif"; + var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n vec3 objectTangent = vec3( tangent.xyz );\n#endif"; + var bsdfs = "float G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( specularColor, 1.0, dotVH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n} // validated"; + var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n vec3 Fresnel0ToIor( vec3 fresnel0 ) {\n vec3 sqrtF0 = sqrt( fresnel0 );\n return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n }\n vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n }\n float IorToFresnel0( float transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n }\n vec3 evalSensitivity( float OPD, vec3 shift ) {\n float phase = 2.0 * PI * OPD * 1.0e-9;\n vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n xyz /= 1.0685e-7;\n vec3 rgb = XYZ_TO_REC709 * xyz;\n return rgb;\n }\n vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n vec3 I;\n float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n if ( cosTheta2Sq < 0.0 ) {\n return vec3( 1.0 );\n }\n float cosTheta2 = sqrt( cosTheta2Sq );\n float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n float R12 = F_Schlick( R0, 1.0, cosTheta1 );\n float T121 = 1.0 - R12;\n float phi12 = 0.0;\n if ( iridescenceIOR < outsideIOR ) phi12 = PI;\n float phi21 = PI - phi12;\n vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n vec3 phi23 = vec3( 0.0 );\n if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n vec3 phi = vec3( phi21 ) + phi23;\n vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n vec3 r123 = sqrt( R123 );\n vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n vec3 C0 = R12 + Rs;\n I = C0;\n vec3 Cm = Rs - T121;\n for ( int m = 1; m <= 2; ++ m ) {\n Cm *= r123;\n vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n I += Cm * Sm;\n }\n return max( I, vec3( 0.0 ) );\n }\n#endif"; + var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vBumpMapUv );\n vec2 dSTdy = dFdy( vBumpMapUv );\n float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 ) * faceDirection;\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif"; + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n vec4 plane;\n #ifdef ALPHA_TO_COVERAGE\n float distanceToPlane, distanceGradient;\n float clipOpacity = 1.0;\n #pragma unroll_loop_start\n for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n distanceGradient = fwidth( distanceToPlane ) / 2.0;\n clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n if ( clipOpacity == 0.0 ) discard;\n }\n #pragma unroll_loop_end\n #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n float unionClipOpacity = 1.0;\n #pragma unroll_loop_start\n for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n distanceGradient = fwidth( distanceToPlane ) / 2.0;\n unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n }\n #pragma unroll_loop_end\n clipOpacity *= 1.0 - unionClipOpacity;\n #endif\n diffuseColor.a *= clipOpacity;\n if ( diffuseColor.a == 0.0 ) discard;\n #else\n #pragma unroll_loop_start\n for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n }\n #pragma unroll_loop_end\n #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n bool clipped = true;\n #pragma unroll_loop_start\n for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n }\n #pragma unroll_loop_end\n if ( clipped ) discard;\n #endif\n #endif\n#endif"; + var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n#endif"; + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n vClipPosition = - mvPosition.xyz;\n#endif"; + var color_fragment = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n diffuseColor *= vColor;\n#endif"; + var color_pars_fragment = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#endif"; + var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n varying vec4 vColor;\n#endif"; + var color_vertex = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n vColor = vec4( 1.0 );\n#endif\n#ifdef USE_COLOR_ALPHA\n vColor *= color;\n#elif defined( USE_COLOR )\n vColor.rgb *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n vColor.rgb *= instanceColor.rgb;\n#endif\n#ifdef USE_BATCHING_COLOR\n vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );\n#endif"; + var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n float precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n float precisionSafeLength( vec3 v ) {\n float maxComponent = max3( abs( v ) );\n return length( v / maxComponent ) * maxComponent;\n }\n#endif\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n bool visible;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n varying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n return vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated"; + var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n #define cubeUV_minMipLevel 4.0\n #define cubeUV_minTileSize 16.0\n float getFace( vec3 direction ) {\n vec3 absDirection = abs( direction );\n float face = - 1.0;\n if ( absDirection.x > absDirection.z ) {\n if ( absDirection.x > absDirection.y )\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if ( absDirection.z > absDirection.y )\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n }\n vec2 getUV( vec3 direction, float face ) {\n vec2 uv;\n if ( face == 0.0 ) {\n uv = vec2( direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 1.0 ) {\n uv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n } else if ( face == 2.0 ) {\n uv = vec2( - direction.x, direction.y ) / abs( direction.z );\n } else if ( face == 3.0 ) {\n uv = vec2( - direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 4.0 ) {\n uv = vec2( - direction.x, direction.z ) / abs( direction.y );\n } else {\n uv = vec2( direction.x, direction.y ) / abs( direction.z );\n }\n return 0.5 * ( uv + 1.0 );\n }\n vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n float face = getFace( direction );\n float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n mipInt = max( mipInt, cubeUV_minMipLevel );\n float faceSize = exp2( mipInt );\n highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n if ( face > 2.0 ) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n uv.x += filterInt * 3.0 * cubeUV_minTileSize;\n uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n uv.x *= CUBEUV_TEXEL_WIDTH;\n uv.y *= CUBEUV_TEXEL_HEIGHT;\n #ifdef texture2DGradEXT\n return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n #else\n return texture2D( envMap, uv ).rgb;\n #endif\n }\n #define cubeUV_r0 1.0\n #define cubeUV_m0 - 2.0\n #define cubeUV_r1 0.8\n #define cubeUV_m1 - 1.0\n #define cubeUV_r4 0.4\n #define cubeUV_m4 2.0\n #define cubeUV_r5 0.305\n #define cubeUV_m5 3.0\n #define cubeUV_r6 0.21\n #define cubeUV_m6 4.0\n float roughnessToMip( float roughness ) {\n float mip = 0.0;\n if ( roughness >= cubeUV_r1 ) {\n mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n } else if ( roughness >= cubeUV_r4 ) {\n mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n } else if ( roughness >= cubeUV_r5 ) {\n mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n } else if ( roughness >= cubeUV_r6 ) {\n mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n } else {\n mip = - 2.0 * log2( 1.16 * roughness ); }\n return mip;\n }\n vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n float mipF = fract( mip );\n float mipInt = floor( mip );\n vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n if ( mipF == 0.0 ) {\n return vec4( color0, 1.0 );\n } else {\n vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n return vec4( mix( color0, color1, mipF ), 1.0 );\n }\n }\n#endif"; + var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n vec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n mat3 bm = mat3( batchingMatrix );\n transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n transformedNormal = bm * transformedNormal;\n #ifdef USE_TANGENT\n transformedTangent = bm * transformedTangent;\n #endif\n#endif\n#ifdef USE_INSTANCING\n mat3 im = mat3( instanceMatrix );\n transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n transformedNormal = im * transformedNormal;\n #ifdef USE_TANGENT\n transformedTangent = im * transformedTangent;\n #endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n transformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n #ifdef FLIP_SIDED\n transformedTangent = - transformedTangent;\n #endif\n#endif"; + var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif"; + var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif"; + var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n emissiveColor = sRGBTransferEOTF( emissiveColor );\n #endif\n totalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif"; + var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n return value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}"; + var envmap_fragment = "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vec3 cameraToFrag;\n if ( isOrthographic ) {\n cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToFrag = normalize( vWorldPosition - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToFrag, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, envMapRotation * reflectVec );\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n #endif\n#endif"; + var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n uniform float envMapIntensity;\n uniform mat3 envMapRotation;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n#endif"; + var envmap_pars_fragment = "#ifdef USE_ENVMAP\n uniform float reflectivity;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n varying vec3 vWorldPosition;\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif"; + var envmap_pars_vertex = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n \n varying vec3 vWorldPosition;\n #else\n varying vec3 vReflect;\n uniform float refractionRatio;\n #endif\n#endif"; + var envmap_vertex = "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vWorldPosition = worldPosition.xyz;\n #else\n vec3 cameraToVertex;\n if ( isOrthographic ) {\n cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #endif\n#endif"; + var fog_vertex = "#ifdef USE_FOG\n vFogDepth = - mvPosition.z;\n#endif"; + var fog_pars_vertex = "#ifdef USE_FOG\n varying float vFogDepth;\n#endif"; + var fog_fragment = "#ifdef USE_FOG\n #ifdef FOG_EXP2\n float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n #endif\n gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + var fog_pars_fragment = "#ifdef USE_FOG\n uniform vec3 fogColor;\n varying float vFogDepth;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif"; + var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n uniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n float dotNL = dot( normal, lightDirection );\n vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n #ifdef USE_GRADIENTMAP\n return vec3( texture2D( gradientMap, coord ).r );\n #else\n vec2 fw = fwidth( coord ) * 0.5;\n return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n #endif\n}"; + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif"; + var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n vec3 diffuseColor;\n float specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Lambert\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert"; + var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n uniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n float x = normal.x, y = normal.y, z = normal.z;\n vec3 result = shCoefficients[ 0 ] * 0.886227;\n result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n return result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n return irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n vec3 irradiance = ambientLightColor;\n return irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n if ( cutoffDistance > 0.0 ) {\n distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n }\n return distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n return smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n light.color = directionalLight.color;\n light.direction = directionalLight.direction;\n light.visible = true;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n vec3 lVector = pointLight.position - geometryPosition;\n light.direction = normalize( lVector );\n float lightDistance = length( lVector );\n light.color = pointLight.color;\n light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float coneCos;\n float penumbraCos;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n vec3 lVector = spotLight.position - geometryPosition;\n light.direction = normalize( lVector );\n float angleCos = dot( light.direction, spotLight.direction );\n float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n if ( spotAttenuation > 0.0 ) {\n float lightDistance = length( lVector );\n light.color = spotLight.color * spotAttenuation;\n light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n } else {\n light.color = vec3( 0.0 );\n light.visible = false;\n }\n }\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n struct RectAreaLight {\n vec3 color;\n vec3 position;\n vec3 halfWidth;\n vec3 halfHeight;\n };\n uniform sampler2D ltc_1; uniform sampler2D ltc_2;\n uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n float dotNL = dot( normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n return irradiance;\n }\n#endif\n#include "; + var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n vec3 getIBLIrradiance( const in vec3 normal ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n return PI * envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 reflectVec = reflect( - viewDir, normal );\n reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n return envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n #ifdef USE_ANISOTROPY\n vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 bentNormal = cross( bitangent, viewDir );\n bentNormal = normalize( cross( bentNormal, bitangent ) );\n bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n return getIBLRadiance( viewDir, bentNormal, roughness );\n #else\n return vec3( 0.0 );\n #endif\n }\n #endif\n#endif"; + var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n vec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Toon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon"; + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong"; + var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n material.ior = ior;\n #ifdef USE_SPECULAR\n float specularIntensityFactor = specularIntensity;\n vec3 specularColorFactor = specularColor;\n #ifdef USE_SPECULAR_COLORMAP\n specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n #endif\n #ifdef USE_SPECULAR_INTENSITYMAP\n specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n #endif\n material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n #else\n float specularIntensityFactor = 1.0;\n vec3 specularColorFactor = vec3( 1.0 );\n material.specularF90 = 1.0;\n #endif\n material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n material.specularColor = vec3( 0.04 );\n material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n material.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n material.clearcoat = clearcoat;\n material.clearcoatRoughness = clearcoatRoughness;\n material.clearcoatF0 = vec3( 0.04 );\n material.clearcoatF90 = 1.0;\n #ifdef USE_CLEARCOATMAP\n material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n #endif\n #ifdef USE_CLEARCOAT_ROUGHNESSMAP\n material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n #endif\n material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n material.clearcoatRoughness += geometryRoughness;\n material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n material.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n material.iridescence = iridescence;\n material.iridescenceIOR = iridescenceIOR;\n #ifdef USE_IRIDESCENCEMAP\n material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n #endif\n #ifdef USE_IRIDESCENCE_THICKNESSMAP\n material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n #else\n material.iridescenceThickness = iridescenceThicknessMaximum;\n #endif\n#endif\n#ifdef USE_SHEEN\n material.sheenColor = sheenColor;\n #ifdef USE_SHEEN_COLORMAP\n material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n #endif\n material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n #ifdef USE_SHEEN_ROUGHNESSMAP\n material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n #endif\n#endif\n#ifdef USE_ANISOTROPY\n #ifdef USE_ANISOTROPYMAP\n mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n #else\n vec2 anisotropyV = anisotropyVector;\n #endif\n material.anisotropy = length( anisotropyV );\n if( material.anisotropy == 0.0 ) {\n anisotropyV = vec2( 1.0, 0.0 );\n } else {\n anisotropyV /= material.anisotropy;\n material.anisotropy = saturate( material.anisotropy );\n }\n material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif"; + var lights_physical_pars_fragment = "uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n vec3 diffuseColor;\n vec3 diffuseContribution;\n vec3 specularColor;\n vec3 specularColorBlended;\n float roughness;\n float metalness;\n float specularF90;\n float dispersion;\n #ifdef USE_CLEARCOAT\n float clearcoat;\n float clearcoatRoughness;\n vec3 clearcoatF0;\n float clearcoatF90;\n #endif\n #ifdef USE_IRIDESCENCE\n float iridescence;\n float iridescenceIOR;\n float iridescenceThickness;\n vec3 iridescenceFresnel;\n vec3 iridescenceF0;\n vec3 iridescenceFresnelDielectric;\n vec3 iridescenceFresnelMetallic;\n #endif\n #ifdef USE_SHEEN\n vec3 sheenColor;\n float sheenRoughness;\n #endif\n #ifdef IOR\n float ior;\n #endif\n #ifdef USE_TRANSMISSION\n float transmission;\n float transmissionAlpha;\n float thickness;\n float attenuationDistance;\n vec3 attenuationColor;\n #endif\n #ifdef USE_ANISOTROPY\n float anisotropy;\n float alphaT;\n vec3 anisotropyT;\n vec3 anisotropyB;\n #endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = pow2( alpha );\n float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n }\n float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n float a2 = alphaT * alphaB;\n highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n highp float v2 = dot( v, v );\n float w2 = a2 / v2;\n return RECIPROCAL_PI * a2 * pow2 ( w2 );\n }\n#endif\n#ifdef USE_CLEARCOAT\n vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n vec3 f0 = material.clearcoatF0;\n float f90 = material.clearcoatF90;\n float roughness = material.clearcoatRoughness;\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( V * D );\n }\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n vec3 f0 = material.specularColorBlended;\n float f90 = material.specularF90;\n float roughness = material.roughness;\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n #ifdef USE_IRIDESCENCE\n F = mix( F, material.iridescenceFresnel, material.iridescence );\n #endif\n #ifdef USE_ANISOTROPY\n float dotTL = dot( material.anisotropyT, lightDir );\n float dotTV = dot( material.anisotropyT, viewDir );\n float dotTH = dot( material.anisotropyT, halfDir );\n float dotBL = dot( material.anisotropyB, lightDir );\n float dotBV = dot( material.anisotropyB, viewDir );\n float dotBH = dot( material.anisotropyB, halfDir );\n float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n #else\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n #endif\n return F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return 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 vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n vec3 lightNormal = cross( v1, v2 );\n if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = - cross( N, T1 );\n mat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n return vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n float alpha = pow2( roughness );\n float invAlpha = 1.0 / alpha;\n float cos2h = dotNH * dotNH;\n float sin2h = max( 1.0 - cos2h, 0.0078125 );\n return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float D = D_Charlie( sheenRoughness, dotNH );\n float V = V_Neubelt( dotNV, dotNL );\n return sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n float r2 = roughness * roughness;\n float rInv = 1.0 / ( roughness + 0.1 );\n float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n float DG = exp( a * dotNV + b );\n return saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n return specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n float dotNV = saturate( dot( normal, viewDir ) );\n vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n #ifdef USE_IRIDESCENCE\n vec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n #else\n vec3 Fr = specularColor;\n #endif\n vec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n float Ess = fab.x + fab.y;\n float Ems = 1.0 - Ess;\n vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n singleScatter += FssEss;\n multiScatter += Fms * Ems;\n}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n float Ess_V = dfgV.x + dfgV.y;\n float Ess_L = dfgL.x + dfgL.y;\n float Ems_V = 1.0 - Ess_V;\n float Ems_L = 1.0 - Ess_L;\n vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n float compensationFactor = Ems_V * Ems_L;\n vec3 multiScatter = Fms * compensationFactor;\n return singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 normal = geometryNormal;\n vec3 viewDir = geometryViewDir;\n vec3 position = geometryPosition;\n vec3 lightPos = rectAreaLight.position;\n vec3 halfWidth = rectAreaLight.halfWidth;\n vec3 halfHeight = rectAreaLight.halfHeight;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.roughness;\n vec3 rectCoords[ 4 ];\n rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n vec2 uv = LTC_Uv( normal, viewDir, roughness );\n vec4 t1 = texture2D( ltc_1, uv );\n vec4 t2 = texture2D( ltc_2, uv );\n mat3 mInv = mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );\n reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n #ifdef USE_CLEARCOAT\n vec3 Ncc = geometryClearcoatNormal;\n vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );\n vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );\n vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );\n mat3 mInvClearcoat = mat3(\n vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),\n vec3( 0, 1, 0 ),\n vec3( t1Clearcoat.z, 0, t1Clearcoat.w )\n );\n vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;\n clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );\n #endif\n }\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifdef USE_CLEARCOAT\n float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n vec3 ccIrradiance = dotNLcc * directLight.color;\n clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n #endif\n #ifdef USE_SHEEN\n \n sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n irradiance *= sheenEnergyComp;\n \n #endif\n reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n #ifdef USE_SHEEN\n float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n diffuse *= sheenEnergyComp;\n #endif\n reflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n #ifdef USE_CLEARCOAT\n clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n #endif\n #ifdef USE_SHEEN\n sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n #endif\n vec3 singleScatteringDielectric = vec3( 0.0 );\n vec3 multiScatteringDielectric = vec3( 0.0 );\n vec3 singleScatteringMetallic = vec3( 0.0 );\n vec3 multiScatteringMetallic = vec3( 0.0 );\n #ifdef USE_IRIDESCENCE\n computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n #else\n computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n #endif\n vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n vec3 indirectSpecular = radiance * singleScattering;\n indirectSpecular += multiScattering * cosineWeightedIrradiance;\n vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n #ifdef USE_SHEEN\n float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n indirectSpecular *= sheenEnergyComp;\n indirectDiffuse *= sheenEnergyComp;\n #endif\n reflectedLight.indirectSpecular += indirectSpecular;\n reflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct RE_Direct_Physical\n#define RE_Direct_RectArea RE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular RE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n geometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n float dotNVi = saturate( dot( normal, geometryViewDir ) );\n if ( material.iridescenceThickness == 0.0 ) {\n material.iridescence = 0.0;\n } else {\n material.iridescence = saturate( material.iridescence );\n }\n if ( material.iridescence > 0.0 ) {\n material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\n material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n }\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n getPointLightInfo( pointLight, geometryPosition, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n pointLightShadow = pointLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n SpotLight spotLight;\n vec4 spotColor;\n vec3 spotLightCoord;\n bool inSpotLightMap;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n getSpotLightInfo( spotLight, geometryPosition, directLight );\n #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n #else\n #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #endif\n #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n #endif\n #undef SPOT_LIGHT_MAP_INDEX\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n getDirectionalLightInfo( directionalLight, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n RectAreaLight rectAreaLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n rectAreaLight = rectAreaLights[ i ];\n RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n vec3 iblIrradiance = vec3( 0.0 );\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #if defined( USE_LIGHT_PROBES )\n irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n }\n #pragma unroll_loop_end\n #endif\n #ifdef USE_LIGHT_PROBES_GRID\n vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;\n vec3 probeWorldNormal = inverseTransformDirection( geometryNormal, viewMatrix );\n irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );\n #endif\n#endif\n#if defined( RE_IndirectSpecular )\n vec3 radiance = vec3( 0.0 );\n vec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n irradiance += lightMapIrradiance;\n #endif\n #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n iblIrradiance += getIBLIrradiance( geometryNormal );\n #endif\n #endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n #ifdef USE_ANISOTROPY\n radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n #else\n radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n #endif\n #ifdef USE_CLEARCOAT\n clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n #endif\n#endif"; + var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n #if defined( LAMBERT ) || defined( PHONG )\n irradiance += iblIrradiance;\n #endif\n RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif"; + var lightprobes_pars_fragment = "#ifdef USE_LIGHT_PROBES_GRID\nuniform highp sampler3D probesSH;\nuniform vec3 probesMin;\nuniform vec3 probesMax;\nuniform vec3 probesResolution;\nvec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {\n vec3 res = probesResolution;\n vec3 gridRange = probesMax - probesMin;\n vec3 resMinusOne = res - 1.0;\n vec3 probeSpacing = gridRange / resMinusOne;\n vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;\n vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 );\n uvw = uvw * resMinusOne / res + 0.5 / res;\n float nz = res.z;\n float paddedSlices = nz + 2.0;\n float atlasDepth = 7.0 * paddedSlices;\n float uvZBase = uvw.z * nz + 1.0;\n vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );\n vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );\n vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );\n vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );\n vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );\n vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );\n vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );\n vec3 c0 = s0.xyz;\n vec3 c1 = vec3( s0.w, s1.xy );\n vec3 c2 = vec3( s1.zw, s2.x );\n vec3 c3 = s2.yzw;\n vec3 c4 = s3.xyz;\n vec3 c5 = vec3( s3.w, s4.xy );\n vec3 c6 = vec3( s4.zw, s5.x );\n vec3 c7 = s5.yzw;\n vec3 c8 = s6.xyz;\n float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;\n vec3 result = c0 * 0.886227;\n result += c1 * 2.0 * 0.511664 * y;\n result += c2 * 2.0 * 0.511664 * z;\n result += c3 * 2.0 * 0.511664 * x;\n result += c4 * 2.0 * 0.429043 * x * y;\n result += c5 * 2.0 * 0.429043 * y * z;\n result += c6 * ( 0.743125 * z * z - 0.247708 );\n result += c7 * 2.0 * 0.429043 * x * z;\n result += c8 * 0.429043 * ( x * x - y * y );\n return max( result, vec3( 0.0 ) );\n}\n#endif"; + var logdepthbuf_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n uniform float logDepthBufFC;\n varying float vFragDepth;\n varying float vIsPerspective;\n#endif"; + var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n varying float vFragDepth;\n varying float vIsPerspective;\n#endif"; + var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n vFragDepth = 1.0 + gl_Position.w;\n vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif"; + var map_fragment = "#ifdef USE_MAP\n vec4 sampledDiffuseColor = texture2D( map, vMapUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n #endif\n diffuseColor *= sampledDiffuseColor;\n#endif"; + var map_pars_fragment = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif"; + var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n #if defined( USE_POINTS_UV )\n vec2 uv = vUv;\n #else\n vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n #endif\n#endif\n#ifdef USE_MAP\n diffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n varying vec2 vUv;\n#else\n #if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n uniform mat3 uvTransform;\n #endif\n#endif\n#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif"; + var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n metalnessFactor *= texelMetalness.b;\n#endif"; + var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif"; + var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n }\n#endif"; + var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n vColor *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n #if defined( USE_COLOR_ALPHA )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n #elif defined( USE_COLOR )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n #endif\n }\n#endif"; + var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n objectNormal *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n }\n#endif"; + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n #ifndef USE_INSTANCING_MORPH\n uniform float morphTargetBaseInfluence;\n uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n #endif\n uniform sampler2DArray morphTargetsTexture;\n uniform ivec2 morphTargetsTextureSize;\n vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n int y = texelIndex / morphTargetsTextureSize.x;\n int x = texelIndex - y * morphTargetsTextureSize.x;\n ivec3 morphUV = ivec3( x, y, morphTargetIndex );\n return texelFetch( morphTargetsTexture, morphUV, 0 );\n }\n#endif"; + var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n transformed *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n }\n#endif"; + var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal *= faceDirection;\n #endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n #ifdef USE_TANGENT\n mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n #else\n mat3 tbn = getTangentFrame( - vViewPosition, normal,\n #if defined( USE_NORMALMAP )\n vNormalMapUv\n #elif defined( USE_CLEARCOAT_NORMALMAP )\n vClearcoatNormalMapUv\n #else\n vUv\n #endif\n );\n #endif\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n tbn[0] *= faceDirection;\n tbn[1] *= faceDirection;\n #endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n #ifdef USE_TANGENT\n mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n #else\n mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n #endif\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n tbn2[0] *= faceDirection;\n tbn2[1] *= faceDirection;\n #endif\n#endif\nvec3 nonPerturbedNormal = normal;"; + var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n #ifdef FLIP_SIDED\n normal = - normal;\n #endif\n #ifdef DOUBLE_SIDED\n normal = normal * faceDirection;\n #endif\n normal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n #if defined( USE_PACKED_NORMALMAP )\n mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );\n #endif\n mapN.xy *= normalScale;\n normal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + var normal_pars_fragment = "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif"; + var normal_pars_vertex = "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif"; + var normal_vertex = "#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #ifdef USE_TANGENT\n vTangent = normalize( transformedTangent );\n vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n #endif\n#endif"; + var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n uniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n vec3 N = surf_norm;\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n return mat3( T * scale, B * scale, N );\n }\n#endif"; + var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n vec3 clearcoatNormal = nonPerturbedNormal;\n#endif"; + var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n clearcoatMapN.xy *= clearcoatNormalScale;\n clearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif"; + var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n uniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform sampler2D clearcoatNormalMap;\n uniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform sampler2D clearcoatRoughnessMap;\n#endif"; + var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n uniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform sampler2D iridescenceThicknessMap;\n#endif"; + var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n if( v <= 0.0 )\n return vec4( 0., 0., 0., 0. );\n if( v >= 1.0 )\n return vec4( 1., 1., 1., 1. );\n float vuf;\n float af = modf( v * PackFactors.a, vuf );\n float bf = modf( vuf * ShiftRight8, vuf );\n float gf = modf( vuf * ShiftRight8, vuf );\n return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n if( v <= 0.0 )\n return vec3( 0., 0., 0. );\n if( v >= 1.0 )\n return vec3( 1., 1., 1. );\n float vuf;\n float bf = modf( v * PackFactors.b, vuf );\n float gf = modf( vuf * ShiftRight8, vuf );\n return vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n if( v <= 0.0 )\n return vec2( 0., 0. );\n if( v >= 1.0 )\n return vec2( 1., 1. );\n float vuf;\n float gf = modf( v * 256., vuf );\n return vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n return dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n #ifdef USE_REVERSED_DEPTH_BUFFER\n \n return depth * ( far - near ) - far;\n #else\n return depth * ( near - far ) - near;\n #endif\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n \n #ifdef USE_REVERSED_DEPTH_BUFFER\n return ( near * far ) / ( ( near - far ) * depth - near );\n #else\n return ( near * far ) / ( ( far - near ) * depth - far );\n #endif\n}"; + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n mvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n mvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + var dithering_fragment = "#ifdef DITHERING\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + var dithering_pars_fragment = "#ifdef DITHERING\n vec3 dithering( vec3 color ) {\n float grid_position = rand( gl_FragCoord.xy );\n vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n return color + dither_shift_RGB;\n }\n#endif"; + var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n roughnessFactor *= texelRoughness.g;\n#endif"; + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif"; + var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n #if defined( SHADOWMAP_TYPE_PCF )\n uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n #else\n uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n #if defined( SHADOWMAP_TYPE_PCF )\n uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n #else\n uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n struct SpotLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n #if defined( SHADOWMAP_TYPE_PCF )\n uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n #elif defined( SHADOWMAP_TYPE_BASIC )\n uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n #if defined( SHADOWMAP_TYPE_PCF )\n float interleavedGradientNoise( vec2 position ) {\n return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n }\n vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n const float goldenAngle = 2.399963229728653;\n float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n float theta = float( sampleIndex ) * goldenAngle + phi;\n return vec2( cos( theta ), sin( theta ) ) * r;\n }\n #endif\n #if defined( SHADOWMAP_TYPE_PCF )\n float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n float shadow = 1.0;\n shadowCoord.xyz /= shadowCoord.w;\n shadowCoord.z += shadowBias;\n bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n bool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n if ( frustumTest ) {\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float radius = shadowRadius * texelSize.x;\n float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n shadow = (\n texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n ) * 0.2;\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n #elif defined( SHADOWMAP_TYPE_VSM )\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n float shadow = 1.0;\n shadowCoord.xyz /= shadowCoord.w;\n #ifdef USE_REVERSED_DEPTH_BUFFER\n shadowCoord.z -= shadowBias;\n #else\n shadowCoord.z += shadowBias;\n #endif\n bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n bool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n if ( frustumTest ) {\n vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n float mean = distribution.x;\n float variance = distribution.y * distribution.y;\n #ifdef USE_REVERSED_DEPTH_BUFFER\n float hard_shadow = step( mean, shadowCoord.z );\n #else\n float hard_shadow = step( shadowCoord.z, mean );\n #endif\n \n if ( hard_shadow == 1.0 ) {\n shadow = 1.0;\n } else {\n variance = max( variance, 0.0000001 );\n float d = shadowCoord.z - mean;\n float p_max = variance / ( variance + d * d );\n p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n shadow = max( hard_shadow, p_max );\n }\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n #else\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n float shadow = 1.0;\n shadowCoord.xyz /= shadowCoord.w;\n #ifdef USE_REVERSED_DEPTH_BUFFER\n shadowCoord.z -= shadowBias;\n #else\n shadowCoord.z += shadowBias;\n #endif\n bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n bool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n if ( frustumTest ) {\n float depth = texture2D( shadowMap, shadowCoord.xy ).r;\n #ifdef USE_REVERSED_DEPTH_BUFFER\n shadow = step( depth, shadowCoord.z );\n #else\n shadow = step( shadowCoord.z, depth );\n #endif\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n #if defined( SHADOWMAP_TYPE_PCF )\n float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n float shadow = 1.0;\n vec3 lightToPosition = shadowCoord.xyz;\n vec3 bd3D = normalize( lightToPosition );\n vec3 absVec = abs( lightToPosition );\n float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n #ifdef USE_REVERSED_DEPTH_BUFFER\n float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n dp -= shadowBias;\n #else\n float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n dp += shadowBias;\n #endif\n float texelSize = shadowRadius / shadowMapSize.x;\n vec3 absDir = abs( bd3D );\n vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n tangent = normalize( cross( bd3D, tangent ) );\n vec3 bitangent = cross( bd3D, tangent );\n float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n vec2 sample0 = vogelDiskSample( 0, 5, phi );\n vec2 sample1 = vogelDiskSample( 1, 5, phi );\n vec2 sample2 = vogelDiskSample( 2, 5, phi );\n vec2 sample3 = vogelDiskSample( 3, 5, phi );\n vec2 sample4 = vogelDiskSample( 4, 5, phi );\n shadow = (\n texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n ) * 0.2;\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n #elif defined( SHADOWMAP_TYPE_BASIC )\n float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n float shadow = 1.0;\n vec3 lightToPosition = shadowCoord.xyz;\n vec3 absVec = abs( lightToPosition );\n float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n dp += shadowBias;\n vec3 bd3D = normalize( lightToPosition );\n float depth = textureCube( shadowMap, bd3D ).r;\n #ifdef USE_REVERSED_DEPTH_BUFFER\n depth = 1.0 - depth;\n #endif\n shadow = step( dp, depth );\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n #endif\n #endif\n#endif"; + var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n struct SpotLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n#endif"; + var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n #ifdef HAS_NORMAL\n vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #else\n vec3 shadowWorldNormal = vec3( 0.0 );\n #endif\n vec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n #if NUM_DIR_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n shadowWorldPosition = worldPosition;\n #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n #endif\n vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n#endif"; + var shadowmask_pars_fragment = "float getShadowMask() {\n float shadow = 1.0;\n #ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n directionalLight = directionalLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n spotLight = spotLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n PointLightShadow pointLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n pointLight = pointLightShadows[ i ];\n shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #endif\n return shadow;\n}"; + var skinbase_vertex = "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + var skinning_pars_vertex = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n uniform highp sampler2D boneTexture;\n mat4 getBoneMatrix( const in float i ) {\n int size = textureSize( boneTexture, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n#endif"; + var skinning_vertex = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n transformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + var skinnormal_vertex = "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n #ifdef USE_TANGENT\n objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n #endif\n#endif"; + var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif"; + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif"; + var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n return saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color *= toneMappingExposure / 0.6;\n color = ACESInputMat * color;\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n return saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;\n color *= toneMappingExposure;\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n color = AgXInsetMatrix * color;\n color = max( color, 1e-10 ); color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n color = clamp( color, 0.0, 1.0 );\n color = agxDefaultContrastApprox( color );\n color = AgXOutsetMatrix * color;\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n color = clamp( color, 0.0, 1.0 );\n return color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n color *= toneMappingExposure;\n float x = min( color.r, min( color.g, color.b ) );\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n color -= offset;\n float peak = max( color.r, max( color.g, color.b ) );\n if ( peak < StartCompression ) return color;\n float d = 1. - StartCompression;\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n color *= newPeak / peak;\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n return mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + var transmission_fragment = "#ifdef USE_TRANSMISSION\n material.transmission = transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n #endif\n vec3 pos = vWorldPosition;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec4 transmitted = getIBLVolumeRefraction(\n n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n material.attenuationColor, material.attenuationDistance );\n material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif"; + var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n uniform float transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n float w0( float a ) {\n return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n }\n float w1( float a ) {\n return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n }\n float w2( float a ){\n return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n }\n float w3( float a ) {\n return ( 1.0 / 6.0 ) * ( a * a * a );\n }\n float g0( float a ) {\n return w0( a ) + w1( a );\n }\n float g1( float a ) {\n return w2( a ) + w3( a );\n }\n float h0( float a ) {\n return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n }\n float h1( float a ) {\n return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n }\n vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n uv = uv * texelSize.zw + 0.5;\n vec2 iuv = floor( uv );\n vec2 fuv = fract( uv );\n float g0x = g0( fuv.x );\n float g1x = g1( fuv.x );\n float h0x = h0( fuv.x );\n float h1x = h1( fuv.x );\n float h0y = h0( fuv.y );\n float h1y = h1( fuv.y );\n vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n }\n vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n vec2 fLodSizeInv = 1.0 / fLodSize;\n vec2 cLodSizeInv = 1.0 / cLodSize;\n vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n return mix( fSample, cSample, fract( lod ) );\n }\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n vec3 modelScale;\n modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n }\n vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n if ( isinf( attenuationDistance ) ) {\n return vec3( 1.0 );\n } else {\n vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;\n }\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n const in vec3 attenuationColor, const in float attenuationDistance ) {\n vec4 transmittedLight;\n vec3 transmittance;\n #ifdef USE_DISPERSION\n float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n for ( int i = 0; i < 3; i ++ ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n transmittedLight[ i ] = transmissionSample[ i ];\n transmittedLight.a += transmissionSample.a;\n transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n }\n transmittedLight.a /= 3.0;\n #else\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n #endif\n vec3 attenuatedColor = transmittance * transmittedLight.rgb;\n vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n }\n#endif"; + var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n uniform mat3 transmissionMapTransform;\n varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n uniform mat3 thicknessMapTransform;\n varying vec2 vThicknessMapUv;\n#endif"; + var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n uniform mat3 mapTransform;\n varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n uniform mat3 alphaMapTransform;\n varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n uniform mat3 lightMapTransform;\n varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n uniform mat3 aoMapTransform;\n varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n uniform mat3 bumpMapTransform;\n varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n uniform mat3 normalMapTransform;\n varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n uniform mat3 displacementMapTransform;\n varying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n uniform mat3 emissiveMapTransform;\n varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n uniform mat3 metalnessMapTransform;\n varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n uniform mat3 roughnessMapTransform;\n varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n uniform mat3 anisotropyMapTransform;\n varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n uniform mat3 clearcoatMapTransform;\n varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform mat3 clearcoatNormalMapTransform;\n varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform mat3 clearcoatRoughnessMapTransform;\n varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n uniform mat3 sheenColorMapTransform;\n varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n uniform mat3 sheenRoughnessMapTransform;\n varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n uniform mat3 iridescenceMapTransform;\n varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform mat3 iridescenceThicknessMapTransform;\n varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n uniform mat3 specularMapTransform;\n varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n uniform mat3 specularColorMapTransform;\n varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n uniform mat3 specularIntensityMapTransform;\n varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n uniform mat3 transmissionMapTransform;\n varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n uniform mat3 thicknessMapTransform;\n varying vec2 vThicknessMapUv;\n#endif"; + var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n vUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif"; + var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n vec4 worldPosition = vec4( transformed, 1.0 );\n #ifdef USE_BATCHING\n worldPosition = batchingMatrix * worldPosition;\n #endif\n #ifdef USE_INSTANCING\n worldPosition = instanceMatrix * worldPosition;\n #endif\n worldPosition = modelMatrix * worldPosition;\n#endif"; + const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n gl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n vec4 texColor = texture2D( t2D, vUv );\n #ifdef DECODE_VIDEO_TEXTURE\n texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n #endif\n texColor.rgb *= backgroundIntensity;\n gl_FragColor = texColor;\n #include \n #include \n}"; + const vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n gl_Position.z = gl_Position.w;\n}"; + const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n uniform sampler2D envMap;\n#endif\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n #ifdef ENVMAP_TYPE_CUBE\n vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n #else\n vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #endif\n texColor.rgb *= backgroundIntensity;\n gl_FragColor = texColor;\n #include \n #include \n}"; + const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n gl_Position.z = gl_Position.w;\n}"; + const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n gl_FragColor = texColor;\n gl_FragColor.a *= opacity;\n #include \n #include \n}"; + const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n #include \n #include \n #include \n #include \n #ifdef USE_DISPLACEMENTMAP\n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vHighPrecisionZW = gl_Position.zw;\n}"; + const fragment$e = "#if DEPTH_PACKING == 3200\n uniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n vec4 diffuseColor = vec4( 1.0 );\n #include \n #if DEPTH_PACKING == 3200\n diffuseColor.a = opacity;\n #endif\n #include \n #include \n #include \n #include \n #include \n #ifdef USE_REVERSED_DEPTH_BUFFER\n float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n #else\n float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n #endif\n #if DEPTH_PACKING == 3200\n gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n #elif DEPTH_PACKING == 3201\n gl_FragColor = packDepthToRGBA( fragCoordZ );\n #elif DEPTH_PACKING == 3202\n gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n #elif DEPTH_PACKING == 3203\n gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n #endif\n}"; + const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #ifdef USE_DISPLACEMENTMAP\n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vWorldPosition = worldPosition.xyz;\n}"; + const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n vec4 diffuseColor = vec4( 1.0 );\n #include \n #include \n #include \n #include \n #include \n float dist = length( vWorldPosition - referencePosition );\n dist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n dist = saturate( dist );\n gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}"; + const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n}"; + const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n vec3 direction = normalize( vWorldDirection );\n vec2 sampleUV = equirectUv( direction );\n gl_FragColor = texture2D( tEquirect, sampleUV );\n #include \n #include \n}"; + const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vLineDistance = scale * lineDistance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n if ( mod( vLineDistance, totalSize ) > dashSize ) {\n discard;\n }\n vec3 outgoingLight = vec3( 0.0 );\n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n #include \n}"; + const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n #include \n #include \n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n #include \n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n #include \n}"; + const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n}"; + const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 viewDir = normalize( vViewPosition );\n vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n vec3 y = cross( viewDir, x );\n vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n #ifdef USE_MATCAP\n vec4 matcapColor = texture2D( matcap, uv );\n #else\n vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n #endif\n vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n varying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n vViewPosition = - mvPosition.xyz;\n#endif\n}"; + const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n varying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n #include \n #include \n #include \n #include \n gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n #ifdef OPAQUE\n gl_FragColor.a = 1.0;\n #endif\n}"; + const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n #include \n}"; + const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n varying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n#ifdef USE_TRANSMISSION\n vWorldPosition = worldPosition.xyz;\n#endif\n}"; + const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n #define IOR\n #define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n uniform float ior;\n#endif\n#ifdef USE_SPECULAR\n uniform float specularIntensity;\n uniform vec3 specularColor;\n #ifdef USE_SPECULAR_COLORMAP\n uniform sampler2D specularColorMap;\n #endif\n #ifdef USE_SPECULAR_INTENSITYMAP\n uniform sampler2D specularIntensityMap;\n #endif\n#endif\n#ifdef USE_CLEARCOAT\n uniform float clearcoat;\n uniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n uniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n uniform float iridescence;\n uniform float iridescenceIOR;\n uniform float iridescenceThicknessMinimum;\n uniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n uniform vec3 sheenColor;\n uniform float sheenRoughness;\n #ifdef USE_SHEEN_COLORMAP\n uniform sampler2D sheenColorMap;\n #endif\n #ifdef USE_SHEEN_ROUGHNESSMAP\n uniform sampler2D sheenRoughnessMap;\n #endif\n#endif\n#ifdef USE_ANISOTROPY\n uniform vec2 anisotropyVector;\n #ifdef USE_ANISOTROPYMAP\n uniform sampler2D anisotropyMap;\n #endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n #include \n vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n #ifdef USE_SHEEN\n \n outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n #endif\n #ifdef USE_CLEARCOAT\n float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n}"; + const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n varying vec2 vUv;\n uniform mat3 uvTransform;\n#endif\nvoid main() {\n #ifdef USE_POINTS_UV\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n gl_PointSize = size;\n #ifdef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n #endif\n #include \n #include \n #include \n #include \n}"; + const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n vec3 outgoingLight = vec3( 0.0 );\n #include \n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n #include \n}"; + const vertex$2 = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n #include \n #include \n #include \n #include \n}"; + const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 mvPosition = modelViewMatrix[ 3 ];\n vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n #ifndef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) scale *= - mvPosition.z;\n #endif\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n mvPosition.xy += rotatedPosition;\n gl_Position = projectionMatrix * mvPosition;\n #include \n #include \n #include \n}"; + const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n vec3 outgoingLight = vec3( 0.0 );\n #include \n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n}"; + const ShaderChunk = { + alphahash_fragment, + alphahash_pars_fragment, + alphamap_fragment, + alphamap_pars_fragment, + alphatest_fragment, + alphatest_pars_fragment, + aomap_fragment, + aomap_pars_fragment, + batching_pars_vertex, + batching_vertex, + begin_vertex, + beginnormal_vertex, + bsdfs, + iridescence_fragment, + bumpmap_pars_fragment, + clipping_planes_fragment, + clipping_planes_pars_fragment, + clipping_planes_pars_vertex, + clipping_planes_vertex, + color_fragment, + color_pars_fragment, + color_pars_vertex, + color_vertex, + common, + cube_uv_reflection_fragment, + defaultnormal_vertex, + displacementmap_pars_vertex, + displacementmap_vertex, + emissivemap_fragment, + emissivemap_pars_fragment, + colorspace_fragment, + colorspace_pars_fragment, + envmap_fragment, + envmap_common_pars_fragment, + envmap_pars_fragment, + envmap_pars_vertex, + envmap_physical_pars_fragment, + envmap_vertex, + fog_vertex, + fog_pars_vertex, + fog_fragment, + fog_pars_fragment, + gradientmap_pars_fragment, + lightmap_pars_fragment, + lights_lambert_fragment, + lights_lambert_pars_fragment, + lights_pars_begin, + lights_toon_fragment, + lights_toon_pars_fragment, + lights_phong_fragment, + lights_phong_pars_fragment, + lights_physical_fragment, + lights_physical_pars_fragment, + lights_fragment_begin, + lights_fragment_maps, + lights_fragment_end, + lightprobes_pars_fragment, + logdepthbuf_fragment, + logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex, + logdepthbuf_vertex, + map_fragment, + map_pars_fragment, + map_particle_fragment, + map_particle_pars_fragment, + metalnessmap_fragment, + metalnessmap_pars_fragment, + morphinstance_vertex, + morphcolor_vertex, + morphnormal_vertex, + morphtarget_pars_vertex, + morphtarget_vertex, + normal_fragment_begin, + normal_fragment_maps, + normal_pars_fragment, + normal_pars_vertex, + normal_vertex, + normalmap_pars_fragment, + clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps, + clearcoat_pars_fragment, + iridescence_pars_fragment, + opaque_fragment, + packing, + premultiplied_alpha_fragment, + project_vertex, + dithering_fragment, + dithering_pars_fragment, + roughnessmap_fragment, + roughnessmap_pars_fragment, + shadowmap_pars_fragment, + shadowmap_pars_vertex, + shadowmap_vertex, + shadowmask_pars_fragment, + skinbase_vertex, + skinning_pars_vertex, + skinning_vertex, + skinnormal_vertex, + specularmap_fragment, + specularmap_pars_fragment, + tonemapping_fragment, + tonemapping_pars_fragment, + transmission_fragment, + transmission_pars_fragment, + uv_pars_fragment, + uv_pars_vertex, + uv_vertex, + worldpos_vertex, + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distance_vert: vertex$d, + distance_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 + }; + const UniformsLib = { + common: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new Matrix3() }, + reflectivity: { value: 1 }, + // basic, lambert, phong + ior: { value: 1.5 }, + // physical + refractionRatio: { value: 0.98 }, + // basic, lambert, phong + dfgLUT: { value: null } + // DFG LUT for physically-based rendering + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + normalScale: { value: /* @__PURE__ */ new Vector2(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 25e-5 }, + fogNear: { value: 1 }, + fogFar: { value: 2e3 }, + fogColor: { value: /* @__PURE__ */ new Color(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null }, + probesSH: { value: null }, + probesMin: { value: /* @__PURE__ */ new Vector3() }, + probesMax: { value: /* @__PURE__ */ new Vector3() }, + probesResolution: { value: /* @__PURE__ */ new Vector3() } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector2(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 } + } + }; + const ShaderLib = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + specular: { value: /* @__PURE__ */ new Color(1118481) }, + shininess: { value: 30 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.points, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap + ]), + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.sprite, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new Matrix3() } + }, + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + }, + distance: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1e3 } + } + ]), + vertexShader: ShaderChunk.distance_vert, + fragmentShader: ShaderChunk.distance_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /* @__PURE__ */ new Color(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + } + }; + ShaderLib.physical = { + uniforms: /* @__PURE__ */ mergeUniforms([ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector2(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color(0) }, + specularColor: { value: /* @__PURE__ */ new Color(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + anisotropyVector: { value: /* @__PURE__ */ new Vector2() }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix3() } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + }; + const _rgb = { r: 0, b: 0, g: 0 }; + const _m1$1 = /* @__PURE__ */ new Matrix4(); + const _m$1 = /* @__PURE__ */ new Matrix3(); + _m$1.set(-1, 0, 0, 0, 1, 0, 0, 0, 1); + function WebGLBackground(renderer, environments, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function getBackground(scene) { + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = environments.get(background, usePMREM); + } + return background; + } + function render(scene) { + let forceClear = false; + const background = getBackground(scene); + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer.autoClear || forceClear) { + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); + } + } + function addToRenderList(renderList, scene) { + const background = getBackground(scene); + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) { + if (boxMesh === void 0) { + boxMesh = new Mesh( + new BoxGeometry(1, 1, 1), + new ShaderMaterial({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false, + allowOverride: false + }) + ); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer2, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$1.makeRotationFromEuler(scene.backgroundRotation)).transpose(); + if (background.isCubeTexture && background.isRenderTargetTexture === false) { + boxMesh.material.uniforms.backgroundRotation.value.premultiply(_m$1); + } + boxMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === void 0) { + planeMesh = new Mesh( + new PlaneGeometry(2, 2), + new ShaderMaterial({ + name: "BackgroundMaterial", + uniforms: cloneUniforms(ShaderLib.background.uniforms), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false, + allowOverride: false + }) + ); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb, getUnlitUniformColorSpace(renderer)); + state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha2, premultipliedAlpha); + } + function dispose() { + if (boxMesh !== void 0) { + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + boxMesh = void 0; + } + if (planeMesh !== void 0) { + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + planeMesh = void 0; + } + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render, + addToRenderList, + dispose + }; + } + function WebGLBindingStates(gl, attributes) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const bindingStates = {}; + const defaultState = createBindingState(null); + let currentState = defaultState; + let forceUpdate = false; + function setup(object, material, program, geometry, index) { + let updateBuffers = false; + const state = getBindingState(object, geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index); + if (updateBuffers) saveCache(object, geometry, program, index); + if (index !== null) { + attributes.update(index, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer); + } + } + } + function createVertexArrayObject() { + return gl.createVertexArray(); + } + function bindVertexArrayObject(vao) { + return gl.bindVertexArray(vao); + } + function deleteVertexArrayObject(vao) { + return gl.deleteVertexArray(vao); + } + function getBindingState(object, geometry, program, material) { + const wireframe = material.wireframe === true; + let objectMap = bindingStates[geometry.id]; + if (objectMap === void 0) { + objectMap = {}; + bindingStates[geometry.id] = objectMap; + } + const objectId = object.isInstancedMesh === true ? object.id : 0; + let programMap = objectMap[objectId]; + if (programMap === void 0) { + programMap = {}; + objectMap[objectId] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === void 0) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === void 0) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i = 0; i < maxVertexAttributes; i++) { + newAttributes[i] = 0; + enabledAttributes[i] = 0; + attributeDivisors[i] = 0; + } + return { + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name]; + let geometryAttribute = geometryAttributes[name]; + if (geometryAttribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor; + } + if (cachedAttribute === void 0) return true; + if (cachedAttribute.attribute !== geometryAttribute) return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) return true; + if (currentState.index !== index) return true; + return false; + } + function saveCache(object, geometry, program, index) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name]; + if (attribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) attribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) attribute = object.instanceColor; + } + const data = {}; + data.attribute = attribute; + if (attribute && attribute.data) { + data.data = attribute.data; + } + cache[name] = data; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i = 0, il = newAttributes.length; i < il; i++) { + newAttributes[i] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + gl.vertexAttribDivisor(attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i = 0, il = enabledAttributes.length; i < il; i++) { + if (enabledAttributes[i] !== newAttributes[i]) { + gl.disableVertexAttribArray(i); + enabledAttributes[i] = 0; + } + } + } + function vertexAttribPointer(index, size, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index, size, type, stride, offset); + } else { + gl.vertexAttribPointer(index, size, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name]; + if (geometryAttribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== void 0) { + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === void 0) continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType; + if (geometryAttribute.isInterleavedBufferAttribute) { + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + if (data.isInstancedInterleavedBuffer) { + for (let i = 0; i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) { + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + } + } else { + for (let i = 0; i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0; i < programAttribute.locationSize; i++) { + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + (offset + size / programAttribute.locationSize * i) * bytesPerElement, + integer + ); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i = 0; i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i = 0; i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0; i < programAttribute.locationSize; i++) { + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + size / programAttribute.locationSize * i * bytesPerElement, + integer + ); + } + } + } else if (materialDefaultAttributeValues !== void 0) { + const value = materialDefaultAttributeValues[name]; + if (value !== void 0) { + switch (value.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const objectMap = bindingStates[geometryId]; + for (const objectId in objectMap) { + const programMap = objectMap[objectId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === void 0) return; + const objectMap = bindingStates[geometry.id]; + for (const objectId in objectMap) { + const programMap = objectMap[objectId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const objectMap = bindingStates[geometryId]; + for (const objectId in objectMap) { + const programMap = objectMap[objectId]; + if (programMap[program.id] === void 0) continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + } + function releaseStatesOfObject(object) { + for (const geometryId in bindingStates) { + const objectMap = bindingStates[geometryId]; + const objectId = object.isInstancedMesh === true ? object.id : 0; + const programMap = objectMap[objectId]; + if (programMap === void 0) continue; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete objectMap[objectId]; + if (Object.keys(objectMap).length === 0) { + delete bindingStates[geometryId]; + } + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState) return; + currentState = defaultState; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfObject, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; + } + function WebGLBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value) { + mode = value; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) return; + gl.drawArraysInstanced(mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i = 0; i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + } + function WebGLCapabilities(gl, extensions, parameters, utils) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== void 0) return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function textureFormatReadable(textureFormat) { + if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + return false; + } + return true; + } + function textureTypeReadable(textureType) { + const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513) + textureType !== FloatType && !halfFloatSupportedByExt) { + return false; + } + return true; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + let precision = parameters.precision !== void 0 ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + warn("WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has("EXT_clip_control"); + if (parameters.reversedDepthBuffer === true && reversedDepthBuffer === false) { + warn("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."); + } + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const maxSamples = gl.getParameter(gl.MAX_SAMPLES); + const samples = gl.getParameter(gl.SAMPLES); + return { + isWebGL2: true, + // keeping this for backwards compatibility + getMaxAnisotropy, + getMaxPrecision, + textureFormatReadable, + textureTypeReadable, + precision, + logarithmicDepthBuffer, + reversedDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + maxSamples, + samples + }; + } + function WebGLClipping(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane(), viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const planes = material.clippingPlanes, clipIntersection = material.clipIntersection, clipShadows = material.clipShadows; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i = 0; i !== lGlobal; ++i) { + dstArray[i] = globalState[i]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) { + plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i4); + dstArray[i4 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } + } + const LOD_MIN = 4; + const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; + const MAX_SAMPLES = 20; + const GGX_SAMPLES = 256; + const _flatCamera = /* @__PURE__ */ new OrthographicCamera(); + const _clearColor = /* @__PURE__ */ new Color(); + let _oldTarget = null; + let _oldActiveCubeFace = 0; + let _oldActiveMipmapLevel = 0; + let _oldXrEnabled = false; + const _origin = /* @__PURE__ */ new Vector3(); + class PMREMGenerator { + /** + * Constructs a new PMREM generator. + * + * @param {WebGLRenderer} renderer - The renderer. + */ + constructor(renderer) { + this._renderer = renderer; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._sizeLods = []; + this._sigmas = []; + this._lodMeshes = []; + this._backgroundBox = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._blurMaterial = null; + this._ggxMaterial = null; + } + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety. + * + * @param {Scene} scene - The scene to be captured. + * @param {number} [sigma=0] - The blur radius in radians. + * @param {number} [near=0.1] - The near plane distance. + * @param {number} [far=100] - The far plane distance. + * @param {Object} [options={}] - The configuration options. + * @param {number} [options.size=256] - The texture size of the PMREM. + * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromScene(scene, sigma = 0, near = 0.1, far = 100, options = {}) { + const { + size = 256, + position = _origin + } = options; + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + this._setSize(size); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget, position); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + * + * @param {Texture} equirectangular - The equirectangular texture to be converted. + * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + * + * @param {Texture} cubemap - The cubemap texture to be converted. + * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial(this._cubemapMaterial); + } + } + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial(this._equirectMaterial); + } + } + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) this._equirectMaterial.dispose(); + if (this._backgroundBox !== null) { + this._backgroundBox.geometry.dispose(); + this._backgroundBox.material.dispose(); + } + } + // private interface + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) this._blurMaterial.dispose(); + if (this._ggxMaterial !== null) this._ggxMaterial.dispose(); + if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose(); + for (let i = 0; i < this._lodMeshes.length; i++) { + this._lodMeshes[i].geometry.dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel); + this._renderer.xr.enabled = _oldXrEnabled; + outputTarget.scissorTest = false; + _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width = 3 * Math.max(this._cubeSize, 16 * 7); + const height = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget(width, height, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget(width, height, params); + const { _lodMax } = this; + ({ lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes(_lodMax)); + this._blurMaterial = _getBlurShader(_lodMax, width, height); + this._ggxMaterial = _getGGXShader(_lodMax, width, height); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const mesh = new Mesh(new BufferGeometry(), material); + this._renderer.compile(mesh, _flatCamera); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget, position) { + const fov2 = 90; + const aspect2 = 1; + const cubeCamera = new PerspectiveCamera(fov2, aspect2, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer = this._renderer; + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor(_clearColor); + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + const reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + if (reversedDepthBuffer) { + renderer.setRenderTarget(cubeUVRenderTarget); + renderer.clearDepth(); + renderer.setRenderTarget(null); + } + if (this._backgroundBox === null) { + this._backgroundBox = new Mesh( + new BoxGeometry(), + new MeshBasicMaterial({ + name: "PMREM.Background", + side: BackSide, + depthWrite: false, + depthTest: false + }) + ); + } + const backgroundBox = this._backgroundBox; + const backgroundMaterial = backgroundBox.material; + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor); + useSolidColor = true; + } + for (let i = 0; i < 6; i++) { + const col = i % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.position.set(position.x, position.y, position.z); + cubeCamera.lookAt(position.x + forwardSign[i], position.y, position.z); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i]); + cubeCamera.position.set(position.x, position.y, position.z); + cubeCamera.lookAt(position.x, position.y + forwardSign[i], position.z); + } else { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.position.set(position.x, position.y, position.z); + cubeCamera.lookAt(position.x, position.y, position.z + forwardSign[i]); + } + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size); + renderer.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer.render(backgroundBox, cubeCamera); + } + renderer.render(scene, cubeCamera); + } + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = this._lodMeshes[0]; + mesh.material = material; + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); + renderer.setRenderTarget(cubeUVRenderTarget); + renderer.render(mesh, _flatCamera); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + const n = this._lodMeshes.length; + for (let i = 1; i < n; i++) { + this._applyGGXFilter(cubeUVRenderTarget, i - 1, i); + } + renderer.autoClear = autoClear; + } + /** + * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map. + * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the + * GGX BRDF for physically-based rendering. Reads from the previous LOD level and + * applies incremental roughness filtering to avoid over-blurring. + * + * @private + * @param {WebGLRenderTarget} cubeUVRenderTarget + * @param {number} lodIn - Source LOD level to read from + * @param {number} lodOut - Target LOD level to write to + */ + _applyGGXFilter(cubeUVRenderTarget, lodIn, lodOut) { + const renderer = this._renderer; + const pingPongRenderTarget = this._pingPongRenderTarget; + const ggxMaterial = this._ggxMaterial; + const ggxMesh = this._lodMeshes[lodOut]; + ggxMesh.material = ggxMaterial; + const ggxUniforms = ggxMaterial.uniforms; + const targetRoughness = lodOut / (this._lodMeshes.length - 1); + const sourceRoughness = lodIn / (this._lodMeshes.length - 1); + const incrementalRoughness = Math.sqrt(targetRoughness * targetRoughness - sourceRoughness * sourceRoughness); + const blurStrength = 0 + targetRoughness * 1.25; + const adjustedRoughness = incrementalRoughness * blurStrength; + const { _lodMax } = this; + const outputSize = this._sizeLods[lodOut]; + const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); + const y = 4 * (this._cubeSize - outputSize); + ggxUniforms["envMap"].value = cubeUVRenderTarget.texture; + ggxUniforms["roughness"].value = adjustedRoughness; + ggxUniforms["mipInt"].value = _lodMax - lodIn; + _setViewport(pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize); + renderer.setRenderTarget(pingPongRenderTarget); + renderer.render(ggxMesh, _flatCamera); + ggxUniforms["envMap"].value = pingPongRenderTarget.texture; + ggxUniforms["roughness"].value = 0; + ggxUniforms["mipInt"].value = _lodMax - lodOut; + _setViewport(cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize); + renderer.setRenderTarget(cubeUVRenderTarget); + renderer.render(ggxMesh, _flatCamera); + } + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + * + * Used for initial scene blur in fromScene() method when sigma > 0. + * + * @private + * @param {WebGLRenderTarget} cubeUVRenderTarget + * @param {number} lodIn + * @param {number} lodOut + * @param {number} sigma + * @param {Vector3} [poleAxis] + */ + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + "latitudinal", + poleAxis + ); + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + "longitudinal", + poleAxis + ); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + error( + "blur direction must be either latitudinal or longitudinal!" + ); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = this._lodMeshes[lodOut]; + blurMesh.material = blurMaterial; + const blurUniforms = blurMaterial.uniforms; + const pixels2 = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels2) : 2 * Math.PI / (2 * MAX_SAMPLES - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES; + if (samples > MAX_SAMPLES) { + warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`); + } + const weights = []; + let sum = 0; + for (let i = 0; i < MAX_SAMPLES; ++i) { + const x2 = i / sigmaPixels; + const weight = Math.exp(-x2 * x2 / 2); + weights.push(weight); + if (i === 0) { + sum += weight; + } else if (i < samples) { + sum += 2 * weight; + } + } + for (let i = 0; i < weights.length; i++) { + weights[i] = weights[i] / sum; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); + const y = 4 * (this._cubeSize - outputSize); + _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize); + renderer.setRenderTarget(targetOut); + renderer.render(blurMesh, _flatCamera); + } + } + function _createPlanes(lodMax) { + const sizeLods = []; + const sigmas = []; + const lodMeshes = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + for (let i = 0; i < totalLods; i++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i > lodMax - LOD_MIN) { + sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1]; + } else if (i === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max = 1 + texelSize; + const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face2 = 0; face2 < cubeFaces; face2++) { + const x = face2 % 3 * 2 / 3 - 1; + const y = face2 > 2 ? 0 : -1; + const coordinates = [ + x, + y, + 0, + x + 2 / 3, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y + 1, + 0 + ]; + position.set(coordinates, positionSize * vertices * face2); + uv.set(uv1, uvSize * vertices * face2); + const fill2 = [face2, face2, face2, face2, face2, face2]; + faceIndex.set(fill2, faceIndexSize * vertices * face2); + } + const planes = new BufferGeometry(); + planes.setAttribute("position", new BufferAttribute(position, positionSize)); + planes.setAttribute("uv", new BufferAttribute(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize)); + lodMeshes.push(new Mesh(planes, null)); + if (lod > LOD_MIN) { + lod--; + } + } + return { lodMeshes, sizeLods, sigmas }; + } + function _createRenderTarget(width, height, params) { + const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + } + function _setViewport(target, x, y, width, height) { + target.viewport.set(x, y, width, height); + target.scissor.set(x, y, width, height); + } + function _getGGXShader(lodMax, width, height) { + const shaderMaterial = new ShaderMaterial({ + name: "PMREMGGXConvolution", + defines: { + "GGX_SAMPLES": GGX_SAMPLES, + "CUBEUV_TEXEL_WIDTH": 1 / width, + "CUBEUV_TEXEL_HEIGHT": 1 / height, + "CUBEUV_MAX_MIP": `${lodMax}.0` + }, + uniforms: { + "envMap": { value: null }, + "roughness": { value: 0 }, + "mipInt": { value: 0 } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision highp float; + precision highp int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform float roughness; + uniform float mipInt; + + #define ENVMAP_TYPE_CUBE_UV + #include + + #define PI 3.14159265359 + + // Van der Corput radical inverse + float radicalInverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 + } + + // Hammersley sequence + vec2 hammersley(uint i, uint N) { + return vec2(float(i) / float(N), radicalInverse_VdC(i)); + } + + // GGX VNDF importance sampling (Eric Heitz 2018) + // "Sampling the GGX Distribution of Visible Normals" + // https://jcgt.org/published/0007/04/01/ + vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { + float alpha = roughness * roughness; + + // Section 4.1: Orthonormal basis + vec3 T1 = vec3(1.0, 0.0, 0.0); + vec3 T2 = cross(V, T1); + + // Section 4.2: Parameterization of projected area + float r = sqrt(Xi.x); + float phi = 2.0 * PI * Xi.y; + float t1 = r * cos(phi); + float t2 = r * sin(phi); + float s = 0.5 * (1.0 + V.z); + t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; + + // Section 4.3: Reprojection onto hemisphere + vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; + + // Section 3.4: Transform back to ellipsoid configuration + return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); + } + + void main() { + vec3 N = normalize(vOutputDirection); + vec3 V = N; // Assume view direction equals normal for pre-filtering + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + // For very low roughness, just sample the environment directly + if (roughness < 0.001) { + gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); + return; + } + + // Tangent space basis for VNDF sampling + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + + for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { + vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); + + // For PMREM, V = N, so in tangent space V is always (0, 0, 1) + vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); + + // Transform H back to world space + vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); + vec3 L = normalize(2.0 * dot(V, H) * H - V); + + float NdotL = max(dot(N, L), 0.0); + + if(NdotL > 0.0) { + // Sample environment at fixed mip level + // VNDF importance sampling handles the distribution filtering + vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); + + // Weight by NdotL for the split-sum approximation + // VNDF PDF naturally accounts for the visible microfacet distribution + prefilteredColor += sampleColor * NdotL; + totalWeight += NdotL; + } + } + + if (totalWeight > 0.0) { + prefilteredColor = prefilteredColor / totalWeight; + } + + gl_FragColor = vec4(prefilteredColor, 1.0); + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; + } + function _getBlurShader(lodMax, width, height) { + const weights = new Float32Array(MAX_SAMPLES); + const poleAxis = new Vector3(0, 1, 0); + const shaderMaterial = new ShaderMaterial({ + name: "SphericalGaussianBlur", + defines: { + "n": MAX_SAMPLES, + "CUBEUV_TEXEL_WIDTH": 1 / width, + "CUBEUV_TEXEL_HEIGHT": 1 / height, + "CUBEUV_MAX_MIP": `${lodMax}.0` + }, + uniforms: { + "envMap": { value: null }, + "samples": { value: 1 }, + "weights": { value: weights }, + "latitudinal": { value: false }, + "dTheta": { value: 0 }, + "mipInt": { value: 0 }, + "poleAxis": { value: poleAxis } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; + } + function _getEquirectMaterial() { + return new ShaderMaterial({ + name: "EquirectangularToCubeUV", + uniforms: { + "envMap": { value: null } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + } + function _getCubemapMaterial() { + return new ShaderMaterial({ + name: "CubemapToCubeUV", + uniforms: { + "envMap": { value: null }, + "flipEnvMap": { value: -1 } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + } + function _getCommonVertexShader() { + return ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + ` + ); + } + class WebGLCubeRenderTarget extends WebGLRenderTarget { + /** + * Constructs a new cube render target. + * + * @param {number} [size=1] - The size of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(size = 1, options = {}) { + super(size, size, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; + const images = [image, image, image, image, image, image]; + this.texture = new CubeTexture(images); + this._setTextureOptions(options); + this.texture.isRenderTargetTexture = true; + } + /** + * Converts the given equirectangular texture to a cube map. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {Texture} texture - The equirectangular texture. + * @return {WebGLCubeRenderTarget} A reference to this cube render target. + */ + fromEquirectangularTexture(renderer, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ( + /* glsl */ + ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + ` + ), + fragmentShader: ( + /* glsl */ + ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + ) + }; + const geometry = new BoxGeometry(5, 5, 5); + const material = new ShaderMaterial({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter; + const camera = new CubeCamera(1, 10, this); + camera.update(renderer, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + /** + * Clears this cube render target. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {boolean} [color=true] - Whether the color buffer should be cleared or not. + * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not. + * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not. + */ + clear(renderer, color = true, depth = true, stencil = true) { + const currentRenderTarget = renderer.getRenderTarget(); + for (let i = 0; i < 6; i++) { + renderer.setRenderTarget(this, i); + renderer.clear(color, depth, stencil); + } + renderer.setRenderTarget(currentRenderTarget); + } + } + function WebGLEnvironments(renderer) { + let cubeMaps = /* @__PURE__ */ new WeakMap(); + let pmremMaps = /* @__PURE__ */ new WeakMap(); + let pmremGenerator = null; + function get(texture, usePMREM = false) { + if (texture === null || texture === void 0) return null; + if (usePMREM) { + return getPMREM(texture); + } + return getCube(texture); + } + function getCube(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) { + if (cubeMaps.has(texture)) { + const cubemap = cubeMaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget(image.height); + renderTarget.fromEquirectangularTexture(renderer, texture); + cubeMaps.set(texture, renderTarget); + texture.addEventListener("dispose", onCubemapDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function getPMREM(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping; + const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; + if (isEquirectMap || isCubeMap) { + let renderTarget = pmremMaps.get(texture); + const currentPMREMVersion = renderTarget !== void 0 ? renderTarget.texture.pmremVersion : 0; + if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) { + if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + renderTarget.texture.pmremVersion = texture.pmremVersion; + pmremMaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (renderTarget !== void 0) { + return renderTarget.texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + renderTarget.texture.pmremVersion = texture.pmremVersion; + pmremMaps.set(texture, renderTarget); + texture.addEventListener("dispose", onPMREMDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping) { + texture.mapping = CubeReflectionMapping; + } else if (mapping === EquirectangularRefractionMapping) { + texture.mapping = CubeRefractionMapping; + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length = 6; + for (let i = 0; i < length; i++) { + if (image[i] !== void 0) count++; + } + return count === length; + } + function onCubemapDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onCubemapDispose); + const cubemap = cubeMaps.get(texture); + if (cubemap !== void 0) { + cubeMaps.delete(texture); + cubemap.dispose(); + } + } + function onPMREMDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onPMREMDispose); + const pmrem = pmremMaps.get(texture); + if (pmrem !== void 0) { + pmremMaps.delete(texture); + pmrem.dispose(); + } + } + function dispose() { + cubeMaps = /* @__PURE__ */ new WeakMap(); + pmremMaps = /* @__PURE__ */ new WeakMap(); + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; + } + function WebGLExtensions(gl) { + const extensions = {}; + function getExtension(name) { + if (extensions[name] !== void 0) { + return extensions[name]; + } + const extension = gl.getExtension(name); + extensions[name] = extension; + return extension; + } + return { + has: function(name) { + return getExtension(name) !== null; + }, + init: function() { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + getExtension("WEBGL_render_shared_exponent"); + }, + get: function(name) { + const extension = getExtension(name); + if (extension === null) { + warnOnce("WebGLRenderer: " + name + " extension not supported."); + } + return extension; + } + }; + } + function WebGLGeometries(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = /* @__PURE__ */ new WeakMap(); + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name in geometry.attributes) { + attributes.remove(geometry.attributes[name]); + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name in geometryAttributes) { + attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER); + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryPosition === void 0) { + return; + } + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i = 0, l = array.length; i < l; i += 3) { + const a = array[i + 0]; + const b = array[i + 1]; + const c = array[i + 2]; + indices.push(a, b, b, c, c, a); + } + } else { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) { + const a = i + 0; + const b = i + 1; + const c = i + 2; + indices.push(a, b, b, c, c, a); + } + } + const attribute = new (geometryPosition.count >= 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; + } + function WebGLIndexedBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value) { + mode = value; + } + let type, bytesPerElement; + function setIndex(value) { + type = value.type; + bytesPerElement = value.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) return; + gl.drawElementsInstanced(mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i = 0; i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + } + function WebGLInfo(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + error("WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; + } + function WebGLMorphtargets(gl, capabilities, textures) { + const morphTextures = /* @__PURE__ */ new WeakMap(); + const morph = new Vector4(); + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === void 0 || entry.count !== morphTargetsCount) { + let disposeTexture2 = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture2); + }; + var disposeTexture = disposeTexture2; + if (entry !== void 0) entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== void 0; + const hasMorphNormals = geometry.morphAttributes.normal !== void 0; + const hasMorphColors = geometry.morphAttributes.color !== void 0; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) vertexDataCount = 1; + if (hasMorphNormals === true) vertexDataCount = 2; + if (hasMorphColors === true) vertexDataCount = 3; + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + if (width > capabilities.maxTextureSize) { + height = Math.ceil(width / capabilities.maxTextureSize); + width = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width * height * 4 * morphTargetsCount); + const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount); + texture.type = FloatType; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i = 0; i < morphTargetsCount; i++) { + const morphTarget = morphTargets[i]; + const morphNormal = morphNormals[i]; + const morphColor = morphColors[i]; + const offset = width * height * 4 * i; + for (let j = 0; j < morphTarget.count; j++) { + const stride = j * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector2(width, height) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture2); + } + if (object.isInstancedMesh === true && object.morphTexture !== null) { + program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures); + } else { + let morphInfluencesSum = 0; + for (let i = 0; i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + } + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } + return { + update + }; + } + function WebGLObjects(gl, geometries, attributes, bindingStates, info) { + let updateMap = /* @__PURE__ */ new WeakMap(); + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = /* @__PURE__ */ new WeakMap(); + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + bindingStates.releaseStatesOfObject(instancedMesh); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; + } + const toneMappingMap = { + [LinearToneMapping]: "LINEAR_TONE_MAPPING", + [ReinhardToneMapping]: "REINHARD_TONE_MAPPING", + [CineonToneMapping]: "CINEON_TONE_MAPPING", + [ACESFilmicToneMapping]: "ACES_FILMIC_TONE_MAPPING", + [AgXToneMapping]: "AGX_TONE_MAPPING", + [NeutralToneMapping]: "NEUTRAL_TONE_MAPPING", + [CustomToneMapping]: "CUSTOM_TONE_MAPPING" + }; + function WebGLOutput(type, width, height, depth, stencil) { + const targetA = new WebGLRenderTarget(width, height, { + type, + depthBuffer: depth, + stencilBuffer: stencil, + depthTexture: depth ? new DepthTexture(width, height) : void 0 + }); + const targetB = new WebGLRenderTarget(width, height, { + type: HalfFloatType, + depthBuffer: false, + stencilBuffer: false + }); + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)); + geometry.setAttribute("uv", new Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2)); + const material = new RawShaderMaterial({ + uniforms: { + tDiffuse: { value: null } + }, + vertexShader: ( + /* glsl */ + ` + precision highp float; + + uniform mat4 modelViewMatrix; + uniform mat4 projectionMatrix; + + attribute vec3 position; + attribute vec2 uv; + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }` + ), + fragmentShader: ( + /* glsl */ + ` + precision highp float; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + #include + #include + + void main() { + gl_FragColor = texture2D( tDiffuse, vUv ); + + #ifdef LINEAR_TONE_MAPPING + gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); + #elif defined( REINHARD_TONE_MAPPING ) + gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); + #elif defined( CINEON_TONE_MAPPING ) + gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); + #elif defined( ACES_FILMIC_TONE_MAPPING ) + gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); + #elif defined( AGX_TONE_MAPPING ) + gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); + #elif defined( NEUTRAL_TONE_MAPPING ) + gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); + #elif defined( CUSTOM_TONE_MAPPING ) + gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); + #endif + + #ifdef SRGB_TRANSFER + gl_FragColor = sRGBTransferOETF( gl_FragColor ); + #endif + }` + ), + depthTest: false, + depthWrite: false + }); + const mesh = new Mesh(geometry, material); + const camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1); + let _outputColorSpace = null; + let _outputToneMapping = null; + let _isCompositing = false; + let _savedToneMapping; + let _savedRenderTarget = null; + let _effects = []; + let _hasRenderPass = false; + this.setSize = function(width2, height2) { + targetA.setSize(width2, height2); + targetB.setSize(width2, height2); + for (let i = 0; i < _effects.length; i++) { + const effect = _effects[i]; + if (effect.setSize) effect.setSize(width2, height2); + } + }; + this.setEffects = function(effects) { + _effects = effects; + _hasRenderPass = _effects.length > 0 && _effects[0].isRenderPass === true; + const width2 = targetA.width; + const height2 = targetA.height; + for (let i = 0; i < _effects.length; i++) { + const effect = _effects[i]; + if (effect.setSize) effect.setSize(width2, height2); + } + }; + this.begin = function(renderer, renderTarget) { + if (_isCompositing) return false; + if (renderer.toneMapping === NoToneMapping && _effects.length === 0) return false; + _savedRenderTarget = renderTarget; + if (renderTarget !== null) { + const width2 = renderTarget.width; + const height2 = renderTarget.height; + if (targetA.width !== width2 || targetA.height !== height2) { + this.setSize(width2, height2); + } + } + if (_hasRenderPass === false) { + renderer.setRenderTarget(targetA); + } + _savedToneMapping = renderer.toneMapping; + renderer.toneMapping = NoToneMapping; + return true; + }; + this.hasRenderPass = function() { + return _hasRenderPass; + }; + this.end = function(renderer, deltaTime) { + renderer.toneMapping = _savedToneMapping; + _isCompositing = true; + let readBuffer = targetA; + let writeBuffer = targetB; + for (let i = 0; i < _effects.length; i++) { + const effect = _effects[i]; + if (effect.enabled === false) continue; + effect.render(renderer, writeBuffer, readBuffer, deltaTime); + if (effect.needsSwap !== false) { + const temp = readBuffer; + readBuffer = writeBuffer; + writeBuffer = temp; + } + } + if (_outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping) { + _outputColorSpace = renderer.outputColorSpace; + _outputToneMapping = renderer.toneMapping; + material.defines = {}; + if (ColorManagement.getTransfer(_outputColorSpace) === SRGBTransfer) material.defines.SRGB_TRANSFER = ""; + const toneMapping = toneMappingMap[_outputToneMapping]; + if (toneMapping) material.defines[toneMapping] = ""; + material.needsUpdate = true; + } + material.uniforms.tDiffuse.value = readBuffer.texture; + renderer.setRenderTarget(_savedRenderTarget); + renderer.render(mesh, camera); + _savedRenderTarget = null; + _isCompositing = false; + }; + this.isCompositing = function() { + return _isCompositing; + }; + this.dispose = function() { + if (targetA.depthTexture) targetA.depthTexture.dispose(); + targetA.dispose(); + targetB.dispose(); + geometry.dispose(); + material.dispose(); + }; + } + const emptyTexture = /* @__PURE__ */ new Texture(); + const emptyShadowTexture = /* @__PURE__ */ new DepthTexture(1, 1); + const emptyArrayTexture = /* @__PURE__ */ new DataArrayTexture(); + const empty3dTexture = /* @__PURE__ */ new Data3DTexture(); + const emptyCubeTexture = /* @__PURE__ */ new CubeTexture(); + const arrayCacheF32 = []; + const arrayCacheI32 = []; + const mat4array = new Float32Array(16); + const mat3array = new Float32Array(9); + const mat2array = new Float32Array(4); + function flatten(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) return array; + const n = nBlocks * blockSize; + let r = arrayCacheF32[n]; + if (r === void 0) { + r = new Float32Array(n); + arrayCacheF32[n] = r; + } + if (nBlocks !== 0) { + firstElem.toArray(r, 0); + for (let i = 1, offset = 0; i !== nBlocks; ++i) { + offset += blockSize; + array[i].toArray(r, offset); + } + } + return r; + } + function arraysEqual(a, b) { + if (a.length !== b.length) return false; + for (let i = 0, l = a.length; i < l; i++) { + if (a[i] !== b[i]) return false; + } + return true; + } + function copyArray(a, b) { + for (let i = 0, l = b.length; i < l; i++) { + a[i] = b[i]; + } + } + function allocTexUnits(textures, n) { + let r = arrayCacheI32[n]; + if (r === void 0) { + r = new Int32Array(n); + arrayCacheI32[n] = r; + } + for (let i = 0; i !== n; ++i) { + r[i] = textures.allocateTextureUnit(); + } + return r; + } + function setValueV1f(gl, v) { + const cache = this.cache; + if (cache[0] === v) return; + gl.uniform1f(this.addr, v); + cache[0] = v; + } + function setValueV2f(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2f(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform2fv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV3f(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3f(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else if (v.r !== void 0) { + if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { + gl.uniform3f(this.addr, v.r, v.g, v.b); + cache[0] = v.r; + cache[1] = v.g; + cache[2] = v.b; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform3fv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV4f(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform4fv(this.addr, v); + copyArray(cache, v); + } + } + function setValueM2(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === void 0) { + if (arraysEqual(cache, v)) return; + gl.uniformMatrix2fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) return; + mat2array.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array); + copyArray(cache, elements); + } + } + function setValueM3(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === void 0) { + if (arraysEqual(cache, v)) return; + gl.uniformMatrix3fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) return; + mat3array.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array); + copyArray(cache, elements); + } + } + function setValueM4(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === void 0) { + if (arraysEqual(cache, v)) return; + gl.uniformMatrix4fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) return; + mat4array.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array); + copyArray(cache, elements); + } + } + function setValueV1i(gl, v) { + const cache = this.cache; + if (cache[0] === v) return; + gl.uniform1i(this.addr, v); + cache[0] = v; + } + function setValueV2i(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2i(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform2iv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV3i(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3i(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform3iv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV4i(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform4iv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV1ui(gl, v) { + const cache = this.cache; + if (cache[0] === v) return; + gl.uniform1ui(this.addr, v); + cache[0] = v; + } + function setValueV2ui(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2ui(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform2uiv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV3ui(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3ui(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform3uiv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV4ui(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform4uiv(this.addr, v); + copyArray(cache, v); + } + } + function setValueT1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare; + emptyTexture2D = emptyShadowTexture; + } else { + emptyTexture2D = emptyTexture; + } + textures.setTexture2D(v || emptyTexture2D, unit); + } + function setValueT3D1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v || empty3dTexture, unit); + } + function setValueT6(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v || emptyCubeTexture, unit); + } + function setValueT2DArray1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v || emptyArrayTexture, unit); + } + function getSingularSetter(type) { + switch (type) { + case 5126: + return setValueV1f; + // FLOAT + case 35664: + return setValueV2f; + // _VEC2 + case 35665: + return setValueV3f; + // _VEC3 + case 35666: + return setValueV4f; + // _VEC4 + case 35674: + return setValueM2; + // _MAT2 + case 35675: + return setValueM3; + // _MAT3 + case 35676: + return setValueM4; + // _MAT4 + case 5124: + case 35670: + return setValueV1i; + // INT, BOOL + case 35667: + case 35671: + return setValueV2i; + // _VEC2 + case 35668: + case 35672: + return setValueV3i; + // _VEC3 + case 35669: + case 35673: + return setValueV4i; + // _VEC4 + case 5125: + return setValueV1ui; + // UINT + case 36294: + return setValueV2ui; + // _VEC2 + case 36295: + return setValueV3ui; + // _VEC3 + case 36296: + return setValueV4ui; + // _VEC4 + case 35678: + // SAMPLER_2D + case 36198: + // SAMPLER_EXTERNAL_OES + case 36298: + // INT_SAMPLER_2D + case 36306: + // UNSIGNED_INT_SAMPLER_2D + case 35682: + return setValueT1; + case 35679: + // SAMPLER_3D + case 36299: + // INT_SAMPLER_3D + case 36307: + return setValueT3D1; + case 35680: + // SAMPLER_CUBE + case 36300: + // INT_SAMPLER_CUBE + case 36308: + // UNSIGNED_INT_SAMPLER_CUBE + case 36293: + return setValueT6; + case 36289: + // SAMPLER_2D_ARRAY + case 36303: + // INT_SAMPLER_2D_ARRAY + case 36311: + // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 36292: + return setValueT2DArray1; + } + } + function setValueV1fArray(gl, v) { + gl.uniform1fv(this.addr, v); + } + function setValueV2fArray(gl, v) { + const data = flatten(v, this.size, 2); + gl.uniform2fv(this.addr, data); + } + function setValueV3fArray(gl, v) { + const data = flatten(v, this.size, 3); + gl.uniform3fv(this.addr, data); + } + function setValueV4fArray(gl, v) { + const data = flatten(v, this.size, 4); + gl.uniform4fv(this.addr, data); + } + function setValueM2Array(gl, v) { + const data = flatten(v, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data); + } + function setValueM3Array(gl, v) { + const data = flatten(v, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data); + } + function setValueM4Array(gl, v) { + const data = flatten(v, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data); + } + function setValueV1iArray(gl, v) { + gl.uniform1iv(this.addr, v); + } + function setValueV2iArray(gl, v) { + gl.uniform2iv(this.addr, v); + } + function setValueV3iArray(gl, v) { + gl.uniform3iv(this.addr, v); + } + function setValueV4iArray(gl, v) { + gl.uniform4iv(this.addr, v); + } + function setValueV1uiArray(gl, v) { + gl.uniform1uiv(this.addr, v); + } + function setValueV2uiArray(gl, v) { + gl.uniform2uiv(this.addr, v); + } + function setValueV3uiArray(gl, v) { + gl.uniform3uiv(this.addr, v); + } + function setValueV4uiArray(gl, v) { + gl.uniform4uiv(this.addr, v); + } + function setValueT1Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyTexture2D = emptyShadowTexture; + } else { + emptyTexture2D = emptyTexture; + } + for (let i = 0; i !== n; ++i) { + textures.setTexture2D(v[i] || emptyTexture2D, units[i]); + } + } + function setValueT3DArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0; i !== n; ++i) { + textures.setTexture3D(v[i] || empty3dTexture, units[i]); + } + } + function setValueT6Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0; i !== n; ++i) { + textures.setTextureCube(v[i] || emptyCubeTexture, units[i]); + } + } + function setValueT2DArrayArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0; i !== n; ++i) { + textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]); + } + } + function getPureArraySetter(type) { + switch (type) { + case 5126: + return setValueV1fArray; + // FLOAT + case 35664: + return setValueV2fArray; + // _VEC2 + case 35665: + return setValueV3fArray; + // _VEC3 + case 35666: + return setValueV4fArray; + // _VEC4 + case 35674: + return setValueM2Array; + // _MAT2 + case 35675: + return setValueM3Array; + // _MAT3 + case 35676: + return setValueM4Array; + // _MAT4 + case 5124: + case 35670: + return setValueV1iArray; + // INT, BOOL + case 35667: + case 35671: + return setValueV2iArray; + // _VEC2 + case 35668: + case 35672: + return setValueV3iArray; + // _VEC3 + case 35669: + case 35673: + return setValueV4iArray; + // _VEC4 + case 5125: + return setValueV1uiArray; + // UINT + case 36294: + return setValueV2uiArray; + // _VEC2 + case 36295: + return setValueV3uiArray; + // _VEC3 + case 36296: + return setValueV4uiArray; + // _VEC4 + case 35678: + // SAMPLER_2D + case 36198: + // SAMPLER_EXTERNAL_OES + case 36298: + // INT_SAMPLER_2D + case 36306: + // UNSIGNED_INT_SAMPLER_2D + case 35682: + return setValueT1Array; + case 35679: + // SAMPLER_3D + case 36299: + // INT_SAMPLER_3D + case 36307: + return setValueT3DArray; + case 35680: + // SAMPLER_CUBE + case 36300: + // INT_SAMPLER_CUBE + case 36308: + // UNSIGNED_INT_SAMPLER_CUBE + case 36293: + return setValueT6Array; + case 36289: + // SAMPLER_2D_ARRAY + case 36303: + // INT_SAMPLER_2D_ARRAY + case 36311: + // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 36292: + return setValueT2DArrayArray; + } + } + class SingleUniform { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter(activeInfo.type); + } + } + class PureArrayUniform { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter(activeInfo.type); + } + } + class StructuredUniform { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value, textures) { + const seq = this.seq; + for (let i = 0, n = seq.length; i !== n; ++i) { + const u = seq[i]; + u.setValue(gl, value[u.id], textures); + } + } + } + const RePathPart = /(\w+)(\])?(\[|\.)?/g; + function addUniform(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; + } + function parseUniform(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart.lastIndex = 0; + while (true) { + const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) id = id | 0; + if (subscript === void 0 || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform(container, subscript === void 0 ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr)); + break; + } else { + const map = container.map; + let next = map[id]; + if (next === void 0) { + next = new StructuredUniform(id); + addUniform(container, next); + } + container = next; + } + } + } + class WebGLUniforms { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0; i < n; ++i) { + const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); + parseUniform(info, addr, this); + } + const shadowSamplers = []; + const otherUniforms = []; + for (const u of this.seq) { + if (u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW) { + shadowSamplers.push(u); + } else { + otherUniforms.push(u); + } + } + if (shadowSamplers.length > 0) { + this.seq = shadowSamplers.concat(otherUniforms); + } + } + setValue(gl, name, value, textures) { + const u = this.map[name]; + if (u !== void 0) u.setValue(gl, value, textures); + } + setOptional(gl, object, name) { + const v = object[name]; + if (v !== void 0) this.setValue(gl, name, v); + } + static upload(gl, seq, values, textures) { + for (let i = 0, n = seq.length; i !== n; ++i) { + const u = seq[i], v = values[u.id]; + if (v.needsUpdate !== false) { + u.setValue(gl, v.value, textures); + } + } + } + static seqWithValue(seq, values) { + const r = []; + for (let i = 0, n = seq.length; i !== n; ++i) { + const u = seq[i]; + if (u.id in values) r.push(u); + } + return r; + } + } + function WebGLShader(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; + } + const COMPLETION_STATUS_KHR = 37297; + let programIdCount = 0; + function handleSource(string, errorLine) { + const lines = string.split("\n"); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i = from; i < to; i++) { + const line = i + 1; + lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i]}`); + } + return lines2.join("\n"); + } + const _m0 = /* @__PURE__ */ new Matrix3(); + function getEncodingComponents(colorSpace) { + ColorManagement._getMatrix(_m0, ColorManagement.workingColorSpace, colorSpace); + const encodingMatrix = `mat3( ${_m0.elements.map((v) => v.toFixed(4))} )`; + switch (ColorManagement.getTransfer(colorSpace)) { + case LinearTransfer: + return [encodingMatrix, "LinearTransferOETF"]; + case SRGBTransfer: + return [encodingMatrix, "sRGBTransferOETF"]; + default: + warn("WebGLProgram: Unsupported color space: ", colorSpace); + return [encodingMatrix, "LinearTransferOETF"]; + } + } + function getShaderErrors(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const shaderInfoLog = gl.getShaderInfoLog(shader) || ""; + const errors = shaderInfoLog.trim(); + if (status && errors === "") return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + "\n\n" + errors + "\n\n" + handleSource(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } + } + function getTexelEncodingFunction(functionName, colorSpace) { + const components = getEncodingComponents(colorSpace); + return [ + `vec4 ${functionName}( vec4 value ) {`, + ` return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`, + "}" + ].join("\n"); + } + const toneMappingFunctions = { + [LinearToneMapping]: "Linear", + [ReinhardToneMapping]: "Reinhard", + [CineonToneMapping]: "Cineon", + [ACESFilmicToneMapping]: "ACESFilmic", + [AgXToneMapping]: "AgX", + [NeutralToneMapping]: "Neutral", + [CustomToneMapping]: "Custom" + }; + function getToneMappingFunction(functionName, toneMapping) { + const toneMappingName = toneMappingFunctions[toneMapping]; + if (toneMappingName === void 0) { + warn("WebGLProgram: Unsupported toneMapping:", toneMapping); + return "vec3 " + functionName + "( vec3 color ) { return LinearToneMapping( color ); }"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + } + const _v0 = /* @__PURE__ */ new Vector3(); + function getLuminanceFunction() { + ColorManagement.getLuminanceCoefficients(_v0); + const r = _v0.x.toFixed(4); + const g = _v0.y.toFixed(4); + const b = _v0.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${r}, ${g}, ${b} );`, + " return dot( weights, rgb );", + "}" + ].join("\n"); + } + function generateVertexExtensions(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ]; + return chunks.filter(filterEmptyLine).join("\n"); + } + function generateDefines(defines) { + const chunks = []; + for (const name in defines) { + const value = defines[name]; + if (value === false) continue; + chunks.push("#define " + name + " " + value); + } + return chunks.join("\n"); + } + function fetchAttributeLocations(gl, program) { + const attributes = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0; i < n; i++) { + const info = gl.getActiveAttrib(program, i); + const name = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) locationSize = 2; + if (info.type === gl.FLOAT_MAT3) locationSize = 3; + if (info.type === gl.FLOAT_MAT4) locationSize = 4; + attributes[name] = { + type: info.type, + location: gl.getAttribLocation(program, name), + locationSize + }; + } + return attributes; + } + function filterEmptyLine(string) { + return string !== ""; + } + function replaceLightNums(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); + } + function replaceClippingPlaneNums(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); + } + const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + function resolveIncludes(string) { + return string.replace(includePattern, includeReplacer); + } + const shaderChunkMap = /* @__PURE__ */ new Map(); + function includeReplacer(match, include) { + let string = ShaderChunk[include]; + if (string === void 0) { + const newInclude = shaderChunkMap.get(include); + if (newInclude !== void 0) { + string = ShaderChunk[newInclude]; + warn('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes(string); + } + const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + function unrollLoops(string) { + return string.replace(unrollLoopPattern, loopReplacer); + } + function loopReplacer(match, start, end, snippet) { + let string = ""; + for (let i = parseInt(start); i < parseInt(end); i++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); + } + return string; + } + function generatePrecision(parameters) { + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + if (parameters.precision === "highp") { + precisionstring += "\n#define HIGH_PRECISION"; + } else if (parameters.precision === "mediump") { + precisionstring += "\n#define MEDIUM_PRECISION"; + } else if (parameters.precision === "lowp") { + precisionstring += "\n#define LOW_PRECISION"; + } + return precisionstring; + } + const shadowMapTypeDefines = { + [PCFShadowMap]: "SHADOWMAP_TYPE_PCF", + [VSMShadowMap]: "SHADOWMAP_TYPE_VSM" + }; + function generateShadowMapTypeDefine(parameters) { + return shadowMapTypeDefines[parameters.shadowMapType] || "SHADOWMAP_TYPE_BASIC"; + } + const envMapTypeDefines = { + [CubeReflectionMapping]: "ENVMAP_TYPE_CUBE", + [CubeRefractionMapping]: "ENVMAP_TYPE_CUBE", + [CubeUVReflectionMapping]: "ENVMAP_TYPE_CUBE_UV" + }; + function generateEnvMapTypeDefine(parameters) { + if (parameters.envMap === false) return "ENVMAP_TYPE_CUBE"; + return envMapTypeDefines[parameters.envMapMode] || "ENVMAP_TYPE_CUBE"; + } + const envMapModeDefines = { + [CubeRefractionMapping]: "ENVMAP_MODE_REFRACTION" + }; + function generateEnvMapModeDefine(parameters) { + if (parameters.envMap === false) return "ENVMAP_MODE_REFLECTION"; + return envMapModeDefines[parameters.envMapMode] || "ENVMAP_MODE_REFLECTION"; + } + const envMapBlendingDefines = { + [MultiplyOperation]: "ENVMAP_BLENDING_MULTIPLY", + [MixOperation]: "ENVMAP_BLENDING_MIX", + [AddOperation]: "ENVMAP_BLENDING_ADD" + }; + function generateEnvMapBlendingDefine(parameters) { + if (parameters.envMap === false) return "ENVMAP_BLENDING_NONE"; + return envMapBlendingDefines[parameters.combine] || "ENVMAP_BLENDING_NONE"; + } + function generateCubeUVSize(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; + } + function WebGLProgram(renderer, cacheKey, parameters, bindingStates) { + const gl = renderer.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine(parameters); + const envMapModeDefine = generateEnvMapModeDefine(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters); + const envMapCubeUVSize = generateCubeUVSize(parameters); + const customVertexExtensions = generateVertexExtensions(parameters); + const customDefines = generateDefines(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + "\n" : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join("\n"); + if (prefixVertex.length > 0) { + prefixVertex += "\n"; + } + prefixFragment = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join("\n"); + if (prefixFragment.length > 0) { + prefixFragment += "\n"; + } + } else { + prefixVertex = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + // + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + // + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexNormals ? "#define HAS_NORMAL" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", + parameters.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + " attribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + " attribute vec3 instanceColor;", + "#endif", + "#ifdef USE_INSTANCING_MORPH", + " uniform sampler2D morphTexture;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + " attribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + " attribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + " attribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + " attribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + " attribute vec4 color;", + "#elif defined( USE_COLOR )", + " attribute vec3 color;", + "#endif", + "#ifdef USE_SKINNING", + " attribute vec4 skinIndex;", + " attribute vec4 skinWeight;", + "#endif", + "\n" + ].filter(filterEmptyLine).join("\n"); + prefixFragment = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.packedNormalMap ? "#define USE_PACKED_NORMALMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.dispersion ? "#define USE_DISPERSION" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas || parameters.batchingColor ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.numLightProbeGrids > 0 ? "#define USE_LIGHT_PROBES_GRID" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", + parameters.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping ? ShaderChunk["tonemapping_pars_fragment"] : "", + // this code is required here because it is used by the toneMapping() function defined below + parameters.toneMapping !== NoToneMapping ? getToneMappingFunction("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk["colorspace_pars_fragment"], + // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction("linearToOutputTexel", parameters.outputColorSpace), + getLuminanceFunction(), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + "\n" + ].filter(filterEmptyLine).join("\n"); + } + vertexShader = resolveIncludes(vertexShader); + vertexShader = replaceLightNums(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums(vertexShader, parameters); + fragmentShader = resolveIncludes(fragmentShader); + fragmentShader = replaceLightNums(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters); + vertexShader = unrollLoops(vertexShader); + fragmentShader = unrollLoops(fragmentShader); + if (parameters.isRawShaderMaterial !== true) { + versionString = "#version 300 es\n"; + prefixVertex = [ + customVertexExtensions, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join("\n") + "\n" + prefixVertex; + prefixFragment = [ + "#define varying in", + parameters.glslVersion === GLSL3 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL3 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join("\n") + "\n" + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== void 0) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer.debug.checkShaderErrors) { + const programInfoLog = gl.getProgramInfoLog(program) || ""; + const vertexShaderInfoLog = gl.getShaderInfoLog(glVertexShader) || ""; + const fragmentShaderInfoLog = gl.getShaderInfoLog(glFragmentShader) || ""; + const programLog = programInfoLog.trim(); + const vertexLog = vertexShaderInfoLog.trim(); + const fragmentLog = fragmentShaderInfoLog.trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer.debug.onShaderError === "function") { + renderer.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors(gl, glFragmentShader, "fragment"); + error( + "THREE.WebGLProgram: Shader Error " + gl.getError() + " - VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + "\n\nMaterial Name: " + self2.name + "\nMaterial Type: " + self2.type + "\n\nProgram Info Log: " + programLog + "\n" + vertexErrors + "\n" + fragmentErrors + ); + } + } else if (programLog !== "") { + warn("WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms(gl, program); + cachedAttributes = fetchAttributeLocations(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === void 0) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === void 0) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = void 0; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; + } + let _id = 0; + class WebGLShaderCache { + constructor() { + this.shaderCache = /* @__PURE__ */ new Map(); + this.materialCache = /* @__PURE__ */ new Map(); + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === void 0) { + set = /* @__PURE__ */ new Set(); + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === void 0) { + stage = new WebGLShaderStage(code); + cache.set(code, stage); + } + return stage; + } + } + class WebGLShaderStage { + constructor(code) { + this.id = _id++; + this.code = code; + this.usedTimes = 0; + } + } + function isPackedRGFormat(format) { + return format === RGFormat || format === RG11_EAC_Format || format === RED_GREEN_RGTC2_Format; + } + function WebGLPrograms(renderer, environments, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const _activeChannels = /* @__PURE__ */ new Set(); + const programs = []; + const programsMap = /* @__PURE__ */ new Map(); + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distance", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value) { + _activeChannels.add(value); + if (value === 0) return "uv"; + return `uv${value}`; + } + function getParameters(material, lights, shadows, scene, object, lightProbeGrids) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ? scene.environment : null; + const usePMREM = material.isMeshStandardMaterial || material.isMeshLambertMaterial && !material.envMap || material.isMeshPhongMaterial && !material.envMap; + const envMap = environments.get(material.envMap || environment, usePMREM); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + warn("WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== void 0) morphTextureStride = 1; + if (geometry.morphAttributes.normal !== void 0) morphTextureStride = 2; + if (geometry.morphAttributes.color !== void 0) morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer.getRenderTarget(); + const reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer.toneMapping; + } + } + const parameters = { + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + outputColorSpace: currentRenderTarget === null ? renderer.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : ColorManagement.workingColorSpace, + alphaToCoverage: !!material.alphaToCoverage, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + packedNormalMap: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap && isPackedRGFormat(material.normalMap.format), + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + dispersion: HAS_DISPERSION, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + // + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + // + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexNormals: !!geometry.attributes.normal, + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: !!fog && fog.isFogExp2, + flatShading: material.wireframe === false && (material.flatShading === true || geometry.attributes.normal === void 0 && HAS_NORMALMAP === false && (material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isMeshPhysicalMaterial)), + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + reversedDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== void 0, + morphNormals: geometry.morphAttributes.normal !== void 0, + morphColors: geometry.morphAttributes.color !== void 0, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numLightProbeGrids: lightProbeGrids.length, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + toneMapping, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement.getTransfer(material.map.colorSpace) === SRGBTransfer, + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + parameters.vertexUv1s = _activeChannels.has(1); + parameters.vertexUv2s = _activeChannels.has(2); + parameters.vertexUv3s = _activeChannels.has(3); + _activeChannels.clear(); + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== void 0) { + for (const name in parameters.defines) { + array.push(name); + array.push(parameters.defines[name]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.instancing) + _programLayers.enable(0); + if (parameters.instancingColor) + _programLayers.enable(1); + if (parameters.instancingMorph) + _programLayers.enable(2); + if (parameters.matcap) + _programLayers.enable(3); + if (parameters.envMap) + _programLayers.enable(4); + if (parameters.normalMapObjectSpace) + _programLayers.enable(5); + if (parameters.normalMapTangentSpace) + _programLayers.enable(6); + if (parameters.clearcoat) + _programLayers.enable(7); + if (parameters.iridescence) + _programLayers.enable(8); + if (parameters.alphaTest) + _programLayers.enable(9); + if (parameters.vertexColors) + _programLayers.enable(10); + if (parameters.vertexAlphas) + _programLayers.enable(11); + if (parameters.vertexUv1s) + _programLayers.enable(12); + if (parameters.vertexUv2s) + _programLayers.enable(13); + if (parameters.vertexUv3s) + _programLayers.enable(14); + if (parameters.vertexTangents) + _programLayers.enable(15); + if (parameters.anisotropy) + _programLayers.enable(16); + if (parameters.alphaHash) + _programLayers.enable(17); + if (parameters.batching) + _programLayers.enable(18); + if (parameters.dispersion) + _programLayers.enable(19); + if (parameters.batchingColor) + _programLayers.enable(20); + if (parameters.gradientMap) + _programLayers.enable(21); + if (parameters.packedNormalMap) + _programLayers.enable(22); + if (parameters.vertexNormals) + _programLayers.enable(23); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.reversedDepthBuffer) + _programLayers.enable(4); + if (parameters.skinning) + _programLayers.enable(5); + if (parameters.morphTargets) + _programLayers.enable(6); + if (parameters.morphNormals) + _programLayers.enable(7); + if (parameters.morphColors) + _programLayers.enable(8); + if (parameters.premultipliedAlpha) + _programLayers.enable(9); + if (parameters.shadowMapEnabled) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + if (parameters.decodeVideoTextureEmissive) + _programLayers.enable(20); + if (parameters.alphaToCoverage) + _programLayers.enable(21); + if (parameters.numLightProbeGrids > 0) + _programLayers.enable(22); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib[shaderID]; + uniforms = UniformsUtils.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program = programsMap.get(cacheKey); + if (program !== void 0) { + ++program.usedTimes; + } else { + program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates); + programs.push(program); + programsMap.set(cacheKey, program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i = programs.indexOf(program); + programs[i] = programs[programs.length - 1]; + programs.pop(); + programsMap.delete(program.cacheKey); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs, + dispose + }; + } + function WebGLProperties() { + let properties = /* @__PURE__ */ new WeakMap(); + function has(object) { + return properties.has(object); + } + function get(object) { + let map = properties.get(object); + if (map === void 0) { + map = {}; + properties.set(object, map); + } + return map; + } + function remove(object) { + properties.delete(object); + } + function update(object, key, value) { + properties.get(object)[key] = value; + } + function dispose() { + properties = /* @__PURE__ */ new WeakMap(); + } + return { + has, + get, + remove, + update, + dispose + }; + } + function painterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.material.id !== b.material.id) { + return a.material.id - b.material.id; + } else if (a.materialVariant !== b.materialVariant) { + return a.materialVariant - b.materialVariant; + } else if (a.z !== b.z) { + return a.z - b.z; + } else { + return a.id - b.id; + } + } + function reversePainterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.z !== b.z) { + return b.z - a.z; + } else { + return a.id - b.id; + } + } + function WebGLRenderList() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function materialVariant(object) { + let variant = 0; + if (object.isInstancedMesh) variant += 2; + if (object.isSkinnedMesh) variant += 1; + return variant; + } + function getNextRenderItem(object, geometry, material, groupOrder, z, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === void 0) { + renderItem = { + id: object.id, + object, + geometry, + material, + materialVariant: materialVariant(object), + groupOrder, + renderOrder: object.renderOrder, + z, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.materialVariant = materialVariant(object); + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable); + if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable); + if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable); + } + function finish() { + for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) { + const renderItem = renderItems[i]; + if (renderItem.id === null) break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; + } + function WebGLRenderLists() { + let lists = /* @__PURE__ */ new WeakMap(); + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === void 0) { + list = new WebGLRenderList(); + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList(); + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = /* @__PURE__ */ new WeakMap(); + } + return { + get, + dispose + }; + } + function UniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== void 0) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + case "SpotLight": + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + function ShadowUniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== void 0) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + case "SpotLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + case "PointLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1e3 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + let nextVersion = 0; + function shadowCastingAndTexturingLightsFirst(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); + } + function WebGLLights(extensions) { + const cache = new UniformsCache(); + const shadowCache = ShadowUniformsCache(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i = 0; i < 9; i++) state.probe.push(new Vector3()); + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + function setup(lights) { + let r = 0, g = 0, b = 0; + for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst); + for (let i = 0, l = lights.length; i < l; i++) { + const light = lights[i]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + let shadowMap = null; + if (light.shadow && light.shadow.map) { + if (light.shadow.map.texture.format === RGFormat) { + shadowMap = light.shadow.map.texture; + } else { + shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture; + } + } + if (light.isAmbientLight) { + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; + } else if (light.isLightProbe) { + for (let j = 0; j < 9; j++) { + state.probe[j].addScaledVector(light.sh.coefficients[j], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + } + } + state.ambient[0] = r; + state.ambient[1] = g; + state.ambient[2] = b; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i = 0, l = lights.length; i < l; i++) { + const light = lights[i]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; + } + function WebGLRenderState(extensions) { + const lights = new WebGLLights(extensions); + const lightsArray = []; + const shadowsArray = []; + const lightProbeGridArray = []; + function init(camera) { + state.camera = camera; + lightsArray.length = 0; + shadowsArray.length = 0; + lightProbeGridArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function pushLightProbeGrid(volume) { + lightProbeGridArray.push(volume); + } + function setupLights() { + lights.setup(lightsArray); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + lightProbeGridArray, + camera: null, + lights, + transmissionRenderTarget: {}, + textureUnits: 0 + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow, + pushLightProbeGrid + }; + } + function WebGLRenderStates(extensions) { + let renderStates = /* @__PURE__ */ new WeakMap(); + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === void 0) { + renderState = new WebGLRenderState(extensions); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState(extensions); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = /* @__PURE__ */ new WeakMap(); + } + return { + get, + dispose + }; + } + const vertex = "void main() {\n gl_Position = vec4( position, 1.0 );\n}"; + const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nvoid main() {\n const float samples = float( VSM_SAMPLES );\n float mean = 0.0;\n float squared_mean = 0.0;\n float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n float uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n for ( float i = 0.0; i < samples; i ++ ) {\n float uvOffset = uvStart + i * uvStride;\n #ifdef HORIZONTAL_PASS\n vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean / samples;\n squared_mean = squared_mean / samples;\n float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );\n gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}"; + const _cubeDirections = [ + /* @__PURE__ */ new Vector3(1, 0, 0), + /* @__PURE__ */ new Vector3(-1, 0, 0), + /* @__PURE__ */ new Vector3(0, 1, 0), + /* @__PURE__ */ new Vector3(0, -1, 0), + /* @__PURE__ */ new Vector3(0, 0, 1), + /* @__PURE__ */ new Vector3(0, 0, -1) + ]; + const _cubeUps = [ + /* @__PURE__ */ new Vector3(0, -1, 0), + /* @__PURE__ */ new Vector3(0, -1, 0), + /* @__PURE__ */ new Vector3(0, 0, 1), + /* @__PURE__ */ new Vector3(0, 0, -1), + /* @__PURE__ */ new Vector3(0, -1, 0), + /* @__PURE__ */ new Vector3(0, -1, 0) + ]; + const _projScreenMatrix = /* @__PURE__ */ new Matrix4(); + const _lightPositionWorld = /* @__PURE__ */ new Vector3(); + const _lookTarget = /* @__PURE__ */ new Vector3(); + function WebGLShadowMap(renderer, objects, capabilities) { + let _frustum2 = new Frustum(); + const _shadowMapSize = new Vector2(), _viewportSize = new Vector2(), _viewport = new Vector4(), _depthMaterial = new MeshDepthMaterial(), _distanceMaterial = new MeshDistanceMaterial(), _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize; + const shadowSide = { [FrontSide]: BackSide, [BackSide]: FrontSide, [DoubleSide]: DoubleSide }; + const shadowMaterialVertical = new ShaderMaterial({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4 } + }, + vertexShader: vertex, + fragmentShader: fragment + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + "position", + new BufferAttribute( + new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), + 3 + ) + ); + const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) return; + if (scope.autoUpdate === false && scope.needsUpdate === false) return; + if (lights.length === 0) return; + if (this.type === PCFSoftShadowMap) { + warn("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."); + this.type = PCFShadowMap; + } + const currentRenderTarget = renderer.getRenderTarget(); + const activeCubeFace = renderer.getActiveCubeFace(); + const activeMipmapLevel = renderer.getActiveMipmapLevel(); + const _state = renderer.state; + _state.setBlending(NoBlending); + if (_state.buffers.depth.getReversed() === true) { + _state.buffers.color.setClear(0, 0, 0, 0); + } else { + _state.buffers.color.setClear(1, 1, 1, 1); + } + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const typeChanged = _previousType !== this.type; + if (typeChanged) { + scene.traverse(function(object) { + if (object.material) { + if (Array.isArray(object.material)) { + object.material.forEach((mat) => mat.needsUpdate = true); + } else { + object.material.needsUpdate = true; + } + } + }); + } + for (let i = 0, il = lights.length; i < il; i++) { + const light = lights[i]; + const shadow = light.shadow; + if (shadow === void 0) { + warn("WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + const reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + shadow.camera._reversedDepth = reversedDepthBuffer; + if (shadow.map === null || typeChanged === true) { + if (shadow.map !== null) { + if (shadow.map.depthTexture !== null) { + shadow.map.depthTexture.dispose(); + shadow.map.depthTexture = null; + } + shadow.map.dispose(); + } + if (this.type === VSMShadowMap) { + if (light.isPointLight) { + warn("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead."); + continue; + } + shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, { + format: RGFormat, + type: HalfFloatType, + minFilter: LinearFilter, + magFilter: LinearFilter, + generateMipmaps: false + }); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.map.depthTexture = new DepthTexture(_shadowMapSize.x, _shadowMapSize.y, FloatType); + shadow.map.depthTexture.name = light.name + ".shadowMapDepth"; + shadow.map.depthTexture.format = DepthFormat; + shadow.map.depthTexture.compareFunction = null; + shadow.map.depthTexture.minFilter = NearestFilter; + shadow.map.depthTexture.magFilter = NearestFilter; + } else { + if (light.isPointLight) { + shadow.map = new WebGLCubeRenderTarget(_shadowMapSize.x); + shadow.map.depthTexture = new CubeDepthTexture(_shadowMapSize.x, UnsignedIntType); + } else { + shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y); + shadow.map.depthTexture = new DepthTexture(_shadowMapSize.x, _shadowMapSize.y, UnsignedIntType); + } + shadow.map.depthTexture.name = light.name + ".shadowMap"; + shadow.map.depthTexture.format = DepthFormat; + if (this.type === PCFShadowMap) { + shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare; + shadow.map.depthTexture.minFilter = LinearFilter; + shadow.map.depthTexture.magFilter = LinearFilter; + } else { + shadow.map.depthTexture.compareFunction = null; + shadow.map.depthTexture.minFilter = NearestFilter; + shadow.map.depthTexture.magFilter = NearestFilter; + } + } + shadow.camera.updateProjectionMatrix(); + } + const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1; + for (let face2 = 0; face2 < faceCount; face2++) { + if (shadow.map.isWebGLCubeRenderTarget) { + renderer.setRenderTarget(shadow.map, face2); + renderer.clear(); + } else { + if (face2 === 0) { + renderer.setRenderTarget(shadow.map); + renderer.clear(); + } + const viewport = shadow.getViewport(face2); + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + _state.viewport(_viewport); + } + if (light.isPointLight) { + const camera2 = shadow.camera; + const shadowMatrix = shadow.matrix; + const far = light.distance || camera2.far; + if (far !== camera2.far) { + camera2.far = far; + camera2.updateProjectionMatrix(); + } + _lightPositionWorld.setFromMatrixPosition(light.matrixWorld); + camera2.position.copy(_lightPositionWorld); + _lookTarget.copy(camera2.position); + _lookTarget.add(_cubeDirections[face2]); + camera2.up.copy(_cubeUps[face2]); + camera2.lookAt(_lookTarget); + camera2.updateMatrixWorld(); + shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z); + _projScreenMatrix.multiplyMatrices(camera2.projectionMatrix, camera2.matrixWorldInverse); + shadow._frustum.setFromProjectionMatrix(_projScreenMatrix, camera2.coordinateSystem, camera2.reversedDepth); + } else { + shadow.updateMatrices(light); + } + _frustum2 = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, { + format: RGFormat, + type: HalfFloatType + }); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer.setRenderTarget(shadow.mapPass); + renderer.clear(); + renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer.setRenderTarget(shadow.map); + renderer.clear(); + renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== void 0) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0 || material.alphaToCoverage === true) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === void 0) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === void 0) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaToCoverage === true ? 0.5 : material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = renderer.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum2.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k = 0, kl = groups.length; k < kl; k++) { + const group = groups[k]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group); + renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, null); + renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i = 0, l = children.length; i < l; i++) { + renderObject(children[i], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } + } + function WebGLState(gl, extensions) { + function ColorBuffer() { + let locked = false; + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r, g, b, a, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r *= a; + g *= a; + b *= a; + } + color.set(r, g, b, a); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r, g, b, a); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let currentReversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setReversed: function(reversed) { + if (currentReversed !== reversed) { + const ext = extensions.get("EXT_clip_control"); + if (reversed) { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT); + } else { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT); + } + currentReversed = reversed; + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear(oldDepth); + } + }, + getReversed: function() { + return currentReversed; + }, + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (currentReversed) depthFunc = ReversedDepthFuncs[depthFunc]; + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + currentDepthClear = depth; + if (currentReversed) { + depth = 1 - depth; + } + gl.clearDepth(depth); + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + currentReversed = false; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + const uboBindings = /* @__PURE__ */ new WeakMap(); + const uboProgramMap = /* @__PURE__ */ new WeakMap(); + let enabledCapabilities = {}; + let parameters = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = /* @__PURE__ */ new WeakMap(); + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector4().fromArray(scissorParam); + const currentViewport = new Vector4().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i = 0; i < count; i++) { + if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); + } else { + gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth); + setFlipSided(false); + setCullFace(CullFaceBack); + enable(gl.CULL_FACE); + setBlending(NoBlending); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === void 0) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + const textures = renderTarget.textures; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i = 0, il = textures.length; i < il; i++) { + drawBuffers2[i] = gl.COLOR_ATTACHMENT0 + i; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + gl.drawBuffers(drawBuffers2); + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation]: gl.FUNC_ADD, + [SubtractEquation]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT + }; + equationToGL[MinEquation] = gl.MIN; + equationToGL[MaxEquation] = gl.MAX; + const factorToGL = { + [ZeroFactor]: gl.ZERO, + [OneFactor]: gl.ONE, + [SrcColorFactor]: gl.SRC_COLOR, + [SrcAlphaFactor]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor]: gl.DST_COLOR, + [DstAlphaFactor]: gl.DST_ALPHA, + [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFuncSeparate(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE); + break; + default: + error("WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE); + break; + case SubtractiveBlending: + error("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true"); + break; + case MultiplyBlending: + error("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true"); + break; + default: + error("WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide; + if (frontFaceCW) flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width) { + if (width !== currentLineWidth) { + if (lineWidthAvailable) gl.lineWidth(width); + currentLineWidth = width; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + if (depthBuffer.getReversed()) { + factor = -factor; + } + gl.polygonOffset(factor, units); + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === void 0) webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === void 0) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === void 0) { + boundTexture = { type: void 0, texture: void 0 }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== void 0 && boundTexture.type !== void 0) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = void 0; + boundTexture.texture = void 0; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function texStorage2D() { + try { + gl.texStorage2D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function texStorage3D() { + try { + gl.texStorage3D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function texImage2D() { + try { + gl.texImage2D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function texImage3D() { + try { + gl.texImage3D(...arguments); + } catch (e) { + error("WebGLState:", e); + } + } + function getParameter(name) { + if (parameters[name] !== void 0) { + return parameters[name]; + } else { + return gl.getParameter(name); + } + } + function pixelStorei(name, value) { + if (parameters[name] !== value) { + gl.pixelStorei(name, value); + parameters[name] = value; + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === void 0) { + mapping = /* @__PURE__ */ new WeakMap(); + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === void 0) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + depthBuffer.setReversed(false); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + gl.pixelStorei(gl.PACK_ALIGNMENT, 4); + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.BROWSER_DEFAULT_WEBGL); + gl.pixelStorei(gl.PACK_ROW_LENGTH, 0); + gl.pixelStorei(gl.PACK_SKIP_PIXELS, 0); + gl.pixelStorei(gl.PACK_SKIP_ROWS, 0); + gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0); + gl.pixelStorei(gl.UNPACK_IMAGE_HEIGHT, 0); + gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0); + gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0); + gl.pixelStorei(gl.UNPACK_SKIP_IMAGES, 0); + enabledCapabilities = {}; + parameters = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = /* @__PURE__ */ new WeakMap(); + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + pixelStorei, + getParameter, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; + } + function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) { + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _imageDimensions = new Vector2(); + const _videoTextures = /* @__PURE__ */ new WeakMap(); + const _htmlTextures = /* @__PURE__ */ new Set(); + let _canvas2; + const _sources = /* @__PURE__ */ new WeakMap(); + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width, height) { + return useOffscreenCanvas ? new OffscreenCanvas(width, height) : createElementNS("canvas"); + } + function resizeImage(image, needsNewCanvas, maxSize) { + let scale = 1; + const dimensions = getDimensions(image); + if (dimensions.width > maxSize || dimensions.height > maxSize) { + scale = maxSize / Math.max(dimensions.width, dimensions.height); + } + if (scale < 1) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + const width = Math.floor(scale * dimensions.width); + const height = Math.floor(scale * dimensions.height); + if (_canvas2 === void 0) _canvas2 = createCanvas(width, height); + const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas2; + canvas.width = width; + canvas.height = height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width, height); + warn("WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width + "x" + height + ")."); + return canvas; + } else { + if ("data" in image) { + warn("WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ")."); + } + return image; + } + } + return image; + } + function textureNeedsGenerateMipmaps(texture) { + return texture.generateMipmaps; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getTargetType(texture) { + if (texture.isWebGLCubeRenderTarget) return _gl.TEXTURE_CUBE_MAP; + if (texture.isWebGL3DRenderTarget) return _gl.TEXTURE_3D; + if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + } + function getInternalFormat(internalFormatName, glFormat, glType, normalized, colorSpace, forceLinearTransfer = false) { + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== void 0) return _gl[internalFormatName]; + warn("WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let ext_texture_norm16; + if (normalized) { + ext_texture_norm16 = extensions.get("EXT_texture_norm16"); + if (!ext_texture_norm16) { + warn("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"); + } + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8; + if (glType === _gl.UNSIGNED_SHORT && ext_texture_norm16) internalFormat = ext_texture_norm16.R16_EXT; + if (glType === _gl.SHORT && ext_texture_norm16) internalFormat = ext_texture_norm16.R16_SNORM_EXT; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) internalFormat = _gl.R8I; + if (glType === _gl.SHORT) internalFormat = _gl.R16I; + if (glType === _gl.INT) internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8; + if (glType === _gl.UNSIGNED_SHORT && ext_texture_norm16) internalFormat = ext_texture_norm16.RG16_EXT; + if (glType === _gl.SHORT && ext_texture_norm16) internalFormat = ext_texture_norm16.RG16_SNORM_EXT; + } + if (glFormat === _gl.RG_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RG16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RG32UI; + if (glType === _gl.BYTE) internalFormat = _gl.RG8I; + if (glType === _gl.SHORT) internalFormat = _gl.RG16I; + if (glType === _gl.INT) internalFormat = _gl.RG32I; + } + if (glFormat === _gl.RGB_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RGB16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RGB32UI; + if (glType === _gl.BYTE) internalFormat = _gl.RGB8I; + if (glType === _gl.SHORT) internalFormat = _gl.RGB16I; + if (glType === _gl.INT) internalFormat = _gl.RGB32I; + } + if (glFormat === _gl.RGBA_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RGBA16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RGBA32UI; + if (glType === _gl.BYTE) internalFormat = _gl.RGBA8I; + if (glType === _gl.SHORT) internalFormat = _gl.RGBA16I; + if (glType === _gl.INT) internalFormat = _gl.RGBA32I; + } + if (glFormat === _gl.RGB) { + if (glType === _gl.UNSIGNED_SHORT && ext_texture_norm16) internalFormat = ext_texture_norm16.RGB16_EXT; + if (glType === _gl.SHORT && ext_texture_norm16) internalFormat = ext_texture_norm16.RGB16_SNORM_EXT; + if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) internalFormat = _gl.RGB9_E5; + if (glType === _gl.UNSIGNED_INT_10F_11F_11F_REV) internalFormat = _gl.R11F_G11F_B10F; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer(colorSpace); + if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = transfer === SRGBTransfer ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT && ext_texture_norm16) internalFormat = ext_texture_norm16.RGBA16_EXT; + if (glType === _gl.SHORT && ext_texture_norm16) internalFormat = ext_texture_norm16.RGBA16_SNORM_EXT; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getInternalDepthFormat(useStencil, depthType) { + let glInternalFormat; + if (useStencil) { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH32F_STENCIL8; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment."); + } + } else { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } + return glInternalFormat; + } + function getMipLevels(texture, image) { + if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== void 0 && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + if (texture.isHTMLTexture) { + _htmlTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === void 0) return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + properties.remove(renderTarget.depthTexture); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i = 0; i < 6; i++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i])) { + for (let level = 0; level < renderTargetProperties.__webglFramebuffer[i].length; level++) _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); + } + if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level++) _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { + if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + const textures = renderTarget.textures; + for (let i = 0, il = textures.length; i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(textures[i]); + } + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function getTextureUnits() { + return textureUnits; + } + function setTextureUnits(value) { + textureUnits = value; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + warn("WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + warn("WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + warn("WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } else if (texture.isExternalTexture) { + textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null; + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } else if (texture.isExternalTexture) { + textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping]: _gl.REPEAT, + [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter]: _gl.NEAREST, + [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter]: _gl.LINEAR, + [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare]: _gl.NEVER, + [AlwaysCompare]: _gl.ALWAYS, + [LessCompare]: _gl.LESS, + [LessEqualCompare]: _gl.LEQUAL, + [EqualCompare]: _gl.EQUAL, + [GreaterEqualCompare]: _gl.GEQUAL, + [GreaterCompare]: _gl.GREATER, + [NotEqualCompare]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture) { + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter)) { + warn("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + if (texture.magFilter === NearestFilter) return; + if (texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter) return; + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false) return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === void 0) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === void 0) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === void 0) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== void 0) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function getRow(index, rowLength, componentStride) { + return Math.floor(Math.floor(index / componentStride) / rowLength); + } + function updateTexture(texture, image, glFormat, glType) { + const componentStride = 4; + const updateRanges = texture.updateRanges; + if (updateRanges.length === 0) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } else { + updateRanges.sort((a, b) => a.start - b.start); + let mergeIndex = 0; + for (let i = 1; i < updateRanges.length; i++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i]; + const previousEnd = previousRange.start + previousRange.count; + const currentRow = getRow(range.start, image.width, componentStride); + const previousRow = getRow(previousRange.start, image.width, componentStride); + if (range.start <= previousEnd + 1 && currentRow === previousRow && getRow(range.start + range.count - 1, image.width, componentStride) === currentRow) { + previousRange.count = Math.max( + previousRange.count, + range.start + range.count - previousRange.start + ); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + const currentUnpackRowLen = state.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackSkipPixels = state.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = state.getParameter(_gl.UNPACK_SKIP_ROWS); + state.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + for (let i = 0, l = updateRanges.length; i < l; i++) { + const range = updateRanges[i]; + const pixelStart = Math.floor(range.start / componentStride); + const pixelCount = Math.ceil(range.count / componentStride); + const x = pixelStart % image.width; + const y = Math.floor(pixelStart / image.width); + const width = pixelCount; + const height = 1; + state.pixelStorei(_gl.UNPACK_SKIP_PIXELS, x); + state.pixelStorei(_gl.UNPACK_SKIP_ROWS, y); + state.texSubImage2D(_gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data); + } + texture.clearUpdateRanges(); + state.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + state.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + state.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + } + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const isImageBitmap = typeof ImageBitmap !== "undefined" && texture.image instanceof ImageBitmap; + if (isImageBitmap === false) { + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + state.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + state.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + state.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + } + state.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + let image = resizeImage(texture.image, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true; + const dataReady = source.dataReady; + const levels = getMipLevels(texture, image); + if (texture.isDepthTexture) { + glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat, texture.type); + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length; i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + if (dataReady) { + updateTexture(texture, image, glFormat, glType); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i = 0, il = mipmaps.length; i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(mipmap.width, mipmap.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = mipmap.data.subarray( + layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, + (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT + ); + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData); + } + texture.clearLayerUpdates(); + } else { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data); + } + } + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + warn("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length; i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + warn("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(image.width, image.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = image.data.subarray( + layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, + (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT + ); + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData); + } + texture.clearLayerUpdates(); + } else { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let width = image.width, height = image.height; + for (let i = 0; i < levels; i++) { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null); + width >>= 1; + height >>= 1; + } + } + } + } else if (texture.isHTMLTexture) { + if ("texElementImage2D" in _gl) { + const canvas = _gl.canvas; + if (!canvas.hasAttribute("layoutsubtree")) { + canvas.setAttribute("layoutsubtree", "true"); + } + if (image.parentNode !== canvas) { + canvas.appendChild(image); + _htmlTextures.add(texture); + canvas.onpaint = (event) => { + const changed = event.changedElements; + for (const t of _htmlTextures) { + if (changed.includes(t.image)) { + t.needsUpdate = true; + } + } + }; + canvas.requestPaint(); + return; + } + const level = 0; + const internalFormat = _gl.RGBA; + const srcFormat = _gl.RGBA; + const srcType = _gl.UNSIGNED_BYTE; + _gl.texElementImage2D(_gl.TEXTURE_2D, level, internalFormat, srcFormat, srcType, image); + _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR); + _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE); + _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE); + } + } else { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + const dimensions = getDimensions(mipmaps[0]); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0, il = mipmaps.length; i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + const dimensions = getDimensions(image); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + state.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + state.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + state.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + state.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i = 0; i < 6; i++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i] = resizeImage(texture.image[i], true, capabilities.maxCubemapSize); + } else { + cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; + } + cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); + } + const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace); + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true; + const dataReady = source.dataReady; + let levels = getMipLevels(texture, image); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i = 0; i < 6; i++) { + mipmaps = cubeImage[i].mipmaps; + for (let j = 0; j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + warn("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) levels++; + const dimensions = getDimensions(cubeImage[0]); + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0; i < 6; i++) { + if (isDataTexture) { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); + } + for (let j = 0; j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + const mipmapImage = mipmap.image[i].image; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); + } + for (let j = 0; j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + textureProperties.__renderTarget = renderTarget; + if (!renderTargetProperties.__hasExternalTextures) { + const width = Math.max(1, renderTarget.width >> level); + const height = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, useMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, getRenderTargetSamples(renderTarget), glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, getRenderTargetSamples(renderTarget), glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.textures; + for (let i = 0; i < textures.length; i++) { + const texture = textures[i]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, getRenderTargetSamples(renderTarget), glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, getRenderTargetSamples(renderTarget), glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget, cubeFace) { + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + const textureProperties = properties.get(renderTarget.depthTexture); + textureProperties.__renderTarget = renderTarget; + if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + if (isCube) { + if (textureProperties.__webglInit === void 0) { + textureProperties.__webglInit = true; + renderTarget.depthTexture.addEventListener("dispose", onTextureDispose); + } + if (textureProperties.__webglTexture === void 0) { + textureProperties.__webglTexture = _gl.createTexture(); + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture); + const glFormat = utils.convert(renderTarget.depthTexture.format); + const glType = utils.convert(renderTarget.depthTexture.type); + let glInternalFormat; + if (renderTarget.depthTexture.format === DepthFormat) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (renderTarget.depthTexture.format === DepthStencilFormat) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } + for (let i = 0; i < 6; i++) { + _gl.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null); + } + } + } else { + setTexture2D(renderTarget.depthTexture, 0); + } + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D; + const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + if (renderTarget.depthTexture.format === DepthFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__depthDisposeCallback) { + renderTargetProperties.__depthDisposeCallback(); + } + if (depthTexture) { + const disposeEvent = () => { + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener("dispose", disposeEvent); + }; + depthTexture.addEventListener("dispose", disposeEvent); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + } + renderTargetProperties.__boundDepthTexture = depthTexture; + } + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) { + for (let i = 0; i < 6; i++) { + setupDepthTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, i); + } + } else { + const mipmaps = renderTarget.texture.mipmaps; + if (mipmaps && mipmaps.length > 0) { + setupDepthTexture(renderTargetProperties.__webglFramebuffer[0], renderTarget, 0); + } else { + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 0); + } + } + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i = 0; i < 6; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); + if (renderTargetProperties.__webglDepthbuffer[i] === void 0) { + renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[i]; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } else { + const mipmaps = renderTarget.texture.mipmaps; + if (mipmaps && mipmaps.length > 0) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[0]); + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer === void 0) { + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== void 0) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== void 0) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + const textures = renderTarget.textures; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = textures.length > 1; + if (!isMultipleRenderTargets) { + if (textureProperties.__webglTexture === void 0) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i = 0; i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i] = []; + for (let level = 0; level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); + } + } + } else { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0; level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length; i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture === void 0) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } + if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i = 0; i < textures.length; i++) { + const texture2 = textures[i]; + renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.normalized, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + for (let i = 0; i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0; level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0); + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length; i < il; i++) { + const attachment = textures[i]; + const attachmentProperties = properties.get(attachment); + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, attachmentProperties.__webglTexture); + setTextureParameters(glTextureType, attachment); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0); + if (textureNeedsGenerateMipmaps(attachment)) { + generateMipmap(glTextureType); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture); + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0; level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const textures = renderTarget.textures; + for (let i = 0, il = textures.length; i < il; i++) { + const texture = textures[i]; + if (textureNeedsGenerateMipmaps(texture)) { + const targetType = getTargetType(renderTarget); + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(targetType, webglTexture); + generateMipmap(targetType); + state.unbindTexture(); + } + } + } + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + function updateMultisampleRenderTarget(renderTarget) { + if (renderTarget.samples > 0) { + if (useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.textures; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = textures.length > 1; + if (isMultipleRenderTargets) { + for (let i = 0; i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + const mipmaps = renderTarget.texture.mipmaps; + if (mipmaps && mipmaps.length > 0) { + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[0]); + } else { + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + } + for (let i = 0; i < textures.length; i++) { + if (renderTarget.resolveDepthBuffer) { + if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST); + if (supportsInvalidateFramebuffer === true) { + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i); + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) { + invalidationArrayRead.push(depthStyle); + invalidationArrayDraw.push(depthStyle); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw); + } + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i = 0; i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } else { + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) { + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + } + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true) return image; + if (colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace) { + if (ColorManagement.getTransfer(colorSpace) === SRGBTransfer) { + if (format !== RGBAFormat || type !== UnsignedByteType) { + warn("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } else { + error("WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + function getDimensions(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) { + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + } else { + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + } + return _imageDimensions; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.getTextureUnits = getTextureUnits; + this.setTextureUnits = setTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + this.isReversedDepthBuffer = function() { + return state.buffers.depth.getReversed(); + }; + } + function WebGLUtils(gl, extensions) { + function convert(p, colorSpace = NoColorSpace) { + let extension; + const transfer = ColorManagement.getTransfer(colorSpace); + if (p === UnsignedByteType) return gl.UNSIGNED_BYTE; + if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4; + if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1; + if (p === UnsignedInt5999Type) return gl.UNSIGNED_INT_5_9_9_9_REV; + if (p === UnsignedInt101111Type) return gl.UNSIGNED_INT_10F_11F_11F_REV; + if (p === ByteType) return gl.BYTE; + if (p === ShortType) return gl.SHORT; + if (p === UnsignedShortType) return gl.UNSIGNED_SHORT; + if (p === IntType) return gl.INT; + if (p === UnsignedIntType) return gl.UNSIGNED_INT; + if (p === FloatType) return gl.FLOAT; + if (p === HalfFloatType) return gl.HALF_FLOAT; + if (p === AlphaFormat) return gl.ALPHA; + if (p === RGBFormat) return gl.RGB; + if (p === RGBAFormat) return gl.RGBA; + if (p === DepthFormat) return gl.DEPTH_COMPONENT; + if (p === DepthStencilFormat) return gl.DEPTH_STENCIL; + if (p === RedFormat) return gl.RED; + if (p === RedIntegerFormat) return gl.RED_INTEGER; + if (p === RGFormat) return gl.RG; + if (p === RGIntegerFormat) return gl.RG_INTEGER; + if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; + if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) { + if (transfer === SRGBTransfer) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p === RGB_ETC1_Format || p === RGB_ETC2_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p === RGBA_ETC2_EAC_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + if (p === R11_EAC_Format) return extension.COMPRESSED_R11_EAC; + if (p === SIGNED_R11_EAC_Format) return extension.COMPRESSED_SIGNED_R11_EAC; + if (p === RG11_EAC_Format) return extension.COMPRESSED_RG11_EAC; + if (p === SIGNED_RG11_EAC_Format) return extension.COMPRESSED_SIGNED_RG11_EAC; + } else { + return null; + } + } + if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p === RGBA_ASTC_4x4_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p === RGBA_ASTC_5x4_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p === RGBA_ASTC_5x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p === RGBA_ASTC_6x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p === RGBA_ASTC_6x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p === RGBA_ASTC_8x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p === RGBA_ASTC_8x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p === RGBA_ASTC_8x8_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p === RGBA_ASTC_10x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p === RGBA_ASTC_10x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p === RGBA_ASTC_10x8_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p === RGBA_ASTC_10x10_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p === RGBA_ASTC_12x10_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p === RGBA_ASTC_12x12_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p === RGB_BPTC_SIGNED_Format) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p === RGB_BPTC_UNSIGNED_Format) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p === RED_RGTC1_Format) return extension.COMPRESSED_RED_RGTC1_EXT; + if (p === SIGNED_RED_RGTC1_Format) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p === RED_GREEN_RGTC2_Format) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p === SIGNED_RED_GREEN_RGTC2_Format) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p === UnsignedInt248Type) return gl.UNSIGNED_INT_24_8; + return gl[p] !== void 0 ? gl[p] : null; + } + return { convert }; + } + const _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + const _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + class WebXRDepthSensing { + /** + * Constructs a new depth sensing module. + */ + constructor() { + this.texture = null; + this.mesh = null; + this.depthNear = 0; + this.depthFar = 0; + } + /** + * Inits the depth sensing module + * + * @param {XRWebGLDepthInformation} depthData - The XR depth data. + * @param {XRRenderState} renderState - The XR render state. + */ + init(depthData, renderState) { + if (this.texture === null) { + const texture = new ExternalTexture(depthData.texture); + if (depthData.depthNear !== renderState.depthNear || depthData.depthFar !== renderState.depthFar) { + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + } + this.texture = texture; + } + } + /** + * Returns a plane mesh that visualizes the depth texture. + * + * @param {ArrayCamera} cameraXR - The XR camera. + * @return {?Mesh} The plane mesh. + */ + getMesh(cameraXR) { + if (this.texture !== null) { + if (this.mesh === null) { + const viewport = cameraXR.cameras[0].viewport; + const material = new ShaderMaterial({ + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + }); + this.mesh = new Mesh(new PlaneGeometry(20, 20), material); + } + } + return this.mesh; + } + /** + * Resets the module + */ + reset() { + this.texture = null; + this.mesh = null; + } + /** + * Returns a texture representing the depth of the user's environment. + * + * @return {?ExternalTexture} The depth texture. + */ + getDepthTexture() { + return this.texture; + } + } + class WebXRManager extends EventDispatcher { + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {WebGL2RenderingContext} gl - The rendering context. + */ + constructor(renderer, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const supportsGlBinding = typeof XRWebGLBinding !== "undefined"; + const depthSensing = new WebXRDepthSensing(); + const cameraAccessTextures = {}; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector2(); + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera(); + cameraL.viewport = new Vector4(); + const cameraR = new PerspectiveCamera(); + cameraR.viewport = new Vector4(); + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera(); + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== void 0) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i = 0; i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + if (inputSource === null) continue; + controllerInputSources[i] = null; + controllers[i].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + depthSensing.reset(); + for (const key in cameraAccessTextures) { + delete cameraAccessTextures[key]; + } + renderer.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer.setPixelRatio(currentPixelRatio); + renderer.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value) { + framebufferScaleFactor = value; + if (scope.isPresenting === true) { + warn("WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value) { + referenceSpaceType = value; + if (scope.isPresenting === true) { + warn("WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + if (glBinding === null && supportsGlBinding) { + glBinding = new XRWebGLBinding(session, gl); + } + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value) { + session = value; + if (session !== null) { + initialRenderTarget = renderer.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer.getPixelRatio(); + renderer.getSize(currentSize); + const supportsLayers = supportsGlBinding && "createProjectionLayer" in XRWebGLBinding.prototype; + if (!supportsLayers) { + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer.setPixelRatio(1); + renderer.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer.outputColorSpace, + stencilBuffer: attributes.stencil, + resolveDepthBuffer: glBaseLayer.ignoreDepthValues === false, + resolveStencilBuffer: glBaseLayer.ignoreDepthValues === false + } + ); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = this.getBinding(); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer.setPixelRatio(1); + renderer.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, void 0, void 0, void 0, void 0, void 0, void 0, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: glProjLayer.ignoreDepthValues === false, + resolveStencilBuffer: glProjLayer.ignoreDepthValues === false + } + ); + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + this.getDepthTexture = function() { + return depthSensing.getDepthTexture(); + }; + function onInputSourcesChange(event) { + for (let i = 0; i < event.removed.length; i++) { + const inputSource = event.removed[i]; + const index = controllerInputSources.indexOf(inputSource); + if (index >= 0) { + controllerInputSources[index] = null; + controllers[index].disconnect(inputSource); + } + } + for (let i = 0; i < event.added.length; i++) { + const inputSource = event.added[i]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i2 = 0; i2 < controllers.length; i2++) { + if (i2 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i2; + break; + } else if (controllerInputSources[i2] === null) { + controllerInputSources[i2] = inputSource; + controllerIndex = i2; + break; + } + } + if (controllerIndex === -1) break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + if (projL[10] === -1) { + camera.projectionMatrix.copy(cameraL2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse); + } else { + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + } + function updateCamera(camera, parent) { + if (parent === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) return; + let depthNear = camera.near; + let depthFar = camera.far; + if (depthSensing.texture !== null) { + if (depthSensing.depthNear > 0) depthNear = depthSensing.depthNear; + if (depthSensing.depthFar > 0) depthFar = depthSensing.depthFar; + } + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + cameraXR.layers.mask = camera.layers.mask | 6; + cameraL.layers.mask = cameraXR.layers.mask & -5; + cameraR.layers.mask = cameraXR.layers.mask & -3; + const parent = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent); + for (let i = 0; i < cameras2.length; i++) { + updateCamera(cameras2[i], parent); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent); + }; + function updateUserCamera(camera, cameraXR2, parent) { + if (parent === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return void 0; + } + return foveation; + }; + this.setFoveation = function(value) { + foveation = value; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== void 0) { + glBaseLayer.fixedFoveation = value; + } + }; + this.hasDepthSensing = function() { + return depthSensing.texture !== null; + }; + this.getDepthSensingMesh = function() { + return depthSensing.getMesh(cameraXR); + }; + this.getCameraTexture = function(xrCamera) { + return cameraAccessTextures[xrCamera]; + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i = 0; i < views.length; i++) { + const view = views[i]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i === 0) { + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glSubImage.depthStencilTexture + ); + renderer.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i]; + if (camera === void 0) { + camera = new PerspectiveCamera(); + camera.layers.enable(i); + camera.viewport = new Vector4(); + cameras[i] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && enabledFeatures.includes("depth-sensing") && session.depthUsage == "gpu-optimized"; + if (gpuDepthSensingEnabled && supportsGlBinding) { + glBinding = scope.getBinding(); + const depthData = glBinding.getDepthInformation(views[0]); + if (depthData && depthData.isValid && depthData.texture) { + depthSensing.init(depthData, session.renderState); + } + } + const cameraAccessEnabled = enabledFeatures && enabledFeatures.includes("camera-access"); + if (cameraAccessEnabled && supportsGlBinding) { + renderer.state.unbindTexture(); + glBinding = scope.getBinding(); + for (let i = 0; i < views.length; i++) { + const camera = views[i].camera; + if (camera) { + let cameraTex = cameraAccessTextures[camera]; + if (!cameraTex) { + cameraTex = new ExternalTexture(); + cameraAccessTextures[camera] = cameraTex; + } + const glTexture = glBinding.getCameraImage(camera); + cameraTex.sourceTexture = glTexture; + } + } + } + } + for (let i = 0; i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + const controller = controllers[i]; + if (inputSource !== null && controller !== void 0) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation(); + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } + } + const _m1 = /* @__PURE__ */ new Matrix4(); + const _m = /* @__PURE__ */ new Matrix3(); + _m.set(-1, 0, 0, 0, 1, 0, 0, 0, 1); + function WebGLMaterials(renderer, properties) { + function refreshTransformUniform(map, uniform) { + if (map.matrixAutoUpdate === true) { + map.updateMatrix(); + } + uniform.value.copy(map.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) { + if (material.isNodeMaterial) { + material.uniformsNeedUpdate = false; + } else if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const materialProperties = properties.get(material); + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + if (envMap) { + uniforms.envMap.value = envMap; + uniforms.envMapRotation.value.setFromMatrix4(_m1.makeRotationFromEuler(envMapRotation)).transpose(); + if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) { + uniforms.envMapRotation.value.premultiply(_m); + } + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 1e-4); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.dispersion > 0) { + uniforms.dispersion.value = material.dispersion; + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; + } + function WebGLUniformsGroups(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS); + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === void 0) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i = 0; i < maxBindingPoints; i++) { + if (allocatedBindingPoints.indexOf(i) === -1) { + allocatedBindingPoints.push(i); + return i; + } + } + error("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i = 0, il = uniforms.length; i < il; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length; j < jl; j++) { + const uniform = uniformArray[j]; + if (hasUniformChanged(uniform, i, j, cache) === true) { + const offset = uniform.__offset; + const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k = 0; k < values.length; k++) { + const value = values[k]; + const info2 = getUniformSize(value); + if (typeof value === "number" || typeof value === "boolean") { + uniform.__data[0] = value; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value.isMatrix3) { + uniform.__data[0] = value.elements[0]; + uniform.__data[1] = value.elements[1]; + uniform.__data[2] = value.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value.elements[3]; + uniform.__data[5] = value.elements[4]; + uniform.__data[6] = value.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value.elements[6]; + uniform.__data[9] = value.elements[7]; + uniform.__data[10] = value.elements[8]; + uniform.__data[11] = 0; + } else if (ArrayBuffer.isView(value)) { + uniform.__data.set(new value.constructor(value.buffer, value.byteOffset, uniform.__data.length)); + } else { + value.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index, indexArray, cache) { + const value = uniform.value; + const indexString = index + "_" + indexArray; + if (cache[indexString] === void 0) { + if (typeof value === "number" || typeof value === "boolean") { + cache[indexString] = value; + } else if (ArrayBuffer.isView(value)) { + cache[indexString] = value.slice(); + } else { + cache[indexString] = value.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value === "number" || typeof value === "boolean") { + if (cachedObject !== value) { + cache[indexString] = value; + return true; + } + } else if (ArrayBuffer.isView(value)) { + return true; + } else { + if (cachedObject.equals(value) === false) { + cachedObject.copy(value); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i = 0, l = uniforms.length; i < l; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length; j < jl; j++) { + const uniform = uniformArray[j]; + const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k = 0, kl = values.length; k < kl; k++) { + const value = values[k]; + const info2 = getUniformSize(value); + const chunkOffset2 = offset % chunkSize; + const chunkPadding = chunkOffset2 % info2.boundary; + const chunkStart = chunkOffset2 + chunkPadding; + offset += chunkPadding; + if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) { + offset += chunkSize - chunkStart; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value) { + const info2 = { + boundary: 0, + // bytes + storage: 0 + // bytes + }; + if (typeof value === "number" || typeof value === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value.isVector3 || value.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value.isTexture) { + warn("WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else if (ArrayBuffer.isView(value)) { + info2.boundary = 16; + info2.storage = value.byteLength; + } else { + warn("WebGLRenderer: Unsupported uniform value type.", value); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; + } + const DATA = new Uint16Array([ + 12469, + 15057, + 12620, + 14925, + 13266, + 14620, + 13807, + 14376, + 14323, + 13990, + 14545, + 13625, + 14713, + 13328, + 14840, + 12882, + 14931, + 12528, + 14996, + 12233, + 15039, + 11829, + 15066, + 11525, + 15080, + 11295, + 15085, + 10976, + 15082, + 10705, + 15073, + 10495, + 13880, + 14564, + 13898, + 14542, + 13977, + 14430, + 14158, + 14124, + 14393, + 13732, + 14556, + 13410, + 14702, + 12996, + 14814, + 12596, + 14891, + 12291, + 14937, + 11834, + 14957, + 11489, + 14958, + 11194, + 14943, + 10803, + 14921, + 10506, + 14893, + 10278, + 14858, + 9960, + 14484, + 14039, + 14487, + 14025, + 14499, + 13941, + 14524, + 13740, + 14574, + 13468, + 14654, + 13106, + 14743, + 12678, + 14818, + 12344, + 14867, + 11893, + 14889, + 11509, + 14893, + 11180, + 14881, + 10751, + 14852, + 10428, + 14812, + 10128, + 14765, + 9754, + 14712, + 9466, + 14764, + 13480, + 14764, + 13475, + 14766, + 13440, + 14766, + 13347, + 14769, + 13070, + 14786, + 12713, + 14816, + 12387, + 14844, + 11957, + 14860, + 11549, + 14868, + 11215, + 14855, + 10751, + 14825, + 10403, + 14782, + 10044, + 14729, + 9651, + 14666, + 9352, + 14599, + 9029, + 14967, + 12835, + 14966, + 12831, + 14963, + 12804, + 14954, + 12723, + 14936, + 12564, + 14917, + 12347, + 14900, + 11958, + 14886, + 11569, + 14878, + 11247, + 14859, + 10765, + 14828, + 10401, + 14784, + 10011, + 14727, + 9600, + 14660, + 9289, + 14586, + 8893, + 14508, + 8533, + 15111, + 12234, + 15110, + 12234, + 15104, + 12216, + 15092, + 12156, + 15067, + 12010, + 15028, + 11776, + 14981, + 11500, + 14942, + 11205, + 14902, + 10752, + 14861, + 10393, + 14812, + 9991, + 14752, + 9570, + 14682, + 9252, + 14603, + 8808, + 14519, + 8445, + 14431, + 8145, + 15209, + 11449, + 15208, + 11451, + 15202, + 11451, + 15190, + 11438, + 15163, + 11384, + 15117, + 11274, + 15055, + 10979, + 14994, + 10648, + 14932, + 10343, + 14871, + 9936, + 14803, + 9532, + 14729, + 9218, + 14645, + 8742, + 14556, + 8381, + 14461, + 8020, + 14365, + 7603, + 15273, + 10603, + 15272, + 10607, + 15267, + 10619, + 15256, + 10631, + 15231, + 10614, + 15182, + 10535, + 15118, + 10389, + 15042, + 10167, + 14963, + 9787, + 14883, + 9447, + 14800, + 9115, + 14710, + 8665, + 14615, + 8318, + 14514, + 7911, + 14411, + 7507, + 14279, + 7198, + 15314, + 9675, + 15313, + 9683, + 15309, + 9712, + 15298, + 9759, + 15277, + 9797, + 15229, + 9773, + 15166, + 9668, + 15084, + 9487, + 14995, + 9274, + 14898, + 8910, + 14800, + 8539, + 14697, + 8234, + 14590, + 7790, + 14479, + 7409, + 14367, + 7067, + 14178, + 6621, + 15337, + 8619, + 15337, + 8631, + 15333, + 8677, + 15325, + 8769, + 15305, + 8871, + 15264, + 8940, + 15202, + 8909, + 15119, + 8775, + 15022, + 8565, + 14916, + 8328, + 14804, + 8009, + 14688, + 7614, + 14569, + 7287, + 14448, + 6888, + 14321, + 6483, + 14088, + 6171, + 15350, + 7402, + 15350, + 7419, + 15347, + 7480, + 15340, + 7613, + 15322, + 7804, + 15287, + 7973, + 15229, + 8057, + 15148, + 8012, + 15046, + 7846, + 14933, + 7611, + 14810, + 7357, + 14682, + 7069, + 14552, + 6656, + 14421, + 6316, + 14251, + 5948, + 14007, + 5528, + 15356, + 5942, + 15356, + 5977, + 15353, + 6119, + 15348, + 6294, + 15332, + 6551, + 15302, + 6824, + 15249, + 7044, + 15171, + 7122, + 15070, + 7050, + 14949, + 6861, + 14818, + 6611, + 14679, + 6349, + 14538, + 6067, + 14398, + 5651, + 14189, + 5311, + 13935, + 4958, + 15359, + 4123, + 15359, + 4153, + 15356, + 4296, + 15353, + 4646, + 15338, + 5160, + 15311, + 5508, + 15263, + 5829, + 15188, + 6042, + 15088, + 6094, + 14966, + 6001, + 14826, + 5796, + 14678, + 5543, + 14527, + 5287, + 14377, + 4985, + 14133, + 4586, + 13869, + 4257, + 15360, + 1563, + 15360, + 1642, + 15358, + 2076, + 15354, + 2636, + 15341, + 3350, + 15317, + 4019, + 15273, + 4429, + 15203, + 4732, + 15105, + 4911, + 14981, + 4932, + 14836, + 4818, + 14679, + 4621, + 14517, + 4386, + 14359, + 4156, + 14083, + 3795, + 13808, + 3437, + 15360, + 122, + 15360, + 137, + 15358, + 285, + 15355, + 636, + 15344, + 1274, + 15322, + 2177, + 15281, + 2765, + 15215, + 3223, + 15120, + 3451, + 14995, + 3569, + 14846, + 3567, + 14681, + 3466, + 14511, + 3305, + 14344, + 3121, + 14037, + 2800, + 13753, + 2467, + 15360, + 0, + 15360, + 1, + 15359, + 21, + 15355, + 89, + 15346, + 253, + 15325, + 479, + 15287, + 796, + 15225, + 1148, + 15133, + 1492, + 15008, + 1749, + 14856, + 1882, + 14685, + 1886, + 14506, + 1783, + 14324, + 1608, + 13996, + 1398, + 13702, + 1183 + ]); + let lut = null; + function getDFGLUT() { + if (lut === null) { + lut = new DataTexture(DATA, 16, 16, RGFormat, HalfFloatType); + lut.name = "DFG_LUT"; + lut.minFilter = LinearFilter; + lut.magFilter = LinearFilter; + lut.wrapS = ClampToEdgeWrapping; + lut.wrapT = ClampToEdgeWrapping; + lut.generateMipmaps = false; + lut.needsUpdate = true; + } + return lut; + } + class WebGLRenderer { + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer~Options} [parameters] - The configuration parameter. + */ + constructor(parameters = {}) { + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false, + reversedDepthBuffer = false, + outputBufferType = UnsignedByteType + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + if (typeof WebGLRenderingContext !== "undefined" && context instanceof WebGLRenderingContext) { + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + } + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const _outputBufferType = outputBufferType; + const INTEGER_FORMATS = /* @__PURE__ */ new Set([ + RGBAIntegerFormat, + RGIntegerFormat, + RedIntegerFormat + ]); + const UNSIGNED_TYPES = /* @__PURE__ */ new Set([ + UnsignedByteType, + UnsignedIntType, + UnsignedShortType, + UnsignedInt248Type, + UnsignedShort4444Type, + UnsignedShort5551Type + ]); + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + const objectPosition = new Vector3(); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + let output = null; + this.domElement = canvas; + this.debug = { + /** + * Enables error checking and reporting when shader programs are being compiled. + * @type {boolean} + */ + checkShaderErrors: true, + /** + * Callback for custom error reporting. + * @type {?Function} + */ + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1; + this.transmissionResolutionScale = 1; + const _this2 = this; + let _isContextLost = false; + let _nodesHandler = null; + this._outputColorSpace = SRGBColorSpace; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + const _currentClearColor = new Color(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport = new Vector4(0, 0, _width, _height); + const _scissor = new Vector4(0, 0, _width, _height); + let _scissorTest = false; + const _frustum2 = new Frustum(); + let _clippingEnabled = false; + let _localClippingEnabled = false; + const _projScreenMatrix2 = new Matrix4(); + const _vector3 = new Vector3(); + const _vector42 = new Vector4(); + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + let _renderBackground = false; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextName, contextAttributes) { + return canvas.getContext(contextName, contextAttributes); + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) canvas.setAttribute("data-engine", `three.js r${REVISION}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextName = "webgl2"; + _gl = getContext(contextName, contextAttributes); + if (_gl === null) { + if (getContext(contextName)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + } catch (e) { + error("WebGLRenderer: " + e.message); + throw e; + } + let extensions, capabilities, state, info; + let properties, textures, environments, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions(_gl); + extensions.init(); + utils = new WebGLUtils(_gl, extensions); + capabilities = new WebGLCapabilities(_gl, extensions, parameters, utils); + state = new WebGLState(_gl, extensions); + if (capabilities.reversedDepthBuffer && reversedDepthBuffer) { + state.buffers.depth.setReversed(true); + } + info = new WebGLInfo(_gl); + properties = new WebGLProperties(); + textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info); + environments = new WebGLEnvironments(_this2); + attributes = new WebGLAttributes(_gl); + bindingStates = new WebGLBindingStates(_gl, attributes); + geometries = new WebGLGeometries(_gl, attributes, info, bindingStates); + objects = new WebGLObjects(_gl, geometries, attributes, bindingStates, info); + morphtargets = new WebGLMorphtargets(_gl, capabilities, textures); + clipping = new WebGLClipping(properties); + programCache = new WebGLPrograms(_this2, environments, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials(_this2, properties); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates(extensions); + background = new WebGLBackground(_this2, environments, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap(_this2, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info); + indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info); + info.programs = programCache.programs; + _this2.capabilities = capabilities; + _this2.extensions = extensions; + _this2.properties = properties; + _this2.renderLists = renderLists; + _this2.shadowMap = shadowMap; + _this2.state = state; + _this2.info = info; + } + initGLContext(); + if (_outputBufferType !== UnsignedByteType) { + output = new WebGLOutput(_outputBufferType, canvas.width, canvas.height, depth, stencil); + } + const xr = new WebXRManager(_this2, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value) { + if (value === void 0) return; + _pixelRatio = value; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width, height, updateStyle = true) { + if (xr.isPresenting) { + warn("WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width; + _height = height; + canvas.width = Math.floor(width * _pixelRatio); + canvas.height = Math.floor(height * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width + "px"; + canvas.style.height = height + "px"; + } + if (output !== null) { + output.setSize(canvas.width, canvas.height); + } + this.setViewport(0, 0, width, height); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width, height, pixelRatio) { + _width = width; + _height = height; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width * pixelRatio); + canvas.height = Math.floor(height * pixelRatio); + this.setViewport(0, 0, width, height); + }; + this.setEffects = function(effects) { + if (_outputBufferType === UnsignedByteType) { + error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType."); + return; + } + if (effects) { + for (let i = 0; i < effects.length; i++) { + if (effects[i].isOutputPass === true) { + warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically."); + break; + } + } + } + output.setEffects(effects || []); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport); + }; + this.setViewport = function(x, y, width, height) { + if (x.isVector4) { + _viewport.set(x.x, x.y, x.z, x.w); + } else { + _viewport.set(x, y, width, height); + } + state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).round()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x, y, width, height) { + if (x.isVector4) { + _scissor.set(x.x, x.y, x.z, x.w); + } else { + _scissor.set(x, y, width, height); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor(...arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha(...arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = INTEGER_FORMATS.has(targetFormat); + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = UNSIGNED_TYPES.has(targetType); + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r; + uintClearColor[1] = g; + uintClearColor[2] = b; + uintClearColor[3] = a; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r; + intClearColor[1] = g; + intClearColor[2] = b; + intClearColor[3] = a; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) { + bits |= _gl.DEPTH_BUFFER_BIT; + this.state.buffers.depth.setMask(true); + } + if (stencil2) { + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + if (bits !== 0) { + _gl.clear(bits); + } + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.setNodesHandler = function(nodesHandler) { + nodesHandler.setRenderer(this); + _nodesHandler = nodesHandler; + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + environments.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + log("WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + log("WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + error("WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== void 0) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index = geometries.getWireframeAttribute(geometry); + if (index === void 0) return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index.count); + } else if (position !== void 0 && position !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) return; + bindingStates.setup(object, material, program, geometry, index); + let attribute; + let renderer = bufferRenderer; + if (index !== null) { + attribute = attributes.get(index); + renderer = indexedBufferRenderer; + renderer.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer.setMode(_gl.LINES); + } else { + renderer.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === void 0) lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer.setMode(_gl.LINE_LOOP); + } else { + renderer.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + if (!extensions.get("WEBGL_multi_draw")) { + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount2 = object._multiDrawCount; + const bytesPerElement = index ? attributes.get(index).bytesPerElement : 1; + const uniforms = properties.get(material).currentProgram.getUniforms(); + for (let i = 0; i < drawCount2; i++) { + uniforms.setValue(_gl, "_gl_DrawID", i); + renderer.render(starts[i] / bytesPerElement, counts[i]); + } + } else { + renderer.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } + } else if (object.isInstancedMesh) { + renderer.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== void 0 ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(); + const materials2 = /* @__PURE__ */ new Set(); + scene.traverse(function(object) { + if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) { + return; + } + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i = 0; i < material.length; i++) { + const material2 = material[i]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + currentRenderState = renderStateStack.pop(); + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time) { + if (onAnimationFrameCallback) onAnimationFrameCallback(time); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation(); + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== void 0 && camera.isCamera !== true) { + error("WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) return; + if (_nodesHandler !== null) { + _nodesHandler.renderStart(scene, camera); + } + const isXRPresenting = xr.enabled === true && xr.isPresenting === true; + const useOutput = output !== null && (_currentRenderTarget === null || isXRPresenting) && output.begin(_this2, _currentRenderTarget); + if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true && (output === null || output.isCompositing() === false)) { + if (xr.cameraAutoUpdate === true) xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) scene.onBeforeRender(_this2, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(camera); + currentRenderState.state.textureUnits = textures.getTextureUnits(); + renderStateStack.push(currentRenderState); + _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum2.setFromProjectionMatrix(_projScreenMatrix2, WebGLCoordinateSystem, camera.reversedDepth); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + if (xr.enabled === true && xr.isPresenting === true) { + const depthSensingMesh = _this2.xr.getDepthSensingMesh(); + if (depthSensingMesh !== null) { + projectObject(depthSensingMesh, camera, -Infinity, _this2.sortObjects); + } + } + projectObject(scene, camera, 0, _this2.sortObjects); + currentRenderList.finish(); + if (_this2.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if (_renderBackground) { + background.addToRenderList(currentRenderList, scene); + } + this.info.render.frame++; + if (_clippingEnabled === true) clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) clipping.endShadows(); + if (this.info.autoReset === true) this.info.reset(); + const skipSceneRender = useOutput && output.hasRenderPass(); + if (skipSceneRender === false) { + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + currentRenderState.setupLights(); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + if (transmissiveObjects.length > 0) { + for (let i = 0, l = cameras.length; i < l; i++) { + const camera2 = cameras[i]; + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2); + } + } + if (_renderBackground) background.render(scene); + for (let i = 0, l = cameras.length; i < l; i++) { + const camera2 = cameras[i]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (_renderBackground) background.render(scene); + renderScene(currentRenderList, scene, camera); + } + } + if (_currentRenderTarget !== null && _currentActiveMipmapLevel === 0) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (useOutput) { + output.end(_this2); + } + if (scene.isScene === true) scene.onAfterRender(_this2, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + textures.setTextureUnits(currentRenderState.state.textureUnits); + if (_clippingEnabled === true) clipping.setGlobalState(_this2.clippingPlanes, currentRenderState.state.camera); + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + if (_nodesHandler !== null) { + _nodesHandler.renderEnd(); + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) object.update(camera); + } else if (object.isLightProbeGrid) { + currentRenderState.pushLightProbeGrid(object); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum2.intersectsSprite(object)) { + if (sortObjects) { + _vector42.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector42.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum2.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== void 0) { + if (object.boundingSphere === null) object.computeBoundingSphere(); + _vector42.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _vector42.copy(geometry.boundingSphere.center); + } + _vector42.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i = 0, l = groups.length; i < l; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector42.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector42.z, null); + } + } + } + } + const children = object.children; + for (let i = 0, l = children.length; i < l; i++) { + projectObject(children[i], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList2; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) clipping.setGlobalState(_this2.clippingPlanes, camera); + if (viewport) state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + if (currentRenderState.state.transmissionRenderTarget[camera.id] === void 0) { + const hasHalfFloatSupport = extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float"); + currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget(1, 1, { + generateMipmaps: true, + type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: Math.max(4, capabilities.samples), + // to avoid feedback loops, the transmission render target requires a resolve, see #26177 + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement.workingColorSpace + }); + } + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id]; + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize(activeViewport.z * _this2.transmissionResolutionScale, activeViewport.w * _this2.transmissionResolutionScale); + const currentRenderTarget = _this2.getRenderTarget(); + const currentActiveCubeFace = _this2.getActiveCubeFace(); + const currentActiveMipmapLevel = _this2.getActiveMipmapLevel(); + _this2.setRenderTarget(transmissionRenderTarget); + _this2.getClearColor(_currentClearColor); + _currentClearAlpha = _this2.getClearAlpha(); + if (_currentClearAlpha < 1) _this2.setClearColor(16777215, 0.5); + _this2.clear(); + if (_renderBackground) background.render(scene); + const currentToneMapping = _this2.toneMapping; + _this2.toneMapping = NoToneMapping; + const currentCameraViewport = camera.viewport; + if (camera.viewport !== void 0) camera.viewport = void 0; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) clipping.setGlobalState(_this2.clippingPlanes, camera); + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + if (extensions.has("WEBGL_multisampled_render_to_texture") === false) { + let renderTargetNeedsUpdate = false; + for (let i = 0, l = transmissiveObjects.length; i < l; i++) { + const renderItem = transmissiveObjects[i]; + const { object, geometry, material, group } = renderItem; + if (material.side === DoubleSide && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + } + } + _this2.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + _this2.setClearColor(_currentClearColor, _currentClearAlpha); + if (currentCameraViewport !== void 0) camera.viewport = currentCameraViewport; + _this2.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i = 0, l = renderList.length; i < l; i++) { + const renderItem = renderList[i]; + const { object, geometry, group } = renderItem; + let material = renderItem.material; + if (material.allowOverride === true && overrideMaterial !== null) { + material = overrideMaterial; + } + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this2, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this2, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + _this2.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide; + material.needsUpdate = true; + _this2.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide; + } else { + _this2.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this2, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object, currentRenderState.state.lightProbeGridArray); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + const usePMREM = material.isMeshStandardMaterial || material.isMeshLambertMaterial && !material.envMap || material.isMeshPhongMaterial && !material.envMap; + materialProperties.envMap = environments.get(material.envMap || materialProperties.environment, usePMREM); + materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation; + if (programs === void 0) { + material.addEventListener("dispose", onMaterialDispose); + programs = /* @__PURE__ */ new Map(); + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== void 0) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + if (_nodesHandler !== null && material.isNodeMaterial) { + _nodesHandler.build(material, object, parameters2); + } + material.onBeforeCompile(parameters2, _this2); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.lightProbeGrid = currentRenderState.state.lightProbeGridArray.length > 0; + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.batchingColor = parameters2.batchingColor; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.instancingMorph = parameters2.instancingMorph; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function findLightProbeGrid(volumes, object) { + if (volumes.length === 0) return null; + if (volumes.length === 1) { + return volumes[0].texture !== null ? volumes[0] : null; + } + objectPosition.setFromMatrixPosition(object.matrixWorld); + for (let i = 0, l = volumes.length; i < l; i++) { + const v = volumes[i]; + if (v.texture !== null && v.boundingBox.containsPoint(objectPosition)) return v; + } + return null; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this2.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : ColorManagement.workingColorSpace; + const usePMREM = material.isMeshStandardMaterial || material.isMeshLambertMaterial && !material.envMap || material.isMeshPhongMaterial && !material.envMap; + const envMap = environments.get(material.envMap || environment, usePMREM); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this2.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== void 0 && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } else if (!!materialProperties.lightProbeGrid !== currentRenderState.state.lightProbeGridArray.length > 0) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + if (_nodesHandler && material.isNodeMaterial) { + _nodesHandler.onUpdateProgram(material, program, materialProperties); + } + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (materialProperties.needsLights) { + const objectVolume = findLightProbeGrid(currentRenderState.state.lightProbeGridArray, object); + if (materialProperties.lightProbeGrid !== objectVolume) { + materialProperties.lightProbeGrid = objectVolume; + refreshMaterial = true; + } + } + if (refreshProgram || _currentCamera !== camera) { + const reversedDepthBuffer2 = state.buffers.depth.getReversed(); + if (reversedDepthBuffer2 && camera.reversedDepth !== true) { + camera._reversedDepth = true; + camera.updateProjectionMatrix(); + } + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== void 0) { + uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue( + _gl, + "logDepthBufFC", + 2 / (Math.log(camera.far + 1) / Math.LN2) + ); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (materialProperties.needsLights) { + if (lights.state.directionalShadowMap.length > 0) { + p_uniforms.setValue(_gl, "directionalShadowMap", lights.state.directionalShadowMap, textures); + } + if (lights.state.spotShadowMap.length > 0) { + p_uniforms.setValue(_gl, "spotShadowMap", lights.state.spotShadowMap, textures); + } + if (lights.state.pointShadowMap.length > 0) { + p_uniforms.setValue(_gl, "pointShadowMap", lights.state.pointShadowMap, textures); + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (skeleton.boneTexture === null) skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingIdTexture"); + p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingColorTexture"); + if (object._colorsTexture !== null) { + p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures); + } + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== void 0 || morphAttributes.normal !== void 0 || morphAttributes.color !== void 0) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if ((material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial) && material.envMap === null && scene.environment !== null) { + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + } + if (m_uniforms.dfgLUT !== void 0) { + m_uniforms.dfgLUT.value = getDFGLUT(); + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this2.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]); + if (materialProperties.needsLights && materialProperties.lightProbeGrid) { + const volume = materialProperties.lightProbeGrid; + m_uniforms.probesSH.value = volume.texture; + m_uniforms.probesMin.value.copy(volume.boundingBox.min); + m_uniforms.probesMax.value.copy(volume.boundingBox.max); + m_uniforms.probesResolution.value.copy(volume.resolution); + } + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.uniformsGroups !== void 0) { + const groups = material.uniformsGroups; + for (let i = 0, l = groups.length; i < l; i++) { + const group = groups[i]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value) { + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false; + if (renderTargetProperties.__autoAllocateDepthBuffer === false) { + renderTargetProperties.__useRenderToTexture = false; + } + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? void 0 : depthTexture; + renderTargetProperties.__hasExternalTextures = true; + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === void 0; + }; + const _scratchFrameBuffer = _gl.createFramebuffer(); + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== void 0) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + _currentMaterialId = -1; + return; + } else if (renderTargetProperties.__webglFramebuffer === void 0) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } else if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__boundDepthTexture !== depthTexture) { + if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) { + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + } + textures.setupDepthRenderbuffer(renderTarget); + } + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + if (activeMipmapLevel !== 0) { + framebuffer = _scratchFrameBuffer; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const layer = activeCubeFace; + for (let i = 0; i < renderTarget.textures.length; i++) { + const textureProperties = properties.get(renderTarget.textures[i]); + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer); + } + } else if (renderTarget !== null && activeMipmapLevel !== 0) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + error("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== void 0) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.textures[textureIndex]; + const textureFormat = texture.format; + const textureType = texture.type; + if (renderTarget.textures.length > 1) _gl.readBuffer(_gl.COLOR_ATTACHMENT0 + textureIndex); + if (!capabilities.textureFormatReadable(textureFormat)) { + error("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!capabilities.textureTypeReadable(textureType)) { + error("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x >= 0 && x <= renderTarget.width - width && (y >= 0 && y <= renderTarget.height - height)) { + _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.readRenderTargetPixelsAsync = async function(renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== void 0) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + if (x >= 0 && x <= renderTarget.width - width && (y >= 0 && y <= renderTarget.height - height)) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + const texture = renderTarget.textures[textureIndex]; + const textureFormat = texture.format; + const textureType = texture.type; + if (renderTarget.textures.length > 1) _gl.readBuffer(_gl.COLOR_ATTACHMENT0 + textureIndex); + if (!capabilities.textureFormatReadable(textureFormat)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + } + if (!capabilities.textureTypeReadable(textureType)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + } + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ); + _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), 0); + const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer); + const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + _gl.flush(); + await probeAsync(_gl, sync, 4); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer); + _gl.deleteBuffer(glBuffer); + _gl.deleteSync(sync); + return buffer; + } else { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + } + } + }; + this.copyFramebufferToTexture = function(texture, position = null, level = 0) { + const levelScale = Math.pow(2, -level); + const width = Math.floor(texture.image.width * levelScale); + const height = Math.floor(texture.image.height * levelScale); + const x = position !== null ? position.x : 0; + const y = position !== null ? position.y : 0; + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x, y, width, height); + state.unbindTexture(); + }; + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0) { + let width, height, depth2, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image; + if (srcRegion !== null) { + width = srcRegion.max.x - srcRegion.min.x; + height = srcRegion.max.y - srcRegion.min.y; + depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + } else { + const levelScale = Math.pow(2, -srcLevel); + width = Math.floor(image.width * levelScale); + height = Math.floor(image.height * levelScale); + if (srcTexture.isDataArrayTexture) { + depth2 = image.depth; + } else if (srcTexture.isData3DTexture) { + depth2 = Math.floor(image.depth * levelScale); + } else { + depth2 = 1; + } + minX = 0; + minY = 0; + minZ = 0; + } + if (dstPosition !== null) { + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + } else { + dstX = 0; + dstY = 0; + dstZ = 0; + } + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + textures.setTexture2D(dstTexture, 0); + glTarget = _gl.TEXTURE_2D; + } + state.activeTexture(_gl.TEXTURE0); + state.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + state.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + state.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const currentUnpackRowLen = state.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackImageHeight = state.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const currentUnpackSkipPixels = state.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = state.getParameter(_gl.UNPACK_SKIP_ROWS); + const currentUnpackSkipImages = state.getParameter(_gl.UNPACK_SKIP_IMAGES); + state.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + state.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + state.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX); + state.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY); + state.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ); + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if (srcTexture.isDepthTexture) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget); + const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer); + for (let i = 0; i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i); + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i); + } + _gl.blitFramebuffer(minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST); + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer); + for (let i = 0; i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i); + } else { + _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel); + } + if (isDst3D) { + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i); + } else { + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel); + } + if (srcLevel !== 0) { + _gl.blitFramebuffer(minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST); + } else if (isDst3D) { + _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height); + } else { + _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width, height); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else { + if (isDst3D) { + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, glType, image.data); + } else if (dstTexture.isCompressedArrayTexture) { + _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, glType, image); + } + } else { + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data); + } else if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image); + } + } + } + state.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + state.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight); + state.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + state.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + state.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages); + if (dstLevel === 0 && dstTexture.generateMipmaps) { + _gl.generateMipmap(glTarget); + } + state.unbindTexture(); + }; + this.initRenderTarget = function(target) { + if (properties.get(target).__webglFramebuffer === void 0) { + textures.setupRenderTarget(target); + } + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + /** + * Defines the coordinate system of the renderer. + * + * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`. + * + * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem} + * @default WebGLCoordinateSystem + * @readonly + */ + get coordinateSystem() { + return WebGLCoordinateSystem; + } + /** + * Defines the output color space of the renderer. + * + * @type {SRGBColorSpace|LinearSRGBColorSpace} + * @default SRGBColorSpace + */ + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace(colorSpace); + gl.unpackColorSpace = ColorManagement._getUnpackColorSpace(); + } + } + three.ACESFilmicToneMapping = ACESFilmicToneMapping; + three.AddEquation = AddEquation; + three.AddOperation = AddOperation; + three.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode; + three.AdditiveBlending = AdditiveBlending; + three.AgXToneMapping = AgXToneMapping; + three.AlphaFormat = AlphaFormat; + three.AlwaysCompare = AlwaysCompare; + three.AlwaysDepth = AlwaysDepth; + three.AlwaysStencilFunc = AlwaysStencilFunc; + three.AmbientLight = AmbientLight; + three.AnimationAction = AnimationAction; + three.AnimationClip = AnimationClip; + three.AnimationLoader = AnimationLoader; + three.AnimationMixer = AnimationMixer; + three.AnimationObjectGroup = AnimationObjectGroup; + three.AnimationUtils = AnimationUtils; + three.ArcCurve = ArcCurve; + three.ArrayCamera = ArrayCamera; + three.ArrowHelper = ArrowHelper; + three.AttachedBindMode = AttachedBindMode; + three.Audio = Audio; + three.AudioAnalyser = AudioAnalyser; + three.AudioContext = AudioContext; + three.AudioListener = AudioListener; + three.AudioLoader = AudioLoader; + three.AxesHelper = AxesHelper; + three.BackSide = BackSide; + three.BasicDepthPacking = BasicDepthPacking; + three.BasicShadowMap = BasicShadowMap; + three.BatchedMesh = BatchedMesh; + three.BezierInterpolant = BezierInterpolant; + three.Bone = Bone; + three.BooleanKeyframeTrack = BooleanKeyframeTrack; + three.Box2 = Box2; + three.Box3 = Box3; + three.Box3Helper = Box3Helper; + three.BoxGeometry = BoxGeometry; + three.BoxHelper = BoxHelper; + three.BufferAttribute = BufferAttribute; + three.BufferGeometry = BufferGeometry; + three.BufferGeometryLoader = BufferGeometryLoader; + three.ByteType = ByteType; + three.Cache = Cache; + three.Camera = Camera; + three.CameraHelper = CameraHelper; + three.CanvasTexture = CanvasTexture; + three.CapsuleGeometry = CapsuleGeometry; + three.CatmullRomCurve3 = CatmullRomCurve3; + three.CineonToneMapping = CineonToneMapping; + three.CircleGeometry = CircleGeometry; + three.ClampToEdgeWrapping = ClampToEdgeWrapping; + three.Clock = Clock; + three.Color = Color; + three.ColorKeyframeTrack = ColorKeyframeTrack; + three.ColorManagement = ColorManagement; + three.Compatibility = Compatibility; + three.CompressedArrayTexture = CompressedArrayTexture; + three.CompressedCubeTexture = CompressedCubeTexture; + three.CompressedTexture = CompressedTexture; + three.CompressedTextureLoader = CompressedTextureLoader; + three.ConeGeometry = ConeGeometry; + three.ConstantAlphaFactor = ConstantAlphaFactor; + three.ConstantColorFactor = ConstantColorFactor; + three.Controls = Controls; + three.CubeCamera = CubeCamera; + three.CubeDepthTexture = CubeDepthTexture; + three.CubeReflectionMapping = CubeReflectionMapping; + three.CubeRefractionMapping = CubeRefractionMapping; + three.CubeTexture = CubeTexture; + three.CubeTextureLoader = CubeTextureLoader; + three.CubeUVReflectionMapping = CubeUVReflectionMapping; + three.CubicBezierCurve = CubicBezierCurve; + three.CubicBezierCurve3 = CubicBezierCurve3; + three.CubicInterpolant = CubicInterpolant; + three.CullFaceBack = CullFaceBack; + three.CullFaceFront = CullFaceFront; + three.CullFaceFrontBack = CullFaceFrontBack; + three.CullFaceNone = CullFaceNone; + three.Curve = Curve; + three.CurvePath = CurvePath; + three.CustomBlending = CustomBlending; + three.CustomToneMapping = CustomToneMapping; + three.CylinderGeometry = CylinderGeometry; + three.Cylindrical = Cylindrical; + three.Data3DTexture = Data3DTexture; + three.DataArrayTexture = DataArrayTexture; + three.DataTexture = DataTexture; + three.DataTextureLoader = DataTextureLoader; + three.DataUtils = DataUtils; + three.DecrementStencilOp = DecrementStencilOp; + three.DecrementWrapStencilOp = DecrementWrapStencilOp; + three.DefaultLoadingManager = DefaultLoadingManager; + three.DepthFormat = DepthFormat; + three.DepthStencilFormat = DepthStencilFormat; + three.DepthTexture = DepthTexture; + three.DetachedBindMode = DetachedBindMode; + three.DirectionalLight = DirectionalLight; + three.DirectionalLightHelper = DirectionalLightHelper; + three.DiscreteInterpolant = DiscreteInterpolant; + three.DodecahedronGeometry = DodecahedronGeometry; + three.DoubleSide = DoubleSide; + three.DstAlphaFactor = DstAlphaFactor; + three.DstColorFactor = DstColorFactor; + three.DynamicCopyUsage = DynamicCopyUsage; + three.DynamicDrawUsage = DynamicDrawUsage; + three.DynamicReadUsage = DynamicReadUsage; + three.EdgesGeometry = EdgesGeometry; + three.EllipseCurve = EllipseCurve; + three.EqualCompare = EqualCompare; + three.EqualDepth = EqualDepth; + three.EqualStencilFunc = EqualStencilFunc; + three.EquirectangularReflectionMapping = EquirectangularReflectionMapping; + three.EquirectangularRefractionMapping = EquirectangularRefractionMapping; + three.Euler = Euler; + three.EventDispatcher = EventDispatcher; + three.ExternalTexture = ExternalTexture; + three.ExtrudeGeometry = ExtrudeGeometry; + three.FileLoader = FileLoader; + three.Float16BufferAttribute = Float16BufferAttribute; + three.Float32BufferAttribute = Float32BufferAttribute; + three.FloatType = FloatType; + three.Fog = Fog; + three.FogExp2 = FogExp2; + three.FramebufferTexture = FramebufferTexture; + three.FrontSide = FrontSide; + three.Frustum = Frustum; + three.FrustumArray = FrustumArray; + three.GLBufferAttribute = GLBufferAttribute; + three.GLSL1 = GLSL1; + three.GLSL3 = GLSL3; + three.GreaterCompare = GreaterCompare; + three.GreaterDepth = GreaterDepth; + three.GreaterEqualCompare = GreaterEqualCompare; + three.GreaterEqualDepth = GreaterEqualDepth; + three.GreaterEqualStencilFunc = GreaterEqualStencilFunc; + three.GreaterStencilFunc = GreaterStencilFunc; + three.GridHelper = GridHelper; + three.Group = Group; + three.HTMLTexture = HTMLTexture; + three.HalfFloatType = HalfFloatType; + three.HemisphereLight = HemisphereLight; + three.HemisphereLightHelper = HemisphereLightHelper; + three.IcosahedronGeometry = IcosahedronGeometry; + three.ImageBitmapLoader = ImageBitmapLoader; + three.ImageLoader = ImageLoader; + three.ImageUtils = ImageUtils; + three.IncrementStencilOp = IncrementStencilOp; + three.IncrementWrapStencilOp = IncrementWrapStencilOp; + three.InstancedBufferAttribute = InstancedBufferAttribute; + three.InstancedBufferGeometry = InstancedBufferGeometry; + three.InstancedInterleavedBuffer = InstancedInterleavedBuffer; + three.InstancedMesh = InstancedMesh; + three.Int16BufferAttribute = Int16BufferAttribute; + three.Int32BufferAttribute = Int32BufferAttribute; + three.Int8BufferAttribute = Int8BufferAttribute; + three.IntType = IntType; + three.InterleavedBuffer = InterleavedBuffer; + three.InterleavedBufferAttribute = InterleavedBufferAttribute; + three.Interpolant = Interpolant; + three.InterpolateBezier = InterpolateBezier; + three.InterpolateDiscrete = InterpolateDiscrete; + three.InterpolateLinear = InterpolateLinear; + three.InterpolateSmooth = InterpolateSmooth; + three.InterpolationSamplingMode = InterpolationSamplingMode; + three.InterpolationSamplingType = InterpolationSamplingType; + three.InvertStencilOp = InvertStencilOp; + three.KeepStencilOp = KeepStencilOp; + three.KeyframeTrack = KeyframeTrack; + three.LOD = LOD; + three.LatheGeometry = LatheGeometry; + three.Layers = Layers; + three.LessCompare = LessCompare; + three.LessDepth = LessDepth; + three.LessEqualCompare = LessEqualCompare; + three.LessEqualDepth = LessEqualDepth; + three.LessEqualStencilFunc = LessEqualStencilFunc; + three.LessStencilFunc = LessStencilFunc; + three.Light = Light; + three.LightProbe = LightProbe; + three.Line = Line; + three.Line3 = Line3; + three.LineBasicMaterial = LineBasicMaterial; + three.LineCurve = LineCurve; + three.LineCurve3 = LineCurve3; + three.LineDashedMaterial = LineDashedMaterial; + three.LineLoop = LineLoop; + three.LineSegments = LineSegments; + three.LinearFilter = LinearFilter; + three.LinearInterpolant = LinearInterpolant; + three.LinearMipMapLinearFilter = LinearMipMapLinearFilter; + three.LinearMipMapNearestFilter = LinearMipMapNearestFilter; + three.LinearMipmapLinearFilter = LinearMipmapLinearFilter; + three.LinearMipmapNearestFilter = LinearMipmapNearestFilter; + three.LinearSRGBColorSpace = LinearSRGBColorSpace; + three.LinearToneMapping = LinearToneMapping; + three.LinearTransfer = LinearTransfer; + three.Loader = Loader; + three.LoaderUtils = LoaderUtils; + three.LoadingManager = LoadingManager; + three.LoopOnce = LoopOnce; + three.LoopPingPong = LoopPingPong; + three.LoopRepeat = LoopRepeat; + three.MOUSE = MOUSE; + three.Material = Material; + three.MaterialBlending = MaterialBlending; + three.MaterialLoader = MaterialLoader; + three.MathUtils = MathUtils; + three.Matrix2 = Matrix2; + three.Matrix3 = Matrix3; + three.Matrix4 = Matrix4; + three.MaxEquation = MaxEquation; + three.Mesh = Mesh; + three.MeshBasicMaterial = MeshBasicMaterial; + three.MeshDepthMaterial = MeshDepthMaterial; + three.MeshDistanceMaterial = MeshDistanceMaterial; + three.MeshLambertMaterial = MeshLambertMaterial; + three.MeshMatcapMaterial = MeshMatcapMaterial; + three.MeshNormalMaterial = MeshNormalMaterial; + three.MeshPhongMaterial = MeshPhongMaterial; + three.MeshPhysicalMaterial = MeshPhysicalMaterial; + three.MeshStandardMaterial = MeshStandardMaterial; + three.MeshToonMaterial = MeshToonMaterial; + three.MinEquation = MinEquation; + three.MirroredRepeatWrapping = MirroredRepeatWrapping; + three.MixOperation = MixOperation; + three.MultiplyBlending = MultiplyBlending; + three.MultiplyOperation = MultiplyOperation; + three.NearestFilter = NearestFilter; + three.NearestMipMapLinearFilter = NearestMipMapLinearFilter; + three.NearestMipMapNearestFilter = NearestMipMapNearestFilter; + three.NearestMipmapLinearFilter = NearestMipmapLinearFilter; + three.NearestMipmapNearestFilter = NearestMipmapNearestFilter; + three.NeutralToneMapping = NeutralToneMapping; + three.NeverCompare = NeverCompare; + three.NeverDepth = NeverDepth; + three.NeverStencilFunc = NeverStencilFunc; + three.NoBlending = NoBlending; + three.NoColorSpace = NoColorSpace; + three.NoNormalPacking = NoNormalPacking; + three.NoToneMapping = NoToneMapping; + three.NormalAnimationBlendMode = NormalAnimationBlendMode; + three.NormalBlending = NormalBlending; + three.NormalGAPacking = NormalGAPacking; + three.NormalRGPacking = NormalRGPacking; + three.NotEqualCompare = NotEqualCompare; + three.NotEqualDepth = NotEqualDepth; + three.NotEqualStencilFunc = NotEqualStencilFunc; + three.NumberKeyframeTrack = NumberKeyframeTrack; + three.Object3D = Object3D; + three.ObjectLoader = ObjectLoader; + three.ObjectSpaceNormalMap = ObjectSpaceNormalMap; + three.OctahedronGeometry = OctahedronGeometry; + three.OneFactor = OneFactor; + three.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor; + three.OneMinusConstantColorFactor = OneMinusConstantColorFactor; + three.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; + three.OneMinusDstColorFactor = OneMinusDstColorFactor; + three.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; + three.OneMinusSrcColorFactor = OneMinusSrcColorFactor; + three.OrthographicCamera = OrthographicCamera; + three.PCFShadowMap = PCFShadowMap; + three.PCFSoftShadowMap = PCFSoftShadowMap; + three.PMREMGenerator = PMREMGenerator; + three.Path = Path; + three.PerspectiveCamera = PerspectiveCamera; + three.Plane = Plane; + three.PlaneGeometry = PlaneGeometry; + three.PlaneHelper = PlaneHelper; + three.PointLight = PointLight; + three.PointLightHelper = PointLightHelper; + three.Points = Points; + three.PointsMaterial = PointsMaterial; + three.PolarGridHelper = PolarGridHelper; + three.PolyhedronGeometry = PolyhedronGeometry; + three.PositionalAudio = PositionalAudio; + three.PropertyBinding = PropertyBinding; + three.PropertyMixer = PropertyMixer; + three.QuadraticBezierCurve = QuadraticBezierCurve; + three.QuadraticBezierCurve3 = QuadraticBezierCurve3; + three.Quaternion = Quaternion; + three.QuaternionKeyframeTrack = QuaternionKeyframeTrack; + three.QuaternionLinearInterpolant = QuaternionLinearInterpolant; + three.R11_EAC_Format = R11_EAC_Format; + three.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format; + three.RED_RGTC1_Format = RED_RGTC1_Format; + three.REVISION = REVISION; + three.RG11_EAC_Format = RG11_EAC_Format; + three.RGBADepthPacking = RGBADepthPacking; + three.RGBAFormat = RGBAFormat; + three.RGBAIntegerFormat = RGBAIntegerFormat; + three.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format; + three.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format; + three.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format; + three.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format; + three.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format; + three.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format; + three.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format; + three.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format; + three.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format; + three.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format; + three.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format; + three.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format; + three.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format; + three.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format; + three.RGBA_BPTC_Format = RGBA_BPTC_Format; + three.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format; + three.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; + three.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format; + three.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format; + three.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format; + three.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format; + three.RGBDepthPacking = RGBDepthPacking; + three.RGBFormat = RGBFormat; + three.RGBIntegerFormat = RGBIntegerFormat; + three.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format; + three.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format; + three.RGB_ETC1_Format = RGB_ETC1_Format; + three.RGB_ETC2_Format = RGB_ETC2_Format; + three.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; + three.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; + three.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; + three.RGDepthPacking = RGDepthPacking; + three.RGFormat = RGFormat; + three.RGIntegerFormat = RGIntegerFormat; + three.RawShaderMaterial = RawShaderMaterial; + three.Ray = Ray; + three.Raycaster = Raycaster; + three.RectAreaLight = RectAreaLight; + three.RedFormat = RedFormat; + three.RedIntegerFormat = RedIntegerFormat; + three.ReinhardToneMapping = ReinhardToneMapping; + three.RenderTarget = RenderTarget; + three.RenderTarget3D = RenderTarget3D; + three.RepeatWrapping = RepeatWrapping; + three.ReplaceStencilOp = ReplaceStencilOp; + three.ReverseSubtractEquation = ReverseSubtractEquation; + three.RingGeometry = RingGeometry; + three.SIGNED_R11_EAC_Format = SIGNED_R11_EAC_Format; + three.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format; + three.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format; + three.SIGNED_RG11_EAC_Format = SIGNED_RG11_EAC_Format; + three.SRGBColorSpace = SRGBColorSpace; + three.SRGBTransfer = SRGBTransfer; + three.Scene = Scene; + three.ShaderChunk = ShaderChunk; + three.ShaderLib = ShaderLib; + three.ShaderMaterial = ShaderMaterial; + three.ShadowMaterial = ShadowMaterial; + three.Shape = Shape; + three.ShapeGeometry = ShapeGeometry; + three.ShapePath = ShapePath; + three.ShapeUtils = ShapeUtils; + three.ShortType = ShortType; + three.Skeleton = Skeleton; + three.SkeletonHelper = SkeletonHelper; + three.SkinnedMesh = SkinnedMesh; + three.Source = Source; + three.Sphere = Sphere; + three.SphereGeometry = SphereGeometry; + three.Spherical = Spherical; + three.SphericalHarmonics3 = SphericalHarmonics3; + three.SplineCurve = SplineCurve; + three.SpotLight = SpotLight; + three.SpotLightHelper = SpotLightHelper; + three.Sprite = Sprite; + three.SpriteMaterial = SpriteMaterial; + three.SrcAlphaFactor = SrcAlphaFactor; + three.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; + three.SrcColorFactor = SrcColorFactor; + three.StaticCopyUsage = StaticCopyUsage; + three.StaticDrawUsage = StaticDrawUsage; + three.StaticReadUsage = StaticReadUsage; + three.StereoCamera = StereoCamera; + three.StreamCopyUsage = StreamCopyUsage; + three.StreamDrawUsage = StreamDrawUsage; + three.StreamReadUsage = StreamReadUsage; + three.StringKeyframeTrack = StringKeyframeTrack; + three.SubtractEquation = SubtractEquation; + three.SubtractiveBlending = SubtractiveBlending; + three.TOUCH = TOUCH; + three.TangentSpaceNormalMap = TangentSpaceNormalMap; + three.TetrahedronGeometry = TetrahedronGeometry; + three.Texture = Texture; + three.TextureLoader = TextureLoader; + three.TextureUtils = TextureUtils; + three.Timer = Timer; + three.TimestampQuery = TimestampQuery; + three.TorusGeometry = TorusGeometry; + three.TorusKnotGeometry = TorusKnotGeometry; + three.Triangle = Triangle; + three.TriangleFanDrawMode = TriangleFanDrawMode; + three.TriangleStripDrawMode = TriangleStripDrawMode; + three.TrianglesDrawMode = TrianglesDrawMode; + three.TubeGeometry = TubeGeometry; + three.UVMapping = UVMapping; + three.Uint16BufferAttribute = Uint16BufferAttribute; + three.Uint32BufferAttribute = Uint32BufferAttribute; + three.Uint8BufferAttribute = Uint8BufferAttribute; + three.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute; + three.Uniform = Uniform; + three.UniformsGroup = UniformsGroup; + three.UniformsLib = UniformsLib; + three.UniformsUtils = UniformsUtils; + three.UnsignedByteType = UnsignedByteType; + three.UnsignedInt101111Type = UnsignedInt101111Type; + three.UnsignedInt248Type = UnsignedInt248Type; + three.UnsignedInt5999Type = UnsignedInt5999Type; + three.UnsignedIntType = UnsignedIntType; + three.UnsignedShort4444Type = UnsignedShort4444Type; + three.UnsignedShort5551Type = UnsignedShort5551Type; + three.UnsignedShortType = UnsignedShortType; + three.VSMShadowMap = VSMShadowMap; + three.Vector2 = Vector2; + three.Vector3 = Vector3; + three.Vector4 = Vector4; + three.VectorKeyframeTrack = VectorKeyframeTrack; + three.VideoFrameTexture = VideoFrameTexture; + three.VideoTexture = VideoTexture; + three.WebGL3DRenderTarget = WebGL3DRenderTarget; + three.WebGLArrayRenderTarget = WebGLArrayRenderTarget; + three.WebGLCoordinateSystem = WebGLCoordinateSystem; + three.WebGLCubeRenderTarget = WebGLCubeRenderTarget; + three.WebGLRenderTarget = WebGLRenderTarget; + three.WebGLRenderer = WebGLRenderer; + three.WebGLUtils = WebGLUtils; + three.WebGPUCoordinateSystem = WebGPUCoordinateSystem; + three.WebXRController = WebXRController; + three.WireframeGeometry = WireframeGeometry; + three.WrapAroundEnding = WrapAroundEnding; + three.ZeroCurvatureEnding = ZeroCurvatureEnding; + three.ZeroFactor = ZeroFactor; + three.ZeroSlopeEnding = ZeroSlopeEnding; + three.ZeroStencilOp = ZeroStencilOp; + three.createCanvasElement = createCanvasElement; + three.error = error; + three.getConsoleFunction = getConsoleFunction; + three.log = log; + three.setConsoleFunction = setConsoleFunction; + three.warn = warn; + three.warnOnce = warnOnce; + return three; + } + var point; + var hasRequiredPoint; + function requirePoint() { + if (hasRequiredPoint) return point; + hasRequiredPoint = 1; + var Point = function(x, y, z) { + if (x !== void 0 && y !== void 0 && z !== void 0) { + this.x = x.toFixed(3); + this.y = y.toFixed(3); + this.z = z.toFixed(3); + } + this.faces = []; + }; + Point.prototype.subdivide = function(point2, count, checkPoint) { + var segments = []; + segments.push(this); + for (var i = 1; i < count; i++) { + var np = new Point( + this.x * (1 - i / count) + point2.x * (i / count), + this.y * (1 - i / count) + point2.y * (i / count), + this.z * (1 - i / count) + point2.z * (i / count) + ); + np = checkPoint(np); + segments.push(np); + } + segments.push(point2); + return segments; + }; + Point.prototype.segment = function(point2, percent) { + percent = Math.max(0.01, Math.min(1, percent)); + var x = point2.x * (1 - percent) + this.x * percent; + var y = point2.y * (1 - percent) + this.y * percent; + var z = point2.z * (1 - percent) + this.z * percent; + var newPoint = new Point(x, y, z); + return newPoint; + }; + Point.prototype.midpoint = function(point2, location) { + return this.segment(point2, 0.5); + }; + Point.prototype.project = function(radius, percent) { + if (percent == void 0) { + percent = 1; + } + percent = Math.max(0, Math.min(1, percent)); + this.y / this.x; + this.z / this.x; + this.z / this.y; + var mag = Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2) + Math.pow(this.z, 2)); + var ratio = radius / mag; + this.x = this.x * ratio * percent; + this.y = this.y * ratio * percent; + this.z = this.z * ratio * percent; + return this; + }; + Point.prototype.registerFace = function(face2) { + this.faces.push(face2); + }; + Point.prototype.getOrderedFaces = function() { + var workingArray = this.faces.slice(); + var ret = []; + var i = 0; + while (i < this.faces.length) { + if (i == 0) { + ret.push(workingArray[i]); + workingArray.splice(i, 1); + } else { + var hit = false; + var j = 0; + while (j < workingArray.length && !hit) { + if (workingArray[j].isAdjacentTo(ret[i - 1])) { + hit = true; + ret.push(workingArray[j]); + workingArray.splice(j, 1); + } + j++; + } + } + i++; + } + return ret; + }; + Point.prototype.findCommonFace = function(other, notThisFace) { + for (var i = 0; i < this.faces.length; i++) { + for (var j = 0; j < other.faces.length; j++) { + if (this.faces[i].id === other.faces[j].id && this.faces[i].id !== notThisFace.id) { + return this.faces[i]; + } + } + } + return null; + }; + Point.prototype.toJson = function() { + return { + x: this.x, + y: this.y, + z: this.z + }; + }; + Point.prototype.toString = function() { + return "" + this.x + "," + this.y + "," + this.z; + }; + point = Point; + return point; + } + var tile; + var hasRequiredTile; + function requireTile() { + if (hasRequiredTile) return tile; + hasRequiredTile = 1; + requirePoint(); + function vector(p1, p2) { + return { + x: p2.x - p1.x, + y: p2.y - p1.y, + z: p2.z - p1.z + }; + } + function calculateSurfaceNormal(p1, p2, p3) { + U = vector(p1, p2); + V = vector(p1, p3); + N = { + x: U.y * V.z - U.z * V.y, + y: U.z * V.x - U.x * V.z, + z: U.x * V.y - U.y * V.x + }; + return N; + } + function pointingAwayFromOrigin(p, v) { + return p.x * v.x >= 0 && p.y * v.y >= 0 && p.z * v.z >= 0; + } + var Tile = function(centerPoint, hexSize) { + if (hexSize == void 0) { + hexSize = 1; + } + hexSize = Math.max(0.01, Math.min(1, hexSize)); + this.centerPoint = centerPoint; + this.faces = centerPoint.getOrderedFaces(); + this.boundary = []; + this.neighborIds = []; + this.neighbors = []; + var neighborHash = {}; + for (var f = 0; f < this.faces.length; f++) { + this.boundary.push(this.faces[f].getCentroid().segment(this.centerPoint, hexSize)); + var otherPoints = this.faces[f].getOtherPoints(this.centerPoint); + for (var o = 0; o < 2; o++) { + neighborHash[otherPoints[o]] = 1; + } + } + this.neighborIds = Object.keys(neighborHash); + var normal = calculateSurfaceNormal(this.boundary[1], this.boundary[2], this.boundary[3]); + if (!pointingAwayFromOrigin(this.centerPoint, normal)) { + this.boundary.reverse(); + } + }; + Tile.prototype.getLatLon = function(radius, boundaryNum) { + var point2 = this.centerPoint; + if (typeof boundaryNum == "number" && boundaryNum < this.boundary.length) { + point2 = this.boundary[boundaryNum]; + } + var phi = Math.acos(point2.y / radius); + var theta = (Math.atan2(point2.x, point2.z) + Math.PI + Math.PI / 2) % (Math.PI * 2) - Math.PI; + return { + lat: 180 * phi / Math.PI - 90, + lon: 180 * theta / Math.PI + }; + }; + Tile.prototype.scaledBoundary = function(scale) { + scale = Math.max(0, Math.min(1, scale)); + var ret = []; + for (var i = 0; i < this.boundary.length; i++) { + ret.push(this.centerPoint.segment(this.boundary[i], 1 - scale)); + } + return ret; + }; + Tile.prototype.toJson = function() { + return { + centerPoint: this.centerPoint.toJson(), + boundary: this.boundary.map(function(point2) { + return point2.toJson(); + }) + }; + }; + Tile.prototype.toString = function() { + return this.centerPoint.toString(); + }; + tile = Tile; + return tile; + } + var face; + var hasRequiredFace; + function requireFace() { + if (hasRequiredFace) return face; + hasRequiredFace = 1; + var Point = requirePoint(); + var _faceCount = 0; + var Face = function(point1, point2, point3, register) { + this.id = _faceCount++; + if (register == void 0) { + register = true; + } + this.points = [ + point1, + point2, + point3 + ]; + if (register) { + point1.registerFace(this); + point2.registerFace(this); + point3.registerFace(this); + } + }; + Face.prototype.getOtherPoints = function(point1) { + var other = []; + for (var i = 0; i < this.points.length; i++) { + if (this.points[i].toString() !== point1.toString()) { + other.push(this.points[i]); + } + } + return other; + }; + Face.prototype.findThirdPoint = function(point1, point2) { + for (var i = 0; i < this.points.length; i++) { + if (this.points[i].toString() !== point1.toString() && this.points[i].toString() !== point2.toString()) { + return this.points[i]; + } + } + }; + Face.prototype.isAdjacentTo = function(face2) { + var count = 0; + for (var i = 0; i < this.points.length; i++) { + for (var j = 0; j < face2.points.length; j++) { + if (this.points[i].toString() == face2.points[j].toString()) { + count++; + } + } + } + return count == 2; + }; + Face.prototype.getCentroid = function(clear) { + if (this.centroid && !clear) { + return this.centroid; + } + var x = (this.points[0].x + this.points[1].x + this.points[2].x) / 3; + var y = (this.points[0].y + this.points[1].y + this.points[2].y) / 3; + var z = (this.points[0].z + this.points[1].z + this.points[2].z) / 3; + var centroid = new Point(x, y, z); + this.centroid = centroid; + return centroid; + }; + face = Face; + return face; + } + var hexasphere; + var hasRequiredHexasphere; + function requireHexasphere() { + if (hasRequiredHexasphere) return hexasphere; + hasRequiredHexasphere = 1; + var Tile = requireTile(), Face = requireFace(), Point = requirePoint(); + var Hexasphere = function(radius, numDivisions, hexSize) { + this.radius = radius; + var tao = 1.61803399; + var corners = [ + new Point(1e3, tao * 1e3, 0), + new Point(-1e3, tao * 1e3, 0), + new Point(1e3, -tao * 1e3, 0), + new Point(-1e3, -tao * 1e3, 0), + new Point(0, 1e3, tao * 1e3), + new Point(0, -1e3, tao * 1e3), + new Point(0, 1e3, -tao * 1e3), + new Point(0, -1e3, -tao * 1e3), + new Point(tao * 1e3, 0, 1e3), + new Point(-tao * 1e3, 0, 1e3), + new Point(tao * 1e3, 0, -1e3), + new Point(-tao * 1e3, 0, -1e3) + ]; + var points = {}; + for (var i = 0; i < corners.length; i++) { + points[corners[i]] = corners[i]; + } + var faces = [ + new Face(corners[0], corners[1], corners[4], false), + new Face(corners[1], corners[9], corners[4], false), + new Face(corners[4], corners[9], corners[5], false), + new Face(corners[5], corners[9], corners[3], false), + new Face(corners[2], corners[3], corners[7], false), + new Face(corners[3], corners[2], corners[5], false), + new Face(corners[7], corners[10], corners[2], false), + new Face(corners[0], corners[8], corners[10], false), + new Face(corners[0], corners[4], corners[8], false), + new Face(corners[8], corners[2], corners[10], false), + new Face(corners[8], corners[4], corners[5], false), + new Face(corners[8], corners[5], corners[2], false), + new Face(corners[1], corners[0], corners[6], false), + new Face(corners[11], corners[1], corners[6], false), + new Face(corners[3], corners[9], corners[11], false), + new Face(corners[6], corners[10], corners[7], false), + new Face(corners[3], corners[11], corners[7], false), + new Face(corners[11], corners[6], corners[7], false), + new Face(corners[6], corners[0], corners[10], false), + new Face(corners[9], corners[1], corners[11], false) + ]; + var getPointIfExists = function(point2) { + if (points[point2]) { + return points[point2]; + } else { + points[point2] = point2; + return point2; + } + }; + var newFaces = []; + for (var f = 0; f < faces.length; f++) { + var prev = null; + var bottom = [faces[f].points[0]]; + var left = faces[f].points[0].subdivide(faces[f].points[1], numDivisions, getPointIfExists); + var right = faces[f].points[0].subdivide(faces[f].points[2], numDivisions, getPointIfExists); + for (var i = 1; i <= numDivisions; i++) { + prev = bottom; + bottom = left[i].subdivide(right[i], i, getPointIfExists); + for (var j = 0; j < i; j++) { + var nf = new Face(prev[j], bottom[j], bottom[j + 1]); + newFaces.push(nf); + if (j > 0) { + nf = new Face(prev[j - 1], prev[j], bottom[j]); + newFaces.push(nf); + } + } + } + } + faces = newFaces; + var newPoints = {}; + for (var p in points) { + var np = points[p].project(radius); + newPoints[np] = np; + } + points = newPoints; + this.tiles = []; + this.tileLookup = {}; + for (var p in points) { + var newTile = new Tile(points[p], hexSize); + this.tiles.push(newTile); + this.tileLookup[newTile.toString()] = newTile; + } + for (var t in this.tiles) { + var _this2 = this; + this.tiles[t].neighbors = this.tiles[t].neighborIds.map(function(item) { + return _this2.tileLookup[item]; + }); + } + }; + Hexasphere.prototype.toJson = function() { + return JSON.stringify({ + radius: this.radius, + tiles: this.tiles.map(function(tile2) { + return tile2.toJson(); + }) + }); + }; + Hexasphere.prototype.toObj = function() { + var objV = []; + var objF = []; + var objText = "# vertices \n"; + var vertexIndexMap = {}; + for (var i = 0; i < this.tiles.length; i++) { + var t = this.tiles[i]; + var F = []; + for (var j = 0; j < t.boundary.length; j++) { + var index = vertexIndexMap[t.boundary[j]]; + if (index == void 0) { + objV.push(t.boundary[j]); + index = objV.length; + vertexIndexMap[t.boundary[j]] = index; + } + F.push(index); + } + objF.push(F); + } + for (var i = 0; i < objV.length; i++) { + objText += "v " + objV[i].x + " " + objV[i].y + " " + objV[i].z + "\n"; + } + objText += "\n# faces\n"; + for (var i = 0; i < objF.length; i++) { + faceString = "f"; + for (var j = 0; j < objF[i].length; j++) { + faceString = faceString + " " + objF[i][j]; + } + objText += faceString + "\n"; + } + return objText; + }; + hexasphere = Hexasphere; + return hexasphere; + } + var vec2$1 = { exports: {} }; + var hasRequiredVec2$1; + function requireVec2$1() { + if (hasRequiredVec2$1) return vec2$1.exports; + hasRequiredVec2$1 = 1; + (function(module) { + (function inject(clean, precision, undef) { + var isArray = function(a) { + return Object.prototype.toString.call(a) === "[object Array]"; + }; + function Vec2(x, y) { + if (!(this instanceof Vec2)) { + return new Vec2(x, y); + } + if (isArray(x)) { + y = x[1]; + x = x[0]; + } else if ("object" === typeof x && x) { + y = x.y; + x = x.x; + } + this.x = Vec2.clean(x || 0); + this.y = Vec2.clean(y || 0); + } + Vec2.prototype = { + change: function(fn) { + if (fn) { + if (this.observers) { + this.observers.push(fn); + } else { + this.observers = [fn]; + } + } else if (this.observers) { + for (var i = this.observers.length - 1; i >= 0; i--) { + this.observers[i](this); + } + } + return this; + }, + ignore: function(fn) { + if (this.observers) { + var o = this.observers, l = o.length; + while (l--) { + o[l] === fn && o.splice(l, 1); + } + } + return this; + }, + // set x and y + set: function(x, y, silent) { + if ("number" != typeof x) { + silent = y; + y = x.y; + x = x.x; + } + if (this.x === x && this.y === y) { + return this; + } + this.x = Vec2.clean(x); + this.y = Vec2.clean(y); + if (silent !== false) { + return this.change(); + } + }, + // reset x and y to zero + zero: function() { + return this.set(0, 0); + }, + // return a new vector with the same component values + // as this one + clone: function() { + return new this.constructor(this.x, this.y); + }, + // negate the values of this vector + negate: function(returnNew) { + if (returnNew) { + return new this.constructor(-this.x, -this.y); + } else { + return this.set(-this.x, -this.y); + } + }, + // Add the incoming `vec2` vector to this vector + add: function(vec22, returnNew) { + if (!returnNew) { + this.x += vec22.x; + this.y += vec22.y; + return this.change(); + } else { + return new this.constructor( + this.x + vec22.x, + this.y + vec22.y + ); + } + }, + // Subtract the incoming `vec2` from this vector + subtract: function(vec22, returnNew) { + if (!returnNew) { + this.x -= vec22.x; + this.y -= vec22.y; + return this.change(); + } else { + return new this.constructor( + this.x - vec22.x, + this.y - vec22.y + ); + } + }, + // Multiply this vector by the incoming `vec2` + multiply: function(vec22, returnNew) { + var x, y; + if ("number" !== typeof vec22) { + x = vec22.x; + y = vec22.y; + } else { + x = y = vec22; + } + if (!returnNew) { + return this.set(this.x * x, this.y * y); + } else { + return new this.constructor( + this.x * x, + this.y * y + ); + } + }, + // Rotate this vector. Accepts a `Rotation` or angle in radians. + // + // Passing a truthy `inverse` will cause the rotation to + // be reversed. + // + // If `returnNew` is truthy, a new + // `Vec2` will be created with the values resulting from + // the rotation. Otherwise the rotation will be applied + // to this vector directly, and this vector will be returned. + rotate: function(r, inverse, returnNew) { + var x = this.x, y = this.y, cos = Math.cos(r), sin = Math.sin(r), rx, ry; + inverse = inverse ? -1 : 1; + rx = cos * x - inverse * sin * y; + ry = inverse * sin * x + cos * y; + if (returnNew) { + return new this.constructor(rx, ry); + } else { + return this.set(rx, ry); + } + }, + // Calculate the length of this vector + length: function() { + var x = this.x, y = this.y; + return Math.sqrt(x * x + y * y); + }, + // Get the length squared. For performance, use this instead of `Vec2#length` (if possible). + lengthSquared: function() { + var x = this.x, y = this.y; + return x * x + y * y; + }, + // Return the distance betwen this `Vec2` and the incoming vec2 vector + // and return a scalar + distance: function(vec22) { + var x = this.x - vec22.x; + var y = this.y - vec22.y; + return Math.sqrt(x * x + y * y); + }, + // Convert this vector into a unit vector. + // Returns the length. + normalize: function(returnNew) { + var length = this.length(); + var invertedLength = length < Number.MIN_VALUE ? 0 : 1 / length; + if (!returnNew) { + return this.set(this.x * invertedLength, this.y * invertedLength); + } else { + return new this.constructor(this.x * invertedLength, this.y * invertedLength); + } + }, + // Determine if another `Vec2`'s components match this one's + // also accepts 2 scalars + equal: function(v, w) { + if (w === undef) { + w = v.y; + v = v.x; + } + return Vec2.clean(v) === this.x && Vec2.clean(w) === this.y; + }, + // Return a new `Vec2` that contains the absolute value of + // each of this vector's parts + abs: function(returnNew) { + var x = Math.abs(this.x), y = Math.abs(this.y); + if (returnNew) { + return new this.constructor(x, y); + } else { + return this.set(x, y); + } + }, + // Return a new `Vec2` consisting of the smallest values + // from this vector and the incoming + // + // When returnNew is truthy, a new `Vec2` will be returned + // otherwise the minimum values in either this or `v` will + // be applied to this vector. + min: function(v, returnNew) { + var tx = this.x, ty = this.y, vx = v.x, vy = v.y, x = tx < vx ? tx : vx, y = ty < vy ? ty : vy; + if (returnNew) { + return new this.constructor(x, y); + } else { + return this.set(x, y); + } + }, + // Return a new `Vec2` consisting of the largest values + // from this vector and the incoming + // + // When returnNew is truthy, a new `Vec2` will be returned + // otherwise the minimum values in either this or `v` will + // be applied to this vector. + max: function(v, returnNew) { + var tx = this.x, ty = this.y, vx = v.x, vy = v.y, x = tx > vx ? tx : vx, y = ty > vy ? ty : vy; + if (returnNew) { + return new this.constructor(x, y); + } else { + return this.set(x, y); + } + }, + // Clamp values into a range. + // If this vector's values are lower than the `low`'s + // values, then raise them. If they are higher than + // `high`'s then lower them. + // + // Passing returnNew as true will cause a new Vec2 to be + // returned. Otherwise, this vector's values will be clamped + clamp: function(low, high, returnNew) { + var ret = this.min(high, true).max(low); + if (returnNew) { + return ret; + } else { + return this.set(ret.x, ret.y); + } + }, + // Perform linear interpolation between two vectors + // amount is a decimal between 0 and 1 + lerp: function(vec, amount) { + return this.add(vec.subtract(this, true).multiply(amount), true); + }, + // Get the skew vector such that dot(skew_vec, other) == cross(vec, other) + skew: function() { + return new this.constructor(-this.y, this.x); + }, + // calculate the dot product between + // this vector and the incoming + dot: function(b) { + return Vec2.clean(this.x * b.x + b.y * this.y); + }, + // calculate the perpendicular dot product between + // this vector and the incoming + perpDot: function(b) { + return Vec2.clean(this.x * b.y - this.y * b.x); + }, + // Determine the angle between two vec2s + angleTo: function(vec) { + return Math.atan2(this.perpDot(vec), this.dot(vec)); + }, + // Divide this vector's components by a scalar + divide: function(vec22, returnNew) { + var x, y; + if ("number" !== typeof vec22) { + x = vec22.x; + y = vec22.y; + } else { + x = y = vec22; + } + if (x === 0 || y === 0) { + throw new Error("division by zero"); + } + if (isNaN(x) || isNaN(y)) { + throw new Error("NaN detected"); + } + if (returnNew) { + return new this.constructor(this.x / x, this.y / y); + } + return this.set(this.x / x, this.y / y); + }, + isPointOnLine: function(start, end) { + return (start.y - this.y) * (start.x - end.x) === (start.y - end.y) * (start.x - this.x); + }, + toArray: function() { + return [this.x, this.y]; + }, + fromArray: function(array) { + return this.set(array[0], array[1]); + }, + toJSON: function() { + return { x: this.x, y: this.y }; + }, + toString: function() { + return "(" + this.x + ", " + this.y + ")"; + }, + constructor: Vec2 + }; + Vec2.fromArray = function(array, ctor) { + return new (ctor || Vec2)(array[0], array[1]); + }; + Vec2.precision = precision || 8; + var p = Math.pow(10, Vec2.precision); + Vec2.clean = clean || function(val) { + if (isNaN(val)) { + throw new Error("NaN detected"); + } + if (!isFinite(val)) { + throw new Error("Infinity detected"); + } + if (Math.round(val) === val) { + return val; + } + return Math.round(val * p) / p; + }; + Vec2.inject = inject; + if (!clean) { + Vec2.fast = inject(function(k) { + return k; + }); + { + module.exports = Vec2; + } + } + return Vec2; + })(); + })(vec2$1); + return vec2$1.exports; + } + var quadtree2helper; + var hasRequiredQuadtree2helper; + function requireQuadtree2helper() { + if (hasRequiredQuadtree2helper) return quadtree2helper; + hasRequiredQuadtree2helper = 1; + var Quadtree2Helper = { + fnName: function fnName(fn) { + var ret = fn.toString(); + ret = ret.substr("function ".length); + ret = ret.substr(0, ret.indexOf("(")); + return ret; + }, + // A verbose exception generator helper. + thrower: function thrower(code, message, key) { + var error = code; + if (key) { + error += "_" + key; + } + if (message) { + error += " - "; + } + if (message && key) { + error += key + ": "; + } + if (message) { + error += message; + } + throw new Error(error); + }, + getIdsOfObjects: function getIdsOfObjects(hash) { + var result = []; + for (var id in hash) { + result.push(hash[id].id_); + } + return result; + }, + compare: function compare(a, b) { + return a - b; + }, + arrayDiffs: function arrayDiffs(arrA, arrB) { + var i = 0, j = 0, retA = [], retB = []; + arrA.sort(this.compare); + arrB.sort(this.compare); + while (i < arrA.length && j < arrB.length) { + if (arrA[i] === arrB[j]) { + i++; + j++; + continue; + } + if (arrA[i] < arrB[j]) { + retA.push(arrA[i]); + i++; + continue; + } else { + retB.push(arrB[j]); + j++; + } + } + if (i < arrA.length) { + retA.push.apply(retA, arrA.slice(i, arrA.length)); + } else { + retB.push.apply(retB, arrB.slice(j, arrB.length)); + } + return [retA, retB]; + } + }; + quadtree2helper = Quadtree2Helper; + return quadtree2helper; + } + var quadtree2validator; + var hasRequiredQuadtree2validator; + function requireQuadtree2validator() { + if (hasRequiredQuadtree2validator) return quadtree2validator; + hasRequiredQuadtree2validator = 1; + requireVec2$1(); + var Quadtree2Helper = requireQuadtree2helper(), Quadtree2Validator = function Quadtree2Validator2() { + }; + Quadtree2Validator.prototype = { + isNumber: function isNumber(param, key) { + if ("number" !== typeof param) { + Quadtree2Helper.thrower("NaN", "Not a Number", key); + } + }, + isString: function isString(param, key) { + if (!(typeof param === "string" || param instanceof String)) { + Quadtree2Helper.thrower("NaS", "Not a String", key); + } + }, + isVec2: function isVec2(param, key) { + var throwIt = false; + throwIt = "object" !== typeof param || param.x === void 0 || param.y === void 0; + if (throwIt) { + Quadtree2Helper.thrower("NaV", "Not a Vec2", key); + } + }, + isDefined: function isDefined(param, key) { + if (param === void 0) { + Quadtree2Helper.thrower("ND", "Not defined", key); + } + }, + isObject: function isObject(param, key) { + if ("object" !== typeof param) { + Quadtree2Helper.thrower("NaO", "Not an Object", key); + } + }, + hasKey: function hasKey(obj, k, key) { + this.isDefined(obj, "obj"); + if (Object.keys(obj).indexOf(k.toString()) === -1) { + Quadtree2Helper.thrower("OhnK", "Object has no key", key + k); + } + }, + hasNoKey: function hasNoKey(obj, k, key) { + this.isDefined(obj, "obj"); + if (Object.keys(obj).indexOf(k.toString()) !== -1) { + Quadtree2Helper.thrower("OhK", "Object has key", key + k); + } + }, + fnFalse: function fn(cb) { + if (cb()) { + Quadtree2Helper.thrower("FarT", "function already returns true", Quadtree2Helper.fnName(cb)); + } + }, + byCallbackObject: function byCallbackObject(obj, cbObj, keyTable) { + var key; + for (key in cbObj) { + if (keyTable !== void 0) { + cbObj[key](obj[keyTable[key]], keyTable[key]); + } else { + cbObj[key](obj[key], key); + } + } + } + }; + quadtree2validator = Quadtree2Validator; + return quadtree2validator; + } + var quadtree2quadrant; + var hasRequiredQuadtree2quadrant; + function requireQuadtree2quadrant() { + if (hasRequiredQuadtree2quadrant) return quadtree2quadrant; + hasRequiredQuadtree2quadrant = 1; + var Quadtree2Quadrant = function Quadtree2Quadrant2(leftTop, size, id, parent) { + this.leftTop_ = leftTop.clone(); + this.children_ = []; + this.objects_ = {}; + this.objectCount_ = 0; + this.id_ = id || 0; + this.parent_ = parent; + this.refactoring_ = false; + this.setSize(size); + }; + Quadtree2Quadrant.prototype = { + setSize: function setSize(size) { + if (!size) { + return; + } + this.size_ = size; + this.rad_ = size.multiply(0.5, true); + this.center_ = this.leftTop_.add(this.rad_, true); + this.leftBot_ = this.leftTop_.clone(); + this.leftBot_.y += size.y; + this.rightTop_ = this.leftTop_.clone(); + this.rightTop_.x += size.x; + this.rightBot_ = this.leftTop_.add(size, true); + this.leftMid_ = this.center_.clone(); + this.leftMid_.x = this.leftTop_.x; + this.topMid_ = this.center_.clone(); + this.topMid_.y = this.leftTop_.y; + }, + makeChildren: function makeChildren(id) { + if (this.children_.length > 0) { + return false; + } + this.children_.push( + new Quadtree2Quadrant(this.leftTop_, this.rad_, id++, this), + new Quadtree2Quadrant(this.topMid_, this.rad_, id++, this), + new Quadtree2Quadrant(this.leftMid_, this.rad_, id++, this), + new Quadtree2Quadrant(this.center_, this.rad_, id++, this) + ); + return id; + }, + looseChildren: function looseChildren() { + this.children_ = []; + }, + addObjects: function addObjects(objs) { + var id; + for (id in objs) { + this.addObject(id, objs[id]); + } + }, + addObject: function addObject(id, obj) { + this.objectCount_++; + this.objects_[id] = obj; + }, + removeObjects: function removeObjects(removed, dir) { + var id; + if (!removed) { + removed = []; + } + for (id in this.objects_) { + removed.push({ obj: this.objects_[id], quadrant: this }); + delete this.objects_[id]; + } + this.objectCount_ = 0; + if (!dir || dir === 1) { + if (this.parent_) { + this.parent_.removeObjects(removed, 1); + } + } + if (!dir || dir === -1) { + this.children_.forEach(function(child) { + child.removeObjects(removed, -1); + }); + } + return removed; + }, + removeObject: function removeObject(id) { + var result = this.objects_[id]; + this.objectCount_--; + delete this.objects_[id]; + return result; + }, + getObjectCountForLimit: function getObjectCountForLimit() { + var i, id, objects = {}; + for (id in this.objects_) { + objects[id] = true; + } + for (i = 0; i < this.children_.length; i++) { + for (id in this.children_[i].objects_) { + objects[id] = true; + } + } + return Object.keys(objects).length; + }, + getObjectCount: function getObjectCount(recursive, onelevel) { + var result = this.objectCount_; + if (recursive) { + this.children_.forEach(function(child) { + result += child.getObjectCount(!onelevel && recursive); + }); + } + return result; + }, + intersectingChildren: function intersectingChildren(pos, rad) { + return this.children_.filter(function(child) { + return child.intersects(pos, rad); + }); + }, + intersects: function intersects(pos, rad) { + var dist = pos.subtract(this.center_, true).abs(); + if (dist.x > this.rad_.x + rad) { + return false; + } + if (dist.y > this.rad_.y + rad) { + return false; + } + if (dist.x <= this.rad_.x) { + return true; + } + if (dist.y <= this.rad_.y) { + return true; + } + cornerDistSq = Math.pow(dist.x - this.rad_.x, 2) + Math.pow(dist.y - this.rad_.y, 2); + return cornerDistSq <= Math.pow(rad, 2); + }, + hasChildren: function hasChildren() { + return this.getChildCount() !== 0; + }, + getChildCount: function getChildCount(recursive) { + var count = this.children_.length; + if (recursive) { + this.children_.forEach(function(child) { + count += child.getChildCount(recursive); + }); + } + return count; + }, + getChildren: function getChildren(recursive, result) { + if (!result) result = []; + result.push.apply(result, this.children_); + if (recursive) { + this.children_.forEach(function(child) { + child.getChildren(recursive, result); + }); + } + return result; + }, + getObjectsUp: function getObjectsUp(result) { + var id; + if (result.quadrants[this.id_]) { + return; + } + result.quadrants[this.id_] = true; + for (id in this.objects_) { + result.objects[id] = this.objects_[id]; + } + if (this.parent_) { + this.parent_.getObjectsUp(result); + } + }, + getObjectsDown: function getObjectsDown(result) { + var id; + if (result.quadrants[this.id_]) { + return; + } + result.quadrants[this.id_] = true; + for (id in this.objects_) { + result.objects[id] = this.objects_[id]; + } + for (id = 0; id < this.children_.length; id++) { + this.children_[id].getObjectsDown(result); + } + } + }; + quadtree2quadrant = Quadtree2Quadrant; + return quadtree2quadrant; + } + var quadtree2; + var hasRequiredQuadtree2; + function requireQuadtree2() { + if (hasRequiredQuadtree2) return quadtree2; + hasRequiredQuadtree2 = 1; + var Vec2 = requireVec2$1(), Quadtree2Helper = requireQuadtree2helper(), Quadtree2Validator = requireQuadtree2validator(), Quadtree2Quadrant = requireQuadtree2quadrant(), Quadtree2; + Quadtree2 = function Quadtree22(size, quadrantObjectsLimit, quadrantLevelLimit) { + var id, data = { + objects_: {}, + quadrants_: {}, + ids_: 1, + quadrantIds_: 1, + autoId_: true, + inited_: false, + debug_: false, + size_: void 0, + root_: void 0, + quadrantObjectsLimit_: void 0, + quadrantLevelLimit_: void 0, + quadrantSizeLimit_: void 0 + }, validator = new Quadtree2Validator(), k = { + p: "pos_", + r: "rad_", + id: "id_" + }, constraints = { + data: { + necessary: { + size_: validator.isVec2, + quadrantObjectsLimit_: validator.isNumber, + quadrantLevelLimit_: validator.isNumber + } + }, + k: { + necessary: { + p: validator.isVec2 + }, + c: { + necessary: { + r: validator.isNumber + } + } + } + }, fns = { + nextId: function nextId() { + return data.ids_++; + }, + nextQuadrantId: function nextQuadrantId(sum) { + var id2 = data.quadrantIds_; + data.quadrantIds_ += sum || 4; + return id2; + }, + hasCollision: function hasCollision(objA, objB) { + return objA[k.r] + objB[k.r] > objA[k.p].distance(objB[k.p]); + }, + removeQuadrantParentQuadrants: function removeQuadrantParentQuadrants(quadrant, quadrants) { + if (!quadrant.parent_) { + return; + } + if (quadrants[quadrant.parent_.id_]) { + delete quadrants[quadrant.parent_.id_]; + fns.removeQuadrantParentQuadrants(quadrant.parent_, quadrants); + } + }, + getSubtreeTopQuadrant: function getSubtreeTopQuadrant(quadrant, quadrants) { + if (!quadrant.parent_ || !quadrants[quadrant.parent_.id_]) { + return quadrant; + } + return getSubtreeTopQuadrant(quadrant.parent_, quadrants); + }, + removeQuadrantChildtree: function removeQuadrantChildtree(quadrant, quadrants) { + var i, children = quadrant.getChildren(); + for (i = 0; i < children.length; i++) { + if (!quadrants[children[i].id_]) { + return; + } + delete quadrants[children[i].id_]; + fns.removeQuadrantChildtree(children[i], quadrants); + } + }, + getIntersectingQuadrants: function getIntersectingQuadrants(obj, quadrant, result) { + var i, children; + if (!quadrant.intersects(obj[k.p], obj[k.r])) { + fns.removeQuadrantParentQuadrants(quadrant, result.biggest); + return; + } + result.biggest[quadrant.id_] = quadrant; + children = quadrant.getChildren(); + if (children.length) { + for (i = 0; i < children.length; i++) { + getIntersectingQuadrants(obj, children[i], result); + } + } else { + result.leaves[quadrant.id_] = quadrant; + } + }, + getSmallestIntersectingQuadrants: function getSmallestIntersectingQuadrants(obj, quadrant, result) { + var id2, top; + if (!quadrant) { + quadrant = data.root_; + } + if (!result) { + result = { leaves: {}, biggest: {} }; + } + fns.getIntersectingQuadrants(obj, quadrant, result); + for (id2 in result.leaves) { + if (!result.biggest[id2]) { + continue; + } + top = fns.getSubtreeTopQuadrant(result.leaves[id2], result.biggest); + fns.removeQuadrantChildtree(top, result.biggest); + } + return result.biggest; + }, + removeQuadrantObjects: function removeQuadrantObjects(quadrant) { + var i, removed = quadrant.removeObjects([], 1); + for (i = 0; i < removed.length; i++) { + delete data.quadrants_[removed[i].obj[k.id]][removed[i].quadrant.id_]; + } + return removed; + }, + removeObjectFromQuadrants: function removeObjectFromQuadrants(obj, quadrants) { + var id2; + if (quadrants === void 0) { + quadrants = data.quadrants_[obj[k.id]]; + } + for (id2 in quadrants) { + fns.removeObjectFromQuadrant(obj, quadrants[id2]); + } + }, + removeObjectFromQuadrant: function removeObjectFromQuadrant(obj, quadrant) { + quadrant.removeObject(obj[k.id]); + delete data.quadrants_[obj[k.id]][quadrant.id_]; + if (quadrant.hasChildren() || !quadrant.parent_) { + return; + } + fns.refactorSubtree(quadrant.parent_); + }, + refactorSubtree: function refactorSubtree(quadrant) { + var i, id2, count, child, obj; + if (quadrant.refactoring_) { + return; + } + for (i = 0; i < quadrant.children_.length; i++) { + child = quadrant.children_[i]; + if (child.hasChildren()) { + return; + } + } + count = quadrant.getObjectCountForLimit(); + if (count > data.quadrantObjectsLimit_) { + return; + } + quadrant.refactoring_ = true; + for (i = 0; i < quadrant.children_.length; i++) { + child = quadrant.children_[i]; + for (id2 in child.objects_) { + obj = child.objects_[id2]; + fns.removeObjectFromQuadrant(obj, child); + fns.addObjectToQuadrant(obj, quadrant); + } + } + quadrant.looseChildren(); + quadrant.refactoring_ = false; + if (!quadrant.parent_) { + return; + } + fns.refactorSubtree(quadrant.parent_); + }, + updateObjectQuadrants: function updateObjectQuadrants(obj) { + var oldQuadrants = data.quadrants_[obj[k.id]], newQuadrants = fns.getSmallestIntersectingQuadrants(obj), oldIds = Quadtree2Helper.getIdsOfObjects(oldQuadrants), newIds = Quadtree2Helper.getIdsOfObjects(newQuadrants), diffIds = Quadtree2Helper.arrayDiffs(oldIds, newIds), removeIds = diffIds[0], addIds = diffIds[1], i; + for (i = 0; i < addIds.length; i++) { + fns.populateSubtree(obj, newQuadrants[addIds[i]]); + } + for (i = 0; i < removeIds.length; i++) { + if (!oldQuadrants[removeIds[i]]) { + continue; + } + fns.removeObjectFromQuadrant(obj, oldQuadrants[removeIds[i]]); + } + }, + addObjectToQuadrant: function addObjectToQuadrant(obj, quadrant) { + var id2 = obj[k.id]; + if (data.quadrants_[id2] === void 0) data.quadrants_[id2] = {}; + data.quadrants_[id2][quadrant.id_] = quadrant; + quadrant.addObject(id2, obj); + }, + populateSubtree: function populateSubtree(obj, quadrant) { + var i, id2, smallestQs, removed; + if (!quadrant) { + quadrant = data.root_; + } + if (quadrant.hasChildren()) { + smallestQs = fns.getSmallestIntersectingQuadrants(obj, quadrant); + for (id2 in smallestQs) { + if (smallestQs[id2] === quadrant) { + fns.addObjectToQuadrant(obj, quadrant); + return; + } + fns.populateSubtree(obj, smallestQs[id2]); + } + } else if (quadrant.getObjectCount() < data.quadrantObjectsLimit_ || quadrant.size_.x < data.quadrantSizeLimit_.x) { + fns.addObjectToQuadrant(obj, quadrant); + } else { + quadrant.makeChildren(fns.nextQuadrantId()); + removed = fns.removeQuadrantObjects(quadrant); + removed.push({ obj, quadrant }); + for (i = 0; i < removed.length; i++) { + fns.populateSubtree(removed[i].obj, removed[i].quadrant); + } + } + }, + init: function init() { + var divider; + if (!data.quadrantLevelLimit_) data.quadrantLevelLimit_ = 6; + validator.byCallbackObject(data, constraints.data.necessary); + data.root_ = new Quadtree2Quadrant(new Vec2(0, 0), data.size_.clone(), fns.nextQuadrantId(1)); + divider = Math.pow(2, data.quadrantLevelLimit_); + data.quadrantSizeLimit_ = data.size_.clone().divide(divider); + data.inited_ = true; + }, + checkInit: function checkInit(init) { + if (init && !data.inited_) { + fns.init(); + } + return data.inited_; + }, + checkObjectKeys: function checkObjectKeys(obj) { + validator.isNumber(obj[k.id], k.id); + validator.isNumber(obj[k.r], k.r); + validator.hasNoKey(data.objects_, obj[k.id], k.id); + validator.byCallbackObject(obj, constraints.k.necessary, k); + }, + setObjId: function setObjId(obj) { + if (data.autoId_ && !obj[k.id]) { + obj[k.id] = fns.nextId(); + } + }, + removeObjectById: function removeObjectById(id2) { + validator.hasKey(data.objects_, id2, k.id); + fns.removeObjectFromQuadrants(data.objects_[id2]); + delete data.objects_[id2]; + }, + updateObjectById: function updateObjectById(id2) { + validator.hasKey(data.objects_, id2, k.id); + fns.updateObjectQuadrants(data.objects_[id2]); + }, + getObjectsByObject: function getObjectsByObject(obj) { + var i, id2, quadrants = data.quadrants_[obj[k.id]], result = { objects: {}, quadrants: {} }; + for (id2 in quadrants) { + quadrants[id2].getObjectsUp(result); + for (i = 0; i < quadrants[id2].children_.length; i++) { + quadrants[id2].children_[i].getObjectsDown(result); + } + } + delete result.objects[obj[k.id]]; + return result.objects; + } + }, debugFns = { + getQuadrants: function getQuadrants() { + return data.root_.getChildren(true, [data.root_]); + }, + getLeafQuadrants: function getLeafQuadrants() { + return debugFns.getQuadrants().filter(function(q) { + return !q.hasChildren(); + }); + } + }, publicFns = { + getQuadrantObjectsLimit: function getQuadrantObjectsLimit() { + return data.quadrantObjectsLimit_; + }, + setQuadrantObjectsLimit: function getQuadrantObjectsLimit(quadrantObjectsLimit2) { + if (quadrantObjectsLimit2 === void 0) { + return; + } + validator.isNumber(quadrantObjectsLimit2, "quadrantObjectsLimit_"); + data.quadrantObjectsLimit_ = quadrantObjectsLimit2; + }, + getQuadrantLevelLimit: function getQuadrantLevelLimit() { + return data.quadrantLevelLimit_; + }, + setQuadrantLevelLimit: function setQuadrantLevelLimit(quadrantLevelLimit2) { + if (quadrantLevelLimit2 === void 0) { + return; + } + validator.isNumber(quadrantLevelLimit2, "quadrantLevelLimit_"); + data.quadrantLevelLimit_ = quadrantLevelLimit2; + }, + setObjectKey: function setObjectKey(key, val) { + validator.fnFalse(fns.checkInit); + if (val === void 0) { + return; + } + validator.hasKey(k, key, key); + validator.isString(val, key); + if (key === "id") { + data.autoId_ = false; + } + k[key] = val; + }, + getSize: function getSize() { + return data.size_.clone(); + }, + setSize: function setSize(size2) { + if (size2 === void 0) { + return; + } + validator.isVec2(size2, "size_"); + data.size_ = size2.clone(); + }, + addObjects: function addObject(objs) { + objs.forEach(function(obj) { + publicFns.addObject(obj); + }); + }, + addObject: function addObject(obj) { + validator.isDefined(obj, "obj"); + validator.isObject(obj, "obj"); + fns.checkInit(true); + fns.setObjId(obj); + fns.checkObjectKeys(obj); + fns.populateSubtree(obj); + data.objects_[obj[k.id]] = obj; + }, + removeObjects: function removeObjects(objs) { + var i; + for (i = 0; i < objs.length; i++) { + publicFns.removeObject(objs[i]); + } + }, + removeObject: function removeObject(obj) { + fns.checkInit(true); + validator.hasKey(obj, k.id, k.id); + fns.removeObjectById(obj[k.id]); + }, + updateObjects: function updateObjects(objs) { + var i; + for (i = 0; i < objs.length; i++) { + publicFns.updateObject(objs[i]); + } + }, + updateObject: function updateObject(obj) { + fns.checkInit(true); + validator.hasKey(obj, k.id, k.id); + fns.updateObjectById(obj[k.id]); + }, + getPossibleCollisionsForObject: function getPossibleCollisionsForObject(obj) { + fns.checkInit(true); + validator.hasKey(obj, k.id, k.id); + return fns.getObjectsByObject(obj); + }, + getCollisionsForObject: function getCollisionsForObject(obj) { + var id2, objects; + fns.checkInit(true); + validator.hasKey(obj, k.id, k.id); + objects = fns.getObjectsByObject(obj); + for (id2 in objects) { + if (!fns.hasCollision(obj, objects[id2])) { + delete objects[id2]; + } + } + return objects; + }, + getCount: function getCount() { + return Object.keys(data.objects_).length; + }, + // Copies and returns data.objects_; + getObjects: function getObjects() { + var id2, result = {}; + for (id2 in data.objects_) { + result[id2] = data.objects_[id2]; + } + return result; + }, + getQuadrantCount: function getQuadrantCount(obj) { + if (obj) { + return Object.keys(data.quadrants_[obj[k.id]]).length; + } + return 1 + data.root_.getChildCount(true); + }, + getQuadrantObjectCount: function getQuadrantObjectCount() { + return data.root_.getObjectCount(true); + }, + debug: function debug(val) { + var id2; + if (val !== void 0) { + data.debug_ = val; + fns.checkInit(true); + for (id2 in debugFns) { + this[id2] = debugFns[id2]; + } + for (id2 in fns) { + this[id2] = fns[id2]; + } + this.data_ = data; + } + return data.debug_; + } + }; + for (id in publicFns) { + this[id] = publicFns[id]; + } + this.setSize(size); + this.setQuadrantObjectsLimit(quadrantObjectsLimit); + this.setQuadrantLevelLimit(quadrantLevelLimit); + }; + quadtree2 = Quadtree2; + return quadtree2; + } + var vec2 = { exports: {} }; + var hasRequiredVec2; + function requireVec2() { + if (hasRequiredVec2) return vec2.exports; + hasRequiredVec2 = 1; + (function(module) { + (function inject(clean, precision, undef) { + var isArray = function(a) { + return Object.prototype.toString.call(a) === "[object Array]"; + }; + function Vec2(x, y) { + if (!(this instanceof Vec2)) { + return new Vec2(x, y); + } + if (isArray(x)) { + y = x[1]; + x = x[0]; + } else if ("object" === typeof x && x) { + y = x.y; + x = x.x; + } + this.x = Vec2.clean(x || 0); + this.y = Vec2.clean(y || 0); + } + Vec2.prototype = { + change: function(fn) { + if (typeof fn === "function") { + if (this.observers) { + this.observers.push(fn); + } else { + this.observers = [fn]; + } + } else if (this.observers && this.observers.length) { + for (var i = this.observers.length - 1; i >= 0; i--) { + this.observers[i](this, fn); + } + } + return this; + }, + ignore: function(fn) { + if (this.observers) { + if (!fn) { + this.observers = []; + } else { + var o = this.observers, l = o.length; + while (l--) { + o[l] === fn && o.splice(l, 1); + } + } + } + return this; + }, + // set x and y + set: function(x, y, notify) { + if ("number" != typeof x) { + notify = y; + y = x.y; + x = x.x; + } + if (this.x === x && this.y === y) { + return this; + } + var orig = null; + if (notify !== false && this.observers && this.observers.length) { + orig = this.clone(); + } + this.x = Vec2.clean(x); + this.y = Vec2.clean(y); + if (notify !== false) { + return this.change(orig); + } + }, + // reset x and y to zero + zero: function() { + return this.set(0, 0); + }, + // return a new vector with the same component values + // as this one + clone: function() { + return new this.constructor(this.x, this.y); + }, + // negate the values of this vector + negate: function(returnNew) { + if (returnNew) { + return new this.constructor(-this.x, -this.y); + } else { + return this.set(-this.x, -this.y); + } + }, + // Add the incoming `vec2` vector to this vector + add: function(x, y, returnNew) { + if (typeof x != "number") { + returnNew = y; + if (isArray(x)) { + y = x[1]; + x = x[0]; + } else { + y = x.y; + x = x.x; + } + } + x += this.x; + y += this.y; + if (!returnNew) { + return this.set(x, y); + } else { + return new this.constructor(x, y); + } + }, + // Subtract the incoming `vec2` from this vector + subtract: function(x, y, returnNew) { + if (typeof x != "number") { + returnNew = y; + if (isArray(x)) { + y = x[1]; + x = x[0]; + } else { + y = x.y; + x = x.x; + } + } + x = this.x - x; + y = this.y - y; + if (!returnNew) { + return this.set(x, y); + } else { + return new this.constructor(x, y); + } + }, + // Multiply this vector by the incoming `vec2` + multiply: function(x, y, returnNew) { + if (typeof x != "number") { + returnNew = y; + if (isArray(x)) { + y = x[1]; + x = x[0]; + } else { + y = x.y; + x = x.x; + } + } else if (typeof y != "number") { + returnNew = y; + y = x; + } + x *= this.x; + y *= this.y; + if (!returnNew) { + return this.set(x, y); + } else { + return new this.constructor(x, y); + } + }, + // Rotate this vector. Accepts a `Rotation` or angle in radians. + // + // Passing a truthy `inverse` will cause the rotation to + // be reversed. + // + // If `returnNew` is truthy, a new + // `Vec2` will be created with the values resulting from + // the rotation. Otherwise the rotation will be applied + // to this vector directly, and this vector will be returned. + rotate: function(r, inverse, returnNew) { + var x = this.x, y = this.y, cos = Math.cos(r), sin = Math.sin(r), rx, ry; + inverse = inverse ? -1 : 1; + rx = cos * x - inverse * sin * y; + ry = inverse * sin * x + cos * y; + if (returnNew) { + return new this.constructor(rx, ry); + } else { + return this.set(rx, ry); + } + }, + // Calculate the length of this vector + length: function() { + var x = this.x, y = this.y; + return Math.sqrt(x * x + y * y); + }, + // Get the length squared. For performance, use this instead of `Vec2#length` (if possible). + lengthSquared: function() { + var x = this.x, y = this.y; + return x * x + y * y; + }, + // Return the distance betwen this `Vec2` and the incoming vec2 vector + // and return a scalar + distance: function(vec22) { + var x = this.x - vec22.x; + var y = this.y - vec22.y; + return Math.sqrt(x * x + y * y); + }, + // Convert this vector into a unit vector. + // Returns the length. + normalize: function(returnNew) { + var length = this.length(); + var invertedLength = length < Number.MIN_VALUE ? 0 : 1 / length; + if (!returnNew) { + return this.set(this.x * invertedLength, this.y * invertedLength); + } else { + return new this.constructor(this.x * invertedLength, this.y * invertedLength); + } + }, + // Determine if another `Vec2`'s components match this one's + // also accepts 2 scalars + equal: function(v, w) { + if (typeof v != "number") { + if (isArray(v)) { + w = v[1]; + v = v[0]; + } else { + w = v.y; + v = v.x; + } + } + return Vec2.clean(v) === this.x && Vec2.clean(w) === this.y; + }, + // Return a new `Vec2` that contains the absolute value of + // each of this vector's parts + abs: function(returnNew) { + var x = Math.abs(this.x), y = Math.abs(this.y); + if (returnNew) { + return new this.constructor(x, y); + } else { + return this.set(x, y); + } + }, + // Return a new `Vec2` consisting of the smallest values + // from this vector and the incoming + // + // When returnNew is truthy, a new `Vec2` will be returned + // otherwise the minimum values in either this or `v` will + // be applied to this vector. + min: function(v, returnNew) { + var tx = this.x, ty = this.y, vx = v.x, vy = v.y, x = tx < vx ? tx : vx, y = ty < vy ? ty : vy; + if (returnNew) { + return new this.constructor(x, y); + } else { + return this.set(x, y); + } + }, + // Return a new `Vec2` consisting of the largest values + // from this vector and the incoming + // + // When returnNew is truthy, a new `Vec2` will be returned + // otherwise the minimum values in either this or `v` will + // be applied to this vector. + max: function(v, returnNew) { + var tx = this.x, ty = this.y, vx = v.x, vy = v.y, x = tx > vx ? tx : vx, y = ty > vy ? ty : vy; + if (returnNew) { + return new this.constructor(x, y); + } else { + return this.set(x, y); + } + }, + // Clamp values into a range. + // If this vector's values are lower than the `low`'s + // values, then raise them. If they are higher than + // `high`'s then lower them. + // + // Passing returnNew as true will cause a new Vec2 to be + // returned. Otherwise, this vector's values will be clamped + clamp: function(low, high, returnNew) { + var ret = this.min(high, true).max(low); + if (returnNew) { + return ret; + } else { + return this.set(ret.x, ret.y); + } + }, + // Perform linear interpolation between two vectors + // amount is a decimal between 0 and 1 + lerp: function(vec, amount, returnNew) { + return this.add(vec.subtract(this, true).multiply(amount), returnNew); + }, + // Get the skew vector such that dot(skew_vec, other) == cross(vec, other) + skew: function(returnNew) { + if (!returnNew) { + return this.set(-this.y, this.x); + } else { + return new this.constructor(-this.y, this.x); + } + }, + // calculate the dot product between + // this vector and the incoming + dot: function(b) { + return Vec2.clean(this.x * b.x + b.y * this.y); + }, + // calculate the perpendicular dot product between + // this vector and the incoming + perpDot: function(b) { + return Vec2.clean(this.x * b.y - this.y * b.x); + }, + // Determine the angle between two vec2s + angleTo: function(vec) { + return Math.atan2(this.perpDot(vec), this.dot(vec)); + }, + // Divide this vector's components by a scalar + divide: function(x, y, returnNew) { + if (typeof x != "number") { + returnNew = y; + if (isArray(x)) { + y = x[1]; + x = x[0]; + } else { + y = x.y; + x = x.x; + } + } else if (typeof y != "number") { + returnNew = y; + y = x; + } + if (x === 0 || y === 0) { + throw new Error("division by zero"); + } + if (isNaN(x) || isNaN(y)) { + throw new Error("NaN detected"); + } + if (returnNew) { + return new this.constructor(this.x / x, this.y / y); + } + return this.set(this.x / x, this.y / y); + }, + isPointOnLine: function(start, end) { + return (start.y - this.y) * (start.x - end.x) === (start.y - end.y) * (start.x - this.x); + }, + toArray: function() { + return [this.x, this.y]; + }, + fromArray: function(array) { + return this.set(array[0], array[1]); + }, + toJSON: function() { + return { x: this.x, y: this.y }; + }, + toString: function() { + return "(" + this.x + ", " + this.y + ")"; + }, + constructor: Vec2 + }; + Vec2.fromArray = function(array, ctor) { + return new (ctor || Vec2)(array[0], array[1]); + }; + Vec2.precision = precision || 8; + var p = Math.pow(10, Vec2.precision); + Vec2.clean = clean || function(val) { + if (isNaN(val)) { + throw new Error("NaN detected"); + } + if (!isFinite(val)) { + throw new Error("Infinity detected"); + } + if (Math.round(val) === val) { + return val; + } + return Math.round(val * p) / p; + }; + Vec2.inject = inject; + if (!clean) { + Vec2.fast = inject(function(k) { + return k; + }); + { + module.exports = Vec2; + } + } + return Vec2; + })(); + })(vec2); + return vec2.exports; + } + var utils_1; + var hasRequiredUtils; + function requireUtils() { + if (hasRequiredUtils) return utils_1; + hasRequiredUtils = 1; + var utils = { + renderToCanvas: function(width, height, renderFunction) { + var buffer = document.createElement("canvas"); + buffer.width = width; + buffer.height = height; + renderFunction(buffer.getContext("2d")); + return buffer; + }, + mapPoint: function(lat, lng, scale) { + if (!scale) { + scale = 500; + } + var phi = (90 - lat) * Math.PI / 180; + var theta = (180 - lng) * Math.PI / 180; + var x = scale * Math.sin(phi) * Math.cos(theta); + var y = scale * Math.cos(phi); + var z = scale * Math.sin(phi) * Math.sin(theta); + return { x, y, z }; + }, + /* from http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb */ + hexToRgb: function(hex) { + var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; + hex = hex.replace(shorthandRegex, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : null; + }, + createLabel: function(text, size, color, font, underlineColor) { + var canvas = document.createElement("canvas"); + var context = canvas.getContext("2d"); + context.font = size + "pt " + font; + var textWidth = context.measureText(text).width; + canvas.width = textWidth; + canvas.height = size + 10; + if (canvas.width % 2) { + canvas.width++; + } + if (canvas.height % 2) { + canvas.height++; + } + if (underlineColor) { + canvas.height += 30; + } + context.font = size + "pt " + font; + context.textAlign = "center"; + context.textBaseline = "middle"; + context.strokeStyle = "black"; + context.miterLimit = 2; + context.lineJoin = "circle"; + context.lineWidth = 6; + context.strokeText(text, canvas.width / 2, canvas.height / 2); + context.lineWidth = 2; + context.fillStyle = color; + context.fillText(text, canvas.width / 2, canvas.height / 2); + if (underlineColor) { + context.strokeStyle = underlineColor; + context.lineWidth = 4; + context.beginPath(); + context.moveTo(0, canvas.height - 10); + context.lineTo(canvas.width - 1, canvas.height - 10); + context.stroke(); + } + return canvas; + } + }; + utils_1 = utils; + return utils_1; + } + var Pin_1; + var hasRequiredPin; + function requirePin() { + if (hasRequiredPin) return Pin_1; + hasRequiredPin = 1; + var THREE = /* @__PURE__ */ requireThree(), TWEEN = requireTween(), utils = requireUtils(); + var createTopCanvas = function(color) { + var markerWidth = 20, markerHeight = 20; + return utils.renderToCanvas(markerWidth, markerHeight, function(ctx) { + ctx.fillStyle = color; + ctx.beginPath(); + ctx.arc(markerWidth / 2, markerHeight / 2, markerWidth / 4, 0, 2 * Math.PI); + ctx.fill(); + }); + }; + var Pin = function(lat, lon, text, altitude, scene, smokeProvider, _opts) { + var opts = { + lineColor: "#8FD8D8", + lineWidth: 1, + topColor: "#8FD8D8", + smokeColor: "#FFF", + labelColor: "#FFF", + font: "Inconsolata", + showLabel: text.length > 0, + showTop: text.length > 0, + showSmoke: text.length > 0 + }; + var lineMaterial, labelCanvas, labelTexture, labelMaterial, topTexture, topMaterial, point2; + this.lat = lat; + this.lon = lon; + this.text = text; + this.altitude = altitude; + this.scene = scene; + this.smokeProvider = smokeProvider; + this.dateCreated = Date.now(); + if (_opts) { + for (var i in opts) { + if (_opts[i] != void 0) { + opts[i] = _opts[i]; + } + } + } + this.opts = opts; + this.topVisible = opts.showTop; + this.smokeVisible = opts.showSmoke; + this.labelVisible = opts.showLabel; + lineMaterial = new THREE.LineBasicMaterial({ + color: opts.lineColor, + linewidth: opts.lineWidth + }); + point2 = utils.mapPoint(lat, lon); + this.lineGeometry = new THREE.BufferGeometry(); + this._linePosAttr = new THREE.BufferAttribute( + new Float32Array([point2.x, point2.y, point2.z, point2.x, point2.y, point2.z]), + 3 + ); + this.lineGeometry.setAttribute("position", this._linePosAttr); + this.line = new THREE.Line(this.lineGeometry, lineMaterial); + labelCanvas = utils.createLabel(text, 18, opts.labelColor, opts.font); + labelTexture = new THREE.Texture(labelCanvas); + labelTexture.needsUpdate = true; + labelMaterial = new THREE.SpriteMaterial({ + map: labelTexture, + opacity: 0, + depthTest: true, + fog: true + }); + this.labelSprite = new THREE.Sprite(labelMaterial); + this.labelSprite.position.set(point2.x * altitude * 1.1, point2.y * altitude + (point2.y < 0 ? -15 : 30), point2.z * altitude * 1.1); + this.labelSprite.scale.set(labelCanvas.width, labelCanvas.height); + topTexture = new THREE.Texture(createTopCanvas(opts.topColor)); + topTexture.needsUpdate = true; + topMaterial = new THREE.SpriteMaterial({ map: topTexture, depthTest: true, fog: true, opacity: 0 }); + this.topSprite = new THREE.Sprite(topMaterial); + this.topSprite.scale.set(20, 20); + this.topSprite.position.set(point2.x * altitude, point2.y * altitude, point2.z * altitude); + if (this.smokeVisible) { + this.smokeId = smokeProvider.setFire(lat, lon, altitude); + } + var _this2 = this; + if (opts.showTop || opts.showLabel) { + new TWEEN.Tween({ opacity: 0 }, true).to({ opacity: 1 }, 500).onUpdate(function(o) { + if (_this2.topVisible) { + topMaterial.opacity = o.opacity; + } else { + topMaterial.opacity = 0; + } + if (_this2.labelVisible) { + labelMaterial.opacity = o.opacity; + } else { + labelMaterial.opacity = 0; + } + }).delay(1e3).start(); + } + new TWEEN.Tween(point2, true).to({ x: point2.x * altitude, y: point2.y * altitude, z: point2.z * altitude }, 1500).easing(TWEEN.Easing.Elastic.Out).onUpdate(function(o) { + _this2._linePosAttr.setXYZ(1, o.x, o.y, o.z); + _this2._linePosAttr.needsUpdate = true; + }).start(); + this.scene.add(this.labelSprite); + this.scene.add(this.line); + this.scene.add(this.topSprite); + }; + Pin.prototype.toString = function() { + return "" + this.lat + "_" + this.lon; + }; + Pin.prototype.changeAltitude = function(altitude) { + var point2 = utils.mapPoint(this.lat, this.lon); + var _this2 = this; + new TWEEN.Tween({ altitude: this.altitude }, true).to({ altitude }, 1500).easing(TWEEN.Easing.Elastic.Out).onUpdate(function(o) { + if (_this2.smokeVisible) { + _this2.smokeProvider.changeAltitude(o.altitude, _this2.smokeId); + } + if (_this2.topVisible) { + _this2.topSprite.position.set(point2.x * o.altitude, point2.y * o.altitude, point2.z * o.altitude); + } + if (_this2.labelVisible) { + _this2.labelSprite.position.set(point2.x * o.altitude * 1.1, point2.y * o.altitude + (point2.y < 0 ? -15 : 30), point2.z * o.altitude * 1.1); + } + _this2._linePosAttr.setXYZ(1, point2.x * o.altitude, point2.y * o.altitude, point2.z * o.altitude); + _this2._linePosAttr.needsUpdate = true; + }).onComplete(function() { + _this2.altitude = altitude; + }).start(); + }; + Pin.prototype.hideTop = function() { + if (this.topVisible) { + this.topSprite.material.opacity = 0; + this.topVisible = false; + } + }; + Pin.prototype.showTop = function() { + if (!this.topVisible) { + this.topSprite.material.opacity = 1; + this.topVisible = true; + } + }; + Pin.prototype.hideLabel = function() { + if (this.labelVisible) { + this.labelSprite.material.opacity = 0; + this.labelVisible = false; + } + }; + Pin.prototype.showLabel = function() { + if (!this.labelVisible) { + this.labelSprite.material.opacity = 1; + this.labelVisible = true; + } + }; + Pin.prototype.hideSmoke = function() { + if (this.smokeVisible) { + this.smokeProvider.extinguish(this.smokeId); + this.smokeVisible = false; + } + }; + Pin.prototype.showSmoke = function() { + if (!this.smokeVisible) { + this.smokeId = this.smokeProvider.setFire(this.lat, this.lon, this.altitude); + this.smokeVisible = true; + } + }; + Pin.prototype.age = function() { + return Date.now() - this.dateCreated; + }; + Pin.prototype.remove = function() { + this.scene.remove(this.labelSprite); + this.scene.remove(this.line); + this.scene.remove(this.topSprite); + if (this.smokeVisible) { + this.smokeProvider.extinguish(this.smokeId); + } + }; + Pin_1 = Pin; + return Pin_1; + } + var Marker_1; + var hasRequiredMarker; + function requireMarker() { + if (hasRequiredMarker) return Marker_1; + hasRequiredMarker = 1; + var THREE = /* @__PURE__ */ requireThree(), TWEEN = requireTween(), utils = requireUtils(); + var createMarkerTexture = function(markerColor) { + var markerWidth = 30, markerHeight = 30, canvas, texture; + canvas = utils.renderToCanvas(markerWidth, markerHeight, function(ctx) { + ctx.fillStyle = markerColor; + ctx.strokeStyle = markerColor; + ctx.lineWidth = 3; + ctx.beginPath(); + ctx.arc(markerWidth / 2, markerHeight / 2, markerWidth / 3, 0, 2 * Math.PI); + ctx.stroke(); + ctx.beginPath(); + ctx.arc(markerWidth / 2, markerHeight / 2, markerWidth / 5, 0, 2 * Math.PI); + ctx.fill(); + }); + texture = new THREE.Texture(canvas); + texture.needsUpdate = true; + return texture; + }; + var Marker = function(lat, lon, text, altitude, previous, scene, _opts) { + var opts = { + lineColor: "#FFCC00", + lineWidth: 1, + markerColor: "#FFCC00", + labelColor: "#FFF", + font: "Inconsolata", + fontSize: 20, + drawTime: 2e3, + lineSegments: 150 + }; + var point2, markerMaterial, labelCanvas, labelTexture, labelMaterial; + this.lat = parseFloat(lat); + this.lon = parseFloat(lon); + this.text = text; + this.altitude = parseFloat(altitude); + this.scene = scene; + this.previous = previous; + this.next = []; + if (this.previous) { + this.previous.next.push(this); + } + if (_opts) { + for (var i in opts) { + if (_opts[i] != void 0) { + opts[i] = _opts[i]; + } + } + } + this.opts = opts; + point2 = utils.mapPoint(lat, lon); + if (previous) { + utils.mapPoint(previous.lat, previous.lon); + } + if (!scene._encom_markerTexture) { + scene._encom_markerTexture = createMarkerTexture(this.opts.markerColor); + } + markerMaterial = new THREE.SpriteMaterial({ map: scene._encom_markerTexture, opacity: 0.7, depthTest: true, fog: true }); + this.marker = new THREE.Sprite(markerMaterial); + this.marker.scale.set(0, 0); + this.marker.position.set(point2.x * altitude, point2.y * altitude, point2.z * altitude); + labelCanvas = utils.createLabel(text.toUpperCase(), this.opts.fontSize, this.opts.labelColor, this.opts.font, this.opts.markerColor); + labelTexture = new THREE.Texture(labelCanvas); + labelTexture.needsUpdate = true; + labelMaterial = new THREE.SpriteMaterial({ + map: labelTexture, + opacity: 0, + depthTest: true, + fog: true + }); + this.labelSprite = new THREE.Sprite(labelMaterial); + this.labelSprite.position.set(point2.x * altitude * 1.1, point2.y * altitude * 1.05 + (point2.y < 0 ? -15 : 30), point2.z * altitude * 1.1); + this.labelSprite.scale.set(labelCanvas.width, labelCanvas.height); + new TWEEN.Tween({ opacity: 0 }, true).to({ opacity: 1 }, 500).onUpdate(function(o) { + labelMaterial.opacity = o.opacity; + }).start(); + var _this2 = this; + new TWEEN.Tween({ x: 0, y: 0 }, true).to({ x: 50, y: 50 }, 2e3).easing(TWEEN.Easing.Elastic.Out).onUpdate(function(o) { + _this2.marker.scale.set(o.x, o.y); + }).delay(this.previous ? _this2.opts.drawTime : 0).start(); + if (this.previous) { + var materialSpline, materialSplineDotted, latdist, londist, startPoint, pointList = [], pointList2 = [], currentPoint, currentPoint2, update; + materialSpline = new THREE.LineBasicMaterial({ + color: this.opts.lineColor, + transparent: true, + linewidth: 3, + opacity: 0.5 + }); + materialSplineDotted = new THREE.LineBasicMaterial({ + color: this.opts.lineColor, + linewidth: 1, + transparent: true, + opacity: 0.5 + }); + latdist = (lat - previous.lat) / _this2.opts.lineSegments; + londist = (lon - previous.lon) / _this2.opts.lineSegments; + startPoint = utils.mapPoint(previous.lat, previous.lon); + pointList = []; + pointList2 = []; + var vertCount = _this2.opts.lineSegments + 1; + var splineArr = new Float32Array(vertCount * 3); + var splineDottedArr = new Float32Array(vertCount * 3); + for (var j = 0; j < vertCount; j++) { + var nextlat = ((90 + previous.lat + j * latdist) % 180 - 90) * (0.5 + Math.cos(j * (5 * Math.PI / 2) / _this2.opts.lineSegments) / 2) + j * lat / _this2.opts.lineSegments / 2; + var nextlon = (180 + previous.lon + j * londist) % 360 - 180; + pointList.push({ lat: nextlat, lon: nextlon, index: j }); + if (j == 0 || j == _this2.opts.lineSegments) { + pointList2.push({ lat: nextlat, lon: nextlon, index: j }); + } else { + pointList2.push({ lat: nextlat + 1, lon: nextlon, index: j }); + } + splineArr[j * 3] = startPoint.x * 1.2; + splineArr[j * 3 + 1] = startPoint.y * 1.2; + splineArr[j * 3 + 2] = startPoint.z * 1.2; + splineDottedArr[j * 3] = startPoint.x * 1.2; + splineDottedArr[j * 3 + 1] = startPoint.y * 1.2; + splineDottedArr[j * 3 + 2] = startPoint.z * 1.2; + } + _this2.geometrySpline = new THREE.BufferGeometry(); + _this2._splinePosAttr = new THREE.BufferAttribute(splineArr, 3); + _this2.geometrySpline.setAttribute("position", _this2._splinePosAttr); + _this2.geometrySplineDotted = new THREE.BufferGeometry(); + _this2._splineDottedPosAttr = new THREE.BufferAttribute(splineDottedArr, 3); + _this2.geometrySplineDotted.setAttribute("position", _this2._splineDottedPosAttr); + previous.lat; + previous.lon; + update = function() { + var nextSpot = pointList.shift(); + var nextSpot2 = pointList2.shift(); + for (var x = 0; x < vertCount; x++) { + currentPoint = utils.mapPoint(nextSpot.lat, nextSpot.lon); + currentPoint2 = utils.mapPoint(nextSpot2.lat, nextSpot2.lon); + if (x >= nextSpot.index) { + _this2._splinePosAttr.setXYZ(x, currentPoint.x * 1.2, currentPoint.y * 1.2, currentPoint.z * 1.2); + _this2._splineDottedPosAttr.setXYZ(x, currentPoint2.x * 1.19, currentPoint2.y * 1.19, currentPoint2.z * 1.19); + } + } + _this2._splinePosAttr.needsUpdate = true; + _this2._splineDottedPosAttr.needsUpdate = true; + if (pointList.length > 0) { + setTimeout(update, _this2.opts.drawTime / _this2.opts.lineSegments); + } + }; + update(); + _this2.lineSpline = new THREE.Line(_this2.geometrySpline, materialSpline); + _this2.lineDotted = new THREE.Line(_this2.geometrySplineDotted, materialSplineDotted); + this.scene.add(_this2.lineSpline); + this.scene.add(_this2.lineDotted); + } + this.scene.add(this.marker); + this.scene.add(this.labelSprite); + }; + Marker.prototype.remove = function() { + var x = 0; + var _this2 = this; + var update = function(ref) { + for (var i = 0; i < x; i++) { + ref._splinePosAttr.setXYZ( + i, + ref._splinePosAttr.getX(i + 1), + ref._splinePosAttr.getY(i + 1), + ref._splinePosAttr.getZ(i + 1) + ); + ref._splineDottedPosAttr.setXYZ( + i, + ref._splineDottedPosAttr.getX(i + 1), + ref._splineDottedPosAttr.getY(i + 1), + ref._splineDottedPosAttr.getZ(i + 1) + ); + ref._splinePosAttr.needsUpdate = true; + ref._splineDottedPosAttr.needsUpdate = true; + } + x++; + if (x < ref._splinePosAttr.count) { + setTimeout(function() { + update(ref); + }, _this2.opts.drawTime / _this2.opts.lineSegments); + } else { + _this2.scene.remove(ref.lineSpline); + _this2.scene.remove(ref.lineDotted); + } + }; + for (var j = 0; j < _this2.next.length; j++) { + (function(k) { + update(_this2.next[k]); + })(j); + } + _this2.scene.remove(_this2.marker); + _this2.scene.remove(_this2.labelSprite); + }; + Marker_1 = Marker; + return Marker_1; + } + var TextureAnimator_1; + var hasRequiredTextureAnimator; + function requireTextureAnimator() { + if (hasRequiredTextureAnimator) return TextureAnimator_1; + hasRequiredTextureAnimator = 1; + var THREE = /* @__PURE__ */ requireThree(); + var TextureAnimator = function(texture, tilesVert, tilesHoriz, numTiles, tileDispDuration, repeatAtTile) { + if (repeatAtTile == void 0) { + this.repeatAtTile = -1; + } + this.shutDownFlag = this.repeatAtTile < 0; + this.done = false; + this.tilesHorizontal = tilesHoriz; + this.tilesVertical = tilesVert; + this.numberOfTiles = numTiles; + texture.wrapS = texture.wrapT = THREE.RepeatWrapping; + texture.repeat.set(1 / this.tilesHorizontal, 1 / this.tilesVertical); + this.tileDisplayDuration = tileDispDuration; + this.currentDisplayTime = 0; + this.currentTile = 0; + texture.offset.y = 1; + this.update = function(milliSec) { + this.currentDisplayTime += milliSec; + while (!this.done && this.currentDisplayTime > this.tileDisplayDuration) { + if (this.shutDownFlag && this.currentTile >= numTiles) { + this.done = true; + this.shutDownCb(); + } else { + this.currentDisplayTime -= this.tileDisplayDuration; + this.currentTile++; + if (this.currentTile == numTiles && !this.shutDownFlag) + this.currentTile = repeatAtTile; + var currentColumn = this.currentTile % this.tilesHorizontal; + texture.offset.x = currentColumn / this.tilesHorizontal; + var currentRow = Math.floor(this.currentTile / this.tilesHorizontal); + texture.offset.y = 1 - currentRow / this.tilesVertical - 1 / this.tilesVertical; + } + } + }; + this.shutDown = function(cb) { + _this.shutDownFlag = true; + _this.shutDownCb = cb; + }; + }; + TextureAnimator_1 = TextureAnimator; + return TextureAnimator_1; + } + var Satellite_1; + var hasRequiredSatellite; + function requireSatellite() { + if (hasRequiredSatellite) return Satellite_1; + hasRequiredSatellite = 1; + var TextureAnimator = requireTextureAnimator(), THREE = /* @__PURE__ */ requireThree(), utils = requireUtils(); + var createCanvas = function(numFrames2, pixels2, rows2, waveStart2, numWaves, waveColor, coreColor, shieldColor) { + var cols = numFrames2 / rows2; + var waveInterval = Math.floor((numFrames2 - waveStart2) / numWaves); + var waveDist = pixels2 - 25; + var distPerFrame = waveDist / (numFrames2 - waveStart2); + var offsetx = 0; + var offsety = 0; + var curRow = 0; + var waveColorRGB = utils.hexToRgb(waveColor); + return utils.renderToCanvas(numFrames2 * pixels2 / rows2, pixels2 * rows2, function(ctx) { + for (var i = 0; i < numFrames2; i++) { + if (i - curRow * cols >= cols) { + offsetx = 0; + offsety += pixels2; + curRow++; + } + var centerx = offsetx + 25; + var centery = offsety + Math.floor(pixels2 / 2); + ctx.lineWidth = 2; + ctx.strokeStyle = shieldColor; + var buffer = Math.PI / 16; + var start = -Math.PI + Math.PI / 4; + var radius = 8; + var repeatAt2 = Math.floor(numFrames2 - 2 * (numFrames2 - waveStart2) / numWaves) + 1; + if (i < waveStart2) { + radius = radius * i / waveStart2; + } + var swirlDone = Math.floor((repeatAt2 - waveStart2) / 2) + waveStart2; + for (var n = 0; n < 4; n++) { + ctx.beginPath(); + if (i < waveStart2 || i >= numFrames2) { + ctx.arc(centerx, centery, radius, n * Math.PI / 2 + start + buffer, n * Math.PI / 2 + start + Math.PI / 2 - 2 * buffer); + } else if (i > waveStart2 && i < swirlDone) { + var totalTimeToComplete = swirlDone - waveStart2; + var distToGo = 3 * Math.PI / 2; + var currentStep = i - waveStart2; + var movementPerStep = distToGo / totalTimeToComplete; + var startAngle = -Math.PI + Math.PI / 4 + buffer + movementPerStep * currentStep; + ctx.arc(centerx, centery, radius, Math.max(n * Math.PI / 2 + start, startAngle), Math.max(n * Math.PI / 2 + start + Math.PI / 2 - 2 * buffer, startAngle + Math.PI / 2 - 2 * buffer)); + } else if (i >= swirlDone && i < repeatAt2) { + var totalTimeToComplete = repeatAt2 - swirlDone; + var distToGo = n * 2 * Math.PI / 4; + var currentStep = i - swirlDone; + var movementPerStep = distToGo / totalTimeToComplete; + var startAngle = Math.PI / 2 + Math.PI / 4 + buffer + movementPerStep * currentStep; + ctx.arc(centerx, centery, radius, startAngle, startAngle + Math.PI / 2 - 2 * buffer); + } else if (i >= repeatAt2 && i < (numFrames2 - repeatAt2) / 2 + repeatAt2) { + var totalTimeToComplete = (numFrames2 - repeatAt2) / 2; + var distToGo = Math.PI / 2; + var currentStep = i - repeatAt2; + var movementPerStep = distToGo / totalTimeToComplete; + var startAngle = n * (Math.PI / 2) + Math.PI / 4 + buffer + movementPerStep * currentStep; + ctx.arc(centerx, centery, radius, startAngle, startAngle + Math.PI / 2 - 2 * buffer); + } else { + ctx.arc(centerx, centery, radius, n * Math.PI / 2 + start + buffer, n * Math.PI / 2 + start + Math.PI / 2 - 2 * buffer); + } + ctx.stroke(); + } + var frameOn; + for (var wi = 0; wi < numWaves; wi++) { + frameOn = i - waveInterval * wi - waveStart2; + if (frameOn > 0 && frameOn * distPerFrame < pixels2 - 25) { + ctx.strokeStyle = "rgba(" + waveColorRGB.r + "," + waveColorRGB.g + "," + waveColorRGB.b + "," + (0.9 - frameOn * distPerFrame / (pixels2 - 25)) + ")"; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.arc(centerx, centery, frameOn * distPerFrame, -Math.PI / 12, Math.PI / 12); + ctx.stroke(); + } + } + ctx.fillStyle = "#000"; + ctx.beginPath(); + ctx.arc(centerx, centery, 3, 0, 2 * Math.PI); + ctx.fill(); + ctx.strokeStyle = coreColor; + ctx.lineWidth = 2; + ctx.beginPath(); + if (i < waveStart2) { + ctx.arc(centerx, centery, 3 * i / waveStart2, 0, 2 * Math.PI); + } else { + ctx.arc(centerx, centery, 3, 0, 2 * Math.PI); + } + ctx.stroke(); + offsetx += pixels2; + } + }); + }; + var Satellite = function(lat, lon, altitude, scene, _opts, canvas, texture) { + var geometry, point2 = utils.mapPoint(lat, lon), opts, numFrames2, pixels2, rows2, waveStart2, repeatAt2; + point2.x *= altitude; + point2.y *= altitude; + point2.z *= altitude; + var opts = { + numWaves: 8, + waveColor: "#FFF", + coreColor: "#FF0000", + shieldColor: "#FFF", + size: 1 + }; + this.lat = lat; + this.lon = lon; + this.altitude = altitude; + this.scene = scene; + this.onRemoveList = []; + numFrames2 = 50; + pixels2 = 100; + rows2 = 10; + waveStart2 = Math.floor(numFrames2 / 8); + if (_opts) { + for (var i in opts) { + if (_opts[i] != void 0) { + opts[i] = _opts[i]; + } + } + } + this.opts = opts; + if (!canvas) { + this.canvas = createCanvas(numFrames2, pixels2, rows2, waveStart2, opts.numWaves, opts.waveColor, opts.coreColor, opts.shieldColor); + this.texture = new THREE.Texture(this.canvas); + this.texture.needsUpdate = true; + repeatAt2 = Math.floor(numFrames2 - 2 * (numFrames2 - waveStart2) / opts.numWaves) + 1; + this.animator = new TextureAnimator(this.texture, rows2, numFrames2 / rows2, numFrames2, 80, repeatAt2); + } else { + this.canvas = canvas; + if (!texture) { + this.texture = new THREE.Texture(this.canvas); + this.texture.needsUpdate = true; + repeatAt2 = Math.floor(numFrames2 - 2 * (numFrames2 - waveStart2) / opts.numWaves) + 1; + this.animator = new TextureAnimator(this.texture, rows2, numFrames2 / rows2, numFrames2, 80, repeatAt2); + } else { + this.texture = texture; + } + } + geometry = new THREE.PlaneGeometry(opts.size * 150, opts.size * 150, 1, 1); + this.material = new THREE.MeshBasicMaterial({ + map: this.texture, + depthTest: false, + transparent: true + }); + this.mesh = new THREE.Mesh(geometry, this.material); + this.mesh.tiltMultiplier = Math.PI / 2 * (1 - Math.abs(lat / 90)); + this.mesh.tiltDirection = lat > 0 ? -1 : 1; + this.mesh.lon = lon; + this.mesh.position.set(point2.x, point2.y, point2.z); + this.mesh.rotation.z = -1 * (lat / 90) * Math.PI / 2; + this.mesh.rotation.y = lon / 180 * Math.PI; + scene.add(this.mesh); + }; + Satellite.prototype.changeAltitude = function(_altitude) { + var newPoint = utils.mapPoint(this.lat, this.lon); + newPoint.x *= _altitude; + newPoint.y *= _altitude; + newPoint.z *= _altitude; + this.altitude = _altitude; + this.mesh.position.set(newPoint.x, newPoint.y, newPoint.z); + }; + Satellite.prototype.changeCanvas = function(numWaves, waveColor, coreColor, shieldColor) { + numFrames = 50; + pixels = 100; + rows = 10; + waveStart = Math.floor(numFrames / 8); + if (!numWaves) { + numWaves = this.opts.numWaves; + } else { + this.opts.numWaves = numWaves; + } + if (!waveColor) { + waveColor = this.opts.waveColor; + } else { + this.opts.waveColor = waveColor; + } + if (!coreColor) { + coreColor = this.opts.coreColor; + } else { + this.opts.coreColor = coreColor; + } + if (!shieldColor) { + shieldColor = this.opts.shieldColor; + } else { + this.opts.shieldColor = shieldColor; + } + this.canvas = createCanvas(numFrames, pixels, rows, waveStart, numWaves, waveColor, coreColor, shieldColor); + this.texture = new THREE.Texture(this.canvas); + this.texture.needsUpdate = true; + repeatAt = Math.floor(numFrames - 2 * (numFrames - waveStart) / numWaves) + 1; + this.animator = new TextureAnimator(this.texture, rows, numFrames / rows, numFrames, 80, repeatAt); + this.material.map = this.texture; + }; + Satellite.prototype.tick = function(cameraPosition, cameraAngle, renderTime) { + this.mesh.lookAt(cameraPosition); + this.mesh.rotateZ(this.mesh.tiltDirection * Math.PI / 2); + this.mesh.rotateZ(Math.sin(cameraAngle + this.mesh.lon / 180 * Math.PI) * this.mesh.tiltMultiplier * this.mesh.tiltDirection * -1); + if (this.animator) { + this.animator.update(renderTime); + } + }; + Satellite.prototype.remove = function() { + this.scene.remove(this.mesh); + for (var i = 0; i < this.onRemoveList.length; i++) { + this.onRemoveList[i](); + } + }; + Satellite.prototype.onRemove = function(fn) { + this.onRemoveList.push(fn); + }; + Satellite.prototype.toString = function() { + return "" + this.lat + "_" + this.lon + "_" + this.altitude; + }; + Satellite_1 = Satellite; + return Satellite_1; + } + var SmokeProvider_1; + var hasRequiredSmokeProvider; + function requireSmokeProvider() { + if (hasRequiredSmokeProvider) return SmokeProvider_1; + hasRequiredSmokeProvider = 1; + var THREE = /* @__PURE__ */ requireThree(); + requireUtils(); + var vertexShader = [ + "#define PI 3.141592653589793238462643", + "#define DISTANCE 500.0", + "attribute float myStartTime;", + "attribute float myStartLat;", + "attribute float myStartLon;", + "attribute float altitude;", + "attribute float active;", + "uniform float currentTime;", + "uniform vec3 color;", + "varying vec4 vColor;", + "", + "vec3 getPos(float lat, float lon)", + "{", + " if (lon < -180.0){", + " lon = lon + 360.0;", + " }", + " float phi = (90.0 - lat) * PI / 180.0;", + " float theta = (180.0 - lon) * PI / 180.0;", + " float x = DISTANCE * sin(phi) * cos(theta) * altitude;", + " float y = DISTANCE * cos(phi) * altitude;", + " float z = DISTANCE * sin(phi) * sin(theta) * altitude;", + " return vec3(x, y, z);", + "}", + "", + "void main()", + "{", + " float dt = currentTime - myStartTime;", + " if (dt < 0.0){", + " dt = 0.0;", + " }", + " if (dt > 0.0 && active > 0.0) {", + " dt = mod(dt,1500.0);", + " }", + " float opacity = 1.0 - dt/ 1500.0;", + " if (dt == 0.0 || active == 0.0){", + " opacity = 0.0;", + " }", + " vec3 newPos = getPos(myStartLat, myStartLon - ( dt / 50.0));", + " vColor = vec4( color, opacity );", + " vec4 mvPosition = modelViewMatrix * vec4( newPos, 1.0 );", + " gl_PointSize = 2.5 - (dt / 1500.0);", + " gl_Position = projectionMatrix * mvPosition;", + "}" + ].join("\n"); + var fragmentShader = [ + "varying vec4 vColor;", + "void main()", + "{", + " gl_FragColor = vColor;", + " float depth = gl_FragCoord.z / gl_FragCoord.w;", + " float fogFactor = smoothstep(1500.0, 1800.0, depth );", + " vec3 fogColor = vec3(0.0);", + " gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w), fogFactor );", + "}" + ].join("\n"); + var SmokeProvider = function(scene, _opts) { + var opts = { + smokeCount: 5e3, + smokePerPin: 30, + smokePerSecond: 20 + }; + if (_opts) { + for (var i in opts) { + if (_opts[i] !== void 0) { + opts[i] = _opts[i]; + } + } + } + this.opts = opts; + var count = opts.smokeCount; + this._myStartTime = new Float32Array(count); + this._myStartLat = new Float32Array(count); + this._myStartLon = new Float32Array(count); + this._altitude = new Float32Array(count); + this._active = new Float32Array(count); + var geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(count * 3), 3)); + geometry.setAttribute("myStartTime", new THREE.BufferAttribute(this._myStartTime, 1)); + geometry.setAttribute("myStartLat", new THREE.BufferAttribute(this._myStartLat, 1)); + geometry.setAttribute("myStartLon", new THREE.BufferAttribute(this._myStartLon, 1)); + geometry.setAttribute("altitude", new THREE.BufferAttribute(this._altitude, 1)); + geometry.setAttribute("active", new THREE.BufferAttribute(this._active, 1)); + this._geometry = geometry; + this.uniforms = { + currentTime: { type: "f", value: 0 }, + color: { type: "c", value: new THREE.Color("#aaa") } + }; + var material = new THREE.ShaderMaterial({ + uniforms: this.uniforms, + vertexShader, + fragmentShader, + transparent: true + }); + this.smokeIndex = 0; + this.totalRunTime = 0; + scene.add(new THREE.Points(geometry, material)); + }; + SmokeProvider.prototype.setFire = function(lat, lon, altitude) { + var startSmokeIndex = this.smokeIndex; + for (var i = 0; i < this.opts.smokePerPin; i++) { + var si = this.smokeIndex; + this._myStartTime[si] = this.totalRunTime + (1e3 * i / this.opts.smokePerSecond + 1500); + this._myStartLat[si] = lat; + this._myStartLon[si] = lon; + this._altitude[si] = altitude; + this._active[si] = 1; + this.smokeIndex++; + this.smokeIndex = this.smokeIndex % this.opts.smokeCount; + } + this._geometry.getAttribute("myStartTime").needsUpdate = true; + this._geometry.getAttribute("myStartLat").needsUpdate = true; + this._geometry.getAttribute("myStartLon").needsUpdate = true; + this._geometry.getAttribute("altitude").needsUpdate = true; + this._geometry.getAttribute("active").needsUpdate = true; + return startSmokeIndex; + }; + SmokeProvider.prototype.extinguish = function(index) { + for (var i = 0; i < this.opts.smokePerPin; i++) { + this._active[(i + index) % this.opts.smokeCount] = 0; + } + this._geometry.getAttribute("active").needsUpdate = true; + }; + SmokeProvider.prototype.changeAltitude = function(altitude, index) { + for (var i = 0; i < this.opts.smokePerPin; i++) { + this._altitude[(i + index) % this.opts.smokeCount] = altitude; + } + this._geometry.getAttribute("altitude").needsUpdate = true; + }; + SmokeProvider.prototype.tick = function(totalRunTime) { + this.totalRunTime = totalRunTime; + this.uniforms.currentTime.value = this.totalRunTime; + }; + SmokeProvider_1 = SmokeProvider; + return SmokeProvider_1; + } + var Globe_1; + var hasRequiredGlobe; + function requireGlobe() { + if (hasRequiredGlobe) return Globe_1; + hasRequiredGlobe = 1; + var TWEEN = requireTween(), THREE = /* @__PURE__ */ requireThree(); + requireHexasphere(); + var Quadtree2 = requireQuadtree2(), Vec2 = requireVec2(), Pin = requirePin(), Marker = requireMarker(), Satellite = requireSatellite(), SmokeProvider = requireSmokeProvider(), utils = requireUtils(); + var latLon2d = function(lat, lon) { + var rad = 2 + Math.abs(lat) / 90 * 15; + return { x: lat + 90, y: lon + 180, rad }; + }; + var addInitialData = function() { + if (this.data.length == 0) { + return; + } + var next; + while (this.data.length > 0 && this.firstRunTime + (next = this.data.pop()).when < Date.now()) { + this.addPin(next.lat, next.lng, next.label); + } + if (next && this.firstRunTime + next.when >= Date.now()) { + this.data.push(next); + } + }; + var createParticles = function() { + if (this.hexGrid) { + this.scene.remove(this.hexGrid); + } + var pointVertexShader = [ + "#define PI 3.141592653589793238462643", + "#define DISTANCE 500.0", + "#define INTRODURATION " + (parseFloat(this.introLinesDuration) + 1e-5), + "#define INTROALTITUDE " + (parseFloat(this.introLinesAltitude) + 1e-5), + "attribute float lng;", + "uniform float currentTime;", + "varying vec4 vColor;", + "", + "void main()", + "{", + " vec3 newPos = position;", + " float opacityVal = 0.0;", + " float introStart = INTRODURATION * ((180.0 + lng)/360.0);", + " if(currentTime > introStart){", + " opacityVal = 1.0;", + " }", + " if(currentTime > introStart && currentTime < introStart + INTRODURATION / 8.0){", + " newPos = position * INTROALTITUDE;", + " opacityVal = .3;", + " }", + " if(currentTime > introStart + INTRODURATION / 8.0 && currentTime < introStart + INTRODURATION / 8.0 + 200.0){", + " newPos = position * (1.0 + ((INTROALTITUDE-1.0) * (1.0-(currentTime - introStart-(INTRODURATION/8.0))/200.0)));", + " }", + " vColor = vec4( color, opacityVal );", + // set color associated to vertex; use later in fragment shader. + " gl_Position = projectionMatrix * modelViewMatrix * vec4(newPos, 1.0);", + "}" + ].join("\n"); + var pointFragmentShader = [ + "varying vec4 vColor;", + "void main()", + "{", + " gl_FragColor = vColor;", + " float depth = gl_FragCoord.z / gl_FragCoord.w;", + " float fogFactor = smoothstep(" + parseInt(this.cameraDistance) + ".0," + parseInt(this.cameraDistance + 300) + ".0, depth );", + " vec3 fogColor = vec3(0.0);", + " gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w ), fogFactor );", + "}" + ].join("\n"); + this.pointUniforms = { + currentTime: { type: "f", value: 0 } + }; + var pointMaterial = new THREE.ShaderMaterial({ + uniforms: this.pointUniforms, + vertexShader: pointVertexShader, + fragmentShader: pointFragmentShader, + transparent: true, + vertexColors: true, + side: THREE.DoubleSide + }); + var triangles = this.tiles.length * 4; + var geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(triangles * 9), 3)); + geometry.setAttribute("color", new THREE.BufferAttribute(new Float32Array(triangles * 9), 3)); + geometry.setAttribute("lng", new THREE.BufferAttribute(new Float32Array(triangles * 3), 1)); + var lng_values = geometry.attributes.lng.array; + var baseHsl = {}; + new THREE.Color(this.baseColor).getHSL(baseHsl); + var myColors = []; + for (var ci = 0; ci < 10; ci++) { + var c = new THREE.Color(); + c.setHSL( + (baseHsl.h + (ci - 5) * 0.02 + 1) % 1, + baseHsl.s, + Math.min(1, baseHsl.l + Math.random() / 3) + ); + myColors.push(c); + } + var positions = geometry.attributes.position.array; + var colors = geometry.attributes.color.array; + var addTriangle = function(k2, ax, ay, az, bx, by, bz, cx, cy, cz, lat, lng, color2) { + var p = k2 * 3; + var i2 = p * 3; + lng_values[p] = lng; + lng_values[p + 1] = lng; + lng_values[p + 2] = lng; + positions[i2] = ax; + positions[i2 + 1] = ay; + positions[i2 + 2] = az; + positions[i2 + 3] = bx; + positions[i2 + 4] = by; + positions[i2 + 5] = bz; + positions[i2 + 6] = cx; + positions[i2 + 7] = cy; + positions[i2 + 8] = cz; + colors[i2] = color2.r; + colors[i2 + 1] = color2.g; + colors[i2 + 2] = color2.b; + colors[i2 + 3] = color2.r; + colors[i2 + 4] = color2.g; + colors[i2 + 5] = color2.b; + colors[i2 + 6] = color2.r; + colors[i2 + 7] = color2.g; + colors[i2 + 8] = color2.b; + }; + for (var i = 0; i < this.tiles.length; i++) { + var t = this.tiles[i]; + var k = i * 4; + var colorIndex = Math.floor(Math.random() * myColors.length); + var color = myColors[colorIndex]; + addTriangle(k, t.b[0].x, t.b[0].y, t.b[0].z, t.b[1].x, t.b[1].y, t.b[1].z, t.b[2].x, t.b[2].y, t.b[2].z, t.lat, t.lon, color); + addTriangle(k + 1, t.b[0].x, t.b[0].y, t.b[0].z, t.b[2].x, t.b[2].y, t.b[2].z, t.b[3].x, t.b[3].y, t.b[3].z, t.lat, t.lon, color); + addTriangle(k + 2, t.b[0].x, t.b[0].y, t.b[0].z, t.b[3].x, t.b[3].y, t.b[3].z, t.b[4].x, t.b[4].y, t.b[4].z, t.lat, t.lon, color); + if (t.b.length > 5) { + addTriangle(k + 3, t.b[0].x, t.b[0].y, t.b[0].z, t.b[5].x, t.b[5].y, t.b[5].z, t.b[4].x, t.b[4].y, t.b[4].z, t.lat, t.lon, color); + } + } + geometry.computeBoundingSphere(); + this.hexGrid = new THREE.Mesh(geometry, pointMaterial); + this.scene.add(this.hexGrid); + }; + var createIntroLines = function() { + var introLinesMaterial = new THREE.LineBasicMaterial({ + color: this.introLinesColor, + transparent: true, + linewidth: 2, + opacity: 0.5 + }); + for (var i = 0; i < this.introLinesCount; i++) { + var lat = Math.random() * 180 + 90; + var lon = Math.random() * 5; + var lenBase = 4 + Math.floor(Math.random() * 5); + if (Math.random() < 0.3) { + lon = Math.random() * 30 - 50; + lenBase = 3 + Math.floor(Math.random() * 3); + } + var linePositions = new Float32Array(lenBase * 3); + for (var j = 0; j < lenBase; j++) { + var thisPoint = utils.mapPoint(lat, lon - j * 5); + linePositions[j * 3] = thisPoint.x * this.introLinesAltitude; + linePositions[j * 3 + 1] = thisPoint.y * this.introLinesAltitude; + linePositions[j * 3 + 2] = thisPoint.z * this.introLinesAltitude; + } + var geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.BufferAttribute(linePositions, 3)); + this.introLines.add(new THREE.Line(geometry, introLinesMaterial)); + } + this.scene.add(this.introLines); + }; + function Globe(width, height, opts) { + if (!opts) { + opts = {}; + } + this.width = width; + this.height = height; + this.points = []; + this.introLines = new THREE.Object3D(); + this.pins = []; + this.markers = []; + this.satelliteAnimations = []; + this.satelliteMeshes = []; + this.satellites = {}; + this.quadtree = new Quadtree2(new Vec2(180, 360), 5); + this.active = true; + var defaults = { + font: "Inconsolata", + baseColor: "#ffcc00", + markerColor: "#ffcc00", + pinColor: "#00eeee", + satelliteColor: "#ff0000", + blankPercentage: 0, + thinAntarctica: 0.01, + // only show 1% of antartica... you can't really see it on the map anyhow + mapUrl: "resources/equirectangle_projection.png", + introLinesAltitude: 1.1, + introLinesDuration: 2e3, + introLinesColor: "#8FD8D8", + introLinesCount: 60, + scale: 1, + dayLength: 28e3, + pointsPerDegree: 1.1, + pointSize: 0.6, + pointsVariance: 0.2, + maxPins: 500, + maxMarkers: 4, + data: [], + tiles: [], + viewAngle: 0 + }; + for (var i in defaults) { + if (!this[i]) { + this[i] = defaults[i]; + if (opts[i]) { + this[i] = opts[i]; + } } - - }); - -}; - -var Satellite = function(lat, lon, altitude, scene, _opts, canvas, texture){ - - var geometry, - point = utils.mapPoint(lat, lon), - opts, - numFrames, - pixels, - rows, - waveStart, - repeatAt; - - point.x *= altitude; - point.y *= altitude; - point.z *= altitude; - - /* options that can be passed in */ - var opts = { - numWaves: 8, - waveColor: "#FFF", - coreColor: "#FF0000", - shieldColor: "#FFF", - size: 1 + } + this.setScale(this.scale); + this.renderer = new THREE.WebGLRenderer({ antialias: true }); + this.renderer.setSize(this.width, this.height); + this.domElement = this.renderer.domElement; + this.data.sort(function(a, b) { + return b.lng - b.label.length * 2 - (a.lng - a.label.length * 2); + }); + for (var i = 0; i < this.data.length; i++) { + this.data[i].when = this.introLinesDuration * ((180 + this.data[i].lng) / 360) + 500; + } } - - /* required field */ - this.lat = lat; - this.lon = lon; - this.altitude = altitude; - this.scene = scene; - - this.onRemoveList = []; - - /* private vars */ - numFrames = 50; - pixels = 100; - rows = 10; - waveStart = Math.floor(numFrames/8); - - if(_opts){ - for(var i in opts){ - if(_opts[i] != undefined){ - opts[i] = _opts[i]; - } + Globe.prototype.init = function(cb) { + this.camera = new THREE.PerspectiveCamera(50, this.width / this.height, 1, this.cameraDistance + 300); + this.camera.position.z = this.cameraDistance; + this.cameraAngle = Math.PI; + this.scene = new THREE.Scene(); + this.scene.fog = new THREE.Fog(0, this.cameraDistance, this.cameraDistance + 300); + createIntroLines.call(this); + this.smokeProvider = new SmokeProvider(this.scene); + createParticles.call(this); + setTimeout(cb, 500); + }; + Globe.prototype.destroy = function(callback) { + var _this2 = this; + this.active = false; + setTimeout(function() { + while (_this2.scene.children.length > 0) { + _this2.scene.remove(_this2.scene.children[0]); } - } - - this.opts = opts; - - if(!canvas){ - this.canvas = createCanvas(numFrames, pixels, rows, waveStart, opts.numWaves, opts.waveColor, opts.coreColor, opts.shieldColor); - this.texture = new THREE.Texture(this.canvas) - this.texture.needsUpdate = true; - repeatAt = Math.floor(numFrames-2*(numFrames-waveStart)/opts.numWaves)+1; - this.animator = new TextureAnimator(this.texture,rows, numFrames/rows, numFrames, 80, repeatAt); - } else { - this.canvas = canvas; - if(!texture){ - this.texture = new THREE.Texture(this.canvas) - this.texture.needsUpdate = true; - repeatAt = Math.floor(numFrames-2*(numFrames-waveStart)/opts.numWaves)+1; - this.animator = new TextureAnimator(this.texture,rows, numFrames/rows, numFrames, 80, repeatAt); - } else { - this.texture = texture; + if (typeof callback == "function") { + callback(); } - } - - geometry = new THREE.PlaneGeometry(opts.size * 150, opts.size * 150,1,1); - this.material = new THREE.MeshBasicMaterial({ - map : this.texture, - depthTest: false, - transparent: true - }); - - this.mesh = new THREE.Mesh(geometry, this.material); - this.mesh.tiltMultiplier = Math.PI/2 * (1 - Math.abs(lat / 90)); - this.mesh.tiltDirection = (lat > 0 ? -1 : 1); - this.mesh.lon = lon; - - this.mesh.position.set(point.x, point.y, point.z); - - this.mesh.rotation.z = -1*(lat/90)* Math.PI/2; - this.mesh.rotation.y = (lon/180)* Math.PI - - scene.add(this.mesh); - -} - -Satellite.prototype.changeAltitude = function(_altitude){ - - var newPoint = utils.mapPoint(this.lat, this.lon); - newPoint.x *= _altitude; - newPoint.y *= _altitude; - newPoint.z *= _altitude; - - this.altitude = _altitude; - - this.mesh.position.set(newPoint.x, newPoint.y, newPoint.z); - -}; - -Satellite.prototype.changeCanvas = function(numWaves, waveColor, coreColor, shieldColor){ - /* private vars */ - numFrames = 50; - pixels = 100; - rows = 10; - waveStart = Math.floor(numFrames/8); - - if(!numWaves){ - numWaves = this.opts.numWaves; - } else { - this.opts.numWaves = numWaves; - } - if(!waveColor){ - waveColor = this.opts.waveColor; - } else { - this.opts.waveColor = waveColor; - } - if(!coreColor){ - coreColor = this.opts.coreColor; - } else { - this.opts.coreColor = coreColor; - } - if(!shieldColor){ - shieldColor = this.opts.shieldColor; - } else { - this.opts.shieldColor = shieldColor; - } - - this.canvas = createCanvas(numFrames, pixels, rows, waveStart, numWaves, waveColor, coreColor, shieldColor); - this.texture = new THREE.Texture(this.canvas) - this.texture.needsUpdate = true; - repeatAt = Math.floor(numFrames-2*(numFrames-waveStart)/numWaves)+1; - this.animator = new TextureAnimator(this.texture,rows, numFrames/rows, numFrames, 80, repeatAt); - this.material.map = this.texture; -}; - -Satellite.prototype.tick = function(cameraPosition, cameraAngle, renderTime) { - // underscore should be good enough - - this.mesh.lookAt(cameraPosition); - - this.mesh.rotateZ(this.mesh.tiltDirection * Math.PI/2); - this.mesh.rotateZ(Math.sin(cameraAngle + (this.mesh.lon / 180) * Math.PI) * this.mesh.tiltMultiplier * this.mesh.tiltDirection * -1); - - if(this.animator){ - this.animator.update(renderTime); - } - - -}; - -Satellite.prototype.remove = function() { - - - this.scene.remove(this.mesh); - - for(var i = 0; i< this.onRemoveList.length; i++){ - this.onRemoveList[i](); - } -}; - -Satellite.prototype.onRemove = function(fn){ - this.onRemoveList.push(fn); -} - -Satellite.prototype.toString = function(){ - return "" + this.lat + '_' + this.lon + '_' + this.altitude; -}; - -module.exports = Satellite; - - -},{"./TextureAnimator":20,"./utils":21,"three":12}],19:[function(require,module,exports){ -var THREE = require('three'), - utils = require('./utils'); - -var vertexShader = [ - "#define PI 3.141592653589793238462643", - "#define DISTANCE 500.0", - "attribute float myStartTime;", - "attribute float myStartLat;", - "attribute float myStartLon;", - "attribute float altitude;", - "attribute float active;", - "uniform float currentTime;", - "uniform vec3 color;", - "varying vec4 vColor;", - "", - "vec3 getPos(float lat, float lon)", - "{", - " if (lon < -180.0){", - " lon = lon + 360.0;", - " }", - " float phi = (90.0 - lat) * PI / 180.0;", - " float theta = (180.0 - lon) * PI / 180.0;", - " float x = DISTANCE * sin(phi) * cos(theta) * altitude;", - " float y = DISTANCE * cos(phi) * altitude;", - " float z = DISTANCE * sin(phi) * sin(theta) * altitude;", - " return vec3(x, y, z);", - "}", - "", - "void main()", - "{", - " float dt = currentTime - myStartTime;", - " if (dt < 0.0){", - " dt = 0.0;", - " }", - " if (dt > 0.0 && active > 0.0) {", - " dt = mod(dt,1500.0);", - " }", - " float opacity = 1.0 - dt/ 1500.0;", - " if (dt == 0.0 || active == 0.0){", - " opacity = 0.0;", - " }", - " vec3 newPos = getPos(myStartLat, myStartLon - ( dt / 50.0));", - " vColor = vec4( color, opacity );", // set color associated to vertex; use later in fragment shader. - " vec4 mvPosition = modelViewMatrix * vec4( newPos, 1.0 );", - " gl_PointSize = 2.5 - (dt / 1500.0);", - " gl_Position = projectionMatrix * mvPosition;", - "}" -].join("\n"); - -var fragmentShader = [ - "varying vec4 vColor;", - "void main()", - "{", - " gl_FragColor = vColor;", - " float depth = gl_FragCoord.z / gl_FragCoord.w;", - " float fogFactor = smoothstep(1500.0, 1800.0, depth );", - " vec3 fogColor = vec3(0.0);", - " gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w), fogFactor );", - - "}" -].join("\n"); - -var SmokeProvider = function(scene, _opts){ - - /* options that can be passed in */ - var opts = { - smokeCount: 5000, - smokePerPin: 30, - smokePerSecond: 20 - } - - if(_opts){ - for(var i in opts){ - if(_opts[i] !== undefined){ - opts[i] = _opts[i]; + }, 1e3); + }; + Globe.prototype.addPin = function(lat, lon, text) { + lat = parseFloat(lat); + lon = parseFloat(lon); + var opts = { + lineColor: this.pinColor, + topColor: this.pinColor, + font: this.font + }; + var altitude = 1.2; + if (typeof text != "string" || text.length === 0) { + altitude -= 0.05 + Math.random() * 0.05; + } + var pin = new Pin(lat, lon, text, altitude, this.scene, this.smokeProvider, opts); + this.pins.push(pin); + var pos = latLon2d(lat, lon); + pin.pos_ = new Vec2(parseInt(pos.x), parseInt(pos.y)); + if (text.length > 0) { + pin.rad_ = pos.rad; + } else { + pin.rad_ = 1; + } + this.quadtree.addObject(pin); + if (text.length > 0) { + var collisions = this.quadtree.getCollisionsForObject(pin); + var collisionCount = 0; + var tooYoungCount = 0; + var hidePins = []; + for (var i in collisions) { + if (collisions[i].text.length > 0) { + collisionCount++; + if (collisions[i].age() > 5e3) { + hidePins.push(collisions[i]); + } else { + tooYoungCount++; } + } } - } - - this.opts = opts; - this.geometry = new THREE.Geometry(); - this.attributes = { - myStartTime: {type: 'f', value: []}, - myStartLat: {type: 'f', value: []}, - myStartLon: {type: 'f', value: []}, - altitude: {type: 'f', value: []}, - active: {type: 'f', value: []} + if (collisionCount > 0 && tooYoungCount == 0) { + for (var i = 0; i < hidePins.length; i++) { + hidePins[i].hideLabel(); + hidePins[i].hideSmoke(); + hidePins[i].hideTop(); + hidePins[i].changeAltitude(Math.random() * 0.05 + 1.1); + } + } else if (collisionCount > 0) { + pin.hideLabel(); + pin.hideSmoke(); + pin.hideTop(); + pin.changeAltitude(Math.random() * 0.05 + 1.1); + } + } + if (this.pins.length > this.maxPins) { + var oldPin = this.pins.shift(); + this.quadtree.removeObject(oldPin); + oldPin.remove(); + } + return pin; }; - - this.uniforms = { - currentTime: { type: 'f', value: 0.0}, - color: { type: 'c', value: new THREE.Color("#aaa")}, - } - - var material = new THREE.ShaderMaterial( { - uniforms: this.uniforms, - attributes: this.attributes, - vertexShader: vertexShader, - fragmentShader: fragmentShader, - transparent: true - }); - - for(var i = 0; i< opts.smokeCount; i++){ - var vertex = new THREE.Vector3(); - vertex.set(0,0,0); - this.geometry.vertices.push( vertex ); - this.attributes.myStartTime.value[i] = 0.0; - this.attributes.myStartLat.value[i] = 0.0; - this.attributes.myStartLon.value[i] = 0.0; - this.attributes.altitude.value[i] = 0.0; - this.attributes.active.value[i] = 0.0; - } - - this.attributes.myStartTime.needsUpdate = true; - this.attributes.myStartLat.needsUpdate = true; - this.attributes.myStartLon.needsUpdate = true; - this.attributes.altitude.needsUpdate = true; - this.attributes.active.needsUpdate = true; - - this.smokeIndex = 0; - this.totalRunTime = 0; - - scene.add( new THREE.ParticleSystem( this.geometry, material)); - -}; - -SmokeProvider.prototype.setFire = function(lat, lon, altitude){ - - var point = utils.mapPoint(lat, lon); - - /* add the smoke */ - var startSmokeIndex = this.smokeIndex; - - for(var i = 0; i< this.opts.smokePerPin; i++){ - this.geometry.vertices[this.smokeIndex].set(point.x * altitude, point.y * altitude, point.z * altitude); - this.geometry.verticesNeedUpdate = true; - this.attributes.myStartTime.value[this.smokeIndex] = this.totalRunTime + (1000*i/this.opts.smokePerSecond + 1500); - this.attributes.myStartLat.value[this.smokeIndex] = lat; - this.attributes.myStartLon.value[this.smokeIndex] = lon; - this.attributes.altitude.value[this.smokeIndex] = altitude; - this.attributes.active.value[this.smokeIndex] = 1.0; - - this.attributes.myStartTime.needsUpdate = true; - this.attributes.myStartLat.needsUpdate = true; - this.attributes.myStartLon.needsUpdate = true; - this.attributes.altitude.needsUpdate = true; - this.attributes.active.needsUpdate = true; - - this.smokeIndex++; - this.smokeIndex = this.smokeIndex % this.geometry.vertices.length; - } - - - return startSmokeIndex; - -}; - -SmokeProvider.prototype.extinguish = function(index){ - for(var i = 0; i< this.opts.smokePerPin; i++){ - this.attributes.active.value[(i + index) % this.opts.smokeCount] = 0.0; - this.attributes.active.needsUpdate = true; - } -}; - -SmokeProvider.prototype.changeAltitude = function(altitude, index){ - for(var i = 0; i< this.opts.smokePerPin; i++){ - this.attributes.altitude.value[(i + index) % this.opts.smokeCount] = altitude; - this.attributes.altitude.needsUpdate = true; - } - -}; - -SmokeProvider.prototype.tick = function(totalRunTime){ - this.totalRunTime = totalRunTime; - this.uniforms.currentTime.value = this.totalRunTime; -}; - -module.exports = SmokeProvider; - -},{"./utils":21,"three":12}],20:[function(require,module,exports){ -var THREE = require('three'); - -// based on http://stemkoski.github.io/Three.js/Texture-Animation.html -var TextureAnimator = function(texture, tilesVert, tilesHoriz, numTiles, tileDispDuration, repeatAtTile) -{ - // note: texture passed by reference, will be updated by the update function. - - if(repeatAtTile == undefined){ - this.repeatAtTile=-1; - } - - this.shutDownFlag = (this.repeatAtTile < 0); - this.done = false; - - this.tilesHorizontal = tilesHoriz; - this.tilesVertical = tilesVert; - - // how many images does this spritesheet contain? - // usually equals tilesHoriz * tilesVert, but not necessarily, - // if there at blank tiles at the bottom of the spritesheet. - this.numberOfTiles = numTiles; - texture.wrapS = texture.wrapT = THREE.RepeatWrapping; - texture.repeat.set( 1 / this.tilesHorizontal, 1 / this.tilesVertical ); - - // how long should each image be displayed? - this.tileDisplayDuration = tileDispDuration; - - // how long has the current image been displayed? - this.currentDisplayTime = 0; - - // which image is currently being displayed? - this.currentTile = 0; - - texture.offset.y = 1; - - this.update = function( milliSec ) - { - this.currentDisplayTime += milliSec; - while (!this.done && this.currentDisplayTime > this.tileDisplayDuration) - { - if(this.shutDownFlag && this.currentTile >= numTiles){ - this.done = true; - this.shutDownCb(); - } else { - this.currentDisplayTime -= this.tileDisplayDuration; - this.currentTile++; - if (this.currentTile == numTiles && !this.shutDownFlag) - this.currentTile = repeatAtTile; - var currentColumn = this.currentTile % this.tilesHorizontal; - texture.offset.x = currentColumn / this.tilesHorizontal; - var currentRow = Math.floor( this.currentTile / this.tilesHorizontal ); - texture.offset.y = 1-(currentRow / this.tilesVertical) - 1/this.tilesVertical; - } - } + Globe.prototype.addMarker = function(lat, lon, text, connected) { + var marker; + var opts = { + markerColor: this.markerColor, + lineColor: this.markerColor, + font: this.font + }; + if (typeof connected == "boolean" && connected) { + marker = new Marker(lat, lon, text, 1.2, this.markers[this.markers.length - 1], this.scene, opts); + } else if (typeof connected == "object") { + marker = new Marker(lat, lon, text, 1.2, connected, this.scene, opts); + } else { + marker = new Marker(lat, lon, text, 1.2, null, this.scene, opts); + } + this.markers.push(marker); + if (this.markers.length > this.maxMarkers) { + this.markers.shift().remove(); + } + return marker; }; - this.shutDown = function(cb){ - _this.shutDownFlag = true; - _this.shutDownCb = cb; - } - -}; - -module.exports = TextureAnimator; - -},{"three":12}],21:[function(require,module,exports){ -var utils = { - - renderToCanvas: function (width, height, renderFunction) { - var buffer = document.createElement('canvas'); - buffer.width = width; - buffer.height = height; - renderFunction(buffer.getContext('2d')); - - return buffer; - }, - - mapPoint: function(lat, lng, scale) { - if(!scale){ - scale = 500; + Globe.prototype.addSatellite = function(lat, lon, altitude, opts, texture, animator) { + if (!opts) { + opts = {}; + } + if (opts.coreColor == void 0) { + opts.coreColor = this.satelliteColor; + } + var satellite = new Satellite(lat, lon, altitude, this.scene, opts, texture, animator); + if (!this.satellites[satellite.toString()]) { + this.satellites[satellite.toString()] = satellite; + } + satellite.onRemove((function() { + delete this.satellites[satellite.toString()]; + }).bind(this)); + return satellite; + }; + Globe.prototype.addConstellation = function(sats, opts) { + var satellite, constellation = []; + for (var i = 0; i < sats.length; i++) { + if (i === 0) { + satellite = this.addSatellite(sats[i].lat, sats[i].lon, sats[i].altitude, opts); + } else { + satellite = this.addSatellite(sats[i].lat, sats[i].lon, sats[i].altitude, opts, constellation[0].canvas, constellation[0].texture); } - var phi = (90 - lat) * Math.PI / 180; - var theta = (180 - lng) * Math.PI / 180; - var x = scale * Math.sin(phi) * Math.cos(theta); - var y = scale * Math.cos(phi); - var z = scale * Math.sin(phi) * Math.sin(theta); - return {x: x, y: y, z:z}; - }, - - /* from http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb */ - - hexToRgb: function(hex) { - // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") - var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; - hex = hex.replace(shorthandRegex, function(m, r, g, b) { - return r + r + g + g + b + b; - }); - - var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); - return result ? { - r: parseInt(result[1], 16), - g: parseInt(result[2], 16), - b: parseInt(result[3], 16) - } : null; - }, - - createLabel: function(text, size, color, font, underlineColor) { - - var canvas = document.createElement("canvas"); - var context = canvas.getContext("2d"); - context.font = size + "pt " + font; - - var textWidth = context.measureText(text).width; - - canvas.width = textWidth; - canvas.height = size + 10; - - // better if canvases have even heights - if(canvas.width % 2){ - canvas.width++; + constellation.push(satellite); } - if(canvas.height % 2){ - canvas.height++; + return constellation; + }; + Globe.prototype.setMaxPins = function(_maxPins) { + this.maxPins = _maxPins; + while (this.pins.length > this.maxPins) { + var oldPin = this.pins.shift(); + this.quadtree.removeObject(oldPin); + oldPin.remove(); } - - if(underlineColor){ - canvas.height += 30; + }; + Globe.prototype.setMaxMarkers = function(_maxMarkers) { + this.maxMarkers = _maxMarkers; + while (this.markers.length > this.maxMarkers) { + this.markers.shift().remove(); } - context.font = size + "pt " + font; - - context.textAlign = "center"; - context.textBaseline = "middle"; - - context.strokeStyle = 'black'; - - context.miterLimit = 2; - context.lineJoin = 'circle'; - context.lineWidth = 6; - - context.strokeText(text, canvas.width / 2, canvas.height / 2); - - context.lineWidth = 2; - - context.fillStyle = color; - context.fillText(text, canvas.width / 2, canvas.height / 2); - - if(underlineColor){ - context.strokeStyle=underlineColor; - context.lineWidth=4; - context.beginPath(); - context.moveTo(0, canvas.height-10); - context.lineTo(canvas.width-1, canvas.height-10); - context.stroke(); + }; + Globe.prototype.setBaseColor = function(_color) { + this.baseColor = _color; + createParticles.call(this); + }; + Globe.prototype.setMarkerColor = function(_color) { + this.markerColor = _color; + this.scene._encom_markerTexture = null; + }; + Globe.prototype.setPinColor = function(_color) { + this.pinColor = _color; + }; + Globe.prototype.setScale = function(_scale) { + this.scale = _scale; + this.cameraDistance = 1700 / _scale; + if (this.scene && this.scene.fog) { + this.scene.fog.near = this.cameraDistance; + this.scene.fog.far = this.cameraDistance + 300; + createParticles.call(this); + this.camera.far = this.cameraDistance + 300; + this.camera.updateProjectionMatrix(); } - - return canvas; - - }, - -}; - -module.exports = utils; - -},{}]},{},[1]); \ No newline at end of file + }; + Globe.prototype.tick = function() { + if (!this.camera) { + return; + } + if (!this.firstRunTime) { + this.firstRunTime = Date.now(); + } + addInitialData.call(this); + TWEEN.update(); + if (!this.lastRenderDate) { + this.lastRenderDate = /* @__PURE__ */ new Date(); + } + if (!this.firstRenderDate) { + this.firstRenderDate = /* @__PURE__ */ new Date(); + } + this.totalRunTime = /* @__PURE__ */ new Date() - this.firstRenderDate; + var renderTime = /* @__PURE__ */ new Date() - this.lastRenderDate; + this.lastRenderDate = /* @__PURE__ */ new Date(); + var rotateCameraBy = 2 * Math.PI / (this.dayLength / renderTime); + this.cameraAngle += rotateCameraBy; + if (!this.active) { + this.cameraDistance += 1e3 * renderTime / 1e3; + } + this.camera.position.x = this.cameraDistance * Math.cos(this.cameraAngle) * Math.cos(this.viewAngle); + this.camera.position.y = Math.sin(this.viewAngle) * this.cameraDistance; + this.camera.position.z = this.cameraDistance * Math.sin(this.cameraAngle) * Math.cos(this.viewAngle); + for (var i in this.satellites) { + this.satellites[i].tick(this.camera.position, this.cameraAngle, renderTime); + } + for (var i = 0; i < this.satelliteMeshes.length; i++) { + var mesh = this.satelliteMeshes[i]; + mesh.lookAt(this.camera.position); + mesh.rotateZ(mesh.tiltDirection * Math.PI / 2); + mesh.rotateZ(Math.sin(this.cameraAngle + mesh.lon / 180 * Math.PI) * mesh.tiltMultiplier * mesh.tiltDirection * -1); + } + if (this.introLinesDuration > this.totalRunTime) { + if (this.totalRunTime / this.introLinesDuration < 0.1) { + this.introLines.children[0].material.opacity = this.totalRunTime / this.introLinesDuration * (1 / 0.1) - 0.2; + } + if (this.totalRunTime / this.introLinesDuration > 0.8) { + this.introLines.children[0].material.opacity = Math.max(1 - this.totalRunTime / this.introLinesDuration, 0) * (1 / 0.2); + } else { + this.introLines.children[0].material.opacity = 1; + } + this.introLines.rotateY(2 * Math.PI / (this.introLinesDuration / renderTime)); + } else if (this.introLines) { + this.scene.remove(this.introLines); + delete [this.introLines]; + } + this.pointUniforms.currentTime.value = this.totalRunTime; + this.smokeProvider.tick(this.totalRunTime); + this.camera.lookAt(this.scene.position); + this.renderer.render(this.scene, this.camera); + }; + Globe_1 = Globe; + return Globe_1; + } + var hasRequiredBrowserify; + function requireBrowserify() { + if (hasRequiredBrowserify) return browserify$1; + hasRequiredBrowserify = 1; + window.ENCOM = window.ENCOM || {}; + window.ENCOM.Globe = requireGlobe(); + return browserify$1; + } + var browserifyExports = requireBrowserify(); + const browserify = /* @__PURE__ */ getDefaultExportFromCjs(browserifyExports); + return browserify; +})(); diff --git a/build/encom-globe.min.js b/build/encom-globe.min.js index 1bd1b8e..00f4c73 100644 --- a/build/encom-globe.min.js +++ b/build/encom-globe.min.js @@ -1,15 +1,4117 @@ -!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g=j;j++){o=p,p=q[j].subdivide(r[j],j,l);for(var s=0;j>s;s++){var t=new d(o[s],p[s],p[s+1]);m.push(t),s>0&&(t=new d(o[s-1],o[s],p[s]),m.push(t))}}k=m;var u={};for(var v in i){var w=i[v].project(a);u[w]=w}i=u,this.tiles=[];for(var v in i)this.tiles.push(new c(i[v],f))};b.exports=f},{"./face":2,"./point":4,"./tile":5}],4:[function(a,b){var c=function(a,b,c){void 0!==a&&void 0!==b&&void 0!==c&&(this.x=a,this.y=b,this.z=c),this.faces=[]};c.prototype.subdivide=function(a,b,d){var e=[];e.push(this);for(var f=1;b>f;f++){var g=new c(this.x*(1-f/b)+a.x*(f/b),this.y*(1-f/b)+a.y*(f/b),this.z*(1-f/b)+a.z*(f/b));g=d(g),e.push(g)}return e.push(a),e},c.prototype.segment=function(a,b){var d=new c;return b=Math.max(.01,Math.min(1,b)),d.x=a.x*(1-b)+this.x*b,d.y=a.y*(1-b)+this.y*b,d.z=a.z*(1-b)+this.z*b,d},c.prototype.midpoint=function(a){return this.segment(a,.5)},c.prototype.project=function(a,b){void 0==b&&(b=1),b=Math.max(0,Math.min(1,b));var c=(this.y/this.x,this.z/this.x,this.z/this.y,Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2)+Math.pow(this.z,2))),d=a/c;return this.x=this.x*d*b,this.y=this.y*d*b,this.z=this.z*d*b,this},c.prototype.registerFace=function(a){this.faces.push(a)},c.prototype.getOrderedFaces=function(){for(var a=this.faces.slice(),b=[],c=0;ca?360+a:a}function d(a){return a>>>0}function e(a){return a.replace(/^\s+/,"").replace(/\s+$/,"").toLowerCase()}function f(a,b){return Array.prototype.slice.call(a,b)}function g(a,b,c){return a>b?c>a?a:c:b}function h(a,b,c){return(1-c)*a+c*b}function i(a){return a=Math.round(255*a),a>0?255>a?255&a:255:0}function j(a){return a/255}function k(a,b,c){var d,e,f=Math.max(a,b,c),g=Math.min(a,b,c),h=(f+g)/2;if(f==g)d=e=0;else{var i=f-g;switch(e=h>.5?i/(2-f-g):i/(f+g),f){case a:d=(b-c)/i+(c>b?6:0);break;case b:d=(c-a)/i+2;break;case c:d=(a-b)/i+4}d/=6}return[d,e,h]}function l(a,b,c){function d(a,b,c){return 0>c&&(c+=1),c>1&&(c-=1),1/6>c?a+6*(b-a)*c:.5>c?b:2/3>c?a+(b-a)*(2/3-c)*6:a}var e,f,g;if(0==b)e=f=g=c;else{var h=.5>c?c*(1+b):c+b-c*b,i=2*c-h;e=d(i,h,a+1/3),f=d(i,h,a),g=d(i,h,a-1/3)}return[e,f,g]}function m(a){for(var b=[parseInt(a.substr(1,1),16),parseInt(a.substr(2,1),16),parseInt(a.substr(3,1),16),1],c=0;3>c;++c)b[c]=(16*b[c]+b[c])/255;return b}function n(a){return[parseInt(a.substr(1,2),16)/255,parseInt(a.substr(3,2),16)/255,parseInt(a.substr(5,2),16)/255,1]}function o(a){var b,c,d=a[0],e=a[1],f=a[2],g=Math.min(Math.min(d,e),f),h=Math.max(Math.max(d,e),f),i=h;return h==g?c=0:h==d?c=60*((e-f)/(h-g))%360:h==e?c=60*((f-d)/(h-g))+120:h==f&&(c=60*((d-e)/(h-g))+240),0>c&&(c+=360),b=0==h?0:1-g/h,[Math.round(c),Math.round(100*b),Math.round(100*i),a[3]]}function p(b){var c=a(b[0]),d=b[1],e=b[2],d=d/100,e=e/100,f=Math.floor(c/60%6),g=c/60-f,h=e*(1-d),i=e*(1-g*d),j=e*(1-(1-g)*d),k=[];switch(f){case 0:k=[e,j,h];break;case 1:k=[i,e,h];break;case 2:k=[h,e,j];break;case 3:k=[h,i,e];break;case 4:k=[j,h,e];break;case 5:k=[e,h,i]}return[k[0],k[1],k[2],b[3]]}function q(b){var c=k(b[0],b[1],b[2]);return c[0]=a(Math.floor(360*c[0])),c[1]=Math.floor(100*c[1]),c[2]=Math.floor(100*c[2]),c}function r(a){var b=q(a);return b.push(a[3]),b}function s(a){var b=parseFloat(a[0])/360,c=parseFloat(a[1])/100,d=parseFloat(a[2])/100,e=l(b,c,d);return[e[0],e[1],e[2],parseFloat(a[3])]}function t(a){this._value=a}function u(a,b){if(void 0==b)return i(this._value[a]);var c=f(this._value,0);if("string"!=typeof b){var d=this.clone();return d._value[a]=b,d}var e;if(e=b.match(/^([+\-\\*]=?)([0-9.]+)/)){var g=e[1],h=parseFloat(e[2]);switch(g[0]){case"+":c[a]+=h/255;break;case"-":c[a]-=h/255;break;case"*":c[a]*=h}return"="==g[1]?(this._value=c,this):new t(c)}}function v(b){return function(){function c(c,d,e){e=parseFloat(e);var f=o(c._value),g=0;switch(d){case"=":f[b]=e,g=1;break;case"+":f[b]+=e,g=1;break;case"+=":f[b]+=e;break;case"-":f[b]-=e,g=1;break;case"-=":f[b]-=e;break;case"*":f[b]*=e,g=1;break;case"*=":f[b]*=e;break;default:throw"Bad op "+d}return 0==b?f[b]=a(f[b]):(1==b||2==b)&&(f[b]<0?f[b]=0:f[b]>99&&(f[b]=99)),g&&(c=c.clone()),c._value=p(f),c}if(0==arguments.length)return o(this._value)[b];if(1==arguments.length){var d;return"string"==typeof arguments[0]&&(d=arguments[0].match(/^([\+\-\*]=?)([0-9.]+)/))?c(this,d[1],d[2]):c(this,"=",arguments[0])}return 2==arguments.length?c(this,arguments[0],arguments[1]):void 0}}var w={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,216],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[216,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},x={byteOrPercent:function(a){var b;return"string"==typeof a&&(b=a.match(/^([0-9]+)%$/))?Math.floor(255*parseFloat(b[1])/100):parseFloat(a)},floatOrPercent:function(a){var b;return"string"==typeof a&&(b=a.match(/^([0-9]+)%$/))?parseFloat(b[1])/100:parseFloat(a)},numberOrPercent:function(a,b){var c;return"string"==typeof a&&(c=a.match(/^([0-9]+)%$/))?parseFloat(c[1])/100*b:parseFloat(a)},rgba:function(a){for(var b=0;3>b;++b)a[b]=j(x.byteOrPercent(a[b]));return a[3]=x.floatOrPercent(a[b]),new t(a)},rgba8:function(a){return new t([j(x.byteOrPercent(a[0])),j(x.byteOrPercent(a[1])),j(x.byteOrPercent(a[2])),j(x.byteOrPercent(a[3]))])},float3:function(a){for(var b=0;3>b;++b)a[b]=x.floatOrPercent(a[b]);return a[3]=1,new t(a)},float4:function(a){for(var b=0;3>b;++b)a[b]=x.floatOrPercent(a[b]);return a[3]=x.floatOrPercent(a[b]),new t(a)},hsla:function(a){return a[0]=x.numberOrPercent(a[0],360),a[1]=x.numberOrPercent(a[1],100),a[2]=x.numberOrPercent(a[2],100),a[3]=x.numberOrPercent(a[3],1),new t(s(a))},hsva:function(b){return b[0]=a(parseFloat(b[0])),b[1]=Math.max(0,Math.min(100,parseFloat(b[1]))),b[2]=Math.max(0,Math.min(100,parseFloat(b[2]))),b[3]=x.floatOrPercent(b[3]),new t(p(b))}},y={keyword:{},hex3:{},hex7:{},rgb:{parse:function(a){return a=a.slice(0),a.push(1),x.rgba(a)}},rgba:{parse:x.rgba},hsl:{parse:function(a){return a=a.slice(0),a.push(1),x.hsla(a)}},hsla:{parse:x.hsla},hsv:{parse:function(a){return a=a.slice(0),a.push(1),x.hsva(a)}},hsva:{parse:x.hsva},rgb8:{parse:function(a){return a=a.slice(0),a.push(1),x.rgba(a)}},rgba8:{parse:function(a){return x.rgba8(a)}},packed_rgba:{parse:function(a){return a=[a>>24&255,a>>16&255,a>>8&255,(255&a)/255],x.rgba(a)},output:function(a){return d(i(a[0])<<24|i(a[1])<<16|i(a[2])<<8|i(a[3]))}},packed_argb:{parse:function(a){return a=[a>>16&255,a>>8&255,a>>0&255,(a>>24&255)/255],x.rgba(a)},output:function(a){return d(i(a[3])<<24|i(a[0])<<16|i(a[1])<<8|i(a[2]))}},float3:{parse:x.float3},float4:{parse:x.float4}},z=function(){var a=null;if(arguments[0]instanceof t)return new t(arguments[0]._value);if("string"==typeof arguments[0]){var b=arguments[0][0];if("#"==b){if(a=arguments[0].match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/i))return new t(m(a[0]));if(a=arguments[0].match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/i))return new t(n(a[0]))}else{if(a=y[arguments[0].toLowerCase()])return a.parse(2==arguments.length?arguments[1]:f(arguments,1));if(a=arguments[0].match(/^\s*([A-Z][A-Z0-9_]+)\s*\(\s*([\-0-9A-FX]+)\s*\)\s*$/i)){var c=y[a[1].toLowerCase()];return c.parse(a[2])}if(a=arguments[0].match(/^\s*([A-Z][A-Z0-9]+)\s*\(\s*([0-9\.]+%?)\s*,\s*([0-9\.]+%?)\s*,\s*([0-9\.]+%?)\s*(,\s*([0-9\.]+%?)\s*)?\)\s*$/i)){var c=y[a[1].toLowerCase()];if(void 0===a[5]){var d=[a[2],a[3],a[4]];return c.parse(d)}var d=[a[2],a[3],a[4],a[6]];return c.parse(d)}if(1==arguments.length&&(a=w[e(arguments[0])])){var d=a;return new t([j(d[0]),j(d[1]),j(d[2]),1])}}}throw"Could not parse color '"+arguments[0]+"'"},A={white:z("white"),black:z("black"),gray:z("gray")},B={clone:function(){return new t(this._value.slice(0))},html:function(){var a=this,b=this._value,c={hex3:function(){return a.hex3()},hex6:function(){return a.hex6()},rgb:function(){return"rgb("+a.rgb().join(",")+")"},rgba:function(){return"rgba("+a.rgba().join(",")+")"},hsl:function(){return"hsl("+q(b).join(",")+")"},hsla:function(){return"hsla("+r(b).join(",")+")"},keyword:function(){var a,c=195076;for(C in w){for(var d=w[C],e=0,f=0;3>f;++f){var g=b[f]-j(d[f]);e+=g*g}c>e&&(a=C,c=e)}return a}},d=arguments[0]||"rgba";return c[d]()},red:function(){return u.call(this,0,arguments[0])},green:function(){return u.call(this,1,arguments[0])},blue:function(){return u.call(this,2,arguments[0])},alpha:function(){return 1==arguments.length?(c=this.clone(),c._value[3]=x.floatOrPercent(arguments[0]),c):this._value[3]},alpha8:function(){return 1==arguments.length?(c=this.clone(),c._value[3]=x.byteOrPercent(arguments[0])/255,c):Math.floor(255*this._value[3])},grayvalue:function(){var a=this._value;return(a[0]+a[1]+a[2])/3},grayvalue8:function(){return i(this.grayvalue())},luminance:function(){var a=this._value;return.2126*a[0]+.7152*a[1]+.0722*a[2]},luminance8:function(){return i(this.luminance())},hsv:function(){return o(this._value).slice(0,3)},hsva:function(){return o(this._value)},packed_rgba:function(){return y.packed_rgba.output(this._value)},packed_argb:function(){return y.packed_argb.output(this._value)},hue:v(0),saturation:v(1),value:v(2),clamp:function(){var a=this._value;return new t([g(a[0],0,1),g(a[1],0,1),g(a[2],0,1),g(a[3],0,1)])},blend:function(a,b){"number"!=typeof b&&(b=x.floatOrPercent(b));var c=this,d=z(a);return new t([h(c._value[0],d._value[0],b),h(c._value[1],d._value[1],b),h(c._value[2],d._value[2],b),h(c._value[3],d._value[3],b)])},add:function(a){var b=this._value,c=z(a)._value;return new t([b[0]+c[0]*c[3],b[1]+c[1]*c[3],b[2]+c[2]*c[3],b[3]])},inc:function(a){var b=this._value,c=z(a)._value;return b[0]+=c[0]*c[3],b[1]+=c[1]*c[3],b[2]+=c[2]*c[3],this},dec:function(a){var b=this._value,c=z(a)._value;return b[0]-=c[0]*c[3],b[1]-=c[1]*c[3],b[2]-=c[2]*c[3],this},subtract:function(a){var b=this._value,c=z(a)._value;return new t([b[0]-c[0]*c[3],b[1]-c[1]*c[3],b[2]-c[2]*c[3],b[3]])},multiply:function(a){var b=this._value,c=z(a)._value;return new t([b[0]*c[0],b[1]*c[1],b[2]*c[2],b[3]*c[3]])},scale:function(a){var b=this._value;return new t([b[0]*a,b[1]*a,b[2]*a,b[3]])},xor:function(a){var b=this.rgba8(),c=z(a).rgba8();return z("rgba8",b[0]^c[0],b[1]^c[1],b[2]^c[2],b[3])},tint:function(a){return this.blend(A.white,a)},shade:function(a){return this.blend(A.black,a)},tone:function(a){return this.blend(A.gray,a)},complement:function(){var b=this.hsva();return b[0]=a(b[0]+180),new t(p(b))},triad:function(){return[new t(this._value),this.hue("+120"),this.hue("+240")]},hueSet:function(){for(var a=0,b=[],c=100;c>=30;c-=35)for(var d=100;d>=30;d-=35)b.push(this.hue("+",a).saturation(c).value(d));return b},hueRange:function(a,b){for(var c=this.hue(),d=[],e=0;b>e;++e){var f=c+2*(e/(b-1)-.5)*a;d.push(this.hue("=",f))}return d},contrastWhiteBlack:function(){return z(this.value()<50?"white":"black")},contrastGray:function(){var a=this.hsva(),b=a[2]<30?a[2]+20:a[2]-20;return new t(p([a[0],0,b,a[3]]))},hex3:function(){function a(a){return Math.min(Math.round(i(a)/16),15).toString(16)}return"#"+a(this._value[0])+a(this._value[1])+a(this._value[2])},hex6:function(){function a(a){var b=i(a).toString(16);return b.length<2?"0"+b:b}return"#"+a(this._value[0])+a(this._value[1])+a(this._value[2])},rgb:function(){var a=this._value;return[i(a[0]),i(a[1]),i(a[2])]},rgba:function(){var a=this._value;return[i(a[0]),i(a[1]),i(a[2]),a[3]]},rgb8:function(){var a=this._value;return[i(a[0]),i(a[1]),i(a[2])]},rgba8:function(){var a=this._value;return[i(a[0]),i(a[1]),i(a[2]),this.alpha8()]},float3:function(){return[this._value[0],this._value[1],this._value[2]]},float4:function(){return[this._value[0],this._value[1],this._value[2],this._value[3]]}};B.sub=B.subtract,B.mul=B.multiply;for(var C in B)t.prototype[C]=B[C];z.float3=function(a,b,c){return new t([a,b,c,1])},z.float4=function(a,b,c,d){return new t([a,b,c,d])},z.version="0.2.4",z.Color=t,"undefined"!=typeof b&&b.exports?b.exports=z:"undefined"!=typeof window&&(window.pusher=window.pusher||{},window.pusher.color=z)}()},{}],7:[function(a,b){!function c(a,d,e){function f(a,b){return this instanceof f?(g(a)?(b=a[1],a=a[0]):"object"==typeof a&&a&&(b=a.y,a=a.x),this.x=f.clean(a||0),void(this.y=f.clean(b||0))):new f(a,b)}var g=function(a){return"[object Array]"===Object.prototype.toString.call(a)};f.prototype={change:function(a){if(a)this.observers?this.observers.push(a):this.observers=[a];else if(this.observers)for(var b=this.observers.length-1;b>=0;b--)this.observers[b](this);return this},ignore:function(a){if(this.observers)for(var b=this.observers,c=b.length;c--;)b[c]===a&&b.splice(c,1);return this},set:function(a,b,c){return"number"!=typeof a&&(c=b,b=a.y,a=a.x),this.x===a&&this.y===b?this:(this.x=f.clean(a),this.y=f.clean(b),c!==!1?this.change():void 0)},zero:function(){return this.set(0,0)},clone:function(){return new this.constructor(this.x,this.y)},negate:function(a){return a?new this.constructor(-this.x,-this.y):this.set(-this.x,-this.y)},add:function(a,b){return b?new this.constructor(this.x+a.x,this.y+a.y):(this.x+=a.x,this.y+=a.y,this.change())},subtract:function(a,b){return b?new this.constructor(this.x-a.x,this.y-a.y):(this.x-=a.x,this.y-=a.y,this.change())},multiply:function(a,b){var c,d;return"number"!=typeof a?(c=a.x,d=a.y):c=d=a,b?new this.constructor(this.x*c,this.y*d):this.set(this.x*c,this.y*d)},rotate:function(a,b,c){var d,e,f=this.x,g=this.y,h=Math.cos(a),i=Math.sin(a);return b=b?-1:1,d=h*f-b*i*g,e=b*i*f+h*g,c?new this.constructor(d,e):this.set(d,e)},length:function(){var a=this.x,b=this.y;return Math.sqrt(a*a+b*b)},lengthSquared:function(){var a=this.x,b=this.y;return a*a+b*b},distance:function(a){var b=this.x-a.x,c=this.y-a.y;return Math.sqrt(b*b+c*c)},normalize:function(a){var b=this.length(),c=bc?c:e,h=f>d?d:f;return b?new this.constructor(g,h):this.set(g,h)},max:function(a,b){var c=this.x,d=this.y,e=a.x,f=a.y,g=c>e?c:e,h=d>f?d:f;return b?new this.constructor(g,h):this.set(g,h)},clamp:function(a,b,c){var d=this.min(b,!0).max(a);return c?d:this.set(d.x,d.y)},lerp:function(a,b){return this.add(a.subtract(this,!0).multiply(b),!0)},skew:function(){return new this.constructor(-this.y,this.x)},dot:function(a){return f.clean(this.x*a.x+a.y*this.y)},perpDot:function(a){return f.clean(this.x*a.y-this.y*a.x)},angleTo:function(a){return Math.atan2(this.perpDot(a),this.dot(a))},divide:function(a,b){var c,d;if("number"!=typeof a?(c=a.x,d=a.y):c=d=a,0===c||0===d)throw new Error("division by zero");if(isNaN(c)||isNaN(d))throw new Error("NaN detected");return b?new this.constructor(this.x/c,this.y/d):this.set(this.x/c,this.y/d)},isPointOnLine:function(a,b){return(a.y-this.y)*(a.x-b.x)===(a.y-b.y)*(a.x-this.x)},toArray:function(){return[this.x,this.y]},fromArray:function(a){return this.set(a[0],a[1])},toJSON:function(){return{x:this.x,y:this.y}},toString:function(){return"("+this.x+", "+this.y+")"},constructor:f},f.fromArray=function(a,b){return new(b||f)(a[0],a[1])},f.precision=d||8;var h=Math.pow(10,f.precision);return f.clean=a||function(a){if(isNaN(a))throw new Error("NaN detected");if(!isFinite(a))throw new Error("Infinity detected");return Math.round(a)===a?a:Math.round(a*h)/h},f.inject=c,a||(f.fast=c(function(a){return a}),"undefined"!=typeof b&&"object"==typeof b.exports?b.exports=f:window.Vec2=window.Vec2||f),f}()},{}],8:[function(a,b){var c,d=a("vec2"),e=a("./quadtree2helper"),f=a("./quadtree2validator"),g=a("./quadtree2quadrant");c=function(a,b,c){var h,i={objects_:{},quadrants_:{},ids_:1,quadrantIds_:1,autoId_:!0,inited_:!1,debug_:!1,size_:void 0,root_:void 0,quadrantObjectsLimit_:void 0,quadrantLevelLimit_:void 0,quadrantSizeLimit_:void 0},j=new f,k={p:"pos_",r:"rad_",id:"id_"},l={data:{necessary:{size_:j.isVec2,quadrantObjectsLimit_:j.isNumber,quadrantLevelLimit_:j.isNumber}},k:{necessary:{p:j.isVec2},c:{necessary:{r:j.isNumber}}}},m={nextId:function(){return i.ids_++},nextQuadrantId:function(a){var b=i.quadrantIds_;return i.quadrantIds_+=a||4,b},hasCollision:function(a,b){return a[k.r]+b[k.r]>a[k.p].distance(b[k.p])},removeQuadrantParentQuadrants:function(a,b){a.parent_&&b[a.parent_.id_]&&(delete b[a.parent_.id_],m.removeQuadrantParentQuadrants(a.parent_,b))},getSubtreeTopQuadrant:function p(a,b){return a.parent_&&b[a.parent_.id_]?p(a.parent_,b):a},removeQuadrantChildtree:function(a,b){var c,d=a.getChildren();for(c=0;ci.quadrantObjectsLimit_)){for(a.refactoring_=!0,b=0;b0?!1:(this.children_.push(new c(this.leftTop_,this.rad_,a++,this),new c(this.topMid_,this.rad_,a++,this),new c(this.leftMid_,this.rad_,a++,this),new c(this.center_,this.rad_,a++,this)),a)},looseChildren:function(){this.children_=[]},addObjects:function(a){var b;for(b in a)this.addObject(b,a[b])},addObject:function(a,b){this.objectCount_++,this.objects_[a]=b},removeObjects:function(a,b){var c;a||(a=[]);for(c in this.objects_)a.push({obj:this.objects_[c],quadrant:this}),delete this.objects_[c];return this.objectCount_=0,b&&1!==b||this.parent_&&this.parent_.removeObjects(a,1),b&&-1!==b||this.children_.forEach(function(b){b.removeObjects(a,-1)}),a},removeObject:function(a){var b=this.objects_[a];return this.objectCount_--,delete this.objects_[a],b},getObjectCountForLimit:function(){var a,b,c={};for(b in this.objects_)c[b]=!0;for(a=0;athis.rad_.x+b?!1:c.y>this.rad_.y+b?!1:c.x<=this.rad_.x?!0:c.y<=this.rad_.y?!0:(cornerDistSq=Math.pow(c.x-this.rad_.x,2)+Math.pow(c.y-this.rad_.y,2),cornerDistSq<=Math.pow(b,2))},hasChildren:function(){return 0!==this.getChildCount()},getChildCount:function(a){var b=this.children_.length;return a&&this.children_.forEach(function(c){b+=c.getChildCount(a)}),b},getChildren:function(a,b){return b||(b=[]),b.push.apply(b,this.children_),a&&this.children_.forEach(function(c){c.getChildren(a,b)}),b},getObjectsUp:function(a){var b;if(!a.quadrants[this.id_]){a.quadrants[this.id_]=!0;for(b in this.objects_)a.objects[b]=this.objects_[b];this.parent_&&this.parent_.getObjectsUp(a)}},getObjectsDown:function(a){var b;if(!a.quadrants[this.id_]){a.quadrants[this.id_]=!0;for(b in this.objects_)a.objects[b]=this.objects_[b];for(b=0;b>16&255)/255,this.g=(a>>8&255)/255,this.b=(255&a)/255,this},setRGB:function(a,b,c){return this.r=a,this.g=b,this.b=c,this},setHSL:function(a,b,c){if(0===b)this.r=this.g=this.b=c;else{var d=function(a,b,c){return 0>c&&(c+=1),c>1&&(c-=1),1/6>c?a+6*(b-a)*c:.5>c?b:2/3>c?a+6*(b-a)*(2/3-c):a},e=.5>=c?c*(1+b):c+b-c*b,f=2*c-e;this.r=d(f,e,a+1/3),this.g=d(f,e,a),this.b=d(f,e,a-1/3)}return this},setStyle:function(a){if(/^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test(a)){var b=/^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec(a);return this.r=Math.min(255,parseInt(b[1],10))/255,this.g=Math.min(255,parseInt(b[2],10))/255,this.b=Math.min(255,parseInt(b[3],10))/255,this}if(/^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test(a)){var b=/^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec(a);return this.r=Math.min(100,parseInt(b[1],10))/100,this.g=Math.min(100,parseInt(b[2],10))/100,this.b=Math.min(100,parseInt(b[3],10))/100,this}if(/^\#([0-9a-f]{6})$/i.test(a)){var b=/^\#([0-9a-f]{6})$/i.exec(a);return this.setHex(parseInt(b[1],16)),this}if(/^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test(a)){var b=/^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(a);return this.setHex(parseInt(b[1]+b[1]+b[2]+b[2]+b[3]+b[3],16)),this}return/^(\w+)$/i.test(a)?(this.setHex(e.ColorKeywords[a]),this):void 0},copy:function(a){return this.r=a.r,this.g=a.g,this.b=a.b,this},copyGammaToLinear:function(a){return this.r=a.r*a.r,this.g=a.g*a.g,this.b=a.b*a.b,this},copyLinearToGamma:function(a){return this.r=Math.sqrt(a.r),this.g=Math.sqrt(a.g),this.b=Math.sqrt(a.b),this},convertGammaToLinear:function(){var a=this.r,b=this.g,c=this.b;return this.r=a*a,this.g=b*b,this.b=c*c,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),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){var b,c,d=a||{h:0,s:0,l:0},e=this.r,f=this.g,g=this.b,h=Math.max(e,f,g),i=Math.min(e,f,g),j=(i+h)/2;if(i===h)b=0,c=0;else{var k=h-i;switch(c=.5>=j?k/(h+i):k/(2-h-i),h){case e:b=(f-g)/k+(g>f?6:0);break;case f:b=(g-e)/k+2;break;case g:b=(e-f)/k+4}b/=6}return d.h=b,d.s=c,d.l=j,d},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(a,b,c){var d=this.getHSL();return d.h+=a,d.s+=b,d.l+=c,this.setHSL(d.h,d.s,d.l),this},add:function(a){return this.r+=a.r,this.g+=a.g,this.b+=a.b,this},addColors:function(a,b){return this.r=a.r+b.r,this.g=a.g+b.g,this.b=a.b+b.b,this},addScalar:function(a){return this.r+=a,this.g+=a,this.b+=a,this},multiply:function(a){return this.r*=a.r,this.g*=a.g,this.b*=a.b,this},multiplyScalar:function(a){return this.r*=a,this.g*=a,this.b*=a,this},lerp:function(a,b){return this.r+=(a.r-this.r)*b,this.g+=(a.g-this.g)*b,this.b+=(a.b-this.b)*b,this},equals:function(a){return a.r===this.r&&a.g===this.g&&a.b===this.b},fromArray:function(a){return this.r=a[0],this.g=a[1],this.b=a[2],this},toArray:function(){return[this.r,this.g,this.b]},clone:function(){return(new e.Color).setRGB(this.r,this.g,this.b)}},e.ColorKeywords={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,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},e.Quaternion=function(a,b,c,d){this._x=a||0,this._y=b||0,this._z=c||0,this._w=void 0!==d?d:1},e.Quaternion.prototype={constructor:e.Quaternion,_x:0,_y:0,_z:0,_w:0,_euler:void 0,_updateEuler:function(){void 0!==this._euler&&this._euler.setFromQuaternion(this,void 0,!1)},get x(){return this._x},set x(a){this._x=a,this._updateEuler()},get y(){return this._y},set y(a){this._y=a,this._updateEuler()},get z(){return this._z},set z(a){this._z=a,this._updateEuler()},get w(){return this._w},set w(a){this._w=a,this._updateEuler()},set:function(a,b,c,d){return this._x=a,this._y=b,this._z=c,this._w=d,this._updateEuler(),this},copy:function(a){return this._x=a._x,this._y=a._y,this._z=a._z,this._w=a._w,this._updateEuler(),this},setFromEuler:function(a,b){if(a instanceof e.Euler==!1)throw new Error("ERROR: Quaternion's .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.");var c=Math.cos(a._x/2),d=Math.cos(a._y/2),f=Math.cos(a._z/2),g=Math.sin(a._x/2),h=Math.sin(a._y/2),i=Math.sin(a._z/2);return"XYZ"===a.order?(this._x=g*d*f+c*h*i,this._y=c*h*f-g*d*i,this._z=c*d*i+g*h*f,this._w=c*d*f-g*h*i):"YXZ"===a.order?(this._x=g*d*f+c*h*i,this._y=c*h*f-g*d*i,this._z=c*d*i-g*h*f,this._w=c*d*f+g*h*i):"ZXY"===a.order?(this._x=g*d*f-c*h*i,this._y=c*h*f+g*d*i,this._z=c*d*i+g*h*f,this._w=c*d*f-g*h*i):"ZYX"===a.order?(this._x=g*d*f-c*h*i,this._y=c*h*f+g*d*i,this._z=c*d*i-g*h*f,this._w=c*d*f+g*h*i):"YZX"===a.order?(this._x=g*d*f+c*h*i,this._y=c*h*f+g*d*i,this._z=c*d*i-g*h*f,this._w=c*d*f-g*h*i):"XZY"===a.order&&(this._x=g*d*f-c*h*i,this._y=c*h*f-g*d*i,this._z=c*d*i+g*h*f,this._w=c*d*f+g*h*i),b!==!1&&this._updateEuler(),this},setFromAxisAngle:function(a,b){var c=b/2,d=Math.sin(c);return this._x=a.x*d,this._y=a.y*d,this._z=a.z*d,this._w=Math.cos(c),this._updateEuler(),this},setFromRotationMatrix:function(a){var b,c=a.elements,d=c[0],e=c[4],f=c[8],g=c[1],h=c[5],i=c[9],j=c[2],k=c[6],l=c[10],m=d+h+l;return m>0?(b=.5/Math.sqrt(m+1),this._w=.25/b,this._x=(k-i)*b,this._y=(f-j)*b,this._z=(g-e)*b):d>h&&d>l?(b=2*Math.sqrt(1+d-h-l),this._w=(k-i)/b,this._x=.25*b,this._y=(e+g)/b,this._z=(f+j)/b):h>l?(b=2*Math.sqrt(1+h-d-l),this._w=(f-j)/b,this._x=(e+g)/b,this._y=.25*b,this._z=(i+k)/b):(b=2*Math.sqrt(1+l-d-h),this._w=(g-e)/b,this._x=(f+j)/b,this._y=(i+k)/b,this._z=.25*b),this._updateEuler(),this},inverse:function(){return this.conjugate().normalize(),this},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this._updateEuler(),this},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();return 0===a?(this._x=0,this._y=0,this._z=0,this._w=1):(a=1/a,this._x=this._x*a,this._y=this._y*a,this._z=this._z*a,this._w=this._w*a),this},multiply:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Quaternion's .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,i=b._z,j=b._w;return this._x=c*j+f*g+d*i-e*h,this._y=d*j+f*h+e*g-c*i,this._z=e*j+f*i+c*h-d*g,this._w=f*j-c*g-d*h-e*i,this._updateEuler(),this},multiplyVector3:function(a){return console.warn("DEPRECATED: Quaternion's .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead."),a.applyQuaternion(this)},slerp:function(a,b){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;if(0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a),g>=1)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.acos(g),i=Math.sqrt(1-g*g);if(Math.abs(i)<.001)return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var j=Math.sin((1-b)*h)/i,k=Math.sin(b*h)/i;return this._w=f*j+this._w*k,this._x=c*j+this._x*k,this._y=d*j+this._y*k,this._z=e*j+this._z*k,this._updateEuler(),this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a){return this._x=a[0],this._y=a[1],this._z=a[2],this._w=a[3],this._updateEuler(),this},toArray:function(){return[this._x,this._y,this._z,this._w]},clone:function(){return new e.Quaternion(this._x,this._y,this._z,this._w)}},e.Quaternion.slerp=function(a,b,c,d){return c.copy(a).slerp(b,d)},e.Vector2=function(a,b){this.x=a||0,this.y=b||0},e.Vector2.prototype={constructor:e.Vector2,set:function(a,b){return this.x=a,this.y=b,this},setX:function(a){return this.x=a,this},setY:function(a){return this.y=a,this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw new Error("index is out of range: "+a)}},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+a)}},copy:function(a){return this.x=a.x,this.y=a.y,this},add:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Vector2's .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b)):(this.x+=a.x,this.y+=a.y,this)},addVectors:function(a,b){return this.x=a.x+b.x,this.y=a.y+b.y,this},addScalar:function(a){return this.x+=a,this.y+=a,this},sub:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Vector2's .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b)):(this.x-=a.x,this.y-=a.y,this)},subVectors:function(a,b){return this.x=a.x-b.x,this.y=a.y-b.y,this},multiplyScalar:function(a){return this.x*=a,this.y*=a,this},divideScalar:function(a){if(0!==a){var b=1/a;this.x*=b,this.y*=b}else this.x=0,this.y=0;return this},min:function(a){return this.x>a.x&&(this.x=a.x),this.y>a.y&&(this.y=a.y),this},max:function(a){return this.xb.x&&(this.x=b.x),this.yb.y&&(this.y=b.y),this},clampScalar:function(){var a,b;return function(c,d){return void 0===a&&(a=new e.Vector2,b=new e.Vector2),a.set(c,c),b.set(d,d),this.clamp(a,b)}}(),floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.multiplyScalar(-1)},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},normalize:function(){return this.divideScalar(this.length())},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;return b*b+c*c},setLength:function(a){var b=this.length();return 0!==b&&a!==b&&this.multiplyScalar(a/b),this},lerp:function(a,b){return this.x+=(a.x-this.x)*b,this.y+=(a.y-this.y)*b,this},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a){return this.x=a[0],this.y=a[1],this},toArray:function(){return[this.x,this.y]},clone:function(){return new e.Vector2(this.x,this.y)}},e.Vector3=function(a,b,c){this.x=a||0,this.y=b||0,this.z=c||0},e.Vector3.prototype={constructor:e.Vector3,set:function(a,b,c){return this.x=a,this.y=b,this.z=c,this},setX:function(a){return this.x=a,this},setY:function(a){return this.y=a,this},setZ:function(a){return this.z=a,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 new Error("index is out of range: "+a)}},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+a)}},copy:function(a){return this.x=a.x,this.y=a.y,this.z=a.z,this},add:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Vector3's .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)},addScalar:function(a){return this.x+=a,this.y+=a,this.z+=a,this},addVectors:function(a,b){return this.x=a.x+b.x,this.y=a.y+b.y,this.z=a.z+b.z,this},sub:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Vector3's .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)},subVectors:function(a,b){return this.x=a.x-b.x,this.y=a.y-b.y,this.z=a.z-b.z,this},multiply:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Vector3's .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b)):(this.x*=a.x,this.y*=a.y,this.z*=a.z,this)},multiplyScalar:function(a){return this.x*=a,this.y*=a,this.z*=a,this},multiplyVectors:function(a,b){return this.x=a.x*b.x,this.y=a.y*b.y,this.z=a.z*b.z,this},applyEuler:function(){var a;return function(b){return b instanceof e.Euler==!1&&console.error("ERROR: Vector3's .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code."),void 0===a&&(a=new e.Quaternion),this.applyQuaternion(a.setFromEuler(b)),this}}(),applyAxisAngle:function(){var a;return function(b,c){return void 0===a&&(a=new e.Quaternion),this.applyQuaternion(a.setFromAxisAngle(b,c)),this}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z,e=a.elements;return this.x=e[0]*b+e[3]*c+e[6]*d,this.y=e[1]*b+e[4]*c+e[7]*d,this.z=e[2]*b+e[5]*c+e[8]*d,this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=a.elements;return this.x=e[0]*b+e[4]*c+e[8]*d+e[12],this.y=e[1]*b+e[5]*c+e[9]*d+e[13],this.z=e[2]*b+e[6]*c+e[10]*d+e[14],this},applyProjection:function(a){var b=this.x,c=this.y,d=this.z,e=a.elements,f=1/(e[3]*b+e[7]*c+e[11]*d+e[15]);return this.x=(e[0]*b+e[4]*c+e[8]*d+e[12])*f,this.y=(e[1]*b+e[5]*c+e[9]*d+e[13])*f,this.z=(e[2]*b+e[6]*c+e[10]*d+e[14])*f,this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z,h=a.w,i=h*b+f*d-g*c,j=h*c+g*b-e*d,k=h*d+e*c-f*b,l=-e*b-f*c-g*d;return this.x=i*h+l*-e+j*-g-k*-f,this.y=j*h+l*-f+k*-e-i*-g,this.z=k*h+l*-g+i*-f-j*-e,this},transformDirection:function(a){var b=this.x,c=this.y,d=this.z,e=a.elements;return this.x=e[0]*b+e[4]*c+e[8]*d,this.y=e[1]*b+e[5]*c+e[9]*d,this.z=e[2]*b+e[6]*c+e[10]*d,this.normalize(),this},divide:function(a){return this.x/=a.x,this.y/=a.y,this.z/=a.z,this},divideScalar:function(a){if(0!==a){var b=1/a;this.x*=b,this.y*=b,this.z*=b}else this.x=0,this.y=0,this.z=0;return this},min:function(a){return this.x>a.x&&(this.x=a.x),this.y>a.y&&(this.y=a.y),this.z>a.z&&(this.z=a.z),this},max:function(a){return this.xb.x&&(this.x=b.x),this.yb.y&&(this.y=b.y),this.zb.z&&(this.z=b.z),this},clampScalar:function(){var a,b;return function(c,d){return void 0===a&&(a=new e.Vector3,b=new e.Vector3),a.set(c,c,c),b.set(d,d,d),this.clamp(a,b)}}(),floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.multiplyScalar(-1)},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){var b=this.length();return 0!==b&&a!==b&&this.multiplyScalar(a/b),this},lerp:function(a,b){return this.x+=(a.x-this.x)*b,this.y+=(a.y-this.y)*b,this.z+=(a.z-this.z)*b,this},cross:function(a,b){if(void 0!==b)return console.warn("DEPRECATED: Vector3's .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;return this.x=d*a.z-e*a.y,this.y=e*a.x-c*a.z,this.z=c*a.y-d*a.x,this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;return this.x=d*h-e*g,this.y=e*f-c*h,this.z=c*g-d*f,this},projectOnVector:function(){var a,b;return function(c){return void 0===a&&(a=new e.Vector3),a.copy(c).normalize(),b=this.dot(a),this.copy(a).multiplyScalar(b)}}(),projectOnPlane:function(){var a;return function(b){return void 0===a&&(a=new e.Vector3),a.copy(this).projectOnVector(b),this.sub(a)}}(),reflect:function(){var a;return function(b){return void 0===a&&(a=new e.Vector3),this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){var b=this.dot(a)/(this.length()*a.length());return Math.acos(e.Math.clamp(b,-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,d=this.z-a.z;return b*b+c*c+d*d},setEulerFromRotationMatrix:function(){console.error("REMOVED: Vector3's setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.")},setEulerFromQuaternion:function(){console.error("REMOVED: Vector3's setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.")},getPositionFromMatrix:function(a){return console.warn("DEPRECATED: Vector3's .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code."),this.setFromMatrixPosition(a)},getScaleFromMatrix:function(a){return console.warn("DEPRECATED: Vector3's .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code."),this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){return console.warn("DEPRECATED: Vector3's .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code."),this.setFromMatrixColumn(a,b)},setFromMatrixPosition:function(a){return this.x=a.elements[12],this.y=a.elements[13],this.z=a.elements[14],this},setFromMatrixScale:function(a){var b=this.set(a.elements[0],a.elements[1],a.elements[2]).length(),c=this.set(a.elements[4],a.elements[5],a.elements[6]).length(),d=this.set(a.elements[8],a.elements[9],a.elements[10]).length();return this.x=b,this.y=c,this.z=d,this},setFromMatrixColumn:function(a,b){var c=4*a,d=b.elements;return this.x=d[c],this.y=d[c+1],this.z=d[c+2],this},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a){return this.x=a[0],this.y=a[1],this.z=a[2],this},toArray:function(){return[this.x,this.y,this.z]},clone:function(){return new e.Vector3(this.x,this.y,this.z)}},e.Vector4=function(a,b,c,d){this.x=a||0,this.y=b||0,this.z=c||0,this.w=void 0!==d?d:1},e.Vector4.prototype={constructor:e.Vector4,set:function(a,b,c,d){return this.x=a,this.y=b,this.z=c,this.w=d,this},setX:function(a){return this.x=a,this},setY:function(a){return this.y=a,this},setZ:function(a){return this.z=a,this},setW:function(a){return this.w=a,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 new Error("index is out of range: "+a)}},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+a)}},copy:function(a){return this.x=a.x,this.y=a.y,this.z=a.z,this.w=void 0!==a.w?a.w:1,this},add:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Vector4's .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,this)},addScalar:function(a){return this.x+=a,this.y+=a,this.z+=a,this.w+=a,this},addVectors:function(a,b){return this.x=a.x+b.x,this.y=a.y+b.y,this.z=a.z+b.z,this.w=a.w+b.w,this},sub:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Vector4's .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,this)},subVectors:function(a,b){return this.x=a.x-b.x,this.y=a.y-b.y,this.z=a.z-b.z,this.w=a.w-b.w,this},multiplyScalar:function(a){return this.x*=a,this.y*=a,this.z*=a,this.w*=a,this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w,f=a.elements;return this.x=f[0]*b+f[4]*c+f[8]*d+f[12]*e,this.y=f[1]*b+f[5]*c+f[9]*d+f[13]*e,this.z=f[2]*b+f[6]*c+f[10]*d+f[14]*e,this.w=f[3]*b+f[7]*c+f[11]*d+f[15]*e,this},divideScalar:function(a){if(0!==a){var b=1/a;this.x*=b,this.y*=b,this.z*=b,this.w*=b}else this.x=0,this.y=0,this.z=0,this.w=1;return this},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);return 1e-4>b?(this.x=1,this.y=0,this.z=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b),this},setAxisAngleFromRotationMatrix:function(a){var b,c,d,e,f=.01,g=.1,h=a.elements,i=h[0],j=h[4],k=h[8],l=h[1],m=h[5],n=h[9],o=h[2],p=h[6],q=h[10];if(Math.abs(j-l)s&&r>t?f>r?(c=0,d=.707106781,e=.707106781):(c=Math.sqrt(r),d=u/c,e=v/c):s>t?f>s?(c=.707106781,d=0,e=.707106781):(d=Math.sqrt(s),c=u/d,e=w/d):f>t?(c=.707106781,d=.707106781,e=0):(e=Math.sqrt(t),c=v/e,d=w/e),this.set(c,d,e,b),this}var x=Math.sqrt((p-n)*(p-n)+(k-o)*(k-o)+(l-j)*(l-j));return Math.abs(x)<.001&&(x=1),this.x=(p-n)/x,this.y=(k-o)/x,this.z=(l-j)/x,this.w=Math.acos((i+m+q-1)/2),this},min:function(a){return this.x>a.x&&(this.x=a.x),this.y>a.y&&(this.y=a.y),this.z>a.z&&(this.z=a.z),this.w>a.w&&(this.w=a.w),this},max:function(a){return this.xb.x&&(this.x=b.x),this.yb.y&&(this.y=b.y),this.zb.z&&(this.z=b.z),this.wb.w&&(this.w=b.w),this},clampScalar:function(){var a,b;return function(c,d){return void 0===a&&(a=new e.Vector4,b=new e.Vector4),a.set(c,c,c,c),b.set(d,d,d,d),this.clamp(a,b)}}(),floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this.w=this.w<0?Math.ceil(this.w):Math.floor(this.w),this},negate:function(){return this.multiplyScalar(-1)},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){var b=this.length();return 0!==b&&a!==b&&this.multiplyScalar(a/b),this},lerp:function(a,b){return 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,this},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a){return this.x=a[0],this.y=a[1],this.z=a[2],this.w=a[3],this},toArray:function(){return[this.x,this.y,this.z,this.w]},clone:function(){return new e.Vector4(this.x,this.y,this.z,this.w)}},e.Euler=function(a,b,c,d){this._x=a||0,this._y=b||0,this._z=c||0,this._order=d||e.Euler.DefaultOrder},e.Euler.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"],e.Euler.DefaultOrder="XYZ",e.Euler.prototype={constructor:e.Euler,_x:0,_y:0,_z:0,_order:e.Euler.DefaultOrder,_quaternion:void 0,_updateQuaternion:function(){void 0!==this._quaternion&&this._quaternion.setFromEuler(this,!1)},get x(){return this._x},set x(a){this._x=a,this._updateQuaternion()},get y(){return this._y},set y(a){this._y=a,this._updateQuaternion()},get z(){return this._z},set z(a){this._z=a,this._updateQuaternion()},get order(){return this._order},set order(a){this._order=a,this._updateQuaternion()},set:function(a,b,c,d){return this._x=a,this._y=b,this._z=c,this._order=d||this._order,this._updateQuaternion(),this},copy:function(a){return this._x=a._x,this._y=a._y,this._z=a._z,this._order=a._order,this._updateQuaternion(),this},setFromVector:function(a,b){return this._x=a.x,this._y=a.y,this._z=a.z,this._order=b||this._order,this._updateQuaternion(),this},setFromRotationMatrix:function(a,b){function c(a){return Math.min(Math.max(a,-1),1)}var d=a.elements,e=d[0],f=d[4],g=d[8],h=d[1],i=d[5],j=d[9],k=d[2],l=d[6],m=d[10]; -return b=b||this._order,"XYZ"===b?(this._y=Math.asin(c(g)),Math.abs(g)<.99999?(this._x=Math.atan2(-j,m),this._z=Math.atan2(-f,e)):(this._x=Math.atan2(l,i),this._z=0)):"YXZ"===b?(this._x=Math.asin(-c(j)),Math.abs(j)<.99999?(this._y=Math.atan2(g,m),this._z=Math.atan2(h,i)):(this._y=Math.atan2(-k,e),this._z=0)):"ZXY"===b?(this._x=Math.asin(c(l)),Math.abs(l)<.99999?(this._y=Math.atan2(-k,m),this._z=Math.atan2(-f,i)):(this._y=0,this._z=Math.atan2(h,e))):"ZYX"===b?(this._y=Math.asin(-c(k)),Math.abs(k)<.99999?(this._x=Math.atan2(l,m),this._z=Math.atan2(h,e)):(this._x=0,this._z=Math.atan2(-f,i))):"YZX"===b?(this._z=Math.asin(c(h)),Math.abs(h)<.99999?(this._x=Math.atan2(-j,i),this._y=Math.atan2(-k,e)):(this._x=0,this._y=Math.atan2(g,m))):"XZY"===b?(this._z=Math.asin(-c(f)),Math.abs(f)<.99999?(this._x=Math.atan2(l,i),this._y=Math.atan2(g,e)):(this._x=Math.atan2(-j,m),this._y=0)):console.warn("WARNING: Euler.setFromRotationMatrix() given unsupported order: "+b),this._order=b,this._updateQuaternion(),this},setFromQuaternion:function(a,b,c){function d(a){return Math.min(Math.max(a,-1),1)}var e=a.x*a.x,f=a.y*a.y,g=a.z*a.z,h=a.w*a.w;return b=b||this._order,"XYZ"===b?(this._x=Math.atan2(2*(a.x*a.w-a.y*a.z),h-e-f+g),this._y=Math.asin(d(2*(a.x*a.z+a.y*a.w))),this._z=Math.atan2(2*(a.z*a.w-a.x*a.y),h+e-f-g)):"YXZ"===b?(this._x=Math.asin(d(2*(a.x*a.w-a.y*a.z))),this._y=Math.atan2(2*(a.x*a.z+a.y*a.w),h-e-f+g),this._z=Math.atan2(2*(a.x*a.y+a.z*a.w),h-e+f-g)):"ZXY"===b?(this._x=Math.asin(d(2*(a.x*a.w+a.y*a.z))),this._y=Math.atan2(2*(a.y*a.w-a.z*a.x),h-e-f+g),this._z=Math.atan2(2*(a.z*a.w-a.x*a.y),h-e+f-g)):"ZYX"===b?(this._x=Math.atan2(2*(a.x*a.w+a.z*a.y),h-e-f+g),this._y=Math.asin(d(2*(a.y*a.w-a.x*a.z))),this._z=Math.atan2(2*(a.x*a.y+a.z*a.w),h+e-f-g)):"YZX"===b?(this._x=Math.atan2(2*(a.x*a.w-a.z*a.y),h-e+f-g),this._y=Math.atan2(2*(a.y*a.w-a.x*a.z),h+e-f-g),this._z=Math.asin(d(2*(a.x*a.y+a.z*a.w)))):"XZY"===b?(this._x=Math.atan2(2*(a.x*a.w+a.y*a.z),h-e+f-g),this._y=Math.atan2(2*(a.x*a.z+a.y*a.w),h+e-f-g),this._z=Math.asin(d(2*(a.z*a.w-a.x*a.y)))):console.warn("WARNING: Euler.setFromQuaternion() given unsupported order: "+b),this._order=b,c!==!1&&this._updateQuaternion(),this},reorder:function(){var a=new e.Quaternion;return function(b){a.setFromEuler(this),this.setFromQuaternion(a,b)}}(),fromArray:function(a){return this._x=a[0],this._y=a[1],this._z=a[2],void 0!==a[3]&&(this._order=a[3]),this._updateQuaternion(),this},toArray:function(){return[this._x,this._y,this._z,this._order]},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},clone:function(){return new e.Euler(this._x,this._y,this._z,this._order)}},e.Line3=function(a,b){this.start=void 0!==a?a:new e.Vector3,this.end=void 0!==b?b:new e.Vector3},e.Line3.prototype={constructor:e.Line3,set:function(a,b){return this.start.copy(a),this.end.copy(b),this},copy:function(a){return this.start.copy(a.start),this.end.copy(a.end),this},center:function(a){var b=a||new e.Vector3;return b.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){var b=a||new e.Vector3;return b.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){var c=b||new e.Vector3;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new e.Vector3,b=new e.Vector3;return function(c,d){a.subVectors(c,this.start),b.subVectors(this.end,this.start);var f=b.dot(b),g=b.dot(a),h=g/f;return d&&(h=e.Math.clamp(h,0,1)),h}}(),closestPointToPoint:function(a,b,c){var d=this.closestPointToPointParameter(a,b),f=c||new e.Vector3;return this.delta(f).multiplyScalar(d).add(this.start)},applyMatrix4:function(a){return this.start.applyMatrix4(a),this.end.applyMatrix4(a),this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)},clone:function(){return(new e.Line3).copy(this)}},e.Box2=function(a,b){this.min=void 0!==a?a:new e.Vector2(1/0,1/0),this.max=void 0!==b?b:new e.Vector2(-1/0,-1/0)},e.Box2.prototype={constructor:e.Box2,set:function(a,b){return this.min.copy(a),this.max.copy(b),this},setFromPoints:function(a){if(a.length>0){var b=a[0];this.min.copy(b),this.max.copy(b);for(var c=1,d=a.length;d>c;c++)b=a[c],b.xthis.max.x&&(this.max.x=b.x),b.ythis.max.y&&(this.max.y=b.y)}else this.makeEmpty();return this},setFromCenterAndSize:function(){var a=new e.Vector2;return function(b,c){var d=a.copy(c).multiplyScalar(.5);return this.min.copy(b).sub(d),this.max.copy(b).add(d),this}}(),copy:function(a){return this.min.copy(a.min),this.max.copy(a.max),this},makeEmpty:function(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this},empty:function(){return this.max.xthis.max.x||a.ythis.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?!0:!1},getParameter:function(a,b){var c=b||new e.Vector2;return c.set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},isIntersectionBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y?!1:!0},clampPoint:function(a,b){var c=b||new e.Vector2;return c.copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new e.Vector2;return function(b){var c=a.copy(b).clamp(this.min,this.max);return c.sub(b).length()}}(),intersect:function(a){return this.min.max(a.min),this.max.min(a.max),this},union:function(a){return this.min.min(a.min),this.max.max(a.max),this},translate:function(a){return this.min.add(a),this.max.add(a),this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)},clone:function(){return(new e.Box2).copy(this)}},e.Box3=function(a,b){this.min=void 0!==a?a:new e.Vector3(1/0,1/0,1/0),this.max=void 0!==b?b:new e.Vector3(-1/0,-1/0,-1/0)},e.Box3.prototype={constructor:e.Box3,set:function(a,b){return this.min.copy(a),this.max.copy(b),this},addPoint:function(a){a.xthis.max.x&&(this.max.x=a.x),a.ythis.max.y&&(this.max.y=a.y),a.zthis.max.z&&(this.max.z=a.z)},setFromPoints:function(a){if(a.length>0){var b=a[0];this.min.copy(b),this.max.copy(b);for(var c=1,d=a.length;d>c;c++)this.addPoint(a[c])}else this.makeEmpty();return this},setFromCenterAndSize:function(){var a=new e.Vector3;return function(b,c){var d=a.copy(c).multiplyScalar(.5);return this.min.copy(b).sub(d),this.max.copy(b).add(d),this}}(),setFromObject:function(){var a=new e.Vector3;return function(b){var c=this;return b.updateMatrixWorld(!0),this.makeEmpty(),b.traverse(function(b){if(void 0!==b.geometry&&void 0!==b.geometry.vertices)for(var d=b.geometry.vertices,e=0,f=d.length;f>e;e++)a.copy(d[e]),a.applyMatrix4(b.matrixWorld),c.expandByPoint(a)}),this}}(),copy:function(a){return this.min.copy(a.min),this.max.copy(a.max),this},makeEmpty:function(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this},empty:function(){return this.max.xthis.max.x||a.ythis.max.y||a.zthis.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z?!0:!1},getParameter:function(a,b){var c=b||new e.Vector3;return c.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))},isIntersectionBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y||a.max.zthis.max.z?!1:!0},clampPoint:function(a,b){var c=b||new e.Vector3;return c.copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new e.Vector3;return function(b){var c=a.copy(b).clamp(this.min,this.max);return c.sub(b).length()}}(),getBoundingSphere:function(){var a=new e.Vector3;return function(b){var c=b||new e.Sphere;return c.center=this.center(),c.radius=.5*this.size(a).length(),c}}(),intersect:function(a){return this.min.max(a.min),this.max.min(a.max),this},union:function(a){return this.min.min(a.min),this.max.max(a.max),this},applyMatrix4:function(){var a=[new e.Vector3,new e.Vector3,new e.Vector3,new e.Vector3,new e.Vector3,new e.Vector3,new e.Vector3,new e.Vector3];return function(b){return a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b),a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b),a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b),a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b),a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b),a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b),a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b),a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b),this.makeEmpty(),this.setFromPoints(a),this}}(),translate:function(a){return this.min.add(a),this.max.add(a),this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)},clone:function(){return(new e.Box3).copy(this)}},e.Matrix3=function(a,b,c,d,e,f,g,h,i){this.elements=new Float32Array(9),this.set(void 0!==a?a:1,b||0,c||0,d||0,void 0!==e?e:1,f||0,g||0,h||0,void 0!==i?i:1)},e.Matrix3.prototype={constructor:e.Matrix3,set:function(a,b,c,d,e,f,g,h,i){var j=this.elements;return j[0]=a,j[3]=b,j[6]=c,j[1]=d,j[4]=e,j[7]=f,j[2]=g,j[5]=h,j[8]=i,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},copy:function(a){var b=a.elements;return this.set(b[0],b[3],b[6],b[1],b[4],b[7],b[2],b[5],b[8]),this},multiplyVector3:function(a){return console.warn("DEPRECATED: Matrix3's .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead."),a.applyMatrix3(this)},multiplyVector3Array:function(){var a=new e.Vector3;return function(b){for(var c=0,d=b.length;d>c;c+=3)a.x=b[c],a.y=b[c+1],a.z=b[c+2],a.applyMatrix3(this),b[c]=a.x,b[c+1]=a.y,b[c+2]=a.z;return b}}(),multiplyScalar:function(a){var b=this.elements;return b[0]*=a,b[3]*=a,b[6]*=a,b[1]*=a,b[4]*=a,b[7]*=a,b[2]*=a,b[5]*=a,b[8]*=a,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],i=a[7],j=a[8];return b*f*j-b*g*i-c*e*j+c*g*h+d*e*i-d*f*h},getInverse:function(a,b){var c=a.elements,d=this.elements;d[0]=c[10]*c[5]-c[6]*c[9],d[1]=-c[10]*c[1]+c[2]*c[9],d[2]=c[6]*c[1]-c[2]*c[5],d[3]=-c[10]*c[4]+c[6]*c[8],d[4]=c[10]*c[0]-c[2]*c[8],d[5]=-c[6]*c[0]+c[2]*c[4],d[6]=c[9]*c[4]-c[5]*c[8],d[7]=-c[9]*c[0]+c[1]*c[8],d[8]=c[5]*c[0]-c[1]*c[4];var e=c[0]*d[0]+c[1]*d[3]+c[2]*d[6];if(0===e){var f="Matrix3.getInverse(): can't invert matrix, determinant is 0";if(b)throw new Error(f);return console.warn(f),this.identity(),this}return this.multiplyScalar(1/e),this},transpose:function(){var a,b=this.elements;return a=b[1],b[1]=b[3],b[3]=a,a=b[2],b[2]=b[6],b[6]=a,a=b[5],b[5]=b[7],b[7]=a,this},getNormalMatrix:function(a){return this.getInverse(a).transpose(),this},transposeIntoArray:function(a){var b=this.elements;return 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],this},fromArray:function(a){return this.elements.set(a),this},toArray:function(){var a=this.elements;return[a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]]},clone:function(){var a=this.elements;return new e.Matrix3(a[0],a[3],a[6],a[1],a[4],a[7],a[2],a[5],a[8])}},e.Matrix4=function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){this.elements=new Float32Array(16);var q=this.elements;q[0]=void 0!==a?a:1,q[4]=b||0,q[8]=c||0,q[12]=d||0,q[1]=e||0,q[5]=void 0!==f?f:1,q[9]=g||0,q[13]=h||0,q[2]=i||0,q[6]=j||0,q[10]=void 0!==k?k:1,q[14]=l||0,q[3]=m||0,q[7]=n||0,q[11]=o||0,q[15]=void 0!==p?p:1},e.Matrix4.prototype={constructor:e.Matrix4,set:function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){var q=this.elements;return q[0]=a,q[4]=b,q[8]=c,q[12]=d,q[1]=e,q[5]=f,q[9]=g,q[13]=h,q[2]=i,q[6]=j,q[10]=k,q[14]=l,q[3]=m,q[7]=n,q[11]=o,q[15]=p,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},copy:function(a){return this.elements.set(a.elements),this},extractPosition:function(a){return console.warn("DEPRECATED: Matrix4's .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(a)},copyPosition:function(a){var b=this.elements,c=a.elements;return b[12]=c[12],b[13]=c[13],b[14]=c[14],this},extractRotation:function(){var a=new e.Vector3;return function(b){var c=this.elements,d=b.elements,e=1/a.set(d[0],d[1],d[2]).length(),f=1/a.set(d[4],d[5],d[6]).length(),g=1/a.set(d[8],d[9],d[10]).length();return c[0]=d[0]*e,c[1]=d[1]*e,c[2]=d[2]*e,c[4]=d[4]*f,c[5]=d[5]*f,c[6]=d[6]*f,c[8]=d[8]*g,c[9]=d[9]*g,c[10]=d[10]*g,this}}(),makeRotationFromEuler:function(a){a instanceof e.Euler==!1&&console.error("ERROR: Matrix's .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.");var b=this.elements,c=a.x,d=a.y,f=a.z,g=Math.cos(c),h=Math.sin(c),i=Math.cos(d),j=Math.sin(d),k=Math.cos(f),l=Math.sin(f);if("XYZ"===a.order){var m=g*k,n=g*l,o=h*k,p=h*l;b[0]=i*k,b[4]=-i*l,b[8]=j,b[1]=n+o*j,b[5]=m-p*j,b[9]=-h*i,b[2]=p-m*j,b[6]=o+n*j,b[10]=g*i}else if("YXZ"===a.order){var q=i*k,r=i*l,s=j*k,t=j*l;b[0]=q+t*h,b[4]=s*h-r,b[8]=g*j,b[1]=g*l,b[5]=g*k,b[9]=-h,b[2]=r*h-s,b[6]=t+q*h,b[10]=g*i}else if("ZXY"===a.order){var q=i*k,r=i*l,s=j*k,t=j*l;b[0]=q-t*h,b[4]=-g*l,b[8]=s+r*h,b[1]=r+s*h,b[5]=g*k,b[9]=t-q*h,b[2]=-g*j,b[6]=h,b[10]=g*i}else if("ZYX"===a.order){var m=g*k,n=g*l,o=h*k,p=h*l;b[0]=i*k,b[4]=o*j-n,b[8]=m*j+p,b[1]=i*l,b[5]=p*j+m,b[9]=n*j-o,b[2]=-j,b[6]=h*i,b[10]=g*i}else if("YZX"===a.order){var u=g*i,v=g*j,w=h*i,x=h*j;b[0]=i*k,b[4]=x-u*l,b[8]=w*l+v,b[1]=l,b[5]=g*k,b[9]=-h*k,b[2]=-j*k,b[6]=v*l+w,b[10]=u-x*l}else if("XZY"===a.order){var u=g*i,v=g*j,w=h*i,x=h*j;b[0]=i*k,b[4]=-l,b[8]=j*k,b[1]=u*l+x,b[5]=g*k,b[9]=v*l-w,b[2]=w*l-v,b[6]=h*k,b[10]=x*l+u}return b[3]=0,b[7]=0,b[11]=0,b[12]=0,b[13]=0,b[14]=0,b[15]=1,this},setRotationFromQuaternion:function(a){return console.warn("DEPRECATED: Matrix4's .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code."),this.makeRotationFromQuaternion(a)},makeRotationFromQuaternion:function(a){var b=this.elements,c=a.x,d=a.y,e=a.z,f=a.w,g=c+c,h=d+d,i=e+e,j=c*g,k=c*h,l=c*i,m=d*h,n=d*i,o=e*i,p=f*g,q=f*h,r=f*i;return b[0]=1-(m+o),b[4]=k-r,b[8]=l+q,b[1]=k+r,b[5]=1-(j+o),b[9]=n-p,b[2]=l-q,b[6]=n+p,b[10]=1-(j+m),b[3]=0,b[7]=0,b[11]=0,b[12]=0,b[13]=0,b[14]=0,b[15]=1,this},lookAt:function(){var a=new e.Vector3,b=new e.Vector3,c=new e.Vector3;return function(d,e,f){var g=this.elements;return c.subVectors(d,e).normalize(),0===c.length()&&(c.z=1),a.crossVectors(f,c).normalize(),0===a.length()&&(c.x+=1e-4,a.crossVectors(f,c).normalize()),b.crossVectors(c,a),g[0]=a.x,g[4]=b.x,g[8]=c.x,g[1]=a.y,g[5]=b.y,g[9]=c.y,g[2]=a.z,g[6]=b.z,g[10]=c.z,this}}(),multiply:function(a,b){return void 0!==b?(console.warn("DEPRECATED: Matrix4's .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],i=c[12],j=c[1],k=c[5],l=c[9],m=c[13],n=c[2],o=c[6],p=c[10],q=c[14],r=c[3],s=c[7],t=c[11],u=c[15],v=d[0],w=d[4],x=d[8],y=d[12],z=d[1],A=d[5],B=d[9],C=d[13],D=d[2],E=d[6],F=d[10],G=d[14],H=d[3],I=d[7],J=d[11],K=d[15];return e[0]=f*v+g*z+h*D+i*H,e[4]=f*w+g*A+h*E+i*I,e[8]=f*x+g*B+h*F+i*J,e[12]=f*y+g*C+h*G+i*K,e[1]=j*v+k*z+l*D+m*H,e[5]=j*w+k*A+l*E+m*I,e[9]=j*x+k*B+l*F+m*J,e[13]=j*y+k*C+l*G+m*K,e[2]=n*v+o*z+p*D+q*H,e[6]=n*w+o*A+p*E+q*I,e[10]=n*x+o*B+p*F+q*J,e[14]=n*y+o*C+p*G+q*K,e[3]=r*v+s*z+t*D+u*H,e[7]=r*w+s*A+t*E+u*I,e[11]=r*x+s*B+t*F+u*J,e[15]=r*y+s*C+t*G+u*K,this},multiplyToArray:function(a,b,c){var d=this.elements;return this.multiplyMatrices(a,b),c[0]=d[0],c[1]=d[1],c[2]=d[2],c[3]=d[3],c[4]=d[4],c[5]=d[5],c[6]=d[6],c[7]=d[7],c[8]=d[8],c[9]=d[9],c[10]=d[10],c[11]=d[11],c[12]=d[12],c[13]=d[13],c[14]=d[14],c[15]=d[15],this},multiplyScalar:function(a){var b=this.elements;return b[0]*=a,b[4]*=a,b[8]*=a,b[12]*=a,b[1]*=a,b[5]*=a,b[9]*=a,b[13]*=a,b[2]*=a,b[6]*=a,b[10]*=a,b[14]*=a,b[3]*=a,b[7]*=a,b[11]*=a,b[15]*=a,this},multiplyVector3:function(a){return console.warn("DEPRECATED: Matrix4's .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead."),a.applyProjection(this)},multiplyVector4:function(a){return console.warn("DEPRECATED: Matrix4's .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead."),a.applyMatrix4(this)},multiplyVector3Array:function(){var a=new e.Vector3;return function(b){for(var c=0,d=b.length;d>c;c+=3)a.x=b[c],a.y=b[c+1],a.z=b[c+2],a.applyProjection(this),b[c]=a.x,b[c+1]=a.y,b[c+2]=a.z;return b}}(),rotateAxis:function(a){console.warn("DEPRECATED: Matrix4's .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead."),a.transformDirection(this)},crossVector:function(a){return console.warn("DEPRECATED: Matrix4's .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead."),a.applyMatrix4(this)},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],i=a[13],j=a[2],k=a[6],l=a[10],m=a[14],n=a[3],o=a[7],p=a[11],q=a[15];return n*(+e*h*k-d*i*k-e*g*l+c*i*l+d*g*m-c*h*m)+o*(+b*h*m-b*i*l+e*f*l-d*f*m+d*i*j-e*h*j)+p*(+b*i*k-b*g*m-e*f*k+c*f*m+e*g*j-c*i*j)+q*(-d*g*j-b*h*k+b*g*l+d*f*k-c*f*l+c*h*j)},transpose:function(){var a,b=this.elements;return a=b[1],b[1]=b[4],b[4]=a,a=b[2],b[2]=b[8],b[8]=a,a=b[6],b[6]=b[9],b[9]=a,a=b[3],b[3]=b[12],b[12]=a,a=b[7],b[7]=b[13],b[13]=a,a=b[11],b[11]=b[14],b[14]=a,this},flattenToArray:function(a){var b=this.elements;return a[0]=b[0],a[1]=b[1],a[2]=b[2],a[3]=b[3],a[4]=b[4],a[5]=b[5],a[6]=b[6],a[7]=b[7],a[8]=b[8],a[9]=b[9],a[10]=b[10],a[11]=b[11],a[12]=b[12],a[13]=b[13],a[14]=b[14],a[15]=b[15],a},flattenToArrayOffset:function(a,b){var c=this.elements;return a[b]=c[0],a[b+1]=c[1],a[b+2]=c[2],a[b+3]=c[3],a[b+4]=c[4],a[b+5]=c[5],a[b+6]=c[6],a[b+7]=c[7],a[b+8]=c[8],a[b+9]=c[9],a[b+10]=c[10],a[b+11]=c[11],a[b+12]=c[12],a[b+13]=c[13],a[b+14]=c[14],a[b+15]=c[15],a},getPosition:function(){var a=new e.Vector3;return function(){console.warn("DEPRECATED: Matrix4's .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");var b=this.elements;return a.set(b[12],b[13],b[14])}}(),setPosition:function(a){var b=this.elements;return b[12]=a.x,b[13]=a.y,b[14]=a.z,this},getInverse:function(a,b){var c=this.elements,d=a.elements,e=d[0],f=d[4],g=d[8],h=d[12],i=d[1],j=d[5],k=d[9],l=d[13],m=d[2],n=d[6],o=d[10],p=d[14],q=d[3],r=d[7],s=d[11],t=d[15];c[0]=k*p*r-l*o*r+l*n*s-j*p*s-k*n*t+j*o*t,c[4]=h*o*r-g*p*r-h*n*s+f*p*s+g*n*t-f*o*t,c[8]=g*l*r-h*k*r+h*j*s-f*l*s-g*j*t+f*k*t,c[12]=h*k*n-g*l*n-h*j*o+f*l*o+g*j*p-f*k*p,c[1]=l*o*q-k*p*q-l*m*s+i*p*s+k*m*t-i*o*t,c[5]=g*p*q-h*o*q+h*m*s-e*p*s-g*m*t+e*o*t,c[9]=h*k*q-g*l*q-h*i*s+e*l*s+g*i*t-e*k*t,c[13]=g*l*m-h*k*m+h*i*o-e*l*o-g*i*p+e*k*p,c[2]=j*p*q-l*n*q+l*m*r-i*p*r-j*m*t+i*n*t,c[6]=h*n*q-f*p*q-h*m*r+e*p*r+f*m*t-e*n*t,c[10]=f*l*q-h*j*q+h*i*r-e*l*r-f*i*t+e*j*t,c[14]=h*j*m-f*l*m-h*i*n+e*l*n+f*i*p-e*j*p,c[3]=k*n*q-j*o*q-k*m*r+i*o*r+j*m*s-i*n*s,c[7]=f*o*q-g*n*q+g*m*r-e*o*r-f*m*s+e*n*s,c[11]=g*j*q-f*k*q-g*i*r+e*k*r+f*i*s-e*j*s,c[15]=f*k*m-g*j*m+g*i*n-e*k*n-f*i*o+e*j*o;var u=e*c[0]+i*c[4]+m*c[8]+q*c[12];if(0==u){var v="Matrix4.getInverse(): can't invert matrix, determinant is 0";if(b)throw new Error(v);return console.warn(v),this.identity(),this}return this.multiplyScalar(1/u),this},translate:function(){console.warn("DEPRECATED: Matrix4's .translate() has been removed.")},rotateX:function(){console.warn("DEPRECATED: Matrix4's .rotateX() has been removed.")},rotateY:function(){console.warn("DEPRECATED: Matrix4's .rotateY() has been removed.")},rotateZ:function(){console.warn("DEPRECATED: Matrix4's .rotateZ() has been removed.")},rotateByAxis:function(){console.warn("DEPRECATED: Matrix4's .rotateByAxis() has been removed.")},scale:function(a){var b=this.elements,c=a.x,d=a.y,e=a.z;return b[0]*=c,b[4]*=d,b[8]*=e,b[1]*=c,b[5]*=d,b[9]*=e,b[2]*=c,b[6]*=d,b[10]*=e,b[3]*=c,b[7]*=d,b[11]*=e,this},getMaxScaleOnAxis:function(){var a=this.elements,b=a[0]*a[0]+a[1]*a[1]+a[2]*a[2],c=a[4]*a[4]+a[5]*a[5]+a[6]*a[6],d=a[8]*a[8]+a[9]*a[9]+a[10]*a[10];return Math.sqrt(Math.max(b,Math.max(c,d)))},makeTranslation:function(a,b,c){return this.set(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1),this},makeRotationX:function(a){var b=Math.cos(a),c=Math.sin(a);return this.set(1,0,0,0,0,b,-c,0,0,c,b,0,0,0,0,1),this},makeRotationY:function(a){var b=Math.cos(a),c=Math.sin(a);return this.set(b,0,c,0,0,1,0,0,-c,0,b,0,0,0,0,1),this},makeRotationZ:function(a){var b=Math.cos(a),c=Math.sin(a);return this.set(b,-c,0,0,c,b,0,0,0,0,1,0,0,0,0,1),this},makeRotationAxis:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=1-c,f=a.x,g=a.y,h=a.z,i=e*f,j=e*g;return this.set(i*f+c,i*g-d*h,i*h+d*g,0,i*g+d*h,j*g+c,j*h-d*f,0,i*h-d*g,j*h+d*f,e*h*h+c,0,0,0,0,1),this},makeScale:function(a,b,c){return this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1),this},compose:function(a,b,c){return this.makeRotationFromQuaternion(b),this.scale(c),this.setPosition(a),this},decompose:function(){var a=new e.Vector3,b=new e.Matrix4;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(),i=a.set(f[8],f[9],f[10]).length(),j=this.determinant();0>j&&(g=-g),c.x=f[12],c.y=f[13],c.z=f[14],b.elements.set(this.elements);var k=1/g,l=1/h,m=1/i;return b.elements[0]*=k,b.elements[1]*=k,b.elements[2]*=k,b.elements[4]*=l,b.elements[5]*=l,b.elements[6]*=l,b.elements[8]*=m,b.elements[9]*=m,b.elements[10]*=m,d.setFromRotationMatrix(b),e.x=g,e.y=h,e.z=i,this}}(),makeFrustum:function(a,b,c,d,e,f){var g=this.elements,h=2*e/(b-a),i=2*e/(d-c),j=(b+a)/(b-a),k=(d+c)/(d-c),l=-(f+e)/(f-e),m=-2*f*e/(f-e);return g[0]=h,g[4]=0,g[8]=j,g[12]=0,g[1]=0,g[5]=i,g[9]=k,g[13]=0,g[2]=0,g[6]=0,g[10]=l,g[14]=m,g[3]=0,g[7]=0,g[11]=-1,g[15]=0,this},makePerspective:function(a,b,c,d){var f=c*Math.tan(e.Math.degToRad(.5*a)),g=-f,h=g*b,i=f*b;return this.makeFrustum(h,i,g,f,c,d)},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=b-a,i=c-d,j=f-e,k=(b+a)/h,l=(c+d)/i,m=(f+e)/j;return g[0]=2/h,g[4]=0,g[8]=0,g[12]=-k,g[1]=0,g[5]=2/i,g[9]=0,g[13]=-l,g[2]=0,g[6]=0,g[10]=-2/j,g[14]=-m,g[3]=0,g[7]=0,g[11]=0,g[15]=1,this},fromArray:function(a){return this.elements.set(a),this},toArray:function(){var a=this.elements;return[a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],a[12],a[13],a[14],a[15]]},clone:function(){var a=this.elements;return new e.Matrix4(a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15])}},e.Ray=function(a,b){this.origin=void 0!==a?a:new e.Vector3,this.direction=void 0!==b?b:new e.Vector3},e.Ray.prototype={constructor:e.Ray,set:function(a,b){return this.origin.copy(a),this.direction.copy(b),this},copy:function(a){return this.origin.copy(a.origin),this.direction.copy(a.direction),this},at:function(a,b){var c=b||new e.Vector3;return c.copy(this.direction).multiplyScalar(a).add(this.origin)},recast:function(){var a=new e.Vector3;return function(b){return this.origin.copy(this.at(b,a)),this}}(),closestPointToPoint:function(a,b){var c=b||new e.Vector3;c.subVectors(a,this.origin);var d=c.dot(this.direction);return 0>d?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)},distanceToPoint:function(){var a=new e.Vector3;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);return 0>c?this.origin.distanceTo(b):(a.copy(this.direction).multiplyScalar(c).add(this.origin),a.distanceTo(b))}}(),distanceSqToSegment:function(a,b,c,d){var e,f,g,h,i=a.clone().add(b).multiplyScalar(.5),j=b.clone().sub(a).normalize(),k=.5*a.distanceTo(b),l=this.origin.clone().sub(i),m=-this.direction.dot(j),n=l.dot(this.direction),o=-l.dot(j),p=l.lengthSq(),q=Math.abs(1-m*m);if(q>=0)if(e=m*o-n,f=m*n-o,h=k*q,e>=0)if(f>=-h)if(h>=f){var r=1/q;e*=r,f*=r,g=e*(e+m*f+2*n)+f*(m*e+f+2*o)+p}else f=k,e=Math.max(0,-(m*f+n)),g=-e*e+f*(f+2*o)+p;else f=-k,e=Math.max(0,-(m*f+n)),g=-e*e+f*(f+2*o)+p;else-h>=f?(e=Math.max(0,-(-m*k+n)),f=e>0?-k:Math.min(Math.max(-k,-o),k),g=-e*e+f*(f+2*o)+p):h>=f?(e=0,f=Math.min(Math.max(-k,-o),k),g=f*(f+2*o)+p):(e=Math.max(0,-(m*k+n)),f=e>0?k:Math.min(Math.max(-k,-o),k),g=-e*e+f*(f+2*o)+p);else f=m>0?-k:k,e=Math.max(0,-(m*f+n)),g=-e*e+f*(f+2*o)+p;return c&&c.copy(this.direction.clone().multiplyScalar(e).add(this.origin)),d&&d.copy(j.clone().multiplyScalar(f).add(i)),g},isIntersectionSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},isIntersectionPlane:function(a){var b=a.distanceToPoint(this.origin);if(0===b)return!0;var c=a.normal.dot(this.direction);return 0>c*b?!0:!1},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0==b)return 0==a.distanceToPoint(this.origin)?0:null;var c=-(this.origin.dot(a.normal)+a.constant)/b;return c>=0?c:null},intersectPlane:function(a,b){var c=this.distanceToPlane(a);return null===c?null:this.at(c,b)},isIntersectionBox:function(){var a=new e.Vector3;return function(b){return null!==this.intersectBox(b,a)}}(),intersectBox:function(a,b){var c,d,e,f,g,h,i=1/this.direction.x,j=1/this.direction.y,k=1/this.direction.z,l=this.origin;return i>=0?(c=(a.min.x-l.x)*i,d=(a.max.x-l.x)*i):(c=(a.max.x-l.x)*i,d=(a.min.x-l.x)*i),j>=0?(e=(a.min.y-l.y)*j,f=(a.max.y-l.y)*j):(e=(a.max.y-l.y)*j,f=(a.min.y-l.y)*j),c>f||e>d?null:((e>c||c!==c)&&(c=e),(d>f||d!==d)&&(d=f),k>=0?(g=(a.min.z-l.z)*k,h=(a.max.z-l.z)*k):(g=(a.max.z-l.z)*k,h=(a.min.z-l.z)*k),c>h||g>d?null:((g>c||c!==c)&&(c=g),(d>h||d!==d)&&(d=h),0>d?null:this.at(c>=0?c:d,b)))},intersectTriangle:function(){var a=new e.Vector3,b=new e.Vector3,c=new e.Vector3,d=new e.Vector3;return function(e,f,g,h,i){b.subVectors(f,e),c.subVectors(g,e),d.crossVectors(b,c);var j,k=this.direction.dot(d);if(k>0){if(h)return null;j=1}else{if(!(0>k))return null;j=-1,k=-k}a.subVectors(this.origin,e);var l=j*this.direction.dot(c.crossVectors(a,c));if(0>l)return null;var m=j*this.direction.dot(b.cross(a));if(0>m)return null;if(l+m>k)return null;var n=-j*a.dot(d);return 0>n?null:this.at(n/k,i)}}(),applyMatrix4:function(a){return this.direction.add(this.origin).applyMatrix4(a),this.origin.applyMatrix4(a),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)},clone:function(){return(new e.Ray).copy(this)}},e.Sphere=function(a,b){this.center=void 0!==a?a:new e.Vector3,this.radius=void 0!==b?b:0},e.Sphere.prototype={constructor:e.Sphere,set:function(a,b){return this.center.copy(a),this.radius=b,this},setFromPoints:function(){var a=new e.Box3;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).center(d);for(var e=0,f=0,g=b.length;g>f;f++)e=Math.max(e,d.distanceToSquared(b[f]));return this.radius=Math.sqrt(e),this}}(),copy:function(a){return this.center.copy(a.center),this.radius=a.radius,this},empty:function(){return this.radius<=0},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new e.Vector3;return d.copy(a),c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center)),d},getBoundingBox:function(a){var b=a||new e.Box3;return b.set(this.center,this.center),b.expandByScalar(this.radius),b},applyMatrix4:function(a){return this.center.applyMatrix4(a),this.radius=this.radius*a.getMaxScaleOnAxis(),this},translate:function(a){return this.center.add(a),this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius},clone:function(){return(new e.Sphere).copy(this)}},e.Frustum=function(a,b,c,d,f,g){this.planes=[void 0!==a?a:new e.Plane,void 0!==b?b:new e.Plane,void 0!==c?c:new e.Plane,void 0!==d?d:new e.Plane,void 0!==f?f:new e.Plane,void 0!==g?g:new e.Plane]},e.Frustum.prototype={constructor:e.Frustum,set:function(a,b,c,d,e,f){var g=this.planes;return g[0].copy(a),g[1].copy(b),g[2].copy(c),g[3].copy(d),g[4].copy(e),g[5].copy(f),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,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],j=c[6],k=c[7],l=c[8],m=c[9],n=c[10],o=c[11],p=c[12],q=c[13],r=c[14],s=c[15];return b[0].setComponents(g-d,k-h,o-l,s-p).normalize(),b[1].setComponents(g+d,k+h,o+l,s+p).normalize(),b[2].setComponents(g+e,k+i,o+m,s+q).normalize(),b[3].setComponents(g-e,k-i,o-m,s-q).normalize(),b[4].setComponents(g-f,k-j,o-n,s-r).normalize(),b[5].setComponents(g+f,k+j,o+n,s+r).normalize(),this},intersectsObject:function(){var a=new e.Sphere;return function(b){var c=b.geometry;return null===c.boundingSphere&&c.computeBoundingSphere(),a.copy(c.boundingSphere),a.applyMatrix4(b.matrixWorld),this.intersectsSphere(a)}}(),intersectsSphere:function(a){for(var b=this.planes,c=a.center,d=-a.radius,e=0;6>e;e++){var f=b[e].distanceToPoint(c);if(d>f)return!1}return!0},intersectsBox:function(){var a=new e.Vector3,b=new e.Vector3;return function(c){for(var d=this.planes,e=0;6>e;e++){var f=d[e];a.x=f.normal.x>0?c.min.x:c.max.x,b.x=f.normal.x>0?c.max.x:c.min.x,a.y=f.normal.y>0?c.min.y:c.max.y,b.y=f.normal.y>0?c.max.y:c.min.y,a.z=f.normal.z>0?c.min.z:c.max.z,b.z=f.normal.z>0?c.max.z:c.min.z;var g=f.distanceToPoint(a),h=f.distanceToPoint(b);if(0>g&&0>h)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(b[c].distanceToPoint(a)<0)return!1;return!0},clone:function(){return(new e.Frustum).copy(this)}},e.Plane=function(a,b){this.normal=void 0!==a?a:new e.Vector3(1,0,0),this.constant=void 0!==b?b:0},e.Plane.prototype={constructor:e.Plane,set:function(a,b){return this.normal.copy(a),this.constant=b,this},setComponents:function(a,b,c,d){return this.normal.set(a,b,c),this.constant=d,this},setFromNormalAndCoplanarPoint:function(a,b){return this.normal.copy(a),this.constant=-b.dot(this.normal),this},setFromCoplanarPoints:function(){var a=new e.Vector3,b=new e.Vector3;return function(c,d,e){var f=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();return this.setFromNormalAndCoplanarPoint(f,c),this}}(),copy:function(a){return this.normal.copy(a.normal),this.constant=a.constant,this},normalize:function(){var a=1/this.normal.length();return this.normal.multiplyScalar(a),this.constant*=a,this},negate:function(){return this.constant*=-1,this.normal.negate(),this},distanceToPoint:function(a){return this.normal.dot(a)+this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,b){var c=this.distanceToPoint(a),d=b||new e.Vector3; -return d.copy(this.normal).multiplyScalar(c)},isIntersectionLine:function(a){var b=this.distanceToPoint(a.start),c=this.distanceToPoint(a.end);return 0>b&&c>0||0>c&&b>0},intersectLine:function(){var a=new e.Vector3;return function(b,c){var d=c||new e.Vector3,f=b.delta(a),g=this.normal.dot(f);if(0==g)return 0==this.distanceToPoint(b.start)?d.copy(b.start):void 0;var h=-(b.start.dot(this.normal)+this.constant)/g;return 0>h||h>1?void 0:d.copy(f).multiplyScalar(h).add(b.start)}}(),coplanarPoint:function(a){var b=a||new e.Vector3;return b.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new e.Vector3,b=new e.Vector3,c=new e.Matrix3;return function(d,e){var f=e||c.getNormalMatrix(d),g=a.copy(this.normal).applyMatrix3(f),h=this.coplanarPoint(b);return h.applyMatrix4(d),this.setFromNormalAndCoplanarPoint(g,h),this}}(),translate:function(a){return this.constant=this.constant-a.dot(this.normal),this},equals:function(a){return a.normal.equals(this.normal)&&a.constant==this.constant},clone:function(){return(new e.Plane).copy(this)}},e.Math={PI2:2*Math.PI,generateUUID:function(){var a,b="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),c=new Array(36),d=0;return function(){for(var e=0;36>e;e++)8==e||13==e||18==e||23==e?c[e]="-":14==e?c[e]="4":(2>=d&&(d=33554432+16777216*Math.random()|0),a=15&d,d>>=4,c[e]=b[19==e?3&a|8:a]);return c.join("")}}(),clamp:function(a,b,c){return b>a?b:a>c?c:a},clampBottom:function(a,b){return b>a?b:a},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},smoothstep:function(a,b,c){return b>=a?0:a>=c?1:(a=(a-b)/(c-b),a*a*(3-2*a))},smootherstep:function(a,b,c){return b>=a?0:a>=c?1:(a=(a-b)/(c-b),a*a*a*(a*(6*a-15)+10))},random16:function(){return(65280*Math.random()+255*Math.random())/65535},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())},sign:function(a){return 0>a?-1:a>0?1:0},degToRad:function(){var a=Math.PI/180;return function(b){return b*a}}(),radToDeg:function(){var a=180/Math.PI;return function(b){return b*a}}(),isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a}},e.Spline=function(a){function b(a,b,c,d,e,f,g){var h=.5*(c-a),i=.5*(d-b);return(2*(b-c)+h+i)*g+(-3*(b-c)-2*h-i)*f+h*e+b}this.points=a;var c,d,f,g,h,i,j,k,l,m=[],n={x:0,y:0,z:0};this.initFromArray=function(a){this.points=[];for(var b=0;bthis.points.length-2?this.points.length-1:d+1,m[3]=d>this.points.length-3?this.points.length-1:d+2,i=this.points[m[0]],j=this.points[m[1]],k=this.points[m[2]],l=this.points[m[3]],g=f*f,h=f*g,n.x=b(i.x,j.x,k.x,l.x,f,g,h),n.y=b(i.y,j.y,k.y,l.y,f,g,h),n.z=b(i.z,j.z,k.z,l.z,f,g,h),n},this.getControlPointsArray=function(){var a,b,c=this.points.length,d=[];for(a=0;c>a;a++)b=this.points[a],d[a]=[b.x,b.y,b.z];return d},this.getLength=function(a){var b,c,d,f,g=0,h=0,i=0,j=new e.Vector3,k=new e.Vector3,l=[],m=0;for(l[0]=0,a||(a=100),d=this.points.length*a,j.copy(this.points[0]),b=1;d>b;b++)c=b/d,f=this.getPoint(c),k.copy(f),m+=k.distanceTo(j),j.copy(f),g=(this.points.length-1)*c,h=Math.floor(g),h!=i&&(l[h]=m,i=h);return l[l.length]=m,{chunks:l,total:m}},this.reparametrizeByArcLength=function(a){var b,c,d,f,g,h,i,j,k=[],l=new e.Vector3,m=this.getLength();for(k.push(l.copy(this.points[0]).clone()),b=1;bc;c++)d=f+c*(1/i)*(g-f),j=this.getPoint(d),k.push(l.copy(j).clone());k.push(l.copy(this.points[b]).clone())}this.points=k}},e.Triangle=function(a,b,c){this.a=void 0!==a?a:new e.Vector3,this.b=void 0!==b?b:new e.Vector3,this.c=void 0!==c?c:new e.Vector3},e.Triangle.normal=function(){var a=new e.Vector3;return function(b,c,d,f){var g=f||new e.Vector3;g.subVectors(d,c),a.subVectors(b,c),g.cross(a);var h=g.lengthSq();return h>0?g.multiplyScalar(1/Math.sqrt(h)):g.set(0,0,0)}}(),e.Triangle.barycoordFromPoint=function(){var a=new e.Vector3,b=new e.Vector3,c=new e.Vector3;return function(d,f,g,h,i){a.subVectors(h,f),b.subVectors(g,f),c.subVectors(d,f);var j=a.dot(a),k=a.dot(b),l=a.dot(c),m=b.dot(b),n=b.dot(c),o=j*m-k*k,p=i||new e.Vector3;if(0==o)return p.set(-2,-1,-1);var q=1/o,r=(m*l-k*n)*q,s=(j*n-k*l)*q;return p.set(1-r-s,s,r)}}(),e.Triangle.containsPoint=function(){var a=new e.Vector3;return function(b,c,d,f){var g=e.Triangle.barycoordFromPoint(b,c,d,f,a);return g.x>=0&&g.y>=0&&g.x+g.y<=1}}(),e.Triangle.prototype={constructor:e.Triangle,set:function(a,b,c){return this.a.copy(a),this.b.copy(b),this.c.copy(c),this},setFromPointsAndIndices:function(a,b,c,d){return this.a.copy(a[b]),this.b.copy(a[c]),this.c.copy(a[d]),this},copy:function(a){return this.a.copy(a.a),this.b.copy(a.b),this.c.copy(a.c),this},area:function(){var a=new e.Vector3,b=new e.Vector3;return function(){return a.subVectors(this.c,this.b),b.subVectors(this.a,this.b),.5*a.cross(b).length()}}(),midpoint:function(a){var b=a||new e.Vector3;return b.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return e.Triangle.normal(this.a,this.b,this.c,a)},plane:function(a){var b=a||new e.Plane;return b.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return e.Triangle.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return e.Triangle.containsPoint(a,this.a,this.b,this.c)},equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)},clone:function(){return(new e.Triangle).copy(this)}},e.Vertex=function(a){return console.warn("THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead."),a},e.UV=function(a,b){return console.warn("THREE.UV has been DEPRECATED. Use THREE.Vector2 instead."),new e.Vector2(a,b)},e.Clock=function(a){this.autoStart=void 0!==a?a:!0,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1},e.Clock.prototype={constructor:e.Clock,start:function(){this.startTime=void 0!==d.performance&&void 0!==d.performance.now?d.performance.now():Date.now(),this.oldTime=this.startTime,this.running=!0},stop:function(){this.getElapsedTime(),this.running=!1},getElapsedTime:function(){return this.getDelta(),this.elapsedTime},getDelta:function(){var a=0;if(this.autoStart&&!this.running&&this.start(),this.running){var b=void 0!==d.performance&&void 0!==d.performance.now?d.performance.now():Date.now();a=.001*(b-this.oldTime),this.oldTime=b,this.elapsedTime+=a}return a}},e.EventDispatcher=function(){},e.EventDispatcher.prototype={constructor:e.EventDispatcher,apply:function(a){a.addEventListener=e.EventDispatcher.prototype.addEventListener,a.hasEventListener=e.EventDispatcher.prototype.hasEventListener,a.removeEventListener=e.EventDispatcher.prototype.removeEventListener,a.dispatchEvent=e.EventDispatcher.prototype.dispatchEvent},addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]),-1===c[a].indexOf(b)&&c[a].push(b)},hasEventListener:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)?!0:!1},removeEventListener:function(a,b){if(void 0!==this._listeners){var c=this._listeners,d=c[a];if(void 0!==d){var e=d.indexOf(b);-1!==e&&d.splice(e,1)}}},dispatchEvent:function(){var a=[];return function(b){if(void 0!==this._listeners){var c=this._listeners,d=c[b.type];if(void 0!==d){b.target=this;for(var e=d.length,f=0;e>f;f++)a[f]=d[f];for(var f=0;e>f;f++)a[f].call(this,b)}}}}()},function(a){a.Raycaster=function(b,c,d,e){this.ray=new a.Ray(b,c),this.near=d||0,this.far=e||1/0};var b=new a.Sphere,c=new a.Ray,d=(new a.Plane,new a.Vector3,new a.Vector3),e=new a.Matrix4,f=function(a,b){return a.distance-b.distance},g=new a.Vector3,h=new a.Vector3,i=new a.Vector3,j=function(f,k,l){if(f instanceof a.Sprite){d.setFromMatrixPosition(f.matrixWorld);var m=k.ray.distanceToPoint(d);if(m>f.scale.x)return l;l.push({distance:m,point:f.position,face:null,object:f})}else if(f instanceof a.LOD){d.setFromMatrixPosition(f.matrixWorld);var m=k.ray.origin.distanceTo(d);j(f.getObjectForDistance(m),k,l)}else if(f instanceof a.Mesh){var n=f.geometry;if(null===n.boundingSphere&&n.computeBoundingSphere(),b.copy(n.boundingSphere),b.applyMatrix4(f.matrixWorld),k.ray.isIntersectionSphere(b)===!1)return l;if(e.getInverse(f.matrixWorld),c.copy(k.ray).applyMatrix4(e),null!==n.boundingBox&&c.isIntersectionBox(n.boundingBox)===!1)return l;if(n instanceof a.BufferGeometry){var o=f.material;if(void 0===o)return l;var p,q,r,s=n.attributes,t=k.precision;if(void 0!==s.index)for(var u=n.offsets,v=s.index.array,w=s.position.array,x=0,y=u.length;y>x;++x)for(var z=u[x].start,A=u[x].count,B=u[x].index,C=z,D=z+A;D>C;C+=3){if(p=B+v[C],q=B+v[C+1],r=B+v[C+2],g.set(w[3*p],w[3*p+1],w[3*p+2]),h.set(w[3*q],w[3*q+1],w[3*q+2]),i.set(w[3*r],w[3*r+1],w[3*r+2]),o.side===a.BackSide)var E=c.intersectTriangle(i,h,g,!0);else var E=c.intersectTriangle(g,h,i,o.side!==a.DoubleSide);if(null!==E){E.applyMatrix4(f.matrixWorld);var m=k.ray.origin.distanceTo(E);t>m||mk.far||l.push({distance:m,point:E,indices:[p,q,r],face:null,faceIndex:null,object:f})}}else for(var u=n.offsets,w=s.position.array,C=0,D=s.position.array.length;D>C;C+=3){if(p=C,q=C+1,r=C+2,g.set(w[3*p],w[3*p+1],w[3*p+2]),h.set(w[3*q],w[3*q+1],w[3*q+2]),i.set(w[3*r],w[3*r+1],w[3*r+2]),o.side===a.BackSide)var E=c.intersectTriangle(i,h,g,!0);else var E=c.intersectTriangle(g,h,i,o.side!==a.DoubleSide);if(null!==E){E.applyMatrix4(f.matrixWorld);var m=k.ray.origin.distanceTo(E);t>m||mk.far||l.push({distance:m,point:E,indices:[p,q,r],face:null,faceIndex:null,object:f})}}}else if(n instanceof a.Geometry)for(var p,q,r,F=f.material instanceof a.MeshFaceMaterial,G=F===!0?f.material.materials:null,t=k.precision,H=n.vertices,I=0,J=n.faces.length;J>I;I++){var K=n.faces[I],o=F===!0?G[K.materialIndex]:f.material;if(void 0!==o){if(p=H[K.a],q=H[K.b],r=H[K.c],o.morphTargets===!0){var L=n.morphTargets,M=f.morphTargetInfluences;g.set(0,0,0),h.set(0,0,0),i.set(0,0,0);for(var N=0,O=L.length;O>N;N++){var P=M[N];if(0!==P){var Q=L[N].vertices;g.x+=(Q[K.a].x-p.x)*P,g.y+=(Q[K.a].y-p.y)*P,g.z+=(Q[K.a].z-p.z)*P,h.x+=(Q[K.b].x-q.x)*P,h.y+=(Q[K.b].y-q.y)*P,h.z+=(Q[K.b].z-q.z)*P,i.x+=(Q[K.c].x-r.x)*P,i.y+=(Q[K.c].y-r.y)*P,i.z+=(Q[K.c].z-r.z)*P}}g.add(p),h.add(q),i.add(r),p=g,q=h,r=i}if(o.side===a.BackSide)var E=c.intersectTriangle(r,q,p,!0);else var E=c.intersectTriangle(p,q,r,o.side!==a.DoubleSide);if(null!==E){E.applyMatrix4(f.matrixWorld);var m=k.ray.origin.distanceTo(E);t>m||mk.far||l.push({distance:m,point:E,face:K,faceIndex:I,object:f})}}}}else if(f instanceof a.Line){var t=k.linePrecision,R=t*t,n=f.geometry;if(null===n.boundingSphere&&n.computeBoundingSphere(),b.copy(n.boundingSphere),b.applyMatrix4(f.matrixWorld),k.ray.isIntersectionSphere(b)===!1)return l;if(e.getInverse(f.matrixWorld),c.copy(k.ray).applyMatrix4(e),n instanceof a.Geometry)for(var H=n.vertices,S=H.length,T=new a.Vector3,U=new a.Vector3,V=f.type===a.LineStrip?1:2,C=0;S-1>C;C+=V){var W=c.distanceSqToSegment(H[C],H[C+1],U,T);if(!(W>R)){var m=c.origin.distanceTo(U);mk.far||l.push({distance:m,point:T.clone().applyMatrix4(f.matrixWorld),face:null,faceIndex:null,object:f})}}}},k=function(a,b,c){for(var d=a.getDescendants(),e=0,f=d.length;f>e;e++)j(d[e],b,c)};a.Raycaster.prototype.precision=1e-4,a.Raycaster.prototype.linePrecision=1,a.Raycaster.prototype.set=function(a,b){this.ray.set(a,b)},a.Raycaster.prototype.intersectObject=function(a,b){var c=[];return b===!0&&k(a,this,c),j(a,this,c),c.sort(f),c},a.Raycaster.prototype.intersectObjects=function(a,b){for(var c=[],d=0,e=a.length;e>d;d++)j(a[d],this,c),b===!0&&k(a[d],this,c);return c.sort(f),c}}(e),e.Object3D=function(){this.id=e.Object3DIdCount++,this.uuid=e.Math.generateUUID(),this.name="",this.parent=void 0,this.children=[],this.up=new e.Vector3(0,1,0),this.position=new e.Vector3,this._rotation=new e.Euler,this._quaternion=new e.Quaternion,this.scale=new e.Vector3(1,1,1),this._rotation._quaternion=this.quaternion,this._quaternion._euler=this.rotation,this.renderDepth=null,this.rotationAutoUpdate=!0,this.matrix=new e.Matrix4,this.matrixWorld=new e.Matrix4,this.matrixAutoUpdate=!0,this.matrixWorldNeedsUpdate=!0,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.userData={}},e.Object3D.prototype={constructor:e.Object3D,get rotation(){return this._rotation},set rotation(a){this._rotation=a,this._rotation._quaternion=this._quaternion,this._quaternion._euler=this._rotation,this._rotation._updateQuaternion()},get quaternion(){return this._quaternion},set quaternion(a){this._quaternion=a,this._quaternion._euler=this._rotation,this._rotation._quaternion=this._quaternion,this._quaternion._updateEuler()},get eulerOrder(){return console.warn("DEPRECATED: Object3D's .eulerOrder has been moved to Object3D's .rotation.order."),this.rotation.order},set eulerOrder(a){console.warn("DEPRECATED: Object3D's .eulerOrder has been moved to Object3D's .rotation.order."),this.rotation.order=a},get useQuaternion(){console.warn("DEPRECATED: Object3D's .useQuaternion has been removed. The library now uses quaternions by default.")},set useQuaternion(a){console.warn("DEPRECATED: Object3D's .useQuaternion has been removed. The library now uses quaternions by default.")},applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix),this.matrix.decompose(this.position,this.quaternion,this.scale)},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,!0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new e.Quaternion;return function(b,c){return a.setFromAxisAngle(b,c),this.quaternion.multiply(a),this}}(),rotateX:function(){var a=new e.Vector3(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=new e.Vector3(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new e.Vector3(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new e.Vector3;return function(b,c){return a.copy(b),a.applyQuaternion(this.quaternion),this.position.add(a.multiplyScalar(c)),this}}(),translate:function(a,b){return console.warn("DEPRECATED: Object3D's .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed."),this.translateOnAxis(b,a)},translateX:function(){var a=new e.Vector3(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new e.Vector3(0,1,0);return function(b){return this.translateOnAxis(a,b)}}(),translateZ:function(){var a=new e.Vector3(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=new e.Matrix4;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new e.Matrix4;return function(b){a.lookAt(b,this.position,this.up),this.quaternion.setFromRotationMatrix(a)}}(),add:function(a){if(a===this)return void console.warn("THREE.Object3D.add: An object can't be added as a child of itself.");if(a instanceof e.Object3D){void 0!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),this.children.push(a);for(var b=this;void 0!==b.parent;)b=b.parent;void 0!==b&&b instanceof e.Scene&&b.__addObject(a)}},remove:function(a){var b=this.children.indexOf(a);if(-1!==b){a.parent=void 0,a.dispatchEvent({type:"removed"}),this.children.splice(b,1);for(var c=this;void 0!==c.parent;)c=c.parent;void 0!==c&&c instanceof e.Scene&&c.__removeObject(a)}},traverse:function(a){a(this);for(var b=0,c=this.children.length;c>b;b++)this.children[b].traverse(a)},getObjectById:function(a,b){for(var c=0,d=this.children.length;d>c;c++){var e=this.children[c];if(e.id===a)return e;if(b===!0&&(e=e.getObjectById(a,b),void 0!==e))return e}return void 0},getObjectByName:function(a,b){for(var c=0,d=this.children.length;d>c;c++){var e=this.children[c];if(e.name===a)return e;if(b===!0&&(e=e.getObjectByName(a,b),void 0!==e))return e}return void 0},getChildByName:function(a,b){return console.warn("DEPRECATED: Object3D's .getChildByName() has been renamed to .getObjectByName()."),this.getObjectByName(a,b)},getDescendants:function(a){void 0===a&&(a=[]),Array.prototype.push.apply(a,this.children);for(var b=0,c=this.children.length;c>b;b++)this.children[b].getDescendants(a);return a},updateMatrix:function(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate===!0&&this.updateMatrix(),(this.matrixWorldNeedsUpdate===!0||a===!0)&&(void 0===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0);for(var b=0,c=this.children.length;c>b;b++)this.children[b].updateMatrixWorld(a)},clone:function(a,b){if(void 0===a&&(a=new e.Object3D),void 0===b&&(b=!0),a.name=this.name,a.up.copy(this.up),a.position.copy(this.position),a.quaternion.copy(this.quaternion),a.scale.copy(this.scale),a.renderDepth=this.renderDepth,a.rotationAutoUpdate=this.rotationAutoUpdate,a.matrix.copy(this.matrix),a.matrixWorld.copy(this.matrixWorld),a.matrixAutoUpdate=this.matrixAutoUpdate,a.matrixWorldNeedsUpdate=this.matrixWorldNeedsUpdate,a.visible=this.visible,a.castShadow=this.castShadow,a.receiveShadow=this.receiveShadow,a.frustumCulled=this.frustumCulled,a.userData=JSON.parse(JSON.stringify(this.userData)),b===!0)for(var c=0;c=0&&f>=0&&g>=0&&h>=0?!0:0>e&&0>f||0>g&&0>h?!1:(0>e?c=Math.max(c,e/(e-f)):0>f&&(d=Math.min(d,e/(e-f))),0>g?c=Math.max(c,g/(g-h)):0>h&&(d=Math.min(d,g/(g-h))),c>d?!1:(a.lerp(b,c),b.lerp(a,1-d),!0))}var i,j,k,l,m,n,o,p,q,r,s,t=[],u=0,v=[],w=0,x=[],y=0,z=[],A=0,B=[],C=0,D={objects:[],lights:[],elements:[]},E=new e.Vector3,F=new e.Vector3,G=new e.Vector3,H=new e.Vector3,I=new e.Vector4,J=new e.Box3(new e.Vector3(-1,-1,-1),new e.Vector3(1,1,1)),K=new e.Box3,L=new Array(3),M=(new Array(4),new e.Matrix4),N=new e.Matrix4,O=new e.Matrix4,P=new e.Matrix3,Q=new e.Frustum,R=new e.Vector4,S=new e.Vector4;this.projectVector=function(a,b){return b.matrixWorldInverse.getInverse(b.matrixWorld),N.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse),a.applyProjection(N)},this.unprojectVector=function(){var a=new e.Matrix4;return function(b,c){return a.getInverse(c.projectionMatrix),N.multiplyMatrices(c.matrixWorld,a),b.applyProjection(N)}}(),this.pickingRay=function(a,b){a.z=-1;var c=new e.Vector3(a.x,a.y,1);return this.unprojectVector(a,b),this.unprojectVector(c,b),c.sub(a).normalize(),new e.Raycaster(a,c)};var T=function(b){if(b.visible!==!1){b instanceof e.Light?D.lights.push(b):(b instanceof e.Mesh||b instanceof e.Line||b instanceof e.Sprite)&&(b.frustumCulled===!1||Q.intersectsObject(b)===!0)&&(i=a(),i.id=b.id,i.object=b,null!==b.renderDepth?i.z=b.renderDepth:(H.setFromMatrixPosition(b.matrixWorld),H.applyProjection(N),i.z=H.z),D.objects.push(i));for(var c=0,d=b.children.length;d>c;c++)T(b.children[c])}},U=function(a,b){j=0,D.objects.length=0,D.lights.length=0,T(a),b===!0&&D.objects.sort(g)},V=function(){var a=[],f=null,g=new e.Matrix3,h=function(b){f=b,g.getNormalMatrix(f.matrixWorld),a.length=0},i=function(a){var b=a.position,c=a.positionWorld,d=a.positionScreen;c.copy(b).applyMatrix4(s),d.copy(c).applyMatrix4(N);var e=1/d.w;d.x*=e,d.y*=e,d.z*=e,a.visible=d.x>=-1&&d.x<=1&&d.y>=-1&&d.y<=1&&d.z>=-1&&d.z<=1},j=function(a,c,d){k=b(),k.position.set(a,c,d),i(k)},l=function(b,c,d){a.push(b,c,d)},n=function(a,b,c){return L[0]=a.positionScreen,L[1]=b.positionScreen,L[2]=c.positionScreen,a.visible===!0||b.visible===!0||c.visible===!0||J.isIntersectionBox(K.setFromPoints(L))?(c.positionScreen.x-a.positionScreen.x)*(b.positionScreen.y-a.positionScreen.y)-(c.positionScreen.y-a.positionScreen.y)*(b.positionScreen.x-a.positionScreen.x)<0:!1},p=function(a,b){var c=v[a],e=v[b];o=d(),o.id=f.id,o.v1.copy(c),o.v2.copy(e),o.z=(c.positionScreen.z+e.positionScreen.z)/2,o.material=f.material,D.elements.push(o)},q=function(b,d,e){var h=v[b],i=v[d],j=v[e];if(n(h,i,j)===!0){m=c(),m.id=f.id,m.v1.copy(h),m.v2.copy(i),m.v3.copy(j),m.z=(h.positionScreen.z+i.positionScreen.z+j.positionScreen.z)/3;for(var k=0;3>k;k++){var l=3*arguments[k],o=m.vertexNormalsModel[k];o.set(a[l+0],a[l+1],a[l+2]),o.applyMatrix3(g).normalize()}m.vertexNormalsLength=3,m.material=f.material,D.elements.push(m)}};return{setObject:h,projectVertex:i,checkTriangleVisibility:n,pushVertex:j,pushNormal:l,pushLine:p,pushTriangle:q}},W=new V;this.projectScene=function(a,i,j,k){var t,u,w,x,y,z,A,B,C,H;n=0,p=0,r=0,D.elements.length=0,a.autoUpdate===!0&&a.updateMatrixWorld(),void 0===i.parent&&i.updateMatrixWorld(),M.copy(i.matrixWorldInverse.getInverse(i.matrixWorld)),N.multiplyMatrices(i.projectionMatrix,M),Q.setFromMatrix(N),U(a,j);for(var J=0,K=D.objects.length;K>J;J++)if(t=D.objects[J].object,u=t.geometry,W.setObject(t),s=t.matrixWorld,l=0,t instanceof e.Mesh){if(u instanceof e.BufferGeometry){var L=u.attributes,T=u.offsets;if(void 0===L.position)continue;for(var V=L.position.array,X=0,Y=V.length;Y>X;X+=3)W.pushVertex(V[X],V[X+1],V[X+2]);for(var Z=L.normal.array,X=0,Y=Z.length;Y>X;X+=3)W.pushNormal(Z[X],Z[X+1],Z[X+2]);if(void 0!==L.index){var $=L.index.array;if(T.length>0)for(var J=0;JX;X+=3)W.pushTriangle($[X]+ab,$[X+1]+ab,$[X+2]+ab);else for(var X=0,Y=$.length;Y>X;X+=3)W.pushTriangle($[X],$[X+1],$[X+2])}else for(var X=0,Y=V.length/3;Y>X;X+=3)W.pushTriangle(X,X+1,X+2)}else if(u instanceof e.Geometry){w=u.vertices,x=u.faces,A=u.faceVertexUvs,P.getNormalMatrix(s),C=t.material instanceof e.MeshFaceMaterial,H=C===!0?t.material:null;for(var bb=0,cb=w.length;cb>bb;bb++){var db=w[bb];W.pushVertex(db.x,db.y,db.z)}for(var eb=0,fb=x.length;fb>eb;eb++){y=x[eb];var gb=C===!0?H.materials[y.materialIndex]:t.material;if(void 0!==gb){var hb=gb.side,ib=v[y.a],jb=v[y.b],kb=v[y.c];if(gb.morphTargets===!0){var lb=u.morphTargets,mb=t.morphTargetInfluences,nb=ib.position,ob=jb.position,pb=kb.position;E.set(0,0,0),F.set(0,0,0),G.set(0,0,0);for(var qb=0,rb=lb.length;rb>qb;qb++){var sb=mb[qb];if(0!==sb){var tb=lb[qb].vertices;E.x+=(tb[y.a].x-nb.x)*sb,E.y+=(tb[y.a].y-nb.y)*sb,E.z+=(tb[y.a].z-nb.z)*sb,F.x+=(tb[y.b].x-ob.x)*sb,F.y+=(tb[y.b].y-ob.y)*sb,F.z+=(tb[y.b].z-ob.z)*sb,G.x+=(tb[y.c].x-pb.x)*sb,G.y+=(tb[y.c].y-pb.y)*sb,G.z+=(tb[y.c].z-pb.z)*sb}}ib.position.add(E),jb.position.add(F),kb.position.add(G),W.projectVertex(ib),W.projectVertex(jb),W.projectVertex(kb)}var ub=W.checkTriangleVisibility(ib,jb,kb);if(!(ub===!1&&hb===e.FrontSide||ub===!0&&hb===e.BackSide)){m=c(),m.id=t.id,m.v1.copy(ib),m.v2.copy(jb),m.v3.copy(kb),m.normalModel.copy(y.normal),ub!==!1||hb!==e.BackSide&&hb!==e.DoubleSide||m.normalModel.negate(),m.normalModel.applyMatrix3(P).normalize(),m.centroidModel.copy(y.centroid).applyMatrix4(s),z=y.vertexNormals;for(var vb=0,wb=Math.min(z.length,3);wb>vb;vb++){var xb=m.vertexNormalsModel[vb];xb.copy(z[vb]),ub!==!1||hb!==e.BackSide&&hb!==e.DoubleSide||xb.negate(),xb.applyMatrix3(P).normalize()}m.vertexNormalsLength=z.length;for(var yb=0,zb=Math.min(A.length,3);zb>yb;yb++)if(B=A[yb][eb],void 0!==B)for(var Ab=0,Bb=B.length;Bb>Ab;Ab++)m.uvs[yb][Ab]=B[Ab];m.color=y.color,m.material=gb,m.z=(ib.positionScreen.z+jb.positionScreen.z+kb.positionScreen.z)/3,D.elements.push(m)}}}}}else if(t instanceof e.Line){if(u instanceof e.BufferGeometry){var L=u.attributes;if(void 0!==L.position){for(var V=L.position.array,X=0,Y=V.length;Y>X;X+=3)W.pushVertex(V[X],V[X+1],V[X+2]);if(void 0!==L.index)for(var $=L.index.array,X=0,Y=$.length;Y>X;X+=2)W.pushLine($[X],$[X+1]);else for(var X=0,Y=V.length/3-1;Y>X;X++)W.pushLine(X,X+1)}}else if(u instanceof e.Geometry){if(O.multiplyMatrices(N,s),w=t.geometry.vertices,0===w.length)continue;ib=b(),ib.positionScreen.copy(w[0]).applyMatrix4(O);for(var Cb=t.type===e.LinePieces?2:1,bb=1,cb=w.length;cb>bb;bb++)ib=b(),ib.positionScreen.copy(w[bb]).applyMatrix4(O),(bb+1)%Cb>0||(jb=v[l-2],R.copy(ib.positionScreen),S.copy(jb.positionScreen),h(R,S)===!0&&(R.multiplyScalar(1/R.w),S.multiplyScalar(1/S.w),o=d(),o.id=t.id,o.v1.positionScreen.copy(R),o.v2.positionScreen.copy(S),o.z=Math.max(R.z,S.z),o.material=t.material,t.material.vertexColors===e.VertexColors&&(o.vertexColors[0].copy(t.geometry.colors[bb]),o.vertexColors[1].copy(t.geometry.colors[bb-1])),D.elements.push(o)))}}else if(t instanceof e.Sprite){I.set(s.elements[12],s.elements[13],s.elements[14],1),I.applyMatrix4(N);var Db=1/I.w;I.z*=Db,I.z>=-1&&I.z<=1&&(q=f(),q.id=t.id,q.x=I.x*Db,q.y=I.y*Db,q.z=I.z,q.object=t,q.rotation=t.rotation,q.scale.x=t.scale.x*Math.abs(q.x-(I.x+i.projectionMatrix.elements[0])/(I.w+i.projectionMatrix.elements[12])),q.scale.y=t.scale.y*Math.abs(q.y-(I.y+i.projectionMatrix.elements[5])/(I.w+i.projectionMatrix.elements[13])),q.material=t.material,D.elements.push(q))}return k===!0&&D.elements.sort(g),D}},e.Face3=function(a,b,c,d,f,g){this.a=a,this.b=b,this.c=c,this.normal=d instanceof e.Vector3?d:new e.Vector3,this.vertexNormals=d instanceof Array?d:[],this.color=f instanceof e.Color?f:new e.Color,this.vertexColors=f instanceof Array?f:[],this.vertexTangents=[],this.materialIndex=void 0!==g?g:0,this.centroid=new e.Vector3},e.Face3.prototype={constructor:e.Face3,clone:function(){var a=new e.Face3(this.a,this.b,this.c);a.normal.copy(this.normal),a.color.copy(this.color),a.centroid.copy(this.centroid),a.materialIndex=this.materialIndex;var b,c;for(b=0,c=this.vertexNormals.length;c>b;b++)a.vertexNormals[b]=this.vertexNormals[b].clone();for(b=0,c=this.vertexColors.length;c>b;b++)a.vertexColors[b]=this.vertexColors[b].clone();for(b=0,c=this.vertexTangents.length;c>b;b++)a.vertexTangents[b]=this.vertexTangents[b].clone();return a}},e.Face4=function(a,b,c,d,f,g,h){return console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead."),new e.Face3(a,b,c,f,g,h)},e.BufferGeometry=function(){this.id=e.GeometryIdCount++,this.uuid=e.Math.generateUUID(),this.name="",this.attributes={},this.offsets=[],this.boundingBox=null,this.boundingSphere=null},e.BufferGeometry.prototype={constructor:e.BufferGeometry,addAttribute:function(a,b,c,d){return this.attributes[a]={array:new b(c*d),itemSize:d},this.attributes[a]},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.multiplyVector3Array(b.array),b.needsUpdate=!0);var c=this.attributes.normal;if(void 0!==c){var d=(new e.Matrix3).getNormalMatrix(a);d.multiplyVector3Array(c.array),c.needsUpdate=!0}},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new e.Box3);var a=this.attributes.position.array;if(a){var b=this.boundingBox;a.length>=3&&(b.min.x=b.max.x=a[0],b.min.y=b.max.y=a[1],b.min.z=b.max.z=a[2]);for(var c=3,d=a.length;d>c;c+=3){var f=a[c],g=a[c+1],h=a[c+2];fb.max.x&&(b.max.x=f),gb.max.y&&(b.max.y=g),hb.max.z&&(b.max.z=h)}}(void 0===a||0===a.length)&&(this.boundingBox.min.set(0,0,0),this.boundingBox.max.set(0,0,0))},computeBoundingSphere:function(){var a=new e.Box3,b=new e.Vector3;return function(){null===this.boundingSphere&&(this.boundingSphere=new e.Sphere);var c=this.attributes.position.array;if(c){a.makeEmpty();for(var d=this.boundingSphere.center,f=0,g=c.length;g>f;f+=3)b.set(c[f],c[f+1],c[f+2]),a.addPoint(b);a.center(d);for(var h=0,f=0,g=c.length;g>f;f+=3)b.set(c[f],c[f+1],c[f+2]),h=Math.max(h,d.distanceToSquared(b));this.boundingSphere.radius=Math.sqrt(h)}}}(),computeVertexNormals:function(){if(this.attributes.position){var a,b,c,d,f=this.attributes.position.array.length;if(void 0===this.attributes.normal)this.attributes.normal={itemSize:3,array:new Float32Array(f)};else for(a=0,b=this.attributes.normal.array.length;b>a;a++)this.attributes.normal.array[a]=0;var g,h,i,j,k,l,m=this.attributes.position.array,n=this.attributes.normal.array,o=new e.Vector3,p=new e.Vector3,q=new e.Vector3,r=new e.Vector3,s=new e.Vector3;if(this.attributes.index){var t=this.attributes.index.array,u=this.offsets;for(c=0,d=u.length;d>c;++c){var v=u[c].start,w=u[c].count,x=u[c].index;for(a=v,b=v+w;b>a;a+=3)g=x+t[a],h=x+t[a+1],i=x+t[a+2],j=m[3*g],k=m[3*g+1],l=m[3*g+2],o.set(j,k,l),j=m[3*h],k=m[3*h+1],l=m[3*h+2],p.set(j,k,l),j=m[3*i],k=m[3*i+1],l=m[3*i+2],q.set(j,k,l),r.subVectors(q,p),s.subVectors(o,p),r.cross(s),n[3*g]+=r.x,n[3*g+1]+=r.y,n[3*g+2]+=r.z,n[3*h]+=r.x,n[3*h+1]+=r.y,n[3*h+2]+=r.z,n[3*i]+=r.x,n[3*i+1]+=r.y,n[3*i+2]+=r.z}}else for(a=0,b=m.length;b>a;a+=9)j=m[a],k=m[a+1],l=m[a+2],o.set(j,k,l),j=m[a+3],k=m[a+4],l=m[a+5],p.set(j,k,l),j=m[a+6],k=m[a+7],l=m[a+8],q.set(j,k,l),r.subVectors(q,p),s.subVectors(o,p),r.cross(s),n[a]=r.x,n[a+1]=r.y,n[a+2]=r.z,n[a+3]=r.x,n[a+4]=r.y,n[a+5]=r.z,n[a+6]=r.x,n[a+7]=r.y,n[a+8]=r.z;this.normalizeNormals(),this.normalsNeedUpdate=!0}},normalizeNormals:function(){for(var a,b,c,d,e=this.attributes.normal.array,f=0,g=e.length;g>f;f+=3)a=e[f],b=e[f+1],c=e[f+2],d=1/Math.sqrt(a*a+b*b+c*c),e[f]*=d,e[f+1]*=d,e[f+2]*=d},computeTangents:function(){function a(a,b,c){n=d[3*a],o=d[3*a+1],p=d[3*a+2],q=d[3*b],r=d[3*b+1],s=d[3*b+2],t=d[3*c],u=d[3*c+1],v=d[3*c+2],w=g[2*a],x=g[2*a+1],y=g[2*b],z=g[2*b+1],A=g[2*c],B=g[2*c+1],C=q-n,D=t-n,E=r-o,F=u-o,G=s-p,H=v-p,I=y-w,J=A-w,K=z-x,L=B-x,M=1/(I*L-J*K),U.set((L*C-K*D)*M,(L*E-K*F)*M,(L*G-K*H)*M),V.set((I*D-J*C)*M,(I*F-J*E)*M,(I*H-J*G)*M),k[a].add(U),k[b].add(U),k[c].add(U),l[a].add(V),l[b].add(V),l[c].add(V)}function b(a){db.x=f[3*a],db.y=f[3*a+1],db.z=f[3*a+2],eb.copy(db),_=k[a],bb.copy(_),bb.sub(db.multiplyScalar(db.dot(_))).normalize(),cb.crossVectors(eb,_),ab=cb.dot(l[a]),$=0>ab?-1:1,j[4*a]=bb.x,j[4*a+1]=bb.y,j[4*a+2]=bb.z,j[4*a+3]=$}if(void 0===this.attributes.index||void 0===this.attributes.position||void 0===this.attributes.normal||void 0===this.attributes.uv)return void console.warn("Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()");var c=this.attributes.index.array,d=this.attributes.position.array,f=this.attributes.normal.array,g=this.attributes.uv.array,h=d.length/3;if(void 0===this.attributes.tangent){var i=4*h;this.attributes.tangent={itemSize:4,array:new Float32Array(i)}}for(var j=this.attributes.tangent.array,k=[],l=[],m=0;h>m;m++)k[m]=new e.Vector3,l[m]=new e.Vector3;var n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U=new e.Vector3,V=new e.Vector3,W=this.offsets;for(P=0,Q=W.length;Q>P;++P){var X=W[P].start,Y=W[P].count,Z=W[P].index;for(N=X,O=X+Y;O>N;N+=3)R=Z+c[N],S=Z+c[N+1],T=Z+c[N+2],a(R,S,T)}var $,_,ab,bb=new e.Vector3,cb=new e.Vector3,db=new e.Vector3,eb=new e.Vector3;for(P=0,Q=W.length;Q>P;++P){var X=W[P].start,Y=W[P].count,Z=W[P].index;for(N=X,O=X+Y;O>N;N+=3)R=Z+c[N],S=Z+c[N+1],T=Z+c[N+2],b(R),b(S),b(T)}},computeOffsets:function(a){var b=a;void 0===a&&(b=65535);for(var c=(Date.now(),this.attributes.index.array),d=this.attributes.position.array,e=(d.length/3,c.length/3),f=new Uint16Array(c.length),g=0,h=0,i=[{start:0,count:0,index:0}],j=i[0],k=0,l=0,m=new Int32Array(6),n=new Int32Array(d.length),o=new Int32Array(d.length),p=0;pq;q++){l=0;for(var r=0;3>r;r++){var s=c[3*q+r];-1==n[s]?(m[2*r]=s,m[2*r+1]=-1,l++):n[s]j.index+b){var u={start:g,count:0,index:h};i.push(u),j=u;for(var v=0;6>v;v+=2){var w=m[v+1];w>-1&&wv;v+=2){var s=m[v],w=m[v+1];-1===w&&(w=h++),n[s]=w,o[w]=s,f[g++]=w-j.index,j.count++}}return this.reorderBuffers(f,o,h),this.offsets=i,i},reorderBuffers:function(a,b,c){var d={},e=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];for(var f in this.attributes)if("index"!=f)for(var g=this.attributes[f].array,h=0,i=e.length;i>h;h++){var j=e[h];if(g instanceof j){d[f]=new j(this.attributes[f].itemSize*c);break}}for(var k=0;c>k;k++){var l=b[k];for(var f in this.attributes)if("index"!=f)for(var m=this.attributes[f].array,n=this.attributes[f].itemSize,o=d[f],p=0;n>p;p++)o[k*n+p]=m[l*n+p]}this.attributes.index.array=a;for(var f in this.attributes)"index"!=f&&(this.attributes[f].array=d[f],this.attributes[f].numItems=this.attributes[f].itemSize*c)},clone:function(){var a=new e.BufferGeometry,b=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];for(var c in this.attributes){for(var d=this.attributes[c],f=d.array,g={itemSize:d.itemSize,array:null},h=0,i=b.length;i>h;h++){var j=b[h];if(f instanceof j){g.array=new j(f);break}}a.attributes[c]=g}for(var h=0,i=this.offsets.length;i>h;h++){var k=this.offsets[h];a.offsets.push({start:k.start,index:k.index,count:k.count})}return a},dispose:function(){this.dispatchEvent({type:"dispose"})}},e.EventDispatcher.prototype.apply(e.BufferGeometry.prototype),e.Geometry=function(){this.id=e.GeometryIdCount++,this.uuid=e.Math.generateUUID(),this.name="",this.vertices=[],this.colors=[],this.faces=[],this.faceVertexUvs=[[]],this.morphTargets=[],this.morphColors=[],this.morphNormals=[],this.skinWeights=[],this.skinIndices=[],this.lineDistances=[],this.boundingBox=null,this.boundingSphere=null,this.hasTangents=!1,this.dynamic=!0,this.verticesNeedUpdate=!1,this.elementsNeedUpdate=!1,this.uvsNeedUpdate=!1,this.normalsNeedUpdate=!1,this.tangentsNeedUpdate=!1,this.colorsNeedUpdate=!1,this.lineDistancesNeedUpdate=!1,this.buffersNeedUpdate=!1},e.Geometry.prototype={constructor:e.Geometry,applyMatrix:function(a){for(var b=(new e.Matrix3).getNormalMatrix(a),c=0,d=this.vertices.length;d>c;c++){var f=this.vertices[c];f.applyMatrix4(a)}for(var c=0,d=this.faces.length;d>c;c++){var g=this.faces[c];g.normal.applyMatrix3(b).normalize();for(var h=0,i=g.vertexNormals.length;i>h;h++)g.vertexNormals[h].applyMatrix3(b).normalize();g.centroid.applyMatrix4(a)}this.boundingBox instanceof e.Box3&&this.computeBoundingBox(),this.boundingSphere instanceof e.Sphere&&this.computeBoundingSphere()},computeCentroids:function(){var a,b,c;for(a=0,b=this.faces.length;b>a;a++)c=this.faces[a],c.centroid.set(0,0,0),c.centroid.add(this.vertices[c.a]),c.centroid.add(this.vertices[c.b]),c.centroid.add(this.vertices[c.c]),c.centroid.divideScalar(3)},computeFaceNormals:function(){for(var a=new e.Vector3,b=new e.Vector3,c=0,d=this.faces.length;d>c;c++){var f=this.faces[c],g=this.vertices[f.a],h=this.vertices[f.b],i=this.vertices[f.c];a.subVectors(i,h),b.subVectors(g,h),a.cross(b),a.normalize(),f.normal.copy(a)}},computeVertexNormals:function(a){var b,c,d,f,g,h;for(h=new Array(this.vertices.length),b=0,c=this.vertices.length;c>b;b++)h[b]=new e.Vector3;if(a){{var i,j,k,l=new e.Vector3,m=new e.Vector3;new e.Vector3,new e.Vector3,new e.Vector3}for(d=0,f=this.faces.length;f>d;d++)g=this.faces[d],i=this.vertices[g.a],j=this.vertices[g.b],k=this.vertices[g.c],l.subVectors(k,j),m.subVectors(i,j),l.cross(m),h[g.a].add(l),h[g.b].add(l),h[g.c].add(l)}else for(d=0,f=this.faces.length;f>d;d++)g=this.faces[d],h[g.a].add(g.normal),h[g.b].add(g.normal),h[g.c].add(g.normal);for(b=0,c=this.vertices.length;c>b;b++)h[b].normalize();for(d=0,f=this.faces.length;f>d;d++)g=this.faces[d],g.vertexNormals[0]=h[g.a].clone(),g.vertexNormals[1]=h[g.b].clone(),g.vertexNormals[2]=h[g.c].clone()},computeMorphNormals:function(){var a,b,c,d,f;for(c=0,d=this.faces.length;d>c;c++)for(f=this.faces[c],f.__originalFaceNormal?f.__originalFaceNormal.copy(f.normal):f.__originalFaceNormal=f.normal.clone(),f.__originalVertexNormals||(f.__originalVertexNormals=[]),a=0,b=f.vertexNormals.length;b>a;a++)f.__originalVertexNormals[a]?f.__originalVertexNormals[a].copy(f.vertexNormals[a]):f.__originalVertexNormals[a]=f.vertexNormals[a].clone();var g=new e.Geometry;for(g.faces=this.faces,a=0,b=this.morphTargets.length;b>a;a++){if(!this.morphNormals[a]){this.morphNormals[a]={},this.morphNormals[a].faceNormals=[],this.morphNormals[a].vertexNormals=[];var h,i,j=this.morphNormals[a].faceNormals,k=this.morphNormals[a].vertexNormals;for(c=0,d=this.faces.length;d>c;c++)f=this.faces[c],h=new e.Vector3,i={a:new e.Vector3,b:new e.Vector3,c:new e.Vector3},j.push(h),k.push(i)}var l=this.morphNormals[a];g.vertices=this.morphTargets[a].vertices,g.computeFaceNormals(),g.computeVertexNormals();var h,i;for(c=0,d=this.faces.length;d>c;c++)f=this.faces[c],h=l.faceNormals[c],i=l.vertexNormals[c],h.copy(f.normal),i.a.copy(f.vertexNormals[0]),i.b.copy(f.vertexNormals[1]),i.c.copy(f.vertexNormals[2])}for(c=0,d=this.faces.length;d>c;c++)f=this.faces[c],f.normal=f.__originalFaceNormal,f.vertexNormals=f.__originalVertexNormals},computeTangents:function(){function a(a,b,c,d,e,f,g){k=a.vertices[b],l=a.vertices[c],m=a.vertices[d],n=j[e],o=j[f],p=j[g],q=l.x-k.x,r=m.x-k.x,s=l.y-k.y,t=m.y-k.y,u=l.z-k.z,v=m.z-k.z,w=o.x-n.x,x=p.x-n.x,y=o.y-n.y,z=p.y-n.y,A=1/(w*z-x*y),G.set((z*q-y*r)*A,(z*s-y*t)*A,(z*u-y*v)*A),H.set((w*r-x*q)*A,(w*t-x*s)*A,(w*v-x*u)*A),E[b].add(G),E[c].add(G),E[d].add(G),F[b].add(H),F[c].add(H),F[d].add(H)}var b,c,d,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E=[],F=[],G=new e.Vector3,H=new e.Vector3,I=new e.Vector3,J=new e.Vector3,K=new e.Vector3;for(d=0,f=this.vertices.length;f>d;d++)E[d]=new e.Vector3,F[d]=new e.Vector3;for(b=0,c=this.faces.length;c>b;b++)i=this.faces[b],j=this.faceVertexUvs[0][b],a(this,i.a,i.b,i.c,0,1,2);var L=["a","b","c","d"];for(b=0,c=this.faces.length;c>b;b++)for(i=this.faces[b],g=0;gC?-1:1,i.vertexTangents[g]=new e.Vector4(I.x,I.y,I.z,D);this.hasTangents=!0},computeLineDistances:function(){for(var a=0,b=this.vertices,c=0,d=b.length;d>c;c++)c>0&&(a+=b[c].distanceTo(b[c-1])),this.lineDistances[c]=a},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new e.Box3),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new e.Sphere),this.boundingSphere.setFromPoints(this.vertices)},mergeVertices:function(){var a,b,c,d,e,f,g,h,i={},j=[],k=[],l=4,m=Math.pow(10,l);for(c=0,d=this.vertices.length;d>c;c++)a=this.vertices[c],b=Math.round(a.x*m)+"_"+Math.round(a.y*m)+"_"+Math.round(a.z*m),void 0===i[b]?(i[b]=c,j.push(this.vertices[c]),k[c]=j.length-1):k[c]=k[i[b]];var n=[];for(c=0,d=this.faces.length;d>c;c++){e=this.faces[c],e.a=k[e.a],e.b=k[e.b],e.c=k[e.c],f=[e.a,e.b,e.c];for(var o=-1,p=0;3>p;p++)if(f[p]==f[(p+1)%3]){o=p,n.push(c);break}}for(c=n.length-1;c>=0;c--){var q=n[c];for(this.faces.splice(q,1),g=0,h=this.faceVertexUvs.length;h>g;g++)this.faceVertexUvs[g].splice(q,1)}var r=this.vertices.length-j.length;return this.vertices=j,r},makeGroups:function(){var a=0;return function(b){var c,d,e,f,g,h={},i=this.morphTargets.length,j=this.morphNormals.length;for(this.geometryGroups={},c=0,d=this.faces.length;d>c;c++)e=this.faces[c],f=b?e.materialIndex:0,f in h||(h[f]={hash:f,counter:0}),g=h[f].hash+"_"+h[f].counter,g in this.geometryGroups||(this.geometryGroups[g]={faces3:[],materialIndex:f,vertices:0,numMorphTargets:i,numMorphNormals:j}),this.geometryGroups[g].vertices+3>65535&&(h[f].counter+=1,g=h[f].hash+"_"+h[f].counter,g in this.geometryGroups||(this.geometryGroups[g]={faces3:[],materialIndex:f,vertices:0,numMorphTargets:i,numMorphNormals:j})),this.geometryGroups[g].faces3.push(c),this.geometryGroups[g].vertices+=3;this.geometryGroupsList=[];for(var k in this.geometryGroups)this.geometryGroups[k].id=a++,this.geometryGroupsList.push(this.geometryGroups[k])}}(),clone:function(){for(var a=new e.Geometry,b=this.vertices,c=0,d=b.length;d>c;c++)a.vertices.push(b[c].clone());for(var f=this.faces,c=0,d=f.length;d>c;c++)a.faces.push(f[c].clone());for(var g=this.faceVertexUvs[0],c=0,d=g.length;d>c;c++){for(var h=g[c],i=[],j=0,k=h.length;k>j;j++)i.push(new e.Vector2(h[j].x,h[j].y));a.faceVertexUvs[0].push(i)}return a},dispose:function(){this.dispatchEvent({type:"dispose"})}},e.EventDispatcher.prototype.apply(e.Geometry.prototype),e.GeometryIdCount=0,e.Geometry2=function(a){e.BufferGeometry.call(this),this.vertices=this.addAttribute("position",Float32Array,a,3).array,this.normals=this.addAttribute("normal",Float32Array,a,3).array,this.uvs=this.addAttribute("uv",Float32Array,a,2).array,this.boundingBox=null,this.boundingSphere=null},e.Geometry2.prototype=Object.create(e.BufferGeometry.prototype),e.Camera=function(){e.Object3D.call(this),this.matrixWorldInverse=new e.Matrix4,this.projectionMatrix=new e.Matrix4},e.Camera.prototype=Object.create(e.Object3D.prototype),e.Camera.prototype.lookAt=function(){var a=new e.Matrix4;return function(b){a.lookAt(this.position,b,this.up),this.quaternion.setFromRotationMatrix(a)}}(),e.Camera.prototype.clone=function(a){return void 0===a&&(a=new e.Camera),e.Object3D.prototype.clone.call(this,a),a.matrixWorldInverse.copy(this.matrixWorldInverse),a.projectionMatrix.copy(this.projectionMatrix),a},e.OrthographicCamera=function(a,b,c,d,f,g){e.Camera.call(this),this.left=a,this.right=b,this.top=c,this.bottom=d,this.near=void 0!==f?f:.1,this.far=void 0!==g?g:2e3,this.updateProjectionMatrix()},e.OrthographicCamera.prototype=Object.create(e.Camera.prototype),e.OrthographicCamera.prototype.updateProjectionMatrix=function(){this.projectionMatrix.makeOrthographic(this.left,this.right,this.top,this.bottom,this.near,this.far)},e.OrthographicCamera.prototype.clone=function(){var a=new e.OrthographicCamera;return e.Camera.prototype.clone.call(this,a),a.left=this.left,a.right=this.right,a.top=this.top,a.bottom=this.bottom,a.near=this.near,a.far=this.far,a},e.PerspectiveCamera=function(a,b,c,d){e.Camera.call(this),this.fov=void 0!==a?a:50,this.aspect=void 0!==b?b:1,this.near=void 0!==c?c:.1,this.far=void 0!==d?d:2e3,this.updateProjectionMatrix()},e.PerspectiveCamera.prototype=Object.create(e.Camera.prototype),e.PerspectiveCamera.prototype.setLens=function(a,b){void 0===b&&(b=24),this.fov=2*e.Math.radToDeg(Math.atan(b/(2*a))),this.updateProjectionMatrix()},e.PerspectiveCamera.prototype.setViewOffset=function(a,b,c,d,e,f){this.fullWidth=a,this.fullHeight=b,this.x=c,this.y=d,this.width=e,this.height=f,this.updateProjectionMatrix()},e.PerspectiveCamera.prototype.updateProjectionMatrix=function(){if(this.fullWidth){var a=this.fullWidth/this.fullHeight,b=Math.tan(e.Math.degToRad(.5*this.fov))*this.near,c=-b,d=a*c,f=a*b,g=Math.abs(f-d),h=Math.abs(b-c);this.projectionMatrix.makeFrustum(d+this.x*g/this.fullWidth,d+(this.x+this.width)*g/this.fullWidth,b-(this.y+this.height)*h/this.fullHeight,b-this.y*h/this.fullHeight,this.near,this.far)}else this.projectionMatrix.makePerspective(this.fov,this.aspect,this.near,this.far)},e.PerspectiveCamera.prototype.clone=function(){var a=new e.PerspectiveCamera;return e.Camera.prototype.clone.call(this,a),a.fov=this.fov,a.aspect=this.aspect,a.near=this.near,a.far=this.far,a},e.Light=function(a){e.Object3D.call(this),this.color=new e.Color(a)},e.Light.prototype=Object.create(e.Object3D.prototype),e.Light.prototype.clone=function(a){return void 0===a&&(a=new e.Light),e.Object3D.prototype.clone.call(this,a),a.color.copy(this.color),a},e.AmbientLight=function(a){e.Light.call(this,a)},e.AmbientLight.prototype=Object.create(e.Light.prototype),e.AmbientLight.prototype.clone=function(){var a=new e.AmbientLight;return e.Light.prototype.clone.call(this,a),a},e.AreaLight=function(a,b){e.Light.call(this,a),this.normal=new e.Vector3(0,-1,0),this.right=new e.Vector3(1,0,0),this.intensity=void 0!==b?b:1,this.width=1,this.height=1,this.constantAttenuation=1.5,this.linearAttenuation=.5,this.quadraticAttenuation=.1},e.AreaLight.prototype=Object.create(e.Light.prototype),e.DirectionalLight=function(a,b){e.Light.call(this,a),this.position.set(0,1,0),this.target=new e.Object3D,this.intensity=void 0!==b?b:1,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraLeft=-500,this.shadowCameraRight=500,this.shadowCameraTop=500,this.shadowCameraBottom=-500,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.shadowCascade=!1,this.shadowCascadeOffset=new e.Vector3(0,0,-1e3),this.shadowCascadeCount=2,this.shadowCascadeBias=[0,0,0],this.shadowCascadeWidth=[512,512,512],this.shadowCascadeHeight=[512,512,512],this.shadowCascadeNearZ=[-1,.99,.998],this.shadowCascadeFarZ=[.99,.998,1],this.shadowCascadeArray=[],this.shadowMap=null,this.shadowMapSize=null,this.shadowCamera=null,this.shadowMatrix=null},e.DirectionalLight.prototype=Object.create(e.Light.prototype),e.DirectionalLight.prototype.clone=function(){var a=new e.DirectionalLight;return e.Light.prototype.clone.call(this,a),a.target=this.target.clone(),a.intensity=this.intensity,a.castShadow=this.castShadow,a.onlyShadow=this.onlyShadow,a},e.HemisphereLight=function(a,b,c){e.Light.call(this,a),this.position.set(0,100,0),this.groundColor=new e.Color(b),this.intensity=void 0!==c?c:1},e.HemisphereLight.prototype=Object.create(e.Light.prototype),e.HemisphereLight.prototype.clone=function(){var a=new e.HemisphereLight;return e.Light.prototype.clone.call(this,a),a.groundColor.copy(this.groundColor),a.intensity=this.intensity,a},e.PointLight=function(a,b,c){e.Light.call(this,a),this.intensity=void 0!==b?b:1,this.distance=void 0!==c?c:0},e.PointLight.prototype=Object.create(e.Light.prototype),e.PointLight.prototype.clone=function(){var a=new e.PointLight;return e.Light.prototype.clone.call(this,a),a.intensity=this.intensity,a.distance=this.distance,a},e.SpotLight=function(a,b,c,d,f){e.Light.call(this,a),this.position.set(0,1,0),this.target=new e.Object3D,this.intensity=void 0!==b?b:1,this.distance=void 0!==c?c:0,this.angle=void 0!==d?d:Math.PI/3,this.exponent=void 0!==f?f:10,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraFov=50,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.shadowMap=null,this.shadowMapSize=null,this.shadowCamera=null,this.shadowMatrix=null},e.SpotLight.prototype=Object.create(e.Light.prototype),e.SpotLight.prototype.clone=function(){var a=new e.SpotLight;return e.Light.prototype.clone.call(this,a),a.target=this.target.clone(),a.intensity=this.intensity,a.distance=this.distance,a.angle=this.angle,a.exponent=this.exponent,a.castShadow=this.castShadow,a.onlyShadow=this.onlyShadow,a},e.Loader=function(a){this.showStatus=a,this.statusDomElement=a?e.Loader.prototype.addStatusElement():null,this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}},e.Loader.prototype={constructor:e.Loader,crossOrigin:void 0,addStatusElement:function(){var a=document.createElement("div");return a.style.position="absolute",a.style.right="0px",a.style.top="0px",a.style.fontSize="0.8em",a.style.textAlign="left",a.style.background="rgba(0,0,0,0.25)",a.style.color="#fff",a.style.width="120px",a.style.padding="0.5em 0.5em 0.5em 0.5em",a.style.zIndex=1e3,a.innerHTML="Loading ...",a},updateProgress:function(a){var b="Loaded ";b+=a.total?(100*a.loaded/a.total).toFixed(0)+"%":(a.loaded/1e3).toFixed(2)+" KB",this.statusDomElement.innerHTML=b},extractUrlBase:function(a){var b=a.split("/");return 1===b.length?"./":(b.pop(),b.join("/")+"/")},initMaterials:function(a,b){for(var c=[],d=0;db;b++){var d=a[b];if(d instanceof e.ShaderMaterial)return!0}return!1},createMaterial:function(a,b){function c(a){var b=Math.log(a)/Math.LN2;return Math.floor(b)==b}function d(a){var b=Math.log(a)/Math.LN2;return Math.pow(2,Math.round(b))}function f(a,b){var e=new Image;e.onload=function(){if(c(this.width)&&c(this.height))a.image=this;else{var b=d(this.width),e=d(this.height);a.image.width=b,a.image.height=e,a.image.getContext("2d").drawImage(this,0,0,b,e)}a.needsUpdate=!0},void 0!==i.crossOrigin&&(e.crossOrigin=i.crossOrigin),e.src=b}function g(a,c,d,g,h,i,j){var k=/\.dds$/i.test(d),l=b+d;if(k){var m=e.ImageUtils.loadCompressedTexture(l);a[c]=m}else{var m=document.createElement("canvas");a[c]=new e.Texture(m)}if(a[c].sourceFile=d,g&&(a[c].repeat.set(g[0],g[1]),1!==g[0]&&(a[c].wrapS=e.RepeatWrapping),1!==g[1]&&(a[c].wrapT=e.RepeatWrapping)),h&&a[c].offset.set(h[0],h[1]),i){var n={repeat:e.RepeatWrapping,mirror:e.MirroredRepeatWrapping};void 0!==n[i[0]]&&(a[c].wrapS=n[i[0]]),void 0!==n[i[1]]&&(a[c].wrapT=n[i[1]])}j&&(a[c].anisotropy=j),k||f(a[c],l)}function h(a){return(255*a[0]<<16)+(255*a[1]<<8)+255*a[2]}var i=this,j="MeshLambertMaterial",k={color:15658734,opacity:1,map:null,lightMap:null,normalMap:null,bumpMap:null,wireframe:!1};if(a.shading){var l=a.shading.toLowerCase();"phong"===l?j="MeshPhongMaterial":"basic"===l&&(j="MeshBasicMaterial")}if(void 0!==a.blending&&void 0!==e[a.blending]&&(k.blending=e[a.blending]),(void 0!==a.transparent||a.opacity<1)&&(k.transparent=a.transparent),void 0!==a.depthTest&&(k.depthTest=a.depthTest),void 0!==a.depthWrite&&(k.depthWrite=a.depthWrite),void 0!==a.visible&&(k.visible=a.visible),void 0!==a.flipSided&&(k.side=e.BackSide),void 0!==a.doubleSided&&(k.side=e.DoubleSide),void 0!==a.wireframe&&(k.wireframe=a.wireframe),void 0!==a.vertexColors&&("face"===a.vertexColors?k.vertexColors=e.FaceColors:a.vertexColors&&(k.vertexColors=e.VertexColors)),a.colorDiffuse?k.color=h(a.colorDiffuse):a.DbgColor&&(k.color=a.DbgColor),a.colorSpecular&&(k.specular=h(a.colorSpecular)),a.colorAmbient&&(k.ambient=h(a.colorAmbient)),a.transparency&&(k.opacity=a.transparency),a.specularCoef&&(k.shininess=a.specularCoef),a.mapDiffuse&&b&&g(k,"map",a.mapDiffuse,a.mapDiffuseRepeat,a.mapDiffuseOffset,a.mapDiffuseWrap,a.mapDiffuseAnisotropy),a.mapLight&&b&&g(k,"lightMap",a.mapLight,a.mapLightRepeat,a.mapLightOffset,a.mapLightWrap,a.mapLightAnisotropy),a.mapBump&&b&&g(k,"bumpMap",a.mapBump,a.mapBumpRepeat,a.mapBumpOffset,a.mapBumpWrap,a.mapBumpAnisotropy),a.mapNormal&&b&&g(k,"normalMap",a.mapNormal,a.mapNormalRepeat,a.mapNormalOffset,a.mapNormalWrap,a.mapNormalAnisotropy),a.mapSpecular&&b&&g(k,"specularMap",a.mapSpecular,a.mapSpecularRepeat,a.mapSpecularOffset,a.mapSpecularWrap,a.mapSpecularAnisotropy),a.mapBumpScale&&(k.bumpScale=a.mapBumpScale),a.mapNormal){var m=e.ShaderLib.normalmap,n=e.UniformsUtils.clone(m.uniforms);n.tNormal.value=k.normalMap,a.mapNormalFactor&&n.uNormalScale.value.set(a.mapNormalFactor,a.mapNormalFactor),k.map&&(n.tDiffuse.value=k.map,n.enableDiffuse.value=!0),k.specularMap&&(n.tSpecular.value=k.specularMap,n.enableSpecular.value=!0),k.lightMap&&(n.tAO.value=k.lightMap,n.enableAO.value=!0),n.diffuse.value.setHex(k.color),n.specular.value.setHex(k.specular),n.ambient.value.setHex(k.ambient),n.shininess.value=k.shininess,void 0!==k.opacity&&(n.opacity.value=k.opacity);var o={fragmentShader:m.fragmentShader,vertexShader:m.vertexShader,uniforms:n,lights:!0,fog:!0},p=new e.ShaderMaterial(o);k.transparent&&(p.transparent=!0)}else var p=new e[j](k);return void 0!==a.DbgName&&(p.name=a.DbgName),p}},e.XHRLoader=function(a){this.manager=void 0!==a?a:e.DefaultLoadingManager},e.XHRLoader.prototype={constructor:e.XHRLoader,load:function(a,b,c,d){var e=this,f=new XMLHttpRequest;void 0!==b&&f.addEventListener("load",function(c){b(c.target.responseText),e.manager.itemEnd(a)},!1),void 0!==c&&f.addEventListener("progress",function(a){c(a)},!1),void 0!==d&&f.addEventListener("error",function(a){d(a)},!1),void 0!==this.crossOrigin&&(f.crossOrigin=this.crossOrigin),f.open("GET",a,!0),f.send(null),e.manager.itemStart(a)},setCrossOrigin:function(a){this.crossOrigin=a}},e.ImageLoader=function(a){this.manager=void 0!==a?a:e.DefaultLoadingManager},e.ImageLoader.prototype={constructor:e.ImageLoader,load:function(a,b,c,d){var e=this,f=document.createElement("img");return void 0!==b&&f.addEventListener("load",function(){e.manager.itemEnd(a),b(this)},!1),void 0!==c&&f.addEventListener("progress",function(a){c(a)},!1),void 0!==d&&f.addEventListener("error",function(a){d(a)},!1),void 0!==this.crossOrigin&&(f.crossOrigin=this.crossOrigin),f.src=a,e.manager.itemStart(a),f},setCrossOrigin:function(a){this.crossOrigin=a}},e.JSONLoader=function(a){e.Loader.call(this,a),this.withCredentials=!1},e.JSONLoader.prototype=Object.create(e.Loader.prototype),e.JSONLoader.prototype.load=function(a,b,c){c=c&&"string"==typeof c?c:this.extractUrlBase(a),this.onLoadStart(),this.loadAjaxJSON(this,a,b,c)},e.JSONLoader.prototype.loadAjaxJSON=function(a,b,c,d,e){var f=new XMLHttpRequest,g=0;f.onreadystatechange=function(){if(f.readyState===f.DONE)if(200===f.status||0===f.status){if(f.responseText){var h=JSON.parse(f.responseText);if("scene"===h.metadata.type)return void console.error('THREE.JSONLoader: "'+b+'" seems to be a Scene. Use THREE.SceneLoader instead.');var i=a.parse(h,d);c(i.geometry,i.materials)}else console.error('THREE.JSONLoader: "'+b+'" seems to be unreachable or the file is empty.');a.onLoadComplete()}else console.error("THREE.JSONLoader: Couldn't load \""+b+'" ('+f.status+")");else f.readyState===f.LOADING?e&&(0===g&&(g=f.getResponseHeader("Content-Length")),e({total:g,loaded:f.responseText.length})):f.readyState===f.HEADERS_RECEIVED&&void 0!==e&&(g=f.getResponseHeader("Content-Length"))},f.open("GET",b,!0),f.withCredentials=this.withCredentials,f.send(null)},e.JSONLoader.prototype.parse=function(a,b){function c(b){function c(a,b){return a&1<d;d++)g.faceVertexUvs[d]=[]}for(i=0,j=H.length;j>i;)w=new e.Vector3,w.x=H[i++]*b,w.y=H[i++]*b,w.z=H[i++]*b,g.vertices.push(w);for(i=0,j=G.length;j>i;)if(o=G[i++],p=c(o,0),q=c(o,1),r=c(o,3),s=c(o,4),t=c(o,5),u=c(o,6),v=c(o,7),p){if(y=new e.Face3,y.a=G[i],y.b=G[i+1],y.c=G[i+3],z=new e.Face3,z.a=G[i+1],z.b=G[i+2],z.c=G[i+3],i+=4,q&&(n=G[i++],y.materialIndex=n,z.materialIndex=n),h=g.faces.length,r)for(d=0;K>d;d++)for(C=a.uvs[d],g.faceVertexUvs[d][h]=[],g.faceVertexUvs[d][h+1]=[],f=0;4>f;f++)m=G[i++],E=C[2*m],F=C[2*m+1],D=new e.Vector2(E,F),2!==f&&g.faceVertexUvs[d][h].push(D),0!==f&&g.faceVertexUvs[d][h+1].push(D);if(s&&(l=3*G[i++],y.normal.set(I[l++],I[l++],I[l]),z.normal.copy(y.normal)),t)for(d=0;4>d;d++)l=3*G[i++],B=new e.Vector3(I[l++],I[l++],I[l]),2!==d&&y.vertexNormals.push(B),0!==d&&z.vertexNormals.push(B);if(u&&(k=G[i++],A=J[k],y.color.setHex(A),z.color.setHex(A)),v)for(d=0;4>d;d++)k=G[i++],A=J[k],2!==d&&y.vertexColors.push(new e.Color(A)),0!==d&&z.vertexColors.push(new e.Color(A));g.faces.push(y),g.faces.push(z)}else{if(x=new e.Face3,x.a=G[i++],x.b=G[i++],x.c=G[i++],q&&(n=G[i++],x.materialIndex=n),h=g.faces.length,r)for(d=0;K>d;d++)for(C=a.uvs[d],g.faceVertexUvs[d][h]=[],f=0;3>f;f++)m=G[i++],E=C[2*m],F=C[2*m+1],D=new e.Vector2(E,F),g.faceVertexUvs[d][h].push(D);if(s&&(l=3*G[i++],x.normal.set(I[l++],I[l++],I[l])),t)for(d=0;3>d;d++)l=3*G[i++],B=new e.Vector3(I[l++],I[l++],I[l]),x.vertexNormals.push(B);if(u&&(k=G[i++],x.color.setHex(J[k])),v)for(d=0;3>d;d++)k=G[i++],x.vertexColors.push(new e.Color(J[k]));g.faces.push(x)}}function d(){if(a.skinWeights)for(var b=0,c=a.skinWeights.length;c>b;b+=2){var d=a.skinWeights[b],f=a.skinWeights[b+1],h=0,i=0;g.skinWeights.push(new e.Vector4(d,f,h,i))}if(a.skinIndices)for(var b=0,c=a.skinIndices.length;c>b;b+=2){var j=a.skinIndices[b],k=a.skinIndices[b+1],l=0,m=0;g.skinIndices.push(new e.Vector4(j,k,l,m))}g.bones=a.bones,g.bones&&g.bones.length>0&&(g.skinWeights.length!==g.skinIndices.length||g.skinIndices.length!==g.vertices.length)&&console.warn("When skinning, number of vertices ("+g.vertices.length+"), skinIndices ("+g.skinIndices.length+"), and skinWeights ("+g.skinWeights.length+") should match."),g.animation=a.animation,g.animations=a.animations}function f(b){if(void 0!==a.morphTargets){var c,d,f,h,i,j;for(c=0,d=a.morphTargets.length;d>c;c++)for(g.morphTargets[c]={},g.morphTargets[c].name=a.morphTargets[c].name,g.morphTargets[c].vertices=[],i=g.morphTargets[c].vertices,j=a.morphTargets[c].vertices,f=0,h=j.length;h>f;f+=3){var k=new e.Vector3;k.x=j[f]*b,k.y=j[f+1]*b,k.z=j[f+2]*b,i.push(k)}}if(void 0!==a.morphColors){var c,d,l,m,n,o,p;for(c=0,d=a.morphColors.length;d>c;c++)for(g.morphColors[c]={},g.morphColors[c].name=a.morphColors[c].name,g.morphColors[c].colors=[],n=g.morphColors[c].colors,o=a.morphColors[c].colors,l=0,m=o.length;m>l;l+=3)p=new e.Color(16755200),p.setRGB(o[l],o[l+1],o[l+2]),n.push(p)}}var g=new e.Geometry,h=void 0!==a.scale?1/a.scale:1;if(c(h),d(),f(h),g.computeCentroids(),g.computeFaceNormals(),g.computeBoundingSphere(),void 0===a.materials)return{geometry:g};var i=this.initMaterials(a.materials,b);return this.needsTangents(i)&&g.computeTangents(),{geometry:g,materials:i}},e.LoadingManager=function(a,b,c){var d=this,e=0,f=0;this.onLoad=a,this.onProgress=b,this.onError=c,this.itemStart=function(){f++},this.itemEnd=function(a){e++,void 0!==d.onProgress&&d.onProgress(a,e,f),e===f&&void 0!==d.onLoad&&d.onLoad()}},e.DefaultLoadingManager=new e.LoadingManager,e.BufferGeometryLoader=function(a){this.manager=void 0!==a?a:e.DefaultLoadingManager},e.BufferGeometryLoader.prototype={constructor:e.BufferGeometryLoader,load:function(a,b){var c=this,d=new e.XHRLoader;d.setCrossOrigin(this.crossOrigin),d.load(a,function(a){b(c.parse(JSON.parse(a)))})},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a){var b=new e.BufferGeometry,c=a.attributes,f=a.offsets,g=a.boundingSphere;for(var h in c){var i=c[h];b.attributes[h]={itemSize:i.itemSize,array:new d[i.type](i.array)}}return void 0!==f&&(b.offsets=JSON.parse(JSON.stringify(f))),void 0!==g&&(b.boundingSphere=new e.Sphere((new e.Vector3).fromArray(void 0!==g.center?g.center:[0,0,0]),g.radius)),b}},e.Geometry2Loader=function(a){this.manager=void 0!==a?a:e.DefaultLoadingManager},e.Geometry2Loader.prototype={constructor:e.Geometry2Loader,load:function(a,b){var c=this,d=new e.XHRLoader;d.setCrossOrigin(this.crossOrigin),d.load(a,function(a){b(c.parse(JSON.parse(a)))})},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a){var b=new e.Geometry2(a.vertices.length/3),c=["vertices","normals","uvs"],d=a.boundingSphere;for(var f in c){var g=c[f];b[g].set(a[g])}return void 0!==d&&(b.boundingSphere=new e.Sphere((new e.Vector3).fromArray(void 0!==d.center?d.center:[0,0,0]),d.radius)),b}},e.MaterialLoader=function(a){this.manager=void 0!==a?a:e.DefaultLoadingManager},e.MaterialLoader.prototype={constructor:e.MaterialLoader,load:function(a,b){var c=this,d=new e.XHRLoader;d.setCrossOrigin(this.crossOrigin),d.load(a,function(a){b(c.parse(JSON.parse(a)))})},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a){var b=new e[a.type];if(void 0!==a.color&&b.color.setHex(a.color),void 0!==a.ambient&&b.ambient.setHex(a.ambient),void 0!==a.emissive&&b.emissive.setHex(a.emissive),void 0!==a.specular&&b.specular.setHex(a.specular),void 0!==a.shininess&&(b.shininess=a.shininess),void 0!==a.vertexColors&&(b.vertexColors=a.vertexColors),void 0!==a.blending&&(b.blending=a.blending),void 0!==a.side&&(b.side=a.side),void 0!==a.opacity&&(b.opacity=a.opacity),void 0!==a.transparent&&(b.transparent=a.transparent),void 0!==a.wireframe&&(b.wireframe=a.wireframe),void 0!==a.materials)for(var c=0,d=a.materials.length;d>c;c++)b.materials.push(this.parse(a.materials[c]));return b}},e.ObjectLoader=function(a){this.manager=void 0!==a?a:e.DefaultLoadingManager},e.ObjectLoader.prototype={constructor:e.ObjectLoader,load:function(a,b){var c=this,d=new e.XHRLoader(c.manager);d.setCrossOrigin(this.crossOrigin),d.load(a,function(a){b(c.parse(JSON.parse(a)))})},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a){var b=this.parseGeometries(a.geometries),c=this.parseMaterials(a.materials),d=this.parseObject(a.object,b,c);return d},parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new e.JSONLoader,d=new e.Geometry2Loader,f=new e.BufferGeometryLoader,g=0,h=a.length;h>g;g++){var i,j=a[g];switch(j.type){case"PlaneGeometry":i=new e.PlaneGeometry(j.width,j.height,j.widthSegments,j.heightSegments);break;case"BoxGeometry":case"CubeGeometry":i=new e.BoxGeometry(j.width,j.height,j.depth,j.widthSegments,j.heightSegments,j.depthSegments);break;case"CircleGeometry":i=new e.CircleGeometry(j.radius,j.segments);break;case"CylinderGeometry":i=new e.CylinderGeometry(j.radiusTop,j.radiusBottom,j.height,j.radialSegments,j.heightSegments,j.openEnded);break;case"SphereGeometry":i=new e.SphereGeometry(j.radius,j.widthSegments,j.heightSegments,j.phiStart,j.phiLength,j.thetaStart,j.thetaLength);break;case"IcosahedronGeometry":i=new e.IcosahedronGeometry(j.radius,j.detail);break;case"TorusGeometry":i=new e.TorusGeometry(j.radius,j.tube,j.radialSegments,j.tubularSegments,j.arc);break;case"TorusKnotGeometry":i=new e.TorusKnotGeometry(j.radius,j.tube,j.radialSegments,j.tubularSegments,j.p,j.q,j.heightScale);break;case"BufferGeometry":i=f.parse(j.data);break;case"Geometry2":i=d.parse(j.data);break;case"Geometry":i=c.parse(j.data).geometry}i.uuid=j.uuid,void 0!==j.name&&(i.name=j.name),b[j.uuid]=i}return b},parseMaterials:function(a){var b={};if(void 0!==a)for(var c=new e.MaterialLoader,d=0,f=a.length;f>d;d++){var g=a[d],h=c.parse(g);h.uuid=g.uuid,void 0!==g.name&&(h.name=g.name),b[g.uuid]=h}return b},parseObject:function(){var a=new e.Matrix4;return function(b,c,d){var f;switch(b.type){case"Scene":f=new e.Scene;break;case"PerspectiveCamera":f=new e.PerspectiveCamera(b.fov,b.aspect,b.near,b.far);break;case"OrthographicCamera":f=new e.OrthographicCamera(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case"AmbientLight":f=new e.AmbientLight(b.color);break;case"DirectionalLight":f=new e.DirectionalLight(b.color,b.intensity);break;case"PointLight":f=new e.PointLight(b.color,b.intensity,b.distance);break;case"SpotLight":f=new e.SpotLight(b.color,b.intensity,b.distance,b.angle,b.exponent);break;case"HemisphereLight":f=new e.HemisphereLight(b.color,b.groundColor,b.intensity);break;case"Mesh":var g=c[b.geometry],h=d[b.material];void 0===g&&console.error("THREE.ObjectLoader: Undefined geometry "+b.geometry),void 0===h&&console.error("THREE.ObjectLoader: Undefined material "+b.material),f=new e.Mesh(g,h);break;case"Sprite":var h=d[b.material];void 0===h&&console.error("THREE.ObjectLoader: Undefined material "+b.material),f=new e.Sprite(h);break;default:f=new e.Object3D}if(f.uuid=b.uuid,void 0!==b.name&&(f.name=b.name),void 0!==b.matrix?(a.fromArray(b.matrix),a.decompose(f.position,f.quaternion,f.scale)):(void 0!==b.position&&f.position.fromArray(b.position),void 0!==b.rotation&&f.rotation.fromArray(b.rotation),void 0!==b.scale&&f.scale.fromArray(b.scale)),void 0!==b.visible&&(f.visible=b.visible),void 0!==b.userData&&(f.userData=b.userData),void 0!==b.children)for(var i in b.children)f.add(this.parseObject(b.children[i],c,d));return f}}()},e.SceneLoader=function(){this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){},this.callbackSync=function(){},this.callbackProgress=function(){},this.geometryHandlers={},this.hierarchyHandlers={},this.addGeometryHandler("ascii",e.JSONLoader) -},e.SceneLoader.prototype={constructor:e.SceneLoader,load:function(a,b){var c=this,d=new e.XHRLoader(c.manager);d.setCrossOrigin(this.crossOrigin),d.load(a,function(d){c.parse(JSON.parse(d),b,a)})},setCrossOrigin:function(a){this.crossOrigin=a},addGeometryHandler:function(a,b){this.geometryHandlers[a]={loaderClass:b}},addHierarchyHandler:function(a,b){this.hierarchyHandlers[a]={loaderClass:b}},parse:function(a,b,c){function d(a,b){return"relativeToHTML"==b?a:C+a}function f(){g(A.scene,E.objects)}function g(a,b){var c,f,h,i,j;for(var l in b){var m=A.objects[l],n=b[l];if(void 0===m){if(n.type&&n.type in B.hierarchyHandlers){if(void 0===n.loading){var o={type:1,url:1,material:1,position:1,rotation:1,scale:1,visible:1,children:1,userData:1,skin:1,morph:1,mirroredLoop:1,duration:1},s={};for(var t in n)t in o||(s[t]=n[t]);q=A.materials[n.material],n.loading=!0;var u=B.hierarchyHandlers[n.type].loaderObject;u.options?u.load(d(n.url,E.urlBaseType),k(l,a,q,n)):u.load(d(n.url,E.urlBaseType),k(l,a,q,n),s)}}else if(void 0!==n.geometry){if(p=A.geometries[n.geometry]){var w=!1;if(q=A.materials[n.material],w=q instanceof e.ShaderMaterial,f=n.position,h=n.rotation,i=n.scale,c=n.matrix,j=n.quaternion,n.material||(q=new e.MeshFaceMaterial(A.face_materials[n.geometry])),q instanceof e.MeshFaceMaterial&&0===q.materials.length&&(q=new e.MeshFaceMaterial(A.face_materials[n.geometry])),q instanceof e.MeshFaceMaterial)for(var x=0;xbb;bb++)ab[bb]=d(Z.url[bb],E.urlBaseType);var cb=/\.dds$/i.test(ab[0]);t=cb?e.ImageUtils.loadCompressedTextureCube(ab,Z.mapping,N(_)):e.ImageUtils.loadTextureCube(ab,Z.mapping,N(_))}else{var cb=/\.dds$/i.test(Z.url),db=d(Z.url,E.urlBaseType),eb=N(1);if(t=cb?e.ImageUtils.loadCompressedTexture(db,Z.mapping,eb):e.ImageUtils.loadTexture(db,Z.mapping,eb),void 0!==e[Z.minFilter]&&(t.minFilter=e[Z.minFilter]),void 0!==e[Z.magFilter]&&(t.magFilter=e[Z.magFilter]),Z.anisotropy&&(t.anisotropy=Z.anisotropy),Z.repeat&&(t.repeat.set(Z.repeat[0],Z.repeat[1]),1!==Z.repeat[0]&&(t.wrapS=e.RepeatWrapping),1!==Z.repeat[1]&&(t.wrapT=e.RepeatWrapping)),Z.offset&&t.offset.set(Z.offset[0],Z.offset[1]),Z.wrap){var fb={repeat:e.RepeatWrapping,mirror:e.MirroredRepeatWrapping};void 0!==fb[Z.wrap[0]]&&(t.wrapS=fb[Z.wrap[0]]),void 0!==fb[Z.wrap[1]]&&(t.wrapT=fb[Z.wrap[1]])}}A.textures[Y]=t}var gb,hb,ib;for(gb in E.materials){hb=E.materials[gb];for(ib in hb.parameters)if("envMap"===ib||"map"===ib||"lightMap"===ib||"bumpMap"===ib)hb.parameters[ib]=A.textures[hb.parameters[ib]];else if("shading"===ib)hb.parameters[ib]="flat"===hb.parameters[ib]?e.FlatShading:e.SmoothShading;else if("side"===ib)hb.parameters[ib]="double"==hb.parameters[ib]?e.DoubleSide:"back"==hb.parameters[ib]?e.BackSide:e.FrontSide;else if("blending"===ib)hb.parameters[ib]=hb.parameters[ib]in e?e[hb.parameters[ib]]:e.NormalBlending;else if("combine"===ib)hb.parameters[ib]=hb.parameters[ib]in e?e[hb.parameters[ib]]:e.MultiplyOperation;else if("vertexColors"===ib)"face"==hb.parameters[ib]?hb.parameters[ib]=e.FaceColors:hb.parameters[ib]&&(hb.parameters[ib]=e.VertexColors);else if("wrapRGB"===ib){var jb=hb.parameters[ib];hb.parameters[ib]=new e.Vector3(jb[0],jb[1],jb[2])}if(void 0!==hb.parameters.opacity&&hb.parameters.opacity<1&&(hb.parameters.transparent=!0),hb.parameters.normalMap){var kb=e.ShaderLib.normalmap,lb=e.UniformsUtils.clone(kb.uniforms),mb=hb.parameters.color,nb=hb.parameters.specular,ob=hb.parameters.ambient,pb=hb.parameters.shininess;lb.tNormal.value=A.textures[hb.parameters.normalMap],hb.parameters.normalScale&&lb.uNormalScale.value.set(hb.parameters.normalScale[0],hb.parameters.normalScale[1]),hb.parameters.map&&(lb.tDiffuse.value=hb.parameters.map,lb.enableDiffuse.value=!0),hb.parameters.envMap&&(lb.tCube.value=hb.parameters.envMap,lb.enableReflection.value=!0,lb.reflectivity.value=hb.parameters.reflectivity),hb.parameters.lightMap&&(lb.tAO.value=hb.parameters.lightMap,lb.enableAO.value=!0),hb.parameters.specularMap&&(lb.tSpecular.value=A.textures[hb.parameters.specularMap],lb.enableSpecular.value=!0),hb.parameters.displacementMap&&(lb.tDisplacement.value=A.textures[hb.parameters.displacementMap],lb.enableDisplacement.value=!0,lb.uDisplacementBias.value=hb.parameters.displacementBias,lb.uDisplacementScale.value=hb.parameters.displacementScale),lb.diffuse.value.setHex(mb),lb.specular.value.setHex(nb),lb.ambient.value.setHex(ob),lb.shininess.value=pb,hb.parameters.opacity&&(lb.opacity.value=hb.parameters.opacity);var qb={fragmentShader:kb.fragmentShader,vertexShader:kb.vertexShader,uniforms:lb,lights:!0,fog:!0};q=new e.ShaderMaterial(qb)}else q=new e[hb.type](hb.parameters);q.name=gb,A.materials[gb]=q}for(gb in E.materials)if(hb=E.materials[gb],hb.parameters.materials){for(var rb=[],bb=0;bb0){this.morphTargetBase=-1,this.morphTargetForcedOrder=[],this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var a=0,b=this.geometry.morphTargets.length;b>a;a++)this.morphTargetInfluences.push(0),this.morphTargetDictionary[this.geometry.morphTargets[a].name]=a}},e.Mesh.prototype.getMorphTargetIndexByName=function(a){return void 0!==this.morphTargetDictionary[a]?this.morphTargetDictionary[a]:(console.log("THREE.Mesh.getMorphTargetIndexByName: morph target "+a+" does not exist. Returning 0."),0)},e.Mesh.prototype.clone=function(a){return void 0===a&&(a=new e.Mesh(this.geometry,this.material)),e.Object3D.prototype.clone.call(this,a),a},e.Bone=function(a){e.Object3D.call(this),this.skin=a,this.skinMatrix=new e.Matrix4},e.Bone.prototype=Object.create(e.Object3D.prototype),e.Bone.prototype.update=function(a,b){this.matrixAutoUpdate&&(b|=this.updateMatrix()),(b||this.matrixWorldNeedsUpdate)&&(a?this.skinMatrix.multiplyMatrices(a,this.matrix):this.skinMatrix.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,b=!0);var c,d=this.children.length;for(c=0;d>c;c++)this.children[c].update(this.skinMatrix,b)},e.SkinnedMesh=function(a,b,c){e.Mesh.call(this,a,b),this.useVertexTexture=void 0!==c?c:!0,this.identityMatrix=new e.Matrix4,this.bones=[],this.boneMatrices=[];var d,f,g,h,i,j;if(this.geometry&&void 0!==this.geometry.bones){for(d=0;d256?64:k>64?32:k>16?16:8,this.boneTextureWidth=l,this.boneTextureHeight=l,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new e.DataTexture(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,e.RGBAFormat,e.FloatType),this.boneTexture.minFilter=e.NearestFilter,this.boneTexture.magFilter=e.NearestFilter,this.boneTexture.generateMipmaps=!1,this.boneTexture.flipY=!1}else this.boneMatrices=new Float32Array(16*k);this.pose()}},e.SkinnedMesh.prototype=Object.create(e.Mesh.prototype),e.SkinnedMesh.prototype.addBone=function(a){return void 0===a&&(a=new e.Bone(this)),this.bones.push(a),a},e.SkinnedMesh.prototype.updateMatrixWorld=function(){var a=new e.Matrix4;return function(b){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||b)&&(this.parent?this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix):this.matrixWorld.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,b=!0);for(var c=0,d=this.children.length;d>c;c++){var f=this.children[c];f instanceof e.Bone?f.update(this.identityMatrix,!1):f.updateMatrixWorld(!0)}if(void 0==this.boneInverses){this.boneInverses=[];for(var g=0,h=this.bones.length;h>g;g++){var i=new e.Matrix4;i.getInverse(this.bones[g].skinMatrix),this.boneInverses.push(i)}}for(var g=0,h=this.bones.length;h>g;g++)a.multiplyMatrices(this.bones[g].skinMatrix,this.boneInverses[g]),a.flattenToArrayOffset(this.boneMatrices,16*g);this.useVertexTexture&&(this.boneTexture.needsUpdate=!0)}}(),e.SkinnedMesh.prototype.pose=function(){this.updateMatrixWorld(!0),this.normalizeSkinWeights()},e.SkinnedMesh.prototype.normalizeSkinWeights=function(){if(this.geometry instanceof e.Geometry)for(var a=0;ae;e++){var g=a.morphTargets[e],h=g.name.match(d);if(h&&h.length>1){{var i=h[1];h[2]}c[i]||(c[i]={start:1/0,end:-1/0});var j=c[i];ej.end&&(j.end=e),b||(b=i)}}a.firstAnimation=b},e.MorphAnimMesh.prototype.setAnimationLabel=function(a,b,c){this.geometry.animations||(this.geometry.animations={}),this.geometry.animations[a]={start:b,end:c}},e.MorphAnimMesh.prototype.playAnimation=function(a,b){var c=this.geometry.animations[a];c?(this.setFrameRange(c.start,c.end),this.duration=1e3*((c.end-c.start)/b),this.time=0):console.warn("animation["+a+"] undefined")},e.MorphAnimMesh.prototype.updateAnimation=function(a){var b=this.duration/this.length;this.time+=this.direction*a,this.mirroredLoop?(this.time>this.duration||this.time<0)&&(this.direction*=-1,this.time>this.duration&&(this.time=this.duration,this.directionBackwards=!0),this.time<0&&(this.time=0,this.directionBackwards=!1)):(this.time=this.time%this.duration,this.time<0&&(this.time+=this.duration));var c=this.startKeyframe+e.Math.clamp(Math.floor(this.time/b),0,this.length-1);c!==this.currentKeyframe&&(this.morphTargetInfluences[this.lastKeyframe]=0,this.morphTargetInfluences[this.currentKeyframe]=1,this.morphTargetInfluences[c]=0,this.lastKeyframe=this.currentKeyframe,this.currentKeyframe=c);var d=this.time%b/b;this.directionBackwards&&(d=1-d),this.morphTargetInfluences[this.currentKeyframe]=d,this.morphTargetInfluences[this.lastKeyframe]=1-d},e.MorphAnimMesh.prototype.clone=function(a){return void 0===a&&(a=new e.MorphAnimMesh(this.geometry,this.material)),a.duration=this.duration,a.mirroredLoop=this.mirroredLoop,a.time=this.time,a.lastKeyframe=this.lastKeyframe,a.currentKeyframe=this.currentKeyframe,a.direction=this.direction,a.directionBackwards=this.directionBackwards,e.Mesh.prototype.clone.call(this,a),a -},e.LOD=function(){e.Object3D.call(this),this.objects=[]},e.LOD.prototype=Object.create(e.Object3D.prototype),e.LOD.prototype.addLevel=function(a,b){void 0===b&&(b=0),b=Math.abs(b);for(var c=0;cb&&!(a1){a.setFromMatrixPosition(c.matrixWorld),b.setFromMatrixPosition(this.matrixWorld);var d=a.distanceTo(b);this.objects[0].object.visible=!0;for(var e=1,f=this.objects.length;f>e&&d>=this.objects[e].distance;e++)this.objects[e-1].object.visible=!1,this.objects[e].object.visible=!0;for(;f>e;e++)this.objects[e].object.visible=!1}}}(),e.LOD.prototype.clone=function(a){void 0===a&&(a=new e.LOD),e.Object3D.prototype.clone.call(this,a);for(var b=0,c=this.objects.length;c>b;b++){var d=this.objects[b].object.clone();d.visible=0===b,a.addLevel(d,this.objects[b].distance)}return a},e.Sprite=function(){var a=new e.Geometry2(3);return a.vertices.set([-.5,-.5,0,.5,-.5,0,.5,.5,0]),function(b){e.Object3D.call(this),this.geometry=a,this.material=void 0!==b?b:new e.SpriteMaterial}}(),e.Sprite.prototype=Object.create(e.Object3D.prototype),e.Sprite.prototype.updateMatrix=function(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0},e.Sprite.prototype.clone=function(a){return void 0===a&&(a=new e.Sprite(this.material)),e.Object3D.prototype.clone.call(this,a),a},e.Particle=e.Sprite,e.Scene=function(){e.Object3D.call(this),this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0,this.matrixAutoUpdate=!1,this.__lights=[],this.__objectsAdded=[],this.__objectsRemoved=[]},e.Scene.prototype=Object.create(e.Object3D.prototype),e.Scene.prototype.__addObject=function(a){if(a instanceof e.Light)-1===this.__lights.indexOf(a)&&this.__lights.push(a),a.target&&void 0===a.target.parent&&this.add(a.target);else if(!(a instanceof e.Camera||a instanceof e.Bone)){this.__objectsAdded.push(a);var b=this.__objectsRemoved.indexOf(a);-1!==b&&this.__objectsRemoved.splice(b,1)}this.dispatchEvent({type:"objectAdded",object:a}),a.dispatchEvent({type:"addedToScene",scene:this});for(var c=0;ca;a++){var c=C[a],d=c.color;c instanceof e.AmbientLight?Gb.add(d):c instanceof e.DirectionalLight?Hb.add(d):c instanceof e.PointLight&&Ib.add(d)}}function c(a,b,c){for(var d=0,f=C.length;f>d;d++){var g=C[d];if(Bb.copy(g.color),g instanceof e.DirectionalLight){var h=Jb.setFromMatrixPosition(g.matrixWorld).normalize(),i=b.dot(h);if(0>=i)continue;i*=g.intensity,c.add(Bb.multiplyScalar(i))}else if(g instanceof e.PointLight){var h=Jb.setFromMatrixPosition(g.matrixWorld),i=b.dot(Jb.subVectors(h,a).normalize());if(0>=i)continue;if(i*=0==g.distance?1:1-Math.min(a.distanceTo(h)/g.distance,1),0==i)continue;i*=g.intensity,c.add(Bb.multiplyScalar(i))}}}function f(a,b,c){r(c.opacity),s(c.blending);var d=b.scale.x*gb,f=b.scale.y*hb,g=.5*Math.sqrt(d*d+f*f);if(Fb.min.set(a.x-g,a.y-g),Fb.max.set(a.x+g,a.y+g),c instanceof e.SpriteMaterial||c instanceof e.ParticleSystemMaterial){var h=c.map;if(null!==h){h.hasEventListener("update",l)===!1&&(void 0!==h.image&&h.image.width>0&&m(h),h.addEventListener("update",l));var i=Cb[h.id];x(void 0!==i?i:"rgba( 0, 0, 0, 1 )");var j=h.image,k=j.width*h.offset.x,n=j.height*h.offset.y,o=j.width*h.repeat.x,p=j.height*h.repeat.y,q=d/o,t=f/p;ib.save(),ib.translate(a.x,a.y),0!==c.rotation&&ib.rotate(c.rotation),ib.translate(-d/2,-f/2),ib.scale(q,t),ib.translate(-k,-n),ib.fillRect(k,n,o,p),ib.restore()}else x(c.color.getStyle()),ib.save(),ib.translate(a.x,a.y),0!==c.rotation&&ib.rotate(c.rotation),ib.scale(d,-f),ib.fillRect(-.5,-.5,1,1),ib.restore()}else c instanceof e.SpriteCanvasMaterial&&(w(c.color.getStyle()),x(c.color.getStyle()),ib.save(),ib.translate(a.x,a.y),0!==c.rotation&&ib.rotate(c.rotation),ib.scale(d,f),c.program(ib),ib.restore())}function g(a,b,c,d){if(r(d.opacity),s(d.blending),ib.beginPath(),ib.moveTo(a.positionScreen.x,a.positionScreen.y),ib.lineTo(b.positionScreen.x,b.positionScreen.y),d instanceof e.LineBasicMaterial){if(t(d.linewidth),u(d.linecap),v(d.linejoin),d.vertexColors!==e.VertexColors)w(d.color.getStyle());else{var f=c.vertexColors[0].getStyle(),g=c.vertexColors[1].getStyle();if(f===g)w(f);else{try{var h=ib.createLinearGradient(a.positionScreen.x,a.positionScreen.y,b.positionScreen.x,b.positionScreen.y);h.addColorStop(0,f),h.addColorStop(1,g)}catch(i){h=f}w(h)}}ib.stroke(),Fb.expandByScalar(2*d.linewidth)}else d instanceof e.LineDashedMaterial&&(t(d.linewidth),u(d.linecap),v(d.linejoin),w(d.color.getStyle()),y(d.dashSize,d.gapSize),ib.stroke(),Fb.expandByScalar(2*d.linewidth),y(null,null))}function h(a,b,d,f,g,h,l,m){bb.info.render.vertices+=3,bb.info.render.faces++,r(m.opacity),s(m.blending),H=a.positionScreen.x,I=a.positionScreen.y,J=b.positionScreen.x,K=b.positionScreen.y,L=d.positionScreen.x,M=d.positionScreen.y,i(H,I,J,K,L,M),(m instanceof e.MeshLambertMaterial||m instanceof e.MeshPhongMaterial)&&null===m.map?(zb.copy(m.color),Ab.copy(m.emissive),m.vertexColors===e.FaceColors&&zb.multiply(l.color),m.wireframe===!1&&m.shading===e.SmoothShading&&3===l.vertexNormalsLength?(vb.copy(Gb),wb.copy(Gb),xb.copy(Gb),c(l.v1.positionWorld,l.vertexNormalsModel[0],vb),c(l.v2.positionWorld,l.vertexNormalsModel[1],wb),c(l.v3.positionWorld,l.vertexNormalsModel[2],xb),vb.multiply(zb).add(Ab),wb.multiply(zb).add(Ab),xb.multiply(zb).add(Ab),yb.addColors(wb,xb).multiplyScalar(.5),P=p(vb,wb,xb,yb),o(H,I,J,K,L,M,0,0,1,0,0,1,P)):(ub.copy(Gb),c(l.centroidModel,l.normalModel,ub),ub.multiply(zb).add(Ab),m.wireframe===!0?j(ub,m.wireframeLinewidth,m.wireframeLinecap,m.wireframeLinejoin):k(ub))):m instanceof e.MeshBasicMaterial||m instanceof e.MeshLambertMaterial||m instanceof e.MeshPhongMaterial?null!==m.map?m.map.mapping instanceof e.UVMapping&&(Q=l.uvs[0],n(H,I,J,K,L,M,Q[f].x,Q[f].y,Q[g].x,Q[g].y,Q[h].x,Q[h].y,m.map)):null!==m.envMap?m.envMap.mapping instanceof e.SphericalReflectionMapping&&(Kb.copy(l.vertexNormalsModel[f]).applyMatrix3(Lb),R=.5*Kb.x+.5,S=.5*Kb.y+.5,Kb.copy(l.vertexNormalsModel[g]).applyMatrix3(Lb),T=.5*Kb.x+.5,U=.5*Kb.y+.5,Kb.copy(l.vertexNormalsModel[h]).applyMatrix3(Lb),V=.5*Kb.x+.5,W=.5*Kb.y+.5,n(H,I,J,K,L,M,R,S,T,U,V,W,m.envMap)):(ub.copy(m.color),m.vertexColors===e.FaceColors&&ub.multiply(l.color),m.wireframe===!0?j(ub,m.wireframeLinewidth,m.wireframeLinecap,m.wireframeLinejoin):k(ub)):m instanceof e.MeshDepthMaterial?(N=D.near,O=D.far,vb.r=vb.g=vb.b=1-z(a.positionScreen.z*a.positionScreen.w,N,O),wb.r=wb.g=wb.b=1-z(b.positionScreen.z*b.positionScreen.w,N,O),xb.r=xb.g=xb.b=1-z(d.positionScreen.z*d.positionScreen.w,N,O),yb.addColors(wb,xb).multiplyScalar(.5),P=p(vb,wb,xb,yb),o(H,I,J,K,L,M,0,0,1,0,0,1,P)):m instanceof e.MeshNormalMaterial&&(m.shading===e.FlatShading?(Kb.copy(l.normalModel).applyMatrix3(Lb),ub.setRGB(Kb.x,Kb.y,Kb.z).multiplyScalar(.5).addScalar(.5),m.wireframe===!0?j(ub,m.wireframeLinewidth,m.wireframeLinecap,m.wireframeLinejoin):k(ub)):m.shading===e.SmoothShading&&(Kb.copy(l.vertexNormalsModel[f]).applyMatrix3(Lb),vb.setRGB(Kb.x,Kb.y,Kb.z).multiplyScalar(.5).addScalar(.5),Kb.copy(l.vertexNormalsModel[g]).applyMatrix3(Lb),wb.setRGB(Kb.x,Kb.y,Kb.z).multiplyScalar(.5).addScalar(.5),Kb.copy(l.vertexNormalsModel[h]).applyMatrix3(Lb),xb.setRGB(Kb.x,Kb.y,Kb.z).multiplyScalar(.5).addScalar(.5),yb.addColors(wb,xb).multiplyScalar(.5),P=p(vb,wb,xb,yb),o(H,I,J,K,L,M,0,0,1,0,0,1,P)))}function i(a,b,c,d,e,f){ib.beginPath(),ib.moveTo(a,b),ib.lineTo(c,d),ib.lineTo(e,f),ib.closePath()}function j(a,b,c,d){t(b),u(c),v(d),w(a.getStyle()),ib.stroke(),Fb.expandByScalar(2*b)}function k(a){x(a.getStyle()),ib.fill()}function l(a){m(a.target)}function m(a){var b=a.wrapS===e.RepeatWrapping,c=a.wrapT===e.RepeatWrapping,d=a.image,f=document.createElement("canvas");f.width=d.width,f.height=d.height;var g=f.getContext("2d");g.setTransform(1,0,0,-1,0,d.height),g.drawImage(d,0,0),Cb[a.id]=ib.createPattern(f,b===!0&&c===!0?"repeat":b===!0&&c===!1?"repeat-x":b===!1&&c===!0?"repeat-y":"no-repeat")}function n(a,b,c,d,f,g,h,i,j,k,n,o,p){if(!(p instanceof e.DataTexture)){p.hasEventListener("update",l)===!1&&(void 0!==p.image&&p.image.width>0&&m(p),p.addEventListener("update",l));var q=Cb[p.id];if(void 0===q)return x("rgba(0,0,0,1)"),void ib.fill();x(q);var r,s,t,u,v,w,y,z,A=p.offset.x/p.repeat.x,B=p.offset.y/p.repeat.y,C=p.image.width*p.repeat.x,D=p.image.height*p.repeat.y;h=(h+A)*C,i=(i+B)*D,j=(j+A)*C,k=(k+B)*D,n=(n+A)*C,o=(o+B)*D,c-=a,d-=b,f-=a,g-=b,j-=h,k-=i,n-=h,o-=i,y=j*o-n*k,0!==y&&(z=1/y,r=(o*c-k*f)*z,s=(o*d-k*g)*z,t=(j*f-n*c)*z,u=(j*g-n*d)*z,v=a-r*h-t*i,w=b-s*h-u*i,ib.save(),ib.transform(r,s,t,u,v,w),ib.fill(),ib.restore())}}function o(a,b,c,d,e,f,g,h,i,j,k,l,m){var n,o,p,q,r,s,t,u,v=m.width-1,w=m.height-1;g*=v,h*=w,i*=v,j*=w,k*=v,l*=w,c-=a,d-=b,e-=a,f-=b,i-=g,j-=h,k-=g,l-=h,t=i*l-k*j,u=1/t,n=(l*c-j*e)*u,o=(l*d-j*f)*u,p=(i*e-k*c)*u,q=(i*f-k*d)*u,r=a-n*g-p*h,s=b-o*g-q*h,ib.save(),ib.transform(n,o,p,q,r,s),ib.clip(),ib.drawImage(m,0,0),ib.restore()}function p(a,b,c,d){return $[0]=255*a.r|0,$[1]=255*a.g|0,$[2]=255*a.b|0,$[4]=255*b.r|0,$[5]=255*b.g|0,$[6]=255*b.b|0,$[8]=255*c.r|0,$[9]=255*c.g|0,$[10]=255*c.b|0,$[12]=255*d.r|0,$[13]=255*d.g|0,$[14]=255*d.b|0,Y.putImageData(Z,0,0),ab.drawImage(X,0,0),_}function q(a,b,c){var d,e=b.x-a.x,f=b.y-a.y,g=e*e+f*f;0!==g&&(d=c/Math.sqrt(g),e*=d,f*=d,b.x+=e,b.y+=f,a.x-=e,a.y-=f)}function r(a){lb!==a&&(ib.globalAlpha=a,lb=a)}function s(a){mb!==a&&(a===e.NormalBlending?ib.globalCompositeOperation="source-over":a===e.AdditiveBlending?ib.globalCompositeOperation="lighter":a===e.SubtractiveBlending&&(ib.globalCompositeOperation="darker"),mb=a)}function t(a){pb!==a&&(ib.lineWidth=a,pb=a)}function u(a){qb!==a&&(ib.lineCap=a,qb=a)}function v(a){rb!==a&&(ib.lineJoin=a,rb=a)}function w(a){nb!==a&&(ib.strokeStyle=a,nb=a)}function x(a){ob!==a&&(ib.fillStyle=a,ob=a)}function y(a,b){(sb!==a||tb!==b)&&(ib.setLineDash([a,b]),sb=a,tb=b)}console.log("THREE.CanvasRenderer",e.REVISION);var z=e.Math.smoothstep;a=a||{};var A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,ab,bb=this,cb=new e.Projector,db=void 0!==a.canvas?a.canvas:document.createElement("canvas"),eb=db.width,fb=db.height,gb=Math.floor(eb/2),hb=Math.floor(fb/2),ib=db.getContext("2d",{alpha:a.alpha===!0}),jb=new e.Color(0),kb=0,lb=1,mb=0,nb=null,ob=null,pb=null,qb=null,rb=null,sb=null,tb=0,ub=(new e.RenderableVertex,new e.RenderableVertex,new e.Color),vb=new e.Color,wb=new e.Color,xb=new e.Color,yb=new e.Color,zb=new e.Color,Ab=new e.Color,Bb=new e.Color,Cb={},Db=new e.Box2,Eb=new e.Box2,Fb=new e.Box2,Gb=new e.Color,Hb=new e.Color,Ib=new e.Color,Jb=new e.Vector3,Kb=new e.Vector3,Lb=new e.Matrix3,Mb=16;X=document.createElement("canvas"),X.width=X.height=2,Y=X.getContext("2d"),Y.fillStyle="rgba(0,0,0,1)",Y.fillRect(0,0,2,2),Z=Y.getImageData(0,0,2,2),$=Z.data,_=document.createElement("canvas"),_.width=_.height=Mb,ab=_.getContext("2d"),ab.translate(-Mb/2,-Mb/2),ab.scale(Mb,Mb),Mb--,void 0===ib.setLineDash&&(ib.setLineDash=void 0!==ib.mozDash?function(a){ib.mozDash=null!==a[0]?a:null}:function(){}),this.domElement=db,this.devicePixelRatio=void 0!==a.devicePixelRatio?a.devicePixelRatio:void 0!==d.devicePixelRatio?d.devicePixelRatio:1,this.autoClear=!0,this.sortObjects=!0,this.sortElements=!0,this.info={render:{vertices:0,faces:0}},this.supportsVertexTextures=function(){},this.setFaceCulling=function(){},this.setSize=function(a,b,c){eb=a*this.devicePixelRatio,fb=b*this.devicePixelRatio,gb=Math.floor(eb/2),hb=Math.floor(fb/2),db.width=eb,db.height=fb,1!==this.devicePixelRatio&&c!==!1&&(db.style.width=a+"px",db.style.height=b+"px"),Db.min.set(-gb,-hb),Db.max.set(gb,hb),Eb.min.set(-gb,-hb),Eb.max.set(gb,hb),lb=1,mb=0,nb=null,ob=null,pb=null,qb=null,rb=null},this.setClearColor=function(a,b){jb.set(a),kb=void 0!==b?b:1,Eb.min.set(-gb,-hb),Eb.max.set(gb,hb)},this.setClearColorHex=function(a,b){console.warn("DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead."),this.setClearColor(a,b)},this.getMaxAnisotropy=function(){return 0},this.clear=function(){ib.setTransform(1,0,0,-1,gb,hb),Eb.empty()===!1&&(Eb.intersect(Db),Eb.expandByScalar(2),1>kb&&ib.clearRect(0|Eb.min.x,0|Eb.min.y,Eb.max.x-Eb.min.x|0,Eb.max.y-Eb.min.y|0),kb>0&&(s(e.NormalBlending),r(1),x("rgba("+Math.floor(255*jb.r)+","+Math.floor(255*jb.g)+","+Math.floor(255*jb.b)+","+kb+")"),ib.fillRect(0|Eb.min.x,0|Eb.min.y,Eb.max.x-Eb.min.x|0,Eb.max.y-Eb.min.y|0)),Eb.makeEmpty())},this.clearColor=function(){},this.clearDepth=function(){},this.clearStencil=function(){},this.render=function(a,c){if(c instanceof e.Camera==!1)return void console.error("THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.");this.autoClear===!0&&this.clear(),ib.setTransform(1,0,0,-1,gb,hb),bb.info.render.vertices=0,bb.info.render.faces=0,A=cb.projectScene(a,c,this.sortObjects,this.sortElements),B=A.elements,C=A.lights,D=c,Lb.getNormalMatrix(c.matrixWorldInverse),b();for(var d=0,i=B.length;i>d;d++){var j=B[d],k=j.material;if(void 0!==k&&k.visible!==!1){if(Fb.makeEmpty(),j instanceof e.RenderableSprite)E=j,E.x*=gb,E.y*=hb,f(E,j,k);else if(j instanceof e.RenderableLine)E=j.v1,F=j.v2,E.positionScreen.x*=gb,E.positionScreen.y*=hb,F.positionScreen.x*=gb,F.positionScreen.y*=hb,Fb.setFromPoints([E.positionScreen,F.positionScreen]),Db.isIntersectionBox(Fb)===!0&&g(E,F,j,k);else if(j instanceof e.RenderableFace){if(E=j.v1,F=j.v2,G=j.v3,E.positionScreen.z<-1||E.positionScreen.z>1)continue;if(F.positionScreen.z<-1||F.positionScreen.z>1)continue;if(G.positionScreen.z<-1||G.positionScreen.z>1)continue;E.positionScreen.x*=gb,E.positionScreen.y*=hb,F.positionScreen.x*=gb,F.positionScreen.y*=hb,G.positionScreen.x*=gb,G.positionScreen.y*=hb,k.overdraw>0&&(q(E.positionScreen,F.positionScreen,k.overdraw),q(F.positionScreen,G.positionScreen,k.overdraw),q(G.positionScreen,E.positionScreen,k.overdraw)),Fb.setFromPoints([E.positionScreen,F.positionScreen,G.positionScreen]),Db.isIntersectionBox(Fb)===!0&&h(E,F,G,0,1,2,j,k)}Eb.union(Fb)}}ib.setTransform(1,0,0,1,0,0)}},e.ShaderChunk={fog_pars_fragment:["#ifdef USE_FOG","uniform vec3 fogColor;","#ifdef FOG_EXP2","uniform float fogDensity;","#else","uniform float fogNear;","uniform float fogFar;","#endif","#endif"].join("\n"),fog_fragment:["#ifdef USE_FOG","float depth = gl_FragCoord.z / gl_FragCoord.w;","#ifdef FOG_EXP2","const float LOG2 = 1.442695;","float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","#else","float fogFactor = smoothstep( fogNear, fogFar, depth );","#endif","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","#endif"].join("\n"),envmap_pars_fragment:["#ifdef USE_ENVMAP","uniform float reflectivity;","uniform samplerCube envMap;","uniform float flipEnvMap;","uniform int combine;","#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )","uniform bool useRefract;","uniform float refractionRatio;","#else","varying vec3 vReflect;","#endif","#endif"].join("\n"),envmap_fragment:["#ifdef USE_ENVMAP","vec3 reflectVec;","#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )","vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );","if ( useRefract ) {","reflectVec = refract( cameraToVertex, normal, refractionRatio );","} else { ","reflectVec = reflect( cameraToVertex, normal );","}","#else","reflectVec = vReflect;","#endif","#ifdef DOUBLE_SIDED","float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );","vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );","#else","vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );","#endif","#ifdef GAMMA_INPUT","cubeColor.xyz *= cubeColor.xyz;","#endif","if ( combine == 1 ) {","gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );","} else if ( combine == 2 ) {","gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;","} else {","gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );","}","#endif"].join("\n"),envmap_pars_vertex:["#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )","varying vec3 vReflect;","uniform float refractionRatio;","uniform bool useRefract;","#endif"].join("\n"),worldpos_vertex:["#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )","#ifdef USE_SKINNING","vec4 worldPosition = modelMatrix * skinned;","#endif","#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )","vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );","#endif","#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )","vec4 worldPosition = modelMatrix * vec4( position, 1.0 );","#endif","#endif"].join("\n"),envmap_vertex:["#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )","vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;","worldNormal = normalize( worldNormal );","vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );","if ( useRefract ) {","vReflect = refract( cameraToVertex, worldNormal, refractionRatio );","} else {","vReflect = reflect( cameraToVertex, worldNormal );","}","#endif"].join("\n"),map_particle_pars_fragment:["#ifdef USE_MAP","uniform sampler2D map;","#endif"].join("\n"),map_particle_fragment:["#ifdef USE_MAP","gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );","#endif"].join("\n"),map_pars_vertex:["#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )","varying vec2 vUv;","uniform vec4 offsetRepeat;","#endif"].join("\n"),map_pars_fragment:["#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )","varying vec2 vUv;","#endif","#ifdef USE_MAP","uniform sampler2D map;","#endif"].join("\n"),map_vertex:["#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )","vUv = uv * offsetRepeat.zw + offsetRepeat.xy;","#endif"].join("\n"),map_fragment:["#ifdef USE_MAP","vec4 texelColor = texture2D( map, vUv );","#ifdef GAMMA_INPUT","texelColor.xyz *= texelColor.xyz;","#endif","gl_FragColor = gl_FragColor * texelColor;","#endif"].join("\n"),lightmap_pars_fragment:["#ifdef USE_LIGHTMAP","varying vec2 vUv2;","uniform sampler2D lightMap;","#endif"].join("\n"),lightmap_pars_vertex:["#ifdef USE_LIGHTMAP","varying vec2 vUv2;","#endif"].join("\n"),lightmap_fragment:["#ifdef USE_LIGHTMAP","gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );","#endif"].join("\n"),lightmap_vertex:["#ifdef USE_LIGHTMAP","vUv2 = uv2;","#endif"].join("\n"),bumpmap_pars_fragment:["#ifdef USE_BUMPMAP","uniform sampler2D bumpMap;","uniform float bumpScale;","vec2 dHdxy_fwd() {","vec2 dSTdx = dFdx( vUv );","vec2 dSTdy = dFdy( vUv );","float Hll = bumpScale * texture2D( bumpMap, vUv ).x;","float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;","float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;","return vec2( dBx, dBy );","}","vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {","vec3 vSigmaX = dFdx( surf_pos );","vec3 vSigmaY = dFdy( surf_pos );","vec3 vN = surf_norm;","vec3 R1 = cross( vSigmaY, vN );","vec3 R2 = cross( vN, vSigmaX );","float fDet = dot( vSigmaX, R1 );","vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );","return normalize( abs( fDet ) * surf_norm - vGrad );","}","#endif"].join("\n"),normalmap_pars_fragment:["#ifdef USE_NORMALMAP","uniform sampler2D normalMap;","uniform vec2 normalScale;","vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {","vec3 q0 = dFdx( eye_pos.xyz );","vec3 q1 = dFdy( eye_pos.xyz );","vec2 st0 = dFdx( vUv.st );","vec2 st1 = dFdy( vUv.st );","vec3 S = normalize( q0 * st1.t - q1 * st0.t );","vec3 T = normalize( -q0 * st1.s + q1 * st0.s );","vec3 N = normalize( surf_norm );","vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;","mapN.xy = normalScale * mapN.xy;","mat3 tsn = mat3( S, T, N );","return normalize( tsn * mapN );","}","#endif"].join("\n"),specularmap_pars_fragment:["#ifdef USE_SPECULARMAP","uniform sampler2D specularMap;","#endif"].join("\n"),specularmap_fragment:["float specularStrength;","#ifdef USE_SPECULARMAP","vec4 texelSpecular = texture2D( specularMap, vUv );","specularStrength = texelSpecular.r;","#else","specularStrength = 1.0;","#endif"].join("\n"),lights_lambert_pars_vertex:["uniform vec3 ambient;","uniform vec3 diffuse;","uniform vec3 emissive;","uniform vec3 ambientLightColor;","#if MAX_DIR_LIGHTS > 0","uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];","uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];","#endif","#if MAX_HEMI_LIGHTS > 0","uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];","uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];","uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];","#endif","#if MAX_POINT_LIGHTS > 0","uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];","uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];","uniform float pointLightDistance[ MAX_POINT_LIGHTS ];","#endif","#if MAX_SPOT_LIGHTS > 0","uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];","uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];","uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];","uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];","#endif","#ifdef WRAP_AROUND","uniform vec3 wrapRGB;","#endif"].join("\n"),lights_lambert_vertex:["vLightFront = vec3( 0.0 );","#ifdef DOUBLE_SIDED","vLightBack = vec3( 0.0 );","#endif","transformedNormal = normalize( transformedNormal );","#if MAX_DIR_LIGHTS > 0","for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {","vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );","vec3 dirVector = normalize( lDirection.xyz );","float dotProduct = dot( transformedNormal, dirVector );","vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );","#ifdef DOUBLE_SIDED","vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );","#ifdef WRAP_AROUND","vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );","#endif","#endif","#ifdef WRAP_AROUND","vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );","directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );","#ifdef DOUBLE_SIDED","directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );","#endif","#endif","vLightFront += directionalLightColor[ i ] * directionalLightWeighting;","#ifdef DOUBLE_SIDED","vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;","#endif","}","#endif","#if MAX_POINT_LIGHTS > 0","for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {","vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );","vec3 lVector = lPosition.xyz - mvPosition.xyz;","float lDistance = 1.0;","if ( pointLightDistance[ i ] > 0.0 )","lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );","lVector = normalize( lVector );","float dotProduct = dot( transformedNormal, lVector );","vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );","#ifdef DOUBLE_SIDED","vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );","#ifdef WRAP_AROUND","vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );","#endif","#endif","#ifdef WRAP_AROUND","vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );","pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );","#ifdef DOUBLE_SIDED","pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );","#endif","#endif","vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;","#ifdef DOUBLE_SIDED","vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;","#endif","}","#endif","#if MAX_SPOT_LIGHTS > 0","for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {","vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );","vec3 lVector = lPosition.xyz - mvPosition.xyz;","float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );","if ( spotEffect > spotLightAngleCos[ i ] ) {","spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );","float lDistance = 1.0;","if ( spotLightDistance[ i ] > 0.0 )","lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );","lVector = normalize( lVector );","float dotProduct = dot( transformedNormal, lVector );","vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );","#ifdef DOUBLE_SIDED","vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );","#ifdef WRAP_AROUND","vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );","#endif","#endif","#ifdef WRAP_AROUND","vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );","spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );","#ifdef DOUBLE_SIDED","spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );","#endif","#endif","vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;","#ifdef DOUBLE_SIDED","vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;","#endif","}","}","#endif","#if MAX_HEMI_LIGHTS > 0","for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {","vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );","vec3 lVector = normalize( lDirection.xyz );","float dotProduct = dot( transformedNormal, lVector );","float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;","float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;","vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );","#ifdef DOUBLE_SIDED","vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );","#endif","}","#endif","vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;","#ifdef DOUBLE_SIDED","vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;","#endif"].join("\n"),lights_phong_pars_vertex:["#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )","varying vec3 vWorldPosition;","#endif"].join("\n"),lights_phong_vertex:["#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )","vWorldPosition = worldPosition.xyz;","#endif"].join("\n"),lights_phong_pars_fragment:["uniform vec3 ambientLightColor;","#if MAX_DIR_LIGHTS > 0","uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];","uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];","#endif","#if MAX_HEMI_LIGHTS > 0","uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];","uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];","uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];","#endif","#if MAX_POINT_LIGHTS > 0","uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];","uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];","uniform float pointLightDistance[ MAX_POINT_LIGHTS ];","#endif","#if MAX_SPOT_LIGHTS > 0","uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];","uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];","uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];","uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];","#endif","#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )","varying vec3 vWorldPosition;","#endif","#ifdef WRAP_AROUND","uniform vec3 wrapRGB;","#endif","varying vec3 vViewPosition;","varying vec3 vNormal;"].join("\n"),lights_phong_fragment:["vec3 normal = normalize( vNormal );","vec3 viewPosition = normalize( vViewPosition );","#ifdef DOUBLE_SIDED","normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );","#endif","#ifdef USE_NORMALMAP","normal = perturbNormal2Arb( -vViewPosition, normal );","#elif defined( USE_BUMPMAP )","normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );","#endif","#if MAX_POINT_LIGHTS > 0","vec3 pointDiffuse = vec3( 0.0 );","vec3 pointSpecular = vec3( 0.0 );","for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {","vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );","vec3 lVector = lPosition.xyz + vViewPosition.xyz;","float lDistance = 1.0;","if ( pointLightDistance[ i ] > 0.0 )","lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );","lVector = normalize( lVector );","float dotProduct = dot( normal, lVector );","#ifdef WRAP_AROUND","float pointDiffuseWeightFull = max( dotProduct, 0.0 );","float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );","vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );","#else","float pointDiffuseWeight = max( dotProduct, 0.0 );","#endif","pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;","vec3 pointHalfVector = normalize( lVector + viewPosition );","float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );","float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );","float specularNormalization = ( shininess + 2.0001 ) / 8.0;","vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );","pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;","}","#endif","#if MAX_SPOT_LIGHTS > 0","vec3 spotDiffuse = vec3( 0.0 );","vec3 spotSpecular = vec3( 0.0 );","for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {","vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );","vec3 lVector = lPosition.xyz + vViewPosition.xyz;","float lDistance = 1.0;","if ( spotLightDistance[ i ] > 0.0 )","lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );","lVector = normalize( lVector );","float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );","if ( spotEffect > spotLightAngleCos[ i ] ) {","spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );","float dotProduct = dot( normal, lVector );","#ifdef WRAP_AROUND","float spotDiffuseWeightFull = max( dotProduct, 0.0 );","float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );","vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );","#else","float spotDiffuseWeight = max( dotProduct, 0.0 );","#endif","spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;","vec3 spotHalfVector = normalize( lVector + viewPosition );","float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );","float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );","float specularNormalization = ( shininess + 2.0001 ) / 8.0;","vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );","spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;","}","}","#endif","#if MAX_DIR_LIGHTS > 0","vec3 dirDiffuse = vec3( 0.0 );","vec3 dirSpecular = vec3( 0.0 );","for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {","vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );","vec3 dirVector = normalize( lDirection.xyz );","float dotProduct = dot( normal, dirVector );","#ifdef WRAP_AROUND","float dirDiffuseWeightFull = max( dotProduct, 0.0 );","float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );","vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );","#else","float dirDiffuseWeight = max( dotProduct, 0.0 );","#endif","dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;","vec3 dirHalfVector = normalize( dirVector + viewPosition );","float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );","float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );","float specularNormalization = ( shininess + 2.0001 ) / 8.0;","vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );","dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;","}","#endif","#if MAX_HEMI_LIGHTS > 0","vec3 hemiDiffuse = vec3( 0.0 );","vec3 hemiSpecular = vec3( 0.0 );","for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {","vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );","vec3 lVector = normalize( lDirection.xyz );","float dotProduct = dot( normal, lVector );","float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;","vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );","hemiDiffuse += diffuse * hemiColor;","vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );","float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;","float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );","vec3 lVectorGround = -lVector;","vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );","float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;","float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );","float dotProductGround = dot( normal, lVectorGround );","float specularNormalization = ( shininess + 2.0001 ) / 8.0;","vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );","vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );","hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );","}","#endif","vec3 totalDiffuse = vec3( 0.0 );","vec3 totalSpecular = vec3( 0.0 );","#if MAX_DIR_LIGHTS > 0","totalDiffuse += dirDiffuse;","totalSpecular += dirSpecular;","#endif","#if MAX_HEMI_LIGHTS > 0","totalDiffuse += hemiDiffuse;","totalSpecular += hemiSpecular;","#endif","#if MAX_POINT_LIGHTS > 0","totalDiffuse += pointDiffuse;","totalSpecular += pointSpecular;","#endif","#if MAX_SPOT_LIGHTS > 0","totalDiffuse += spotDiffuse;","totalSpecular += spotSpecular;","#endif","#ifdef METAL","gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );","#else","gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;","#endif"].join("\n"),color_pars_fragment:["#ifdef USE_COLOR","varying vec3 vColor;","#endif"].join("\n"),color_fragment:["#ifdef USE_COLOR","gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );","#endif"].join("\n"),color_pars_vertex:["#ifdef USE_COLOR","varying vec3 vColor;","#endif"].join("\n"),color_vertex:["#ifdef USE_COLOR","#ifdef GAMMA_INPUT","vColor = color * color;","#else","vColor = color;","#endif","#endif"].join("\n"),skinning_pars_vertex:["#ifdef USE_SKINNING","#ifdef BONE_TEXTURE","uniform sampler2D boneTexture;","uniform int boneTextureWidth;","uniform int boneTextureHeight;","mat4 getBoneMatrix( const in float i ) {","float j = i * 4.0;","float x = mod( j, float( boneTextureWidth ) );","float y = floor( j / float( boneTextureWidth ) );","float dx = 1.0 / float( boneTextureWidth );","float dy = 1.0 / float( boneTextureHeight );","y = dy * ( y + 0.5 );","vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );","vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );","vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );","vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );","mat4 bone = mat4( v1, v2, v3, v4 );","return bone;","}","#else","uniform mat4 boneGlobalMatrices[ MAX_BONES ];","mat4 getBoneMatrix( const in float i ) {","mat4 bone = boneGlobalMatrices[ int(i) ];","return bone;","}","#endif","#endif"].join("\n"),skinbase_vertex:["#ifdef USE_SKINNING","mat4 boneMatX = getBoneMatrix( skinIndex.x );","mat4 boneMatY = getBoneMatrix( skinIndex.y );","mat4 boneMatZ = getBoneMatrix( skinIndex.z );","mat4 boneMatW = getBoneMatrix( skinIndex.w );","#endif"].join("\n"),skinning_vertex:["#ifdef USE_SKINNING","#ifdef USE_MORPHTARGETS","vec4 skinVertex = vec4( morphed, 1.0 );","#else","vec4 skinVertex = vec4( position, 1.0 );","#endif","vec4 skinned = boneMatX * skinVertex * skinWeight.x;","skinned += boneMatY * skinVertex * skinWeight.y;","skinned += boneMatZ * skinVertex * skinWeight.z;","skinned += boneMatW * skinVertex * skinWeight.w;","#endif"].join("\n"),morphtarget_pars_vertex:["#ifdef USE_MORPHTARGETS","#ifndef USE_MORPHNORMALS","uniform float morphTargetInfluences[ 8 ];","#else","uniform float morphTargetInfluences[ 4 ];","#endif","#endif"].join("\n"),morphtarget_vertex:["#ifdef USE_MORPHTARGETS","vec3 morphed = vec3( 0.0 );","morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];","morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];","morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];","morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];","#ifndef USE_MORPHNORMALS","morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];","morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];","morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];","morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];","#endif","morphed += position;","#endif"].join("\n"),default_vertex:["vec4 mvPosition;","#ifdef USE_SKINNING","mvPosition = modelViewMatrix * skinned;","#endif","#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )","mvPosition = modelViewMatrix * vec4( morphed, 1.0 );","#endif","#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )","mvPosition = modelViewMatrix * vec4( position, 1.0 );","#endif","gl_Position = projectionMatrix * mvPosition;"].join("\n"),morphnormal_vertex:["#ifdef USE_MORPHNORMALS","vec3 morphedNormal = vec3( 0.0 );","morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];","morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];","morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];","morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];","morphedNormal += normal;","#endif"].join("\n"),skinnormal_vertex:["#ifdef USE_SKINNING","mat4 skinMatrix = skinWeight.x * boneMatX;","skinMatrix += skinWeight.y * boneMatY;","#ifdef USE_MORPHNORMALS","vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );","#else","vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );","#endif","#endif"].join("\n"),defaultnormal_vertex:["vec3 objectNormal;","#ifdef USE_SKINNING","objectNormal = skinnedNormal.xyz;","#endif","#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )","objectNormal = morphedNormal;","#endif","#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )","objectNormal = normal;","#endif","#ifdef FLIP_SIDED","objectNormal = -objectNormal;","#endif","vec3 transformedNormal = normalMatrix * objectNormal;"].join("\n"),shadowmap_pars_fragment:["#ifdef USE_SHADOWMAP","uniform sampler2D shadowMap[ MAX_SHADOWS ];","uniform vec2 shadowMapSize[ MAX_SHADOWS ];","uniform float shadowDarkness[ MAX_SHADOWS ];","uniform float shadowBias[ MAX_SHADOWS ];","varying vec4 vShadowCoord[ MAX_SHADOWS ];","float unpackDepth( const in vec4 rgba_depth ) {","const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );","float depth = dot( rgba_depth, bit_shift );","return depth;","}","#endif"].join("\n"),shadowmap_fragment:["#ifdef USE_SHADOWMAP","#ifdef SHADOWMAP_DEBUG","vec3 frustumColors[3];","frustumColors[0] = vec3( 1.0, 0.5, 0.0 );","frustumColors[1] = vec3( 0.0, 1.0, 0.8 );","frustumColors[2] = vec3( 0.0, 0.5, 1.0 );","#endif","#ifdef SHADOWMAP_CASCADE","int inFrustumCount = 0;","#endif","float fDepth;","vec3 shadowColor = vec3( 1.0 );","for( int i = 0; i < MAX_SHADOWS; i ++ ) {","vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;","bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );","bool inFrustum = all( inFrustumVec );","#ifdef SHADOWMAP_CASCADE","inFrustumCount += int( inFrustum );","bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );","#else","bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );","#endif","bool frustumTest = all( frustumTestVec );","if ( frustumTest ) {","shadowCoord.z += shadowBias[ i ];","#if defined( SHADOWMAP_TYPE_PCF )","float shadow = 0.0;","const float shadowDelta = 1.0 / 9.0;","float xPixelOffset = 1.0 / shadowMapSize[ i ].x;","float yPixelOffset = 1.0 / shadowMapSize[ i ].y;","float dx0 = -1.25 * xPixelOffset;","float dy0 = -1.25 * yPixelOffset;","float dx1 = 1.25 * xPixelOffset;","float dy1 = 1.25 * yPixelOffset;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );","if ( fDepth < shadowCoord.z ) shadow += shadowDelta;","shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );","#elif defined( SHADOWMAP_TYPE_PCF_SOFT )","float shadow = 0.0;","float xPixelOffset = 1.0 / shadowMapSize[ i ].x;","float yPixelOffset = 1.0 / shadowMapSize[ i ].y;","float dx0 = -1.0 * xPixelOffset;","float dy0 = -1.0 * yPixelOffset;","float dx1 = 1.0 * xPixelOffset;","float dy1 = 1.0 * yPixelOffset;","mat3 shadowKernel;","mat3 depthKernel;","depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );","depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );","depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );","depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );","depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );","depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );","depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );","depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );","depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );","vec3 shadowZ = vec3( shadowCoord.z );","shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));","shadowKernel[0] *= vec3(0.25);","shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));","shadowKernel[1] *= vec3(0.25);","shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));","shadowKernel[2] *= vec3(0.25);","vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );","shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );","shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );","vec4 shadowValues;","shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );","shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );","shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );","shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );","shadow = dot( shadowValues, vec4( 1.0 ) );","shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );","#else","vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );","float fDepth = unpackDepth( rgbaDepth );","if ( fDepth < shadowCoord.z )","shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );","#endif","}","#ifdef SHADOWMAP_DEBUG","#ifdef SHADOWMAP_CASCADE","if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];","#else","if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];","#endif","#endif","}","#ifdef GAMMA_OUTPUT","shadowColor *= shadowColor;","#endif","gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;","#endif"].join("\n"),shadowmap_pars_vertex:["#ifdef USE_SHADOWMAP","varying vec4 vShadowCoord[ MAX_SHADOWS ];","uniform mat4 shadowMatrix[ MAX_SHADOWS ];","#endif"].join("\n"),shadowmap_vertex:["#ifdef USE_SHADOWMAP","for( int i = 0; i < MAX_SHADOWS; i ++ ) {","vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;","}","#endif"].join("\n"),alphatest_fragment:["#ifdef ALPHATEST","if ( gl_FragColor.a < ALPHATEST ) discard;","#endif"].join("\n"),linear_to_gamma_fragment:["#ifdef GAMMA_OUTPUT","gl_FragColor.xyz = sqrt( gl_FragColor.xyz );","#endif"].join("\n")},e.UniformsUtils={merge:function(a){var b,c,d,e={}; -for(b=0;b dashSize ) {","discard;","}","gl_FragColor = vec4( diffuse, opacity );",e.ShaderChunk.color_fragment,e.ShaderChunk.fog_fragment,"}"].join("\n")},depth:{uniforms:{mNear:{type:"f",value:1},mFar:{type:"f",value:2e3},opacity:{type:"f",value:1}},vertexShader:["void main() {","gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );","}"].join("\n"),fragmentShader:["uniform float mNear;","uniform float mFar;","uniform float opacity;","void main() {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float color = 1.0 - smoothstep( mNear, mFar, depth );","gl_FragColor = vec4( vec3( color ), opacity );","}"].join("\n")},normal:{uniforms:{opacity:{type:"f",value:1}},vertexShader:["varying vec3 vNormal;",e.ShaderChunk.morphtarget_pars_vertex,"void main() {","vNormal = normalize( normalMatrix * normal );",e.ShaderChunk.morphtarget_vertex,e.ShaderChunk.default_vertex,"}"].join("\n"),fragmentShader:["uniform float opacity;","varying vec3 vNormal;","void main() {","gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );","}"].join("\n")},normalmap:{uniforms:e.UniformsUtils.merge([e.UniformsLib.fog,e.UniformsLib.lights,e.UniformsLib.shadowmap,{enableAO:{type:"i",value:0},enableDiffuse:{type:"i",value:0},enableSpecular:{type:"i",value:0},enableReflection:{type:"i",value:0},enableDisplacement:{type:"i",value:0},tDisplacement:{type:"t",value:null},tDiffuse:{type:"t",value:null},tCube:{type:"t",value:null},tNormal:{type:"t",value:null},tSpecular:{type:"t",value:null},tAO:{type:"t",value:null},uNormalScale:{type:"v2",value:new e.Vector2(1,1)},uDisplacementBias:{type:"f",value:0},uDisplacementScale:{type:"f",value:1},diffuse:{type:"c",value:new e.Color(16777215)},specular:{type:"c",value:new e.Color(1118481)},ambient:{type:"c",value:new e.Color(16777215)},shininess:{type:"f",value:30},opacity:{type:"f",value:1},useRefract:{type:"i",value:0},refractionRatio:{type:"f",value:.98},reflectivity:{type:"f",value:.5},uOffset:{type:"v2",value:new e.Vector2(0,0)},uRepeat:{type:"v2",value:new e.Vector2(1,1)},wrapRGB:{type:"v3",value:new e.Vector3(1,1,1)}}]),fragmentShader:["uniform vec3 ambient;","uniform vec3 diffuse;","uniform vec3 specular;","uniform float shininess;","uniform float opacity;","uniform bool enableDiffuse;","uniform bool enableSpecular;","uniform bool enableAO;","uniform bool enableReflection;","uniform sampler2D tDiffuse;","uniform sampler2D tNormal;","uniform sampler2D tSpecular;","uniform sampler2D tAO;","uniform samplerCube tCube;","uniform vec2 uNormalScale;","uniform bool useRefract;","uniform float refractionRatio;","uniform float reflectivity;","varying vec3 vTangent;","varying vec3 vBinormal;","varying vec3 vNormal;","varying vec2 vUv;","uniform vec3 ambientLightColor;","#if MAX_DIR_LIGHTS > 0","uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];","uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];","#endif","#if MAX_HEMI_LIGHTS > 0","uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];","uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];","uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];","#endif","#if MAX_POINT_LIGHTS > 0","uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];","uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];","uniform float pointLightDistance[ MAX_POINT_LIGHTS ];","#endif","#if MAX_SPOT_LIGHTS > 0","uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];","uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];","uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];","uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];","#endif","#ifdef WRAP_AROUND","uniform vec3 wrapRGB;","#endif","varying vec3 vWorldPosition;","varying vec3 vViewPosition;",e.ShaderChunk.shadowmap_pars_fragment,e.ShaderChunk.fog_pars_fragment,"void main() {","gl_FragColor = vec4( vec3( 1.0 ), opacity );","vec3 specularTex = vec3( 1.0 );","vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;","normalTex.xy *= uNormalScale;","normalTex = normalize( normalTex );","if( enableDiffuse ) {","#ifdef GAMMA_INPUT","vec4 texelColor = texture2D( tDiffuse, vUv );","texelColor.xyz *= texelColor.xyz;","gl_FragColor = gl_FragColor * texelColor;","#else","gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );","#endif","}","if( enableAO ) {","#ifdef GAMMA_INPUT","vec4 aoColor = texture2D( tAO, vUv );","aoColor.xyz *= aoColor.xyz;","gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;","#else","gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;","#endif","}","if( enableSpecular )","specularTex = texture2D( tSpecular, vUv ).xyz;","mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );","vec3 finalNormal = tsb * normalTex;","#ifdef FLIP_SIDED","finalNormal = -finalNormal;","#endif","vec3 normal = normalize( finalNormal );","vec3 viewPosition = normalize( vViewPosition );","#if MAX_POINT_LIGHTS > 0","vec3 pointDiffuse = vec3( 0.0 );","vec3 pointSpecular = vec3( 0.0 );","for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {","vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );","vec3 pointVector = lPosition.xyz + vViewPosition.xyz;","float pointDistance = 1.0;","if ( pointLightDistance[ i ] > 0.0 )","pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );","pointVector = normalize( pointVector );","#ifdef WRAP_AROUND","float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );","float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );","vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );","#else","float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );","#endif","pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;","vec3 pointHalfVector = normalize( pointVector + viewPosition );","float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );","float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );","float specularNormalization = ( shininess + 2.0001 ) / 8.0;","vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );","pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;","}","#endif","#if MAX_SPOT_LIGHTS > 0","vec3 spotDiffuse = vec3( 0.0 );","vec3 spotSpecular = vec3( 0.0 );","for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {","vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );","vec3 spotVector = lPosition.xyz + vViewPosition.xyz;","float spotDistance = 1.0;","if ( spotLightDistance[ i ] > 0.0 )","spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );","spotVector = normalize( spotVector );","float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );","if ( spotEffect > spotLightAngleCos[ i ] ) {","spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );","#ifdef WRAP_AROUND","float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );","float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );","vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );","#else","float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );","#endif","spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;","vec3 spotHalfVector = normalize( spotVector + viewPosition );","float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );","float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );","float specularNormalization = ( shininess + 2.0001 ) / 8.0;","vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );","spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;","}","}","#endif","#if MAX_DIR_LIGHTS > 0","vec3 dirDiffuse = vec3( 0.0 );","vec3 dirSpecular = vec3( 0.0 );","for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {","vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );","vec3 dirVector = normalize( lDirection.xyz );","#ifdef WRAP_AROUND","float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );","float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );","vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );","#else","float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );","#endif","dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;","vec3 dirHalfVector = normalize( dirVector + viewPosition );","float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );","float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );","float specularNormalization = ( shininess + 2.0001 ) / 8.0;","vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );","dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;","}","#endif","#if MAX_HEMI_LIGHTS > 0","vec3 hemiDiffuse = vec3( 0.0 );","vec3 hemiSpecular = vec3( 0.0 );","for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {","vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );","vec3 lVector = normalize( lDirection.xyz );","float dotProduct = dot( normal, lVector );","float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;","vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );","hemiDiffuse += diffuse * hemiColor;","vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );","float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;","float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );","vec3 lVectorGround = -lVector;","vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );","float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;","float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );","float dotProductGround = dot( normal, lVectorGround );","float specularNormalization = ( shininess + 2.0001 ) / 8.0;","vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );","vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );","hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );","}","#endif","vec3 totalDiffuse = vec3( 0.0 );","vec3 totalSpecular = vec3( 0.0 );","#if MAX_DIR_LIGHTS > 0","totalDiffuse += dirDiffuse;","totalSpecular += dirSpecular;","#endif","#if MAX_HEMI_LIGHTS > 0","totalDiffuse += hemiDiffuse;","totalSpecular += hemiSpecular;","#endif","#if MAX_POINT_LIGHTS > 0","totalDiffuse += pointDiffuse;","totalSpecular += pointSpecular;","#endif","#if MAX_SPOT_LIGHTS > 0","totalDiffuse += spotDiffuse;","totalSpecular += spotSpecular;","#endif","#ifdef METAL","gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );","#else","gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;","#endif","if ( enableReflection ) {","vec3 vReflect;","vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );","if ( useRefract ) {","vReflect = refract( cameraToVertex, normal, refractionRatio );","} else {","vReflect = reflect( cameraToVertex, normal );","}","vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );","#ifdef GAMMA_INPUT","cubeColor.xyz *= cubeColor.xyz;","#endif","gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );","}",e.ShaderChunk.shadowmap_fragment,e.ShaderChunk.linear_to_gamma_fragment,e.ShaderChunk.fog_fragment,"}"].join("\n"),vertexShader:["attribute vec4 tangent;","uniform vec2 uOffset;","uniform vec2 uRepeat;","uniform bool enableDisplacement;","#ifdef VERTEX_TEXTURES","uniform sampler2D tDisplacement;","uniform float uDisplacementScale;","uniform float uDisplacementBias;","#endif","varying vec3 vTangent;","varying vec3 vBinormal;","varying vec3 vNormal;","varying vec2 vUv;","varying vec3 vWorldPosition;","varying vec3 vViewPosition;",e.ShaderChunk.skinning_pars_vertex,e.ShaderChunk.shadowmap_pars_vertex,"void main() {",e.ShaderChunk.skinbase_vertex,e.ShaderChunk.skinnormal_vertex,"#ifdef USE_SKINNING","vNormal = normalize( normalMatrix * skinnedNormal.xyz );","vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );","vTangent = normalize( normalMatrix * skinnedTangent.xyz );","#else","vNormal = normalize( normalMatrix * normal );","vTangent = normalize( normalMatrix * tangent.xyz );","#endif","vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );","vUv = uv * uRepeat + uOffset;","vec3 displacedPosition;","#ifdef VERTEX_TEXTURES","if ( enableDisplacement ) {","vec3 dv = texture2D( tDisplacement, uv ).xyz;","float df = uDisplacementScale * dv.x + uDisplacementBias;","displacedPosition = position + normalize( normal ) * df;","} else {","#ifdef USE_SKINNING","vec4 skinVertex = vec4( position, 1.0 );","vec4 skinned = boneMatX * skinVertex * skinWeight.x;","skinned += boneMatY * skinVertex * skinWeight.y;","displacedPosition = skinned.xyz;","#else","displacedPosition = position;","#endif","}","#else","#ifdef USE_SKINNING","vec4 skinVertex = vec4( position, 1.0 );","vec4 skinned = boneMatX * skinVertex * skinWeight.x;","skinned += boneMatY * skinVertex * skinWeight.y;","displacedPosition = skinned.xyz;","#else","displacedPosition = position;","#endif","#endif","vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );","vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );","gl_Position = projectionMatrix * mvPosition;","vWorldPosition = worldPosition.xyz;","vViewPosition = -mvPosition.xyz;","#ifdef USE_SHADOWMAP","for( int i = 0; i < MAX_SHADOWS; i ++ ) {","vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;","}","#endif","}"].join("\n")},cube:{uniforms:{tCube:{type:"t",value:null},tFlip:{type:"f",value:-1}},vertexShader:["varying vec3 vWorldPosition;","void main() {","vec4 worldPosition = modelMatrix * vec4( position, 1.0 );","vWorldPosition = worldPosition.xyz;","gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );","}"].join("\n"),fragmentShader:["uniform samplerCube tCube;","uniform float tFlip;","varying vec3 vWorldPosition;","void main() {","gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );","}"].join("\n")},depthRGBA:{uniforms:{},vertexShader:[e.ShaderChunk.morphtarget_pars_vertex,e.ShaderChunk.skinning_pars_vertex,"void main() {",e.ShaderChunk.skinbase_vertex,e.ShaderChunk.morphtarget_vertex,e.ShaderChunk.skinning_vertex,e.ShaderChunk.default_vertex,"}"].join("\n"),fragmentShader:["vec4 pack_depth( const in float depth ) {","const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );","const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );","vec4 res = fract( depth * bit_shift );","res -= res.xxyz * bit_mask;","return res;","}","void main() {","gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );","}"].join("\n")}},e.WebGLRenderer=function(a){function b(a){a.__webglVertexBuffer=Kb.createBuffer(),a.__webglColorBuffer=Kb.createBuffer(),Qb.info.memory.geometries++}function c(a){a.__webglVertexBuffer=Kb.createBuffer(),a.__webglColorBuffer=Kb.createBuffer(),a.__webglLineDistanceBuffer=Kb.createBuffer(),Qb.info.memory.geometries++}function f(a){a.__webglVertexBuffer=Kb.createBuffer(),a.__webglNormalBuffer=Kb.createBuffer(),a.__webglTangentBuffer=Kb.createBuffer(),a.__webglColorBuffer=Kb.createBuffer(),a.__webglUVBuffer=Kb.createBuffer(),a.__webglUV2Buffer=Kb.createBuffer(),a.__webglSkinIndicesBuffer=Kb.createBuffer(),a.__webglSkinWeightsBuffer=Kb.createBuffer(),a.__webglFaceBuffer=Kb.createBuffer(),a.__webglLineBuffer=Kb.createBuffer();var b,c;if(a.numMorphTargets)for(a.__webglMorphTargetsBuffers=[],b=0,c=a.numMorphTargets;c>b;b++)a.__webglMorphTargetsBuffers.push(Kb.createBuffer());if(a.numMorphNormals)for(a.__webglMorphNormalsBuffers=[],b=0,c=a.numMorphNormals;c>b;b++)a.__webglMorphNormalsBuffers.push(Kb.createBuffer());Qb.info.memory.geometries++}function g(a,b){var c=a.vertices.length,d=b.material;if(d.attributes){void 0===a.__webglCustomAttributesList&&(a.__webglCustomAttributesList=[]);for(var e in d.attributes){var f=d.attributes[e];if(!f.__webglInitialized||f.createUniqueBuffers){f.__webglInitialized=!0;var g=1;"v2"===f.type?g=2:"v3"===f.type?g=3:"v4"===f.type?g=4:"c"===f.type&&(g=3),f.size=g,f.array=new Float32Array(c*g),f.buffer=Kb.createBuffer(),f.buffer.belongsToAttribute=e,f.needsUpdate=!0}a.__webglCustomAttributesList.push(f)}}}function h(a,b){var c=a.vertices.length;a.__vertexArray=new Float32Array(3*c),a.__colorArray=new Float32Array(3*c),a.__sortArray=[],a.__webglParticleCount=c,g(a,b)}function i(a,b){var c=a.vertices.length;a.__vertexArray=new Float32Array(3*c),a.__colorArray=new Float32Array(3*c),a.__lineDistanceArray=new Float32Array(1*c),a.__webglLineCount=c,g(a,b)}function j(a,b){var c=b.geometry,d=a.faces3,e=3*d.length,f=1*d.length,g=3*d.length,h=k(b,a),i=o(h),j=m(h),l=n(h);a.__vertexArray=new Float32Array(3*e),j&&(a.__normalArray=new Float32Array(3*e)),c.hasTangents&&(a.__tangentArray=new Float32Array(4*e)),l&&(a.__colorArray=new Float32Array(3*e)),i&&(c.faceVertexUvs.length>0&&(a.__uvArray=new Float32Array(2*e)),c.faceVertexUvs.length>1&&(a.__uv2Array=new Float32Array(2*e))),b.geometry.skinWeights.length&&b.geometry.skinIndices.length&&(a.__skinIndexArray=new Float32Array(4*e),a.__skinWeightArray=new Float32Array(4*e)),a.__faceArray=new Uint16Array(3*f),a.__lineArray=new Uint16Array(2*g);var p,q;if(a.numMorphTargets)for(a.__morphTargetsArrays=[],p=0,q=a.numMorphTargets;q>p;p++)a.__morphTargetsArrays.push(new Float32Array(3*e));if(a.numMorphNormals)for(a.__morphNormalsArrays=[],p=0,q=a.numMorphNormals;q>p;p++)a.__morphNormalsArrays.push(new Float32Array(3*e));if(a.__webglFaceCount=3*f,a.__webglLineCount=2*g,h.attributes){void 0===a.__webglCustomAttributesList&&(a.__webglCustomAttributesList=[]);for(var r in h.attributes){var s=h.attributes[r],t={};for(var u in s)t[u]=s[u];if(!t.__webglInitialized||t.createUniqueBuffers){t.__webglInitialized=!0;var v=1;"v2"===t.type?v=2:"v3"===t.type?v=3:"v4"===t.type?v=4:"c"===t.type&&(v=3),t.size=v,t.array=new Float32Array(e*v),t.buffer=Kb.createBuffer(),t.buffer.belongsToAttribute=r,s.needsUpdate=!0,t.__original=s}a.__webglCustomAttributesList.push(t)}}a.__inittedArrays=!0}function k(a,b){return a.material instanceof e.MeshFaceMaterial?a.material.materials[b.materialIndex]:a.material}function l(a){return a&&void 0!==a.shading&&a.shading===e.SmoothShading}function m(a){return a instanceof e.MeshBasicMaterial&&!a.envMap||a instanceof e.MeshDepthMaterial?!1:l(a)?e.SmoothShading:e.FlatShading}function n(a){return a.vertexColors?a.vertexColors:!1}function o(a){return a.map||a.lightMap||a.bumpMap||a.normalMap||a.specularMap||a instanceof e.ShaderMaterial?!0:!1}function p(a){var b,c,d;for(b in a.attributes)d="index"===b?Kb.ELEMENT_ARRAY_BUFFER:Kb.ARRAY_BUFFER,c=a.attributes[b],c.buffer=Kb.createBuffer(),Kb.bindBuffer(d,c.buffer),Kb.bufferData(d,c.array,Kb.STATIC_DRAW)}function q(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p=a.vertices,q=p.length,r=a.colors,s=r.length,t=a.__vertexArray,u=a.__colorArray,v=a.__sortArray,w=a.verticesNeedUpdate,x=(a.elementsNeedUpdate,a.colorsNeedUpdate),y=a.__webglCustomAttributesList;if(c.sortParticles){for(sc.copy(rc),sc.multiply(c.matrixWorld),d=0;q>d;d++)f=p[d],tc.copy(f),tc.applyProjection(sc),v[d]=[tc.z,d];for(v.sort(z),d=0;q>d;d++)f=p[v[d][1]],g=3*d,t[g]=f.x,t[g+1]=f.y,t[g+2]=f.z;for(e=0;s>e;e++)g=3*e,i=r[v[e][1]],u[g]=i.r,u[g+1]=i.g,u[g+2]=i.b;if(y)for(j=0,k=y.length;k>j;j++)if(o=y[j],void 0===o.boundTo||"vertices"===o.boundTo)if(g=0,m=o.value.length,1===o.size)for(l=0;m>l;l++)h=v[l][1],o.array[l]=o.value[h];else if(2===o.size)for(l=0;m>l;l++)h=v[l][1],n=o.value[h],o.array[g]=n.x,o.array[g+1]=n.y,g+=2;else if(3===o.size)if("c"===o.type)for(l=0;m>l;l++)h=v[l][1],n=o.value[h],o.array[g]=n.r,o.array[g+1]=n.g,o.array[g+2]=n.b,g+=3;else for(l=0;m>l;l++)h=v[l][1],n=o.value[h],o.array[g]=n.x,o.array[g+1]=n.y,o.array[g+2]=n.z,g+=3;else if(4===o.size)for(l=0;m>l;l++)h=v[l][1],n=o.value[h],o.array[g]=n.x,o.array[g+1]=n.y,o.array[g+2]=n.z,o.array[g+3]=n.w,g+=4}else{if(w)for(d=0;q>d;d++)f=p[d],g=3*d,t[g]=f.x,t[g+1]=f.y,t[g+2]=f.z;if(x)for(e=0;s>e;e++)i=r[e],g=3*e,u[g]=i.r,u[g+1]=i.g,u[g+2]=i.b;if(y)for(j=0,k=y.length;k>j;j++)if(o=y[j],o.needsUpdate&&(void 0===o.boundTo||"vertices"===o.boundTo))if(m=o.value.length,g=0,1===o.size)for(l=0;m>l;l++)o.array[l]=o.value[l];else if(2===o.size)for(l=0;m>l;l++)n=o.value[l],o.array[g]=n.x,o.array[g+1]=n.y,g+=2;else if(3===o.size)if("c"===o.type)for(l=0;m>l;l++)n=o.value[l],o.array[g]=n.r,o.array[g+1]=n.g,o.array[g+2]=n.b,g+=3;else for(l=0;m>l;l++)n=o.value[l],o.array[g]=n.x,o.array[g+1]=n.y,o.array[g+2]=n.z,g+=3;else if(4===o.size)for(l=0;m>l;l++)n=o.value[l],o.array[g]=n.x,o.array[g+1]=n.y,o.array[g+2]=n.z,o.array[g+3]=n.w,g+=4}if((w||c.sortParticles)&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglVertexBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,t,b)),(x||c.sortParticles)&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglColorBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,u,b)),y)for(j=0,k=y.length;k>j;j++)o=y[j],(o.needsUpdate||c.sortParticles)&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,o.buffer),Kb.bufferData(Kb.ARRAY_BUFFER,o.array,b))}function r(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o=a.vertices,p=a.colors,q=a.lineDistances,r=o.length,s=p.length,t=q.length,u=a.__vertexArray,v=a.__colorArray,w=a.__lineDistanceArray,x=a.verticesNeedUpdate,y=a.colorsNeedUpdate,z=a.lineDistancesNeedUpdate,A=a.__webglCustomAttributesList; -if(x){for(c=0;r>c;c++)f=o[c],g=3*c,u[g]=f.x,u[g+1]=f.y,u[g+2]=f.z;Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglVertexBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,u,b)}if(y){for(d=0;s>d;d++)h=p[d],g=3*d,v[g]=h.r,v[g+1]=h.g,v[g+2]=h.b;Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglColorBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,v,b)}if(z){for(e=0;t>e;e++)w[e]=q[e];Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglLineDistanceBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,w,b)}if(A)for(i=0,j=A.length;j>i;i++)if(n=A[i],n.needsUpdate&&(void 0===n.boundTo||"vertices"===n.boundTo)){if(g=0,l=n.value.length,1===n.size)for(k=0;l>k;k++)n.array[k]=n.value[k];else if(2===n.size)for(k=0;l>k;k++)m=n.value[k],n.array[g]=m.x,n.array[g+1]=m.y,g+=2;else if(3===n.size)if("c"===n.type)for(k=0;l>k;k++)m=n.value[k],n.array[g]=m.r,n.array[g+1]=m.g,n.array[g+2]=m.b,g+=3;else for(k=0;l>k;k++)m=n.value[k],n.array[g]=m.x,n.array[g+1]=m.y,n.array[g+2]=m.z,g+=3;else if(4===n.size)for(k=0;l>k;k++)m=n.value[k],n.array[g]=m.x,n.array[g+1]=m.y,n.array[g+2]=m.z,n.array[g+3]=m.w,g+=4;Kb.bindBuffer(Kb.ARRAY_BUFFER,n.buffer),Kb.bufferData(Kb.ARRAY_BUFFER,n.array,b)}}function s(a,b,c,d,f){if(a.__inittedArrays){var g,h,i,j,k,l,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z=m(f),$=n(f),_=o(f),ab=Z===e.SmoothShading,bb=0,cb=0,db=0,eb=0,fb=0,gb=0,hb=0,ib=0,jb=0,kb=0,lb=0,mb=0,nb=0,ob=a.__vertexArray,pb=a.__uvArray,qb=a.__uv2Array,rb=a.__normalArray,sb=a.__tangentArray,tb=a.__colorArray,ub=a.__skinIndexArray,vb=a.__skinWeightArray,wb=a.__morphTargetsArrays,xb=a.__morphNormalsArrays,yb=a.__webglCustomAttributesList,zb=a.__faceArray,Ab=a.__lineArray,Bb=b.geometry,Cb=Bb.verticesNeedUpdate,Db=Bb.elementsNeedUpdate,Eb=Bb.uvsNeedUpdate,Fb=Bb.normalsNeedUpdate,Gb=Bb.tangentsNeedUpdate,Hb=Bb.colorsNeedUpdate,Ib=Bb.morphTargetsNeedUpdate,Jb=Bb.vertices,Lb=a.faces3,Mb=Bb.faces,Nb=Bb.faceVertexUvs[0],Ob=Bb.faceVertexUvs[1],Pb=(Bb.colors,Bb.skinIndices),Qb=Bb.skinWeights,Rb=Bb.morphTargets,Sb=Bb.morphNormals;if(Cb){for(g=0,h=Lb.length;h>g;g++)j=Mb[Lb[g]],u=Jb[j.a],v=Jb[j.b],w=Jb[j.c],ob[cb]=u.x,ob[cb+1]=u.y,ob[cb+2]=u.z,ob[cb+3]=v.x,ob[cb+4]=v.y,ob[cb+5]=v.z,ob[cb+6]=w.x,ob[cb+7]=w.y,ob[cb+8]=w.z,cb+=9;Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglVertexBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,ob,c)}if(Ib)for(R=0,S=Rb.length;S>R;R++){for(lb=0,g=0,h=Lb.length;h>g;g++)V=Lb[g],j=Mb[V],u=Rb[R].vertices[j.a],v=Rb[R].vertices[j.b],w=Rb[R].vertices[j.c],T=wb[R],T[lb]=u.x,T[lb+1]=u.y,T[lb+2]=u.z,T[lb+3]=v.x,T[lb+4]=v.y,T[lb+5]=v.z,T[lb+6]=w.x,T[lb+7]=w.y,T[lb+8]=w.z,f.morphNormals&&(ab?(W=Sb[R].vertexNormals[V],A=W.a,B=W.b,C=W.c):(A=Sb[R].faceNormals[V],B=A,C=A),U=xb[R],U[lb]=A.x,U[lb+1]=A.y,U[lb+2]=A.z,U[lb+3]=B.x,U[lb+4]=B.y,U[lb+5]=B.z,U[lb+6]=C.x,U[lb+7]=C.y,U[lb+8]=C.z),lb+=9;Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglMorphTargetsBuffers[R]),Kb.bufferData(Kb.ARRAY_BUFFER,wb[R],c),f.morphNormals&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglMorphNormalsBuffers[R]),Kb.bufferData(Kb.ARRAY_BUFFER,xb[R],c))}if(Qb.length){for(g=0,h=Lb.length;h>g;g++)j=Mb[Lb[g]],G=Qb[j.a],H=Qb[j.b],I=Qb[j.c],vb[kb]=G.x,vb[kb+1]=G.y,vb[kb+2]=G.z,vb[kb+3]=G.w,vb[kb+4]=H.x,vb[kb+5]=H.y,vb[kb+6]=H.z,vb[kb+7]=H.w,vb[kb+8]=I.x,vb[kb+9]=I.y,vb[kb+10]=I.z,vb[kb+11]=I.w,J=Pb[j.a],K=Pb[j.b],L=Pb[j.c],ub[kb]=J.x,ub[kb+1]=J.y,ub[kb+2]=J.z,ub[kb+3]=J.w,ub[kb+4]=K.x,ub[kb+5]=K.y,ub[kb+6]=K.z,ub[kb+7]=K.w,ub[kb+8]=L.x,ub[kb+9]=L.y,ub[kb+10]=L.z,ub[kb+11]=L.w,kb+=12;kb>0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglSkinIndicesBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,ub,c),Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglSkinWeightsBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,vb,c))}if(Hb&&$){for(g=0,h=Lb.length;h>g;g++)j=Mb[Lb[g]],p=j.vertexColors,q=j.color,3===p.length&&$===e.VertexColors?(D=p[0],E=p[1],F=p[2]):(D=q,E=q,F=q),tb[jb]=D.r,tb[jb+1]=D.g,tb[jb+2]=D.b,tb[jb+3]=E.r,tb[jb+4]=E.g,tb[jb+5]=E.b,tb[jb+6]=F.r,tb[jb+7]=F.g,tb[jb+8]=F.b,jb+=9;jb>0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglColorBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,tb,c))}if(Gb&&Bb.hasTangents){for(g=0,h=Lb.length;h>g;g++)j=Mb[Lb[g]],r=j.vertexTangents,x=r[0],y=r[1],z=r[2],sb[hb]=x.x,sb[hb+1]=x.y,sb[hb+2]=x.z,sb[hb+3]=x.w,sb[hb+4]=y.x,sb[hb+5]=y.y,sb[hb+6]=y.z,sb[hb+7]=y.w,sb[hb+8]=z.x,sb[hb+9]=z.y,sb[hb+10]=z.z,sb[hb+11]=z.w,hb+=12;Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglTangentBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,sb,c)}if(Fb&&Z){for(g=0,h=Lb.length;h>g;g++)if(j=Mb[Lb[g]],k=j.vertexNormals,l=j.normal,3===k.length&&ab)for(M=0;3>M;M++)O=k[M],rb[gb]=O.x,rb[gb+1]=O.y,rb[gb+2]=O.z,gb+=3;else for(M=0;3>M;M++)rb[gb]=l.x,rb[gb+1]=l.y,rb[gb+2]=l.z,gb+=3;Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglNormalBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,rb,c)}if(Eb&&Nb&&_){for(g=0,h=Lb.length;h>g;g++)if(i=Lb[g],s=Nb[i],void 0!==s)for(M=0;3>M;M++)P=s[M],pb[db]=P.x,pb[db+1]=P.y,db+=2;db>0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglUVBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,pb,c))}if(Eb&&Ob&&_){for(g=0,h=Lb.length;h>g;g++)if(i=Lb[g],t=Ob[i],void 0!==t)for(M=0;3>M;M++)Q=t[M],qb[eb]=Q.x,qb[eb+1]=Q.y,eb+=2;eb>0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglUV2Buffer),Kb.bufferData(Kb.ARRAY_BUFFER,qb,c))}if(Db){for(g=0,h=Lb.length;h>g;g++)zb[fb]=bb,zb[fb+1]=bb+1,zb[fb+2]=bb+2,fb+=3,Ab[ib]=bb,Ab[ib+1]=bb+1,Ab[ib+2]=bb,Ab[ib+3]=bb+2,Ab[ib+4]=bb+1,Ab[ib+5]=bb+2,ib+=6,bb+=3;Kb.bindBuffer(Kb.ELEMENT_ARRAY_BUFFER,a.__webglFaceBuffer),Kb.bufferData(Kb.ELEMENT_ARRAY_BUFFER,zb,c),Kb.bindBuffer(Kb.ELEMENT_ARRAY_BUFFER,a.__webglLineBuffer),Kb.bufferData(Kb.ELEMENT_ARRAY_BUFFER,Ab,c)}if(yb)for(M=0,N=yb.length;N>M;M++)if(Y=yb[M],Y.__original.needsUpdate){if(mb=0,nb=0,1===Y.size){if(void 0===Y.boundTo||"vertices"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)j=Mb[Lb[g]],Y.array[mb]=Y.value[j.a],Y.array[mb+1]=Y.value[j.b],Y.array[mb+2]=Y.value[j.c],mb+=3;else if("faces"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)X=Y.value[Lb[g]],Y.array[mb]=X,Y.array[mb+1]=X,Y.array[mb+2]=X,mb+=3}else if(2===Y.size){if(void 0===Y.boundTo||"vertices"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)j=Mb[Lb[g]],u=Y.value[j.a],v=Y.value[j.b],w=Y.value[j.c],Y.array[mb]=u.x,Y.array[mb+1]=u.y,Y.array[mb+2]=v.x,Y.array[mb+3]=v.y,Y.array[mb+4]=w.x,Y.array[mb+5]=w.y,mb+=6;else if("faces"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)X=Y.value[Lb[g]],u=X,v=X,w=X,Y.array[mb]=u.x,Y.array[mb+1]=u.y,Y.array[mb+2]=v.x,Y.array[mb+3]=v.y,Y.array[mb+4]=w.x,Y.array[mb+5]=w.y,mb+=6}else if(3===Y.size){var Tb;if(Tb="c"===Y.type?["r","g","b"]:["x","y","z"],void 0===Y.boundTo||"vertices"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)j=Mb[Lb[g]],u=Y.value[j.a],v=Y.value[j.b],w=Y.value[j.c],Y.array[mb]=u[Tb[0]],Y.array[mb+1]=u[Tb[1]],Y.array[mb+2]=u[Tb[2]],Y.array[mb+3]=v[Tb[0]],Y.array[mb+4]=v[Tb[1]],Y.array[mb+5]=v[Tb[2]],Y.array[mb+6]=w[Tb[0]],Y.array[mb+7]=w[Tb[1]],Y.array[mb+8]=w[Tb[2]],mb+=9;else if("faces"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)X=Y.value[Lb[g]],u=X,v=X,w=X,Y.array[mb]=u[Tb[0]],Y.array[mb+1]=u[Tb[1]],Y.array[mb+2]=u[Tb[2]],Y.array[mb+3]=v[Tb[0]],Y.array[mb+4]=v[Tb[1]],Y.array[mb+5]=v[Tb[2]],Y.array[mb+6]=w[Tb[0]],Y.array[mb+7]=w[Tb[1]],Y.array[mb+8]=w[Tb[2]],mb+=9;else if("faceVertices"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)X=Y.value[Lb[g]],u=X[0],v=X[1],w=X[2],Y.array[mb]=u[Tb[0]],Y.array[mb+1]=u[Tb[1]],Y.array[mb+2]=u[Tb[2]],Y.array[mb+3]=v[Tb[0]],Y.array[mb+4]=v[Tb[1]],Y.array[mb+5]=v[Tb[2]],Y.array[mb+6]=w[Tb[0]],Y.array[mb+7]=w[Tb[1]],Y.array[mb+8]=w[Tb[2]],mb+=9}else if(4===Y.size)if(void 0===Y.boundTo||"vertices"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)j=Mb[Lb[g]],u=Y.value[j.a],v=Y.value[j.b],w=Y.value[j.c],Y.array[mb]=u.x,Y.array[mb+1]=u.y,Y.array[mb+2]=u.z,Y.array[mb+3]=u.w,Y.array[mb+4]=v.x,Y.array[mb+5]=v.y,Y.array[mb+6]=v.z,Y.array[mb+7]=v.w,Y.array[mb+8]=w.x,Y.array[mb+9]=w.y,Y.array[mb+10]=w.z,Y.array[mb+11]=w.w,mb+=12;else if("faces"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)X=Y.value[Lb[g]],u=X,v=X,w=X,Y.array[mb]=u.x,Y.array[mb+1]=u.y,Y.array[mb+2]=u.z,Y.array[mb+3]=u.w,Y.array[mb+4]=v.x,Y.array[mb+5]=v.y,Y.array[mb+6]=v.z,Y.array[mb+7]=v.w,Y.array[mb+8]=w.x,Y.array[mb+9]=w.y,Y.array[mb+10]=w.z,Y.array[mb+11]=w.w,mb+=12;else if("faceVertices"===Y.boundTo)for(g=0,h=Lb.length;h>g;g++)X=Y.value[Lb[g]],u=X[0],v=X[1],w=X[2],Y.array[mb]=u.x,Y.array[mb+1]=u.y,Y.array[mb+2]=u.z,Y.array[mb+3]=u.w,Y.array[mb+4]=v.x,Y.array[mb+5]=v.y,Y.array[mb+6]=v.z,Y.array[mb+7]=v.w,Y.array[mb+8]=w.x,Y.array[mb+9]=w.y,Y.array[mb+10]=w.z,Y.array[mb+11]=w.w,mb+=12;Kb.bindBuffer(Kb.ARRAY_BUFFER,Y.buffer),Kb.bufferData(Kb.ARRAY_BUFFER,Y.array,c)}d&&(delete a.__inittedArrays,delete a.__colorArray,delete a.__normalArray,delete a.__tangentArray,delete a.__uvArray,delete a.__uv2Array,delete a.__faceArray,delete a.__vertexArray,delete a.__lineArray,delete a.__skinIndexArray,delete a.__skinWeightArray)}}function t(a,b,c,d){var e,f,g,h;for(f in b)g=b[f],e=c[f],g>=0&&(e?(h=e.itemSize,Kb.bindBuffer(Kb.ARRAY_BUFFER,e.buffer),v(g),Kb.vertexAttribPointer(g,h,Kb.FLOAT,!1,0,d*h*4)):a.defaultAttributeValues&&(2===a.defaultAttributeValues[f].length?Kb.vertexAttrib2fv(g,a.defaultAttributeValues[f]):3===a.defaultAttributeValues[f].length&&Kb.vertexAttrib3fv(g,a.defaultAttributeValues[f])))}function u(a,b){var c,d,e=a.attributes;for(c in e)d=e[c],d.needsUpdate&&("index"===c?(Kb.bindBuffer(Kb.ELEMENT_ARRAY_BUFFER,d.buffer),Kb.bufferData(Kb.ELEMENT_ARRAY_BUFFER,d.array,b)):(Kb.bindBuffer(Kb.ARRAY_BUFFER,d.buffer),Kb.bufferData(Kb.ARRAY_BUFFER,d.array,b)),d.needsUpdate=!1)}function v(a){0===pc[a]&&(Kb.enableVertexAttribArray(a),pc[a]=1)}function w(){for(var a in pc)1===pc[a]&&(Kb.disableVertexAttribArray(a),pc[a]=0)}function x(a,b,c){var d=a.program.attributes;if(-1!==c.morphTargetBase&&d.position>=0?(Kb.bindBuffer(Kb.ARRAY_BUFFER,b.__webglMorphTargetsBuffers[c.morphTargetBase]),v(d.position),Kb.vertexAttribPointer(d.position,3,Kb.FLOAT,!1,0,0)):d.position>=0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,b.__webglVertexBuffer),v(d.position),Kb.vertexAttribPointer(d.position,3,Kb.FLOAT,!1,0,0)),c.morphTargetForcedOrder.length)for(var e=0,f=c.morphTargetForcedOrder,g=c.morphTargetInfluences;e=0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,b.__webglMorphTargetsBuffers[f[e]]),v(d["morphTarget"+e]),Kb.vertexAttribPointer(d["morphTarget"+e],3,Kb.FLOAT,!1,0,0)),d["morphNormal"+e]>=0&&a.morphNormals&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,b.__webglMorphNormalsBuffers[f[e]]),v(d["morphNormal"+e]),Kb.vertexAttribPointer(d["morphNormal"+e],3,Kb.FLOAT,!1,0,0)),c.__webglMorphTargetInfluences[e]=g[f[e]],e++;else{var h,i,j=[],g=c.morphTargetInfluences,k=g.length;for(i=0;k>i;i++)h=g[i],h>0&&j.push([h,i]);j.length>a.numSupportedMorphTargets?(j.sort(z),j.length=a.numSupportedMorphTargets):j.length>a.numSupportedMorphNormals?j.sort(z):0===j.length&&j.push([0,0]);for(var l,e=0;e=0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,b.__webglMorphTargetsBuffers[l]),v(d["morphTarget"+e]),Kb.vertexAttribPointer(d["morphTarget"+e],3,Kb.FLOAT,!1,0,0)),d["morphNormal"+e]>=0&&a.morphNormals&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,b.__webglMorphNormalsBuffers[l]),v(d["morphNormal"+e]),Kb.vertexAttribPointer(d["morphNormal"+e],3,Kb.FLOAT,!1,0,0)),c.__webglMorphTargetInfluences[e]=g[l]):c.__webglMorphTargetInfluences[e]=0,e++}null!==a.program.uniforms.morphTargetInfluences&&Kb.uniform1fv(a.program.uniforms.morphTargetInfluences,c.__webglMorphTargetInfluences)}function y(a,b){return a.z!==b.z?b.z-a.z:a.id-b.id}function z(a,b){return b[0]-a[0]}function A(a,b,c){if(a.length)for(var d=0,e=a.length;e>d;d++)Tb=null,Xb=null,_b=-1,dc=-1,ec=-1,Zb=-1,$b=-1,Wb=-1,Vb=-1,vc=!0,a[d].render(b,c,nc,oc),Tb=null,Xb=null,_b=-1,dc=-1,ec=-1,Zb=-1,$b=-1,Wb=-1,Vb=-1,vc=!0}function B(a,b,c,d,f,g,h,i){var j,k,l,m,n,o,p;b?(n=a.length-1,o=-1,p=-1):(n=0,o=a.length,p=1);for(var q=n;q!==o;q+=p)if(j=a[q],j.render){if(k=j.object,l=j.buffer,i)m=i;else{if(m=j[c],!m)continue;h&&Qb.setBlending(m.blending,m.blendEquation,m.blendSrc,m.blendDst),Qb.setDepthTest(m.depthTest),Qb.setDepthWrite(m.depthWrite),fb(m.polygonOffset,m.polygonOffsetFactor,m.polygonOffsetUnits)}Qb.setMaterialFaces(m),l instanceof e.BufferGeometry?Qb.renderBufferDirect(d,f,g,m,l,k):Qb.renderBuffer(d,f,g,m,l,k)}}function C(a,b,c,d,e,f,g){for(var h,i,j,k=0,l=a.length;l>k;k++)if(h=a[k],i=h.object,i.visible){if(g)j=g;else{if(j=h[b],!j)continue;f&&Qb.setBlending(j.blending,j.blendEquation,j.blendSrc,j.blendDst),Qb.setDepthTest(j.depthTest),Qb.setDepthWrite(j.depthWrite),fb(j.polygonOffset,j.polygonOffsetFactor,j.polygonOffsetUnits)}Qb.renderImmediateObject(c,d,e,j,i)}}function D(a){var b=a.object,c=b.material;c.transparent?(a.transparent=c,a.opaque=null):(a.opaque=c,a.transparent=null)}function E(a){var b=a.object,c=a.buffer,d=b.geometry,f=b.material;if(f instanceof e.MeshFaceMaterial){var g=d instanceof e.BufferGeometry?0:c.materialIndex;f=f.materials[g],f.transparent?(a.transparent=f,a.opaque=null):(a.opaque=f,a.transparent=null)}else f&&(f.transparent?(a.transparent=f,a.opaque=null):(a.opaque=f,a.transparent=null))}function F(a,d){var g,k,l,m;if(void 0===a.__webglInit)if(a.__webglInit=!0,a._modelViewMatrix=new e.Matrix4,a._normalMatrix=new e.Matrix3,void 0!==a.geometry&&void 0===a.geometry.__webglInit&&(a.geometry.__webglInit=!0,a.geometry.addEventListener("dispose",Jc)),k=a.geometry,void 0===k);else if(k instanceof e.BufferGeometry)p(k);else if(a instanceof e.Mesh){l=a.material,void 0===k.geometryGroups&&k.makeGroups(l instanceof e.MeshFaceMaterial);for(g in k.geometryGroups)m=k.geometryGroups[g],m.__webglVertexBuffer||(f(m),j(m,a),k.verticesNeedUpdate=!0,k.morphTargetsNeedUpdate=!0,k.elementsNeedUpdate=!0,k.uvsNeedUpdate=!0,k.normalsNeedUpdate=!0,k.tangentsNeedUpdate=!0,k.colorsNeedUpdate=!0)}else a instanceof e.Line?k.__webglVertexBuffer||(c(k),i(k,a),k.verticesNeedUpdate=!0,k.colorsNeedUpdate=!0,k.lineDistancesNeedUpdate=!0):a instanceof e.ParticleSystem&&(k.__webglVertexBuffer||(b(k),h(k,a),k.verticesNeedUpdate=!0,k.colorsNeedUpdate=!0));if(void 0===a.__webglActive){if(a instanceof e.Mesh){if(k=a.geometry,k instanceof e.BufferGeometry)G(d.__webglObjects,k,a);else if(k instanceof e.Geometry)for(g in k.geometryGroups)m=k.geometryGroups[g],G(d.__webglObjects,m,a)}else a instanceof e.Line||a instanceof e.ParticleSystem?(k=a.geometry,G(d.__webglObjects,k,a)):a instanceof e.ImmediateRenderObject||a.immediateRenderCallback?H(d.__webglObjectsImmediate,a):a instanceof e.Sprite?d.__webglSprites.push(a):a instanceof e.LensFlare&&d.__webglFlares.push(a);a.__webglActive=!0}}function G(a,b,c){a.push({id:null,buffer:b,object:c,opaque:null,transparent:null,z:0})}function H(a,b){a.push({id:null,object:b,opaque:null,transparent:null,z:0})}function I(a){var b,c,d,f=a.geometry;if(f instanceof e.BufferGeometry)u(f,Kb.DYNAMIC_DRAW);else if(a instanceof e.Mesh){for(var g=0,h=f.geometryGroupsList.length;h>g;g++)b=f.geometryGroupsList[g],d=k(a,b),f.buffersNeedUpdate&&j(b,a),c=d.attributes&&J(d),(f.verticesNeedUpdate||f.morphTargetsNeedUpdate||f.elementsNeedUpdate||f.uvsNeedUpdate||f.normalsNeedUpdate||f.colorsNeedUpdate||f.tangentsNeedUpdate||c)&&s(b,a,Kb.DYNAMIC_DRAW,!f.dynamic,d);f.verticesNeedUpdate=!1,f.morphTargetsNeedUpdate=!1,f.elementsNeedUpdate=!1,f.uvsNeedUpdate=!1,f.normalsNeedUpdate=!1,f.colorsNeedUpdate=!1,f.tangentsNeedUpdate=!1,f.buffersNeedUpdate=!1,d.attributes&&K(d)}else a instanceof e.Line?(d=k(a,f),c=d.attributes&&J(d),(f.verticesNeedUpdate||f.colorsNeedUpdate||f.lineDistancesNeedUpdate||c)&&r(f,Kb.DYNAMIC_DRAW),f.verticesNeedUpdate=!1,f.colorsNeedUpdate=!1,f.lineDistancesNeedUpdate=!1,d.attributes&&K(d)):a instanceof e.ParticleSystem&&(d=k(a,f),c=d.attributes&&J(d),(f.verticesNeedUpdate||f.colorsNeedUpdate||a.sortParticles||c)&&q(f,Kb.DYNAMIC_DRAW,a),f.verticesNeedUpdate=!1,f.colorsNeedUpdate=!1,d.attributes&&K(d))}function J(a){for(var b in a.attributes)if(a.attributes[b].needsUpdate)return!0;return!1}function K(a){for(var b in a.attributes)a.attributes[b].needsUpdate=!1}function L(a,b){a instanceof e.Mesh||a instanceof e.ParticleSystem||a instanceof e.Line?M(b.__webglObjects,a):a instanceof e.Sprite?N(b.__webglSprites,a):a instanceof e.LensFlare?N(b.__webglFlares,a):(a instanceof e.ImmediateRenderObject||a.immediateRenderCallback)&&M(b.__webglObjectsImmediate,a),delete a.__webglActive}function M(a,b){for(var c=a.length-1;c>=0;c--)a[c].object===b&&a.splice(c,1)}function N(a,b){for(var c=a.length-1;c>=0;c--)a[c]===b&&a.splice(c,1)}function O(a,b){a.uniforms=e.UniformsUtils.clone(b.uniforms),a.vertexShader=b.vertexShader,a.fragmentShader=b.fragmentShader}function P(a,b,c,d,f){Yb=0,d.needsUpdate&&(d.program&&Rc(d),Qb.initMaterial(d,b,c,f),d.needsUpdate=!1),d.morphTargets&&(f.__webglMorphTargetInfluences||(f.__webglMorphTargetInfluences=new Float32Array(Qb.maxMorphTargets)));var g=!1,h=d.program,i=h.uniforms,j=d.uniforms;if(h!==Tb&&(Kb.useProgram(h),Tb=h,g=!0),d.id!==Vb&&(Vb=d.id,g=!0),(g||a!==Xb)&&(Kb.uniformMatrix4fv(i.projectionMatrix,!1,a.projectionMatrix.elements),a!==Xb&&(Xb=a)),d.skinning)if(Cc&&f.useVertexTexture){if(null!==i.boneTexture){var k=$();Kb.uniform1i(i.boneTexture,k),Qb.setTexture(f.boneTexture,k)}null!==i.boneTextureWidth&&Kb.uniform1i(i.boneTextureWidth,f.boneTextureWidth),null!==i.boneTextureHeight&&Kb.uniform1i(i.boneTextureHeight,f.boneTextureHeight)}else null!==i.boneGlobalMatrices&&Kb.uniformMatrix4fv(i.boneGlobalMatrices,!1,f.boneMatrices);return g&&(c&&d.fog&&U(j,c),(d instanceof e.MeshPhongMaterial||d instanceof e.MeshLambertMaterial||d.lights)&&(vc&&(db(h,b),vc=!1),X(j,wc)),(d instanceof e.MeshBasicMaterial||d instanceof e.MeshLambertMaterial||d instanceof e.MeshPhongMaterial)&&Q(j,d),d instanceof e.LineBasicMaterial?R(j,d):d instanceof e.LineDashedMaterial?(R(j,d),S(j,d)):d instanceof e.ParticleSystemMaterial?T(j,d):d instanceof e.MeshPhongMaterial?V(j,d):d instanceof e.MeshLambertMaterial?W(j,d):d instanceof e.MeshDepthMaterial?(j.mNear.value=a.near,j.mFar.value=a.far,j.opacity.value=d.opacity):d instanceof e.MeshNormalMaterial&&(j.opacity.value=d.opacity),f.receiveShadow&&!d._shadowPass&&Y(j,b),_(h,d.uniformsList),(d instanceof e.ShaderMaterial||d instanceof e.MeshPhongMaterial||d.envMap)&&null!==i.cameraPosition&&(tc.setFromMatrixPosition(a.matrixWorld),Kb.uniform3f(i.cameraPosition,tc.x,tc.y,tc.z)),(d instanceof e.MeshPhongMaterial||d instanceof e.MeshLambertMaterial||d instanceof e.ShaderMaterial||d.skinning)&&null!==i.viewMatrix&&Kb.uniformMatrix4fv(i.viewMatrix,!1,a.matrixWorldInverse.elements)),Z(i,f),null!==i.modelMatrix&&Kb.uniformMatrix4fv(i.modelMatrix,!1,f.matrixWorld.elements),h}function Q(a,b){a.opacity.value=b.opacity,Qb.gammaInput?a.diffuse.value.copyGammaToLinear(b.color):a.diffuse.value=b.color,a.map.value=b.map,a.lightMap.value=b.lightMap,a.specularMap.value=b.specularMap,b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale),b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));var c;if(b.map?c=b.map:b.specularMap?c=b.specularMap:b.normalMap?c=b.normalMap:b.bumpMap&&(c=b.bumpMap),void 0!==c){var d=c.offset,f=c.repeat;a.offsetRepeat.value.set(d.x,d.y,f.x,f.y)}a.envMap.value=b.envMap,a.flipEnvMap.value=b.envMap instanceof e.WebGLRenderTargetCube?1:-1,a.reflectivity.value=Qb.gammaInput?b.reflectivity:b.reflectivity,a.refractionRatio.value=b.refractionRatio,a.combine.value=b.combine,a.useRefract.value=b.envMap&&b.envMap.mapping instanceof e.CubeRefractionMapping}function R(a,b){a.diffuse.value=b.color,a.opacity.value=b.opacity}function S(a,b){a.dashSize.value=b.dashSize,a.totalSize.value=b.dashSize+b.gapSize,a.scale.value=b.scale}function T(a,b){a.psColor.value=b.color,a.opacity.value=b.opacity,a.size.value=b.size,a.scale.value=Ab.height/2,a.map.value=b.map}function U(a,b){a.fogColor.value=b.color,b instanceof e.Fog?(a.fogNear.value=b.near,a.fogFar.value=b.far):b instanceof e.FogExp2&&(a.fogDensity.value=b.density)}function V(a,b){a.shininess.value=b.shininess,Qb.gammaInput?(a.ambient.value.copyGammaToLinear(b.ambient),a.emissive.value.copyGammaToLinear(b.emissive),a.specular.value.copyGammaToLinear(b.specular)):(a.ambient.value=b.ambient,a.emissive.value=b.emissive,a.specular.value=b.specular),b.wrapAround&&a.wrapRGB.value.copy(b.wrapRGB)}function W(a,b){Qb.gammaInput?(a.ambient.value.copyGammaToLinear(b.ambient),a.emissive.value.copyGammaToLinear(b.emissive)):(a.ambient.value=b.ambient,a.emissive.value=b.emissive),b.wrapAround&&a.wrapRGB.value.copy(b.wrapRGB)}function X(a,b){a.ambientLightColor.value=b.ambient,a.directionalLightColor.value=b.directional.colors,a.directionalLightDirection.value=b.directional.positions,a.pointLightColor.value=b.point.colors,a.pointLightPosition.value=b.point.positions,a.pointLightDistance.value=b.point.distances,a.spotLightColor.value=b.spot.colors,a.spotLightPosition.value=b.spot.positions,a.spotLightDistance.value=b.spot.distances,a.spotLightDirection.value=b.spot.directions,a.spotLightAngleCos.value=b.spot.anglesCos,a.spotLightExponent.value=b.spot.exponents,a.hemisphereLightSkyColor.value=b.hemi.skyColors,a.hemisphereLightGroundColor.value=b.hemi.groundColors,a.hemisphereLightDirection.value=b.hemi.positions}function Y(a,b){if(a.shadowMatrix)for(var c=0,d=0,f=b.length;f>d;d++){var g=b[d];g.castShadow&&(g instanceof e.SpotLight||g instanceof e.DirectionalLight&&!g.shadowCascade)&&(a.shadowMap.value[c]=g.shadowMap,a.shadowMapSize.value[c]=g.shadowMapSize,a.shadowMatrix.value[c]=g.shadowMatrix,a.shadowDarkness.value[c]=g.shadowDarkness,a.shadowBias.value[c]=g.shadowBias,c++)}}function Z(a,b){Kb.uniformMatrix4fv(a.modelViewMatrix,!1,b._modelViewMatrix.elements),a.normalMatrix&&Kb.uniformMatrix3fv(a.normalMatrix,!1,b._normalMatrix.elements)}function $(){var a=Yb;return a>=xc&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+xc),Yb+=1,a}function _(a,b){var c,d,f,g,h,i,j,k,l,m,n;for(l=0,m=b.length;m>l;l++)if(g=a.uniforms[b[l][1]])if(c=b[l][0],f=c.type,d=c.value,"i"===f)Kb.uniform1i(g,d);else if("f"===f)Kb.uniform1f(g,d);else if("v2"===f)Kb.uniform2f(g,d.x,d.y);else if("v3"===f)Kb.uniform3f(g,d.x,d.y,d.z);else if("v4"===f)Kb.uniform4f(g,d.x,d.y,d.z,d.w);else if("c"===f)Kb.uniform3f(g,d.r,d.g,d.b);else if("iv1"===f)Kb.uniform1iv(g,d);else if("iv"===f)Kb.uniform3iv(g,d);else if("fv1"===f)Kb.uniform1fv(g,d);else if("fv"===f)Kb.uniform3fv(g,d);else if("v2v"===f){for(void 0===c._array&&(c._array=new Float32Array(2*d.length)),j=0,k=d.length;k>j;j++)n=2*j,c._array[n]=d[j].x,c._array[n+1]=d[j].y;Kb.uniform2fv(g,c._array)}else if("v3v"===f){for(void 0===c._array&&(c._array=new Float32Array(3*d.length)),j=0,k=d.length;k>j;j++)n=3*j,c._array[n]=d[j].x,c._array[n+1]=d[j].y,c._array[n+2]=d[j].z;Kb.uniform3fv(g,c._array)}else if("v4v"===f){for(void 0===c._array&&(c._array=new Float32Array(4*d.length)),j=0,k=d.length;k>j;j++)n=4*j,c._array[n]=d[j].x,c._array[n+1]=d[j].y,c._array[n+2]=d[j].z,c._array[n+3]=d[j].w;Kb.uniform4fv(g,c._array)}else if("m4"===f)void 0===c._array&&(c._array=new Float32Array(16)),d.flattenToArray(c._array),Kb.uniformMatrix4fv(g,!1,c._array);else if("m4v"===f){for(void 0===c._array&&(c._array=new Float32Array(16*d.length)),j=0,k=d.length;k>j;j++)d[j].flattenToArrayOffset(c._array,16*j);Kb.uniformMatrix4fv(g,!1,c._array)}else if("t"===f){if(h=d,i=$(),Kb.uniform1i(g,i),!h)continue;h.image instanceof Array&&6===h.image.length?ob(h,i):h instanceof e.WebGLRenderTargetCube?pb(h,i):Qb.setTexture(h,i)}else if("tv"===f){for(void 0===c._array&&(c._array=[]),j=0,k=c.value.length;k>j;j++)c._array[j]=$();for(Kb.uniform1iv(g,c._array),j=0,k=c.value.length;k>j;j++)h=c.value[j],i=c._array[j],h&&Qb.setTexture(h,i)}else console.warn("THREE.WebGLRenderer: Unknown uniform type: "+f)}function ab(a,b){a._modelViewMatrix.multiplyMatrices(b.matrixWorldInverse,a.matrixWorld),a._normalMatrix.getNormalMatrix(a._modelViewMatrix)}function bb(a,b,c,d){a[b]=c.r*c.r*d,a[b+1]=c.g*c.g*d,a[b+2]=c.b*c.b*d}function cb(a,b,c,d){a[b]=c.r*d,a[b+1]=c.g*d,a[b+2]=c.b*d}function db(a,b){var c,d,f,g,h,i,j,k,l,m=0,n=0,o=0,p=wc,q=p.directional.colors,r=p.directional.positions,s=p.point.colors,t=p.point.positions,u=p.point.distances,v=p.spot.colors,w=p.spot.positions,x=p.spot.distances,y=p.spot.directions,z=p.spot.anglesCos,A=p.spot.exponents,B=p.hemi.skyColors,C=p.hemi.groundColors,D=p.hemi.positions,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0;for(c=0,d=b.length;d>c;c++)if(f=b[c],!f.onlyShadow)if(g=f.color,j=f.intensity,l=f.distance,f instanceof e.AmbientLight){if(!f.visible)continue;Qb.gammaInput?(m+=g.r*g.r,n+=g.g*g.g,o+=g.b*g.b):(m+=g.r,n+=g.g,o+=g.b)}else if(f instanceof e.DirectionalLight){if(I+=1,!f.visible)continue;if(uc.setFromMatrixPosition(f.matrixWorld),tc.setFromMatrixPosition(f.target.matrixWorld),uc.sub(tc),uc.normalize(),0===uc.x&&0===uc.y&&0===uc.z)continue;M=3*E,r[M]=uc.x,r[M+1]=uc.y,r[M+2]=uc.z,Qb.gammaInput?bb(q,M,g,j*j):cb(q,M,g,j),E+=1}else if(f instanceof e.PointLight){if(J+=1,!f.visible)continue;N=3*F,Qb.gammaInput?bb(s,N,g,j*j):cb(s,N,g,j),tc.setFromMatrixPosition(f.matrixWorld),t[N]=tc.x,t[N+1]=tc.y,t[N+2]=tc.z,u[F]=l,F+=1}else if(f instanceof e.SpotLight){if(K+=1,!f.visible)continue;O=3*G,Qb.gammaInput?bb(v,O,g,j*j):cb(v,O,g,j),tc.setFromMatrixPosition(f.matrixWorld),w[O]=tc.x,w[O+1]=tc.y,w[O+2]=tc.z,x[G]=l,uc.copy(tc),tc.setFromMatrixPosition(f.target.matrixWorld),uc.sub(tc),uc.normalize(),y[O]=uc.x,y[O+1]=uc.y,y[O+2]=uc.z,z[G]=Math.cos(f.angle),A[G]=f.exponent,G+=1}else if(f instanceof e.HemisphereLight){if(L+=1,!f.visible)continue;if(uc.setFromMatrixPosition(f.matrixWorld),uc.normalize(),0===uc.x&&0===uc.y&&0===uc.z)continue;P=3*H,D[P]=uc.x,D[P+1]=uc.y,D[P+2]=uc.z,h=f.color,i=f.groundColor,Qb.gammaInput?(k=j*j,bb(B,P,h,k),bb(C,P,i,k)):(cb(B,P,h,j),cb(C,P,i,j)),H+=1}for(c=3*E,d=Math.max(q.length,3*I);d>c;c++)q[c]=0;for(c=3*F,d=Math.max(s.length,3*J);d>c;c++)s[c]=0;for(c=3*G,d=Math.max(v.length,3*K);d>c;c++)v[c]=0;for(c=3*H,d=Math.max(B.length,3*L);d>c;c++)B[c]=0;for(c=3*H,d=Math.max(C.length,3*L);d>c;c++)C[c]=0;p.directional.length=E,p.point.length=F,p.spot.length=G,p.hemi.length=H,p.ambient[0]=m,p.ambient[1]=n,p.ambient[2]=o}function eb(a){a!==ic&&(Kb.lineWidth(a),ic=a)}function fb(a,b,c){fc!==a&&(a?Kb.enable(Kb.POLYGON_OFFSET_FILL):Kb.disable(Kb.POLYGON_OFFSET_FILL),fc=a),!a||gc===b&&hc===c||(Kb.polygonOffset(b,c),gc=b,hc=c)}function gb(a){var b,c,d=[];for(var e in a)b=a[e],b!==!1&&(c="#define "+e+" "+b,d.push(c));return d.join("\n")}function hb(a,b,c,d,f,g,h,i){var j,k,l,m,n,o=[];a?o.push(a):(o.push(b),o.push(c));for(l in g)o.push(l),o.push(g[l]);for(j in h)o.push(j),o.push(h[j]);for(n=o.join(),j=0,k=Rb.length;k>j;j++){var p=Rb[j];if(p.code===n)return p.usedTimes++,p.program}var q="SHADOWMAP_TYPE_BASIC";h.shadowMapType===e.PCFShadowMap?q="SHADOWMAP_TYPE_PCF":h.shadowMapType===e.PCFSoftShadowMap&&(q="SHADOWMAP_TYPE_PCF_SOFT");var r=gb(g);m=Kb.createProgram();var s=["precision "+Cb+" float;","precision "+Cb+" int;",r,Bc?"#define VERTEX_TEXTURES":"",Qb.gammaInput?"#define GAMMA_INPUT":"",Qb.gammaOutput?"#define GAMMA_OUTPUT":"","#define MAX_DIR_LIGHTS "+h.maxDirLights,"#define MAX_POINT_LIGHTS "+h.maxPointLights,"#define MAX_SPOT_LIGHTS "+h.maxSpotLights,"#define MAX_HEMI_LIGHTS "+h.maxHemiLights,"#define MAX_SHADOWS "+h.maxShadows,"#define MAX_BONES "+h.maxBones,h.map?"#define USE_MAP":"",h.envMap?"#define USE_ENVMAP":"",h.lightMap?"#define USE_LIGHTMAP":"",h.bumpMap?"#define USE_BUMPMAP":"",h.normalMap?"#define USE_NORMALMAP":"",h.specularMap?"#define USE_SPECULARMAP":"",h.vertexColors?"#define USE_COLOR":"",h.skinning?"#define USE_SKINNING":"",h.useVertexTexture?"#define BONE_TEXTURE":"",h.morphTargets?"#define USE_MORPHTARGETS":"",h.morphNormals?"#define USE_MORPHNORMALS":"",h.wrapAround?"#define WRAP_AROUND":"",h.doubleSided?"#define DOUBLE_SIDED":"",h.flipSided?"#define FLIP_SIDED":"",h.shadowMapEnabled?"#define USE_SHADOWMAP":"",h.shadowMapEnabled?"#define "+q:"",h.shadowMapDebug?"#define SHADOWMAP_DEBUG":"",h.shadowMapCascade?"#define SHADOWMAP_CASCADE":"",h.sizeAttenuation?"#define USE_SIZEATTENUATION":"","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;","attribute vec2 uv2;","#ifdef USE_COLOR","attribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","attribute vec3 morphTarget0;","attribute vec3 morphTarget1;","attribute vec3 morphTarget2;","attribute vec3 morphTarget3;","#ifdef USE_MORPHNORMALS","attribute vec3 morphNormal0;","attribute vec3 morphNormal1;","attribute vec3 morphNormal2;","attribute vec3 morphNormal3;","#else","attribute vec3 morphTarget4;","attribute vec3 morphTarget5;","attribute vec3 morphTarget6;","attribute vec3 morphTarget7;","#endif","#endif","#ifdef USE_SKINNING","attribute vec4 skinIndex;","attribute vec4 skinWeight;","#endif",""].join("\n"),t=["precision "+Cb+" float;","precision "+Cb+" int;",h.bumpMap||h.normalMap?"#extension GL_OES_standard_derivatives : enable":"",r,"#define MAX_DIR_LIGHTS "+h.maxDirLights,"#define MAX_POINT_LIGHTS "+h.maxPointLights,"#define MAX_SPOT_LIGHTS "+h.maxSpotLights,"#define MAX_HEMI_LIGHTS "+h.maxHemiLights,"#define MAX_SHADOWS "+h.maxShadows,h.alphaTest?"#define ALPHATEST "+h.alphaTest:"",Qb.gammaInput?"#define GAMMA_INPUT":"",Qb.gammaOutput?"#define GAMMA_OUTPUT":"",h.useFog&&h.fog?"#define USE_FOG":"",h.useFog&&h.fogExp?"#define FOG_EXP2":"",h.map?"#define USE_MAP":"",h.envMap?"#define USE_ENVMAP":"",h.lightMap?"#define USE_LIGHTMAP":"",h.bumpMap?"#define USE_BUMPMAP":"",h.normalMap?"#define USE_NORMALMAP":"",h.specularMap?"#define USE_SPECULARMAP":"",h.vertexColors?"#define USE_COLOR":"",h.metal?"#define METAL":"",h.wrapAround?"#define WRAP_AROUND":"",h.doubleSided?"#define DOUBLE_SIDED":"",h.flipSided?"#define FLIP_SIDED":"",h.shadowMapEnabled?"#define USE_SHADOWMAP":"",h.shadowMapEnabled?"#define "+q:"",h.shadowMapDebug?"#define SHADOWMAP_DEBUG":"",h.shadowMapCascade?"#define SHADOWMAP_CASCADE":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",""].join("\n"),u=lb("vertex",s+c),v=lb("fragment",t+b);Kb.attachShader(m,u),Kb.attachShader(m,v),void 0!==i&&Kb.bindAttribLocation(m,0,i),Kb.linkProgram(m),Kb.getProgramParameter(m,Kb.LINK_STATUS)===!1&&(console.error("Could not initialise shader"),console.error("gl.VALIDATE_STATUS",Kb.getProgramParameter(m,Kb.VALIDATE_STATUS)),console.error("gl.getError()",Kb.getError())),""!==Kb.getProgramInfoLog(m)&&console.error("gl.getProgramInfoLog()",Kb.getProgramInfoLog(m)),Kb.deleteShader(v),Kb.deleteShader(u),m.uniforms={},m.attributes={};var w,x,y,z;w=["viewMatrix","modelViewMatrix","projectionMatrix","normalMatrix","modelMatrix","cameraPosition","morphTargetInfluences"],h.useVertexTexture?(w.push("boneTexture"),w.push("boneTextureWidth"),w.push("boneTextureHeight")):w.push("boneGlobalMatrices");for(x in d)w.push(x);for(ib(m,w),w=["position","normal","uv","uv2","tangent","color","skinIndex","skinWeight","lineDistance"],z=0;zc;c++)e=b[c],a.uniforms[e]=Kb.getUniformLocation(a,e)}function jb(a,b){var c,d,e;for(c=0,d=b.length;d>c;c++)e=b[c],a.attributes[e]=Kb.getAttribLocation(a,e)}function kb(a){for(var b=a.split("\n"),c=0,d=b.length;d>c;c++)b[c]=c+1+": "+b[c];return b.join("\n")}function lb(a,b){var c;return"fragment"===a?c=Kb.createShader(Kb.FRAGMENT_SHADER):"vertex"===a&&(c=Kb.createShader(Kb.VERTEX_SHADER)),Kb.shaderSource(c,b),Kb.compileShader(c),Kb.getShaderParameter(c,Kb.COMPILE_STATUS)?c:(console.error(Kb.getShaderInfoLog(c)),console.error(kb(b)),null)}function mb(a,b,c){c?(Kb.texParameteri(a,Kb.TEXTURE_WRAP_S,ub(b.wrapS)),Kb.texParameteri(a,Kb.TEXTURE_WRAP_T,ub(b.wrapT)),Kb.texParameteri(a,Kb.TEXTURE_MAG_FILTER,ub(b.magFilter)),Kb.texParameteri(a,Kb.TEXTURE_MIN_FILTER,ub(b.minFilter))):(Kb.texParameteri(a,Kb.TEXTURE_WRAP_S,Kb.CLAMP_TO_EDGE),Kb.texParameteri(a,Kb.TEXTURE_WRAP_T,Kb.CLAMP_TO_EDGE),Kb.texParameteri(a,Kb.TEXTURE_MAG_FILTER,tb(b.magFilter)),Kb.texParameteri(a,Kb.TEXTURE_MIN_FILTER,tb(b.minFilter))),Ob&&b.type!==e.FloatType&&(b.anisotropy>1||b.__oldAnisotropy)&&(Kb.texParameterf(a,Ob.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(b.anisotropy,Ac)),b.__oldAnisotropy=b.anisotropy) -}function nb(a,b){if(a.width<=b&&a.height<=b)return a;var c=Math.max(a.width,a.height),d=Math.floor(a.width*b/c),e=Math.floor(a.height*b/c),f=document.createElement("canvas");f.width=d,f.height=e;var g=f.getContext("2d");return g.drawImage(a,0,0,a.width,a.height,0,0,d,e),f}function ob(a,b){if(6===a.image.length)if(a.needsUpdate){a.image.__webglTextureCube||(a.addEventListener("dispose",Kc),a.image.__webglTextureCube=Kb.createTexture(),Qb.info.memory.textures++),Kb.activeTexture(Kb.TEXTURE0+b),Kb.bindTexture(Kb.TEXTURE_CUBE_MAP,a.image.__webglTextureCube),Kb.pixelStorei(Kb.UNPACK_FLIP_Y_WEBGL,a.flipY);for(var c=a instanceof e.CompressedTexture,d=[],f=0;6>f;f++)d[f]=Qb.autoScaleCubemaps&&!c?nb(a.image[f],zc):a.image[f];var g=d[0],h=e.Math.isPowerOfTwo(g.width)&&e.Math.isPowerOfTwo(g.height),i=ub(a.format),j=ub(a.type);mb(Kb.TEXTURE_CUBE_MAP,a,h);for(var f=0;6>f;f++)if(c)for(var k,l=d[f].mipmaps,m=0,n=l.length;n>m;m++)k=l[m],a.format!==e.RGBAFormat?Kb.compressedTexImage2D(Kb.TEXTURE_CUBE_MAP_POSITIVE_X+f,m,i,k.width,k.height,0,k.data):Kb.texImage2D(Kb.TEXTURE_CUBE_MAP_POSITIVE_X+f,m,i,k.width,k.height,0,i,j,k.data);else Kb.texImage2D(Kb.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,i,i,j,d[f]);a.generateMipmaps&&h&&Kb.generateMipmap(Kb.TEXTURE_CUBE_MAP),a.needsUpdate=!1,a.onUpdate&&a.onUpdate()}else Kb.activeTexture(Kb.TEXTURE0+b),Kb.bindTexture(Kb.TEXTURE_CUBE_MAP,a.image.__webglTextureCube)}function pb(a,b){Kb.activeTexture(Kb.TEXTURE0+b),Kb.bindTexture(Kb.TEXTURE_CUBE_MAP,a.__webglTexture)}function qb(a,b,c){Kb.bindFramebuffer(Kb.FRAMEBUFFER,a),Kb.framebufferTexture2D(Kb.FRAMEBUFFER,Kb.COLOR_ATTACHMENT0,c,b.__webglTexture,0)}function rb(a,b){Kb.bindRenderbuffer(Kb.RENDERBUFFER,a),b.depthBuffer&&!b.stencilBuffer?(Kb.renderbufferStorage(Kb.RENDERBUFFER,Kb.DEPTH_COMPONENT16,b.width,b.height),Kb.framebufferRenderbuffer(Kb.FRAMEBUFFER,Kb.DEPTH_ATTACHMENT,Kb.RENDERBUFFER,a)):b.depthBuffer&&b.stencilBuffer?(Kb.renderbufferStorage(Kb.RENDERBUFFER,Kb.DEPTH_STENCIL,b.width,b.height),Kb.framebufferRenderbuffer(Kb.FRAMEBUFFER,Kb.DEPTH_STENCIL_ATTACHMENT,Kb.RENDERBUFFER,a)):Kb.renderbufferStorage(Kb.RENDERBUFFER,Kb.RGBA4,b.width,b.height)}function sb(a){a instanceof e.WebGLRenderTargetCube?(Kb.bindTexture(Kb.TEXTURE_CUBE_MAP,a.__webglTexture),Kb.generateMipmap(Kb.TEXTURE_CUBE_MAP),Kb.bindTexture(Kb.TEXTURE_CUBE_MAP,null)):(Kb.bindTexture(Kb.TEXTURE_2D,a.__webglTexture),Kb.generateMipmap(Kb.TEXTURE_2D),Kb.bindTexture(Kb.TEXTURE_2D,null))}function tb(a){return a===e.NearestFilter||a===e.NearestMipMapNearestFilter||a===e.NearestMipMapLinearFilter?Kb.NEAREST:Kb.LINEAR}function ub(a){if(a===e.RepeatWrapping)return Kb.REPEAT;if(a===e.ClampToEdgeWrapping)return Kb.CLAMP_TO_EDGE;if(a===e.MirroredRepeatWrapping)return Kb.MIRRORED_REPEAT;if(a===e.NearestFilter)return Kb.NEAREST;if(a===e.NearestMipMapNearestFilter)return Kb.NEAREST_MIPMAP_NEAREST;if(a===e.NearestMipMapLinearFilter)return Kb.NEAREST_MIPMAP_LINEAR;if(a===e.LinearFilter)return Kb.LINEAR;if(a===e.LinearMipMapNearestFilter)return Kb.LINEAR_MIPMAP_NEAREST;if(a===e.LinearMipMapLinearFilter)return Kb.LINEAR_MIPMAP_LINEAR;if(a===e.UnsignedByteType)return Kb.UNSIGNED_BYTE;if(a===e.UnsignedShort4444Type)return Kb.UNSIGNED_SHORT_4_4_4_4;if(a===e.UnsignedShort5551Type)return Kb.UNSIGNED_SHORT_5_5_5_1;if(a===e.UnsignedShort565Type)return Kb.UNSIGNED_SHORT_5_6_5;if(a===e.ByteType)return Kb.BYTE;if(a===e.ShortType)return Kb.SHORT;if(a===e.UnsignedShortType)return Kb.UNSIGNED_SHORT;if(a===e.IntType)return Kb.INT;if(a===e.UnsignedIntType)return Kb.UNSIGNED_INT;if(a===e.FloatType)return Kb.FLOAT;if(a===e.AlphaFormat)return Kb.ALPHA;if(a===e.RGBFormat)return Kb.RGB;if(a===e.RGBAFormat)return Kb.RGBA;if(a===e.LuminanceFormat)return Kb.LUMINANCE;if(a===e.LuminanceAlphaFormat)return Kb.LUMINANCE_ALPHA;if(a===e.AddEquation)return Kb.FUNC_ADD;if(a===e.SubtractEquation)return Kb.FUNC_SUBTRACT;if(a===e.ReverseSubtractEquation)return Kb.FUNC_REVERSE_SUBTRACT;if(a===e.ZeroFactor)return Kb.ZERO;if(a===e.OneFactor)return Kb.ONE;if(a===e.SrcColorFactor)return Kb.SRC_COLOR;if(a===e.OneMinusSrcColorFactor)return Kb.ONE_MINUS_SRC_COLOR;if(a===e.SrcAlphaFactor)return Kb.SRC_ALPHA;if(a===e.OneMinusSrcAlphaFactor)return Kb.ONE_MINUS_SRC_ALPHA;if(a===e.DstAlphaFactor)return Kb.DST_ALPHA;if(a===e.OneMinusDstAlphaFactor)return Kb.ONE_MINUS_DST_ALPHA;if(a===e.DstColorFactor)return Kb.DST_COLOR;if(a===e.OneMinusDstColorFactor)return Kb.ONE_MINUS_DST_COLOR;if(a===e.SrcAlphaSaturateFactor)return Kb.SRC_ALPHA_SATURATE;if(void 0!==Pb){if(a===e.RGB_S3TC_DXT1_Format)return Pb.COMPRESSED_RGB_S3TC_DXT1_EXT;if(a===e.RGBA_S3TC_DXT1_Format)return Pb.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(a===e.RGBA_S3TC_DXT3_Format)return Pb.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(a===e.RGBA_S3TC_DXT5_Format)return Pb.COMPRESSED_RGBA_S3TC_DXT5_EXT}return 0}function vb(a){if(Cc&&a&&a.useVertexTexture)return 1024;var b=Kb.getParameter(Kb.MAX_VERTEX_UNIFORM_VECTORS),c=Math.floor((b-20)/4),d=c;return void 0!==a&&a instanceof e.SkinnedMesh&&(d=Math.min(a.bones.length,d),dg;g++){var i=a[g];i.onlyShadow||i.visible===!1||(i instanceof e.DirectionalLight&&b++,i instanceof e.PointLight&&c++,i instanceof e.SpotLight&&d++,i instanceof e.HemisphereLight&&f++)}return{directional:b,point:c,spot:d,hemi:f}}function xb(a){for(var b=0,c=0,d=a.length;d>c;c++){var f=a[c];f.castShadow&&(f instanceof e.SpotLight&&b++,f instanceof e.DirectionalLight&&!f.shadowCascade&&b++)}return b}function yb(){try{var a={alpha:Db,premultipliedAlpha:Eb,antialias:Fb,stencil:Gb,preserveDrawingBuffer:Hb};if(Kb=Bb||Ab.getContext("webgl",a)||Ab.getContext("experimental-webgl",a),null===Kb)throw"Error creating WebGL context."}catch(b){console.error(b)}Lb=Kb.getExtension("OES_texture_float"),Mb=Kb.getExtension("OES_texture_float_linear"),Nb=Kb.getExtension("OES_standard_derivatives"),Ob=Kb.getExtension("EXT_texture_filter_anisotropic")||Kb.getExtension("MOZ_EXT_texture_filter_anisotropic")||Kb.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),Pb=Kb.getExtension("WEBGL_compressed_texture_s3tc")||Kb.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||Kb.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),Lb||console.log("THREE.WebGLRenderer: Float textures not supported."),Nb||console.log("THREE.WebGLRenderer: Standard derivatives not supported."),Ob||console.log("THREE.WebGLRenderer: Anisotropic texture filtering not supported."),Pb||console.log("THREE.WebGLRenderer: S3TC compressed textures not supported."),void 0===Kb.getShaderPrecisionFormat&&(Kb.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}function zb(){Kb.clearColor(0,0,0,1),Kb.clearDepth(1),Kb.clearStencil(0),Kb.enable(Kb.DEPTH_TEST),Kb.depthFunc(Kb.LEQUAL),Kb.frontFace(Kb.CCW),Kb.cullFace(Kb.BACK),Kb.enable(Kb.CULL_FACE),Kb.enable(Kb.BLEND),Kb.blendEquation(Kb.FUNC_ADD),Kb.blendFunc(Kb.SRC_ALPHA,Kb.ONE_MINUS_SRC_ALPHA),Kb.viewport(jc,kc,lc,mc),Kb.clearColor(Ib.r,Ib.g,Ib.b,Jb)}console.log("THREE.WebGLRenderer",e.REVISION),a=a||{};var Ab=void 0!==a.canvas?a.canvas:document.createElement("canvas"),Bb=void 0!==a.context?a.context:null,Cb=void 0!==a.precision?a.precision:"highp",Db=void 0!==a.alpha?a.alpha:!1,Eb=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,Fb=void 0!==a.antialias?a.antialias:!1,Gb=void 0!==a.stencil?a.stencil:!0,Hb=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,Ib=new e.Color(0),Jb=0;this.domElement=Ab,this.context=null,this.devicePixelRatio=void 0!==a.devicePixelRatio?a.devicePixelRatio:void 0!==d.devicePixelRatio?d.devicePixelRatio:1,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.autoUpdateObjects=!0,this.gammaInput=!1,this.gammaOutput=!1,this.shadowMapEnabled=!1,this.shadowMapAutoUpdate=!0,this.shadowMapType=e.PCFShadowMap,this.shadowMapCullFace=e.CullFaceFront,this.shadowMapDebug=!1,this.shadowMapCascade=!1,this.maxMorphTargets=8,this.maxMorphNormals=4,this.autoScaleCubemaps=!0,this.renderPluginsPre=[],this.renderPluginsPost=[],this.info={memory:{programs:0,geometries:0,textures:0},render:{calls:0,vertices:0,faces:0,points:0}};var Kb,Lb,Mb,Nb,Ob,Pb,Qb=this,Rb=[],Sb=0,Tb=null,Ub=null,Vb=-1,Wb=null,Xb=null,Yb=0,Zb=-1,$b=-1,_b=-1,ac=-1,bc=-1,cc=-1,dc=-1,ec=-1,fc=null,gc=null,hc=null,ic=null,jc=0,kc=0,lc=Ab.width,mc=Ab.height,nc=0,oc=0,pc=new Uint8Array(16),qc=new e.Frustum,rc=new e.Matrix4,sc=new e.Matrix4,tc=new e.Vector3,uc=new e.Vector3,vc=!0,wc={ambient:[0,0,0],directional:{length:0,colors:new Array,positions:new Array},point:{length:0,colors:new Array,positions:new Array,distances:new Array},spot:{length:0,colors:new Array,positions:new Array,distances:new Array,directions:new Array,anglesCos:new Array,exponents:new Array},hemi:{length:0,skyColors:new Array,groundColors:new Array,positions:new Array}};yb(),zb(),this.context=Kb;var xc=Kb.getParameter(Kb.MAX_TEXTURE_IMAGE_UNITS),yc=Kb.getParameter(Kb.MAX_VERTEX_TEXTURE_IMAGE_UNITS),zc=(Kb.getParameter(Kb.MAX_TEXTURE_SIZE),Kb.getParameter(Kb.MAX_CUBE_MAP_TEXTURE_SIZE)),Ac=Ob?Kb.getParameter(Ob.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,Bc=yc>0,Cc=Bc&&Lb,Dc=(Pb?Kb.getParameter(Kb.COMPRESSED_TEXTURE_FORMATS):[],Kb.getShaderPrecisionFormat(Kb.VERTEX_SHADER,Kb.HIGH_FLOAT)),Ec=Kb.getShaderPrecisionFormat(Kb.VERTEX_SHADER,Kb.MEDIUM_FLOAT),Fc=(Kb.getShaderPrecisionFormat(Kb.VERTEX_SHADER,Kb.LOW_FLOAT),Kb.getShaderPrecisionFormat(Kb.FRAGMENT_SHADER,Kb.HIGH_FLOAT)),Gc=Kb.getShaderPrecisionFormat(Kb.FRAGMENT_SHADER,Kb.MEDIUM_FLOAT),Hc=(Kb.getShaderPrecisionFormat(Kb.FRAGMENT_SHADER,Kb.LOW_FLOAT),Kb.getShaderPrecisionFormat(Kb.VERTEX_SHADER,Kb.HIGH_INT),Kb.getShaderPrecisionFormat(Kb.VERTEX_SHADER,Kb.MEDIUM_INT),Kb.getShaderPrecisionFormat(Kb.VERTEX_SHADER,Kb.LOW_INT),Kb.getShaderPrecisionFormat(Kb.FRAGMENT_SHADER,Kb.HIGH_INT),Kb.getShaderPrecisionFormat(Kb.FRAGMENT_SHADER,Kb.MEDIUM_INT),Kb.getShaderPrecisionFormat(Kb.FRAGMENT_SHADER,Kb.LOW_INT),Dc.precision>0&&Fc.precision>0),Ic=Ec.precision>0&&Gc.precision>0;"highp"!==Cb||Hc||(Ic?(Cb="mediump",console.warn("WebGLRenderer: highp not supported, using mediump")):(Cb="lowp",console.warn("WebGLRenderer: highp and mediump not supported, using lowp"))),"mediump"!==Cb||Ic||(Cb="lowp",console.warn("WebGLRenderer: mediump not supported, using lowp")),this.getContext=function(){return Kb},this.supportsVertexTextures=function(){return Bc},this.supportsFloatTextures=function(){return Lb},this.supportsStandardDerivatives=function(){return Nb},this.supportsCompressedTextureS3TC=function(){return Pb},this.getMaxAnisotropy=function(){return Ac},this.getPrecision=function(){return Cb},this.setSize=function(a,b,c){Ab.width=a*this.devicePixelRatio,Ab.height=b*this.devicePixelRatio,1!==this.devicePixelRatio&&c!==!1&&(Ab.style.width=a+"px",Ab.style.height=b+"px"),this.setViewport(0,0,a,b)},this.setViewport=function(a,b,c,d){jc=a*this.devicePixelRatio,kc=b*this.devicePixelRatio,lc=c*this.devicePixelRatio,mc=d*this.devicePixelRatio,Kb.viewport(jc,kc,lc,mc)},this.setScissor=function(a,b,c,d){Kb.scissor(a*this.devicePixelRatio,b*this.devicePixelRatio,c*this.devicePixelRatio,d*this.devicePixelRatio)},this.enableScissorTest=function(a){a?Kb.enable(Kb.SCISSOR_TEST):Kb.disable(Kb.SCISSOR_TEST)},this.setClearColor=function(a,b){Ib.set(a),Jb=void 0!==b?b:1,Kb.clearColor(Ib.r,Ib.g,Ib.b,Jb)},this.setClearColorHex=function(a,b){console.warn("DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead."),this.setClearColor(a,b)},this.getClearColor=function(){return Ib},this.getClearAlpha=function(){return Jb},this.clear=function(a,b,c){var d=0;(void 0===a||a)&&(d|=Kb.COLOR_BUFFER_BIT),(void 0===b||b)&&(d|=Kb.DEPTH_BUFFER_BIT),(void 0===c||c)&&(d|=Kb.STENCIL_BUFFER_BIT),Kb.clear(d)},this.clearColor=function(){Kb.clear(Kb.COLOR_BUFFER_BIT)},this.clearDepth=function(){Kb.clear(Kb.DEPTH_BUFFER_BIT)},this.clearStencil=function(){Kb.clear(Kb.STENCIL_BUFFER_BIT)},this.clearTarget=function(a,b,c,d){this.setRenderTarget(a),this.clear(b,c,d)},this.addPostPlugin=function(a){a.init(this),this.renderPluginsPost.push(a)},this.addPrePlugin=function(a){a.init(this),this.renderPluginsPre.push(a)},this.updateShadowMap=function(a,b){Tb=null,_b=-1,dc=-1,ec=-1,Wb=-1,Vb=-1,vc=!0,Zb=-1,$b=-1,this.shadowMapPlugin.update(a,b)};var Jc=function(a){var b=a.target;b.removeEventListener("dispose",Jc),Oc(b)},Kc=function(a){var b=a.target;b.removeEventListener("dispose",Kc),Pc(b),Qb.info.memory.textures--},Lc=function(a){var b=a.target;b.removeEventListener("dispose",Lc),Qc(b),Qb.info.memory.textures--},Mc=function(a){var b=a.target;b.removeEventListener("dispose",Mc),Rc(b)},Nc=function(a){if(void 0!==a.__webglVertexBuffer&&Kb.deleteBuffer(a.__webglVertexBuffer),void 0!==a.__webglNormalBuffer&&Kb.deleteBuffer(a.__webglNormalBuffer),void 0!==a.__webglTangentBuffer&&Kb.deleteBuffer(a.__webglTangentBuffer),void 0!==a.__webglColorBuffer&&Kb.deleteBuffer(a.__webglColorBuffer),void 0!==a.__webglUVBuffer&&Kb.deleteBuffer(a.__webglUVBuffer),void 0!==a.__webglUV2Buffer&&Kb.deleteBuffer(a.__webglUV2Buffer),void 0!==a.__webglSkinIndicesBuffer&&Kb.deleteBuffer(a.__webglSkinIndicesBuffer),void 0!==a.__webglSkinWeightsBuffer&&Kb.deleteBuffer(a.__webglSkinWeightsBuffer),void 0!==a.__webglFaceBuffer&&Kb.deleteBuffer(a.__webglFaceBuffer),void 0!==a.__webglLineBuffer&&Kb.deleteBuffer(a.__webglLineBuffer),void 0!==a.__webglLineDistanceBuffer&&Kb.deleteBuffer(a.__webglLineDistanceBuffer),void 0!==a.__webglCustomAttributesList)for(var b in a.__webglCustomAttributesList)Kb.deleteBuffer(a.__webglCustomAttributesList[b].buffer);Qb.info.memory.geometries--},Oc=function(a){if(a.__webglInit=void 0,a instanceof e.BufferGeometry){var b=a.attributes;for(var c in b)void 0!==b[c].buffer&&Kb.deleteBuffer(b[c].buffer);Qb.info.memory.geometries--}else if(void 0!==a.geometryGroups)for(var d in a.geometryGroups){var f=a.geometryGroups[d];if(void 0!==f.numMorphTargets)for(var g=0,h=f.numMorphTargets;h>g;g++)Kb.deleteBuffer(f.__webglMorphTargetsBuffers[g]);if(void 0!==f.numMorphNormals)for(var g=0,h=f.numMorphNormals;h>g;g++)Kb.deleteBuffer(f.__webglMorphNormalsBuffers[g]);Nc(f)}else Nc(a)},Pc=function(a){if(a.image&&a.image.__webglTextureCube)Kb.deleteTexture(a.image.__webglTextureCube);else{if(!a.__webglInit)return;a.__webglInit=!1,Kb.deleteTexture(a.__webglTexture)}},Qc=function(a){if(a&&a.__webglTexture)if(Kb.deleteTexture(a.__webglTexture),a instanceof e.WebGLRenderTargetCube)for(var b=0;6>b;b++)Kb.deleteFramebuffer(a.__webglFramebuffer[b]),Kb.deleteRenderbuffer(a.__webglRenderbuffer[b]);else Kb.deleteFramebuffer(a.__webglFramebuffer),Kb.deleteRenderbuffer(a.__webglRenderbuffer)},Rc=function(a){var b=a.program;if(void 0!==b){a.program=void 0;var c,d,e,f=!1;for(c=0,d=Rb.length;d>c;c++)if(e=Rb[c],e.program===b){e.usedTimes--,0===e.usedTimes&&(f=!0);break}if(f===!0){var g=[];for(c=0,d=Rb.length;d>c;c++)e=Rb[c],e.program!==b&&g.push(e);Rb=g,Kb.deleteProgram(b),Qb.info.memory.programs--}}};this.renderBufferImmediate=function(a,b,c){if(a.hasPositions&&!a.__webglVertexBuffer&&(a.__webglVertexBuffer=Kb.createBuffer()),a.hasNormals&&!a.__webglNormalBuffer&&(a.__webglNormalBuffer=Kb.createBuffer()),a.hasUvs&&!a.__webglUvBuffer&&(a.__webglUvBuffer=Kb.createBuffer()),a.hasColors&&!a.__webglColorBuffer&&(a.__webglColorBuffer=Kb.createBuffer()),a.hasPositions&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglVertexBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,a.positionArray,Kb.DYNAMIC_DRAW),Kb.enableVertexAttribArray(b.attributes.position),Kb.vertexAttribPointer(b.attributes.position,3,Kb.FLOAT,!1,0,0)),a.hasNormals){if(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglNormalBuffer),c.shading===e.FlatShading){var d,f,g,h,i,j,k,l,m,n,o,p,q,r,s=3*a.count;for(r=0;s>r;r+=9)q=a.normalArray,h=q[r],k=q[r+1],n=q[r+2],i=q[r+3],l=q[r+4],o=q[r+5],j=q[r+6],m=q[r+7],p=q[r+8],d=(h+i+j)/3,f=(k+l+m)/3,g=(n+o+p)/3,q[r]=d,q[r+1]=f,q[r+2]=g,q[r+3]=d,q[r+4]=f,q[r+5]=g,q[r+6]=d,q[r+7]=f,q[r+8]=g}Kb.bufferData(Kb.ARRAY_BUFFER,a.normalArray,Kb.DYNAMIC_DRAW),Kb.enableVertexAttribArray(b.attributes.normal),Kb.vertexAttribPointer(b.attributes.normal,3,Kb.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglUvBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,a.uvArray,Kb.DYNAMIC_DRAW),Kb.enableVertexAttribArray(b.attributes.uv),Kb.vertexAttribPointer(b.attributes.uv,2,Kb.FLOAT,!1,0,0)),a.hasColors&&c.vertexColors!==e.NoColors&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,a.__webglColorBuffer),Kb.bufferData(Kb.ARRAY_BUFFER,a.colorArray,Kb.DYNAMIC_DRAW),Kb.enableVertexAttribArray(b.attributes.color),Kb.vertexAttribPointer(b.attributes.color,3,Kb.FLOAT,!1,0,0)),Kb.drawArrays(Kb.TRIANGLES,0,a.count),a.count=0},this.renderBufferDirect=function(a,b,c,d,f,g){if(d.visible!==!1){var h,i,j,k,l=P(a,b,c,d,g),m=l.attributes,n=f.attributes,o=!1,p=d.wireframe?1:0,q=16777215*f.id+2*l.id+p;if(q!==Wb&&(Wb=q,o=!0),o&&w(),g instanceof e.Mesh){var r=n.index;if(r){var s=f.offsets;s.length>1&&(o=!0);for(var u=0,x=s.length;x>u;u++){var y=s[u].index;if(o){for(i in m)j=m[i],h=n[i],j>=0&&(h?(k=h.itemSize,Kb.bindBuffer(Kb.ARRAY_BUFFER,h.buffer),v(j),Kb.vertexAttribPointer(j,k,Kb.FLOAT,!1,0,y*k*4)):d.defaultAttributeValues&&(2===d.defaultAttributeValues[i].length?Kb.vertexAttrib2fv(j,d.defaultAttributeValues[i]):3===d.defaultAttributeValues[i].length&&Kb.vertexAttrib3fv(j,d.defaultAttributeValues[i])));Kb.bindBuffer(Kb.ELEMENT_ARRAY_BUFFER,r.buffer)}Kb.drawElements(Kb.TRIANGLES,s[u].count,Kb.UNSIGNED_SHORT,2*s[u].start),Qb.info.render.calls++,Qb.info.render.vertices+=s[u].count,Qb.info.render.faces+=s[u].count/3}}else{if(o)for(i in m)"index"!==i&&(j=m[i],h=n[i],j>=0&&(h?(k=h.itemSize,Kb.bindBuffer(Kb.ARRAY_BUFFER,h.buffer),v(j),Kb.vertexAttribPointer(j,k,Kb.FLOAT,!1,0,0)):d.defaultAttributeValues&&d.defaultAttributeValues[i]&&(2===d.defaultAttributeValues[i].length?Kb.vertexAttrib2fv(j,d.defaultAttributeValues[i]):3===d.defaultAttributeValues[i].length&&Kb.vertexAttrib3fv(j,d.defaultAttributeValues[i]))));var z=f.attributes.position;Kb.drawArrays(Kb.TRIANGLES,0,z.array.length/3),Qb.info.render.calls++,Qb.info.render.vertices+=z.array.length/3,Qb.info.render.faces+=z.array.length/3/3}}else if(g instanceof e.ParticleSystem){if(o)for(i in m)j=m[i],h=n[i],j>=0&&(h?(k=h.itemSize,Kb.bindBuffer(Kb.ARRAY_BUFFER,h.buffer),v(j),Kb.vertexAttribPointer(j,k,Kb.FLOAT,!1,0,0)):d.defaultAttributeValues&&d.defaultAttributeValues[i]&&(2===d.defaultAttributeValues[i].length?Kb.vertexAttrib2fv(j,d.defaultAttributeValues[i]):3===d.defaultAttributeValues[i].length&&Kb.vertexAttrib3fv(j,d.defaultAttributeValues[i])));var z=n.position;Kb.drawArrays(Kb.POINTS,0,z.array.length/3),Qb.info.render.calls++,Qb.info.render.points+=z.array.length/3}else if(g instanceof e.Line){var A=g.type===e.LineStrip?Kb.LINE_STRIP:Kb.LINES;eb(d.linewidth);var r=n.index;if(r){var s=f.offsets;s.length>1&&(o=!0);for(var u=0,x=s.length;x>u;u++){var y=s[u].index;o&&(t(d,m,n,y),Kb.bindBuffer(Kb.ELEMENT_ARRAY_BUFFER,r.buffer)),Kb.drawElements(Kb.LINES,s[u].count,Kb.UNSIGNED_SHORT,2*s[u].start),Qb.info.render.calls++,Qb.info.render.vertices+=s[u].count}}else{o&&t(d,m,n,0);var z=n.position;Kb.drawArrays(A,0,z.array.length/3),Qb.info.render.calls++,Qb.info.render.points+=z.array.length}}}},this.renderBuffer=function(a,b,c,d,f,g){if(d.visible!==!1){var h,i,j,k=P(a,b,c,d,g),l=k.attributes,m=!1,n=d.wireframe?1:0,o=16777215*f.id+2*k.id+n;if(o!==Wb&&(Wb=o,m=!0),m&&w(),!d.morphTargets&&l.position>=0?m&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglVertexBuffer),v(l.position),Kb.vertexAttribPointer(l.position,3,Kb.FLOAT,!1,0,0)):g.morphTargetBase&&x(d,f,g),m){if(f.__webglCustomAttributesList)for(i=0,j=f.__webglCustomAttributesList.length;j>i;i++)h=f.__webglCustomAttributesList[i],l[h.buffer.belongsToAttribute]>=0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,h.buffer),v(l[h.buffer.belongsToAttribute]),Kb.vertexAttribPointer(l[h.buffer.belongsToAttribute],h.size,Kb.FLOAT,!1,0,0));l.color>=0&&(g.geometry.colors.length>0||g.geometry.faces.length>0?(Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglColorBuffer),v(l.color),Kb.vertexAttribPointer(l.color,3,Kb.FLOAT,!1,0,0)):d.defaultAttributeValues&&Kb.vertexAttrib3fv(l.color,d.defaultAttributeValues.color)),l.normal>=0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglNormalBuffer),v(l.normal),Kb.vertexAttribPointer(l.normal,3,Kb.FLOAT,!1,0,0)),l.tangent>=0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglTangentBuffer),v(l.tangent),Kb.vertexAttribPointer(l.tangent,4,Kb.FLOAT,!1,0,0)),l.uv>=0&&(g.geometry.faceVertexUvs[0]?(Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglUVBuffer),v(l.uv),Kb.vertexAttribPointer(l.uv,2,Kb.FLOAT,!1,0,0)):d.defaultAttributeValues&&Kb.vertexAttrib2fv(l.uv,d.defaultAttributeValues.uv)),l.uv2>=0&&(g.geometry.faceVertexUvs[1]?(Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglUV2Buffer),v(l.uv2),Kb.vertexAttribPointer(l.uv2,2,Kb.FLOAT,!1,0,0)):d.defaultAttributeValues&&Kb.vertexAttrib2fv(l.uv2,d.defaultAttributeValues.uv2)),d.skinning&&l.skinIndex>=0&&l.skinWeight>=0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglSkinIndicesBuffer),v(l.skinIndex),Kb.vertexAttribPointer(l.skinIndex,4,Kb.FLOAT,!1,0,0),Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglSkinWeightsBuffer),v(l.skinWeight),Kb.vertexAttribPointer(l.skinWeight,4,Kb.FLOAT,!1,0,0)),l.lineDistance>=0&&(Kb.bindBuffer(Kb.ARRAY_BUFFER,f.__webglLineDistanceBuffer),v(l.lineDistance),Kb.vertexAttribPointer(l.lineDistance,1,Kb.FLOAT,!1,0,0))}if(g instanceof e.Mesh)d.wireframe?(eb(d.wireframeLinewidth),m&&Kb.bindBuffer(Kb.ELEMENT_ARRAY_BUFFER,f.__webglLineBuffer),Kb.drawElements(Kb.LINES,f.__webglLineCount,Kb.UNSIGNED_SHORT,0)):(m&&Kb.bindBuffer(Kb.ELEMENT_ARRAY_BUFFER,f.__webglFaceBuffer),Kb.drawElements(Kb.TRIANGLES,f.__webglFaceCount,Kb.UNSIGNED_SHORT,0)),Qb.info.render.calls++,Qb.info.render.vertices+=f.__webglFaceCount,Qb.info.render.faces+=f.__webglFaceCount/3;else if(g instanceof e.Line){var p=g.type===e.LineStrip?Kb.LINE_STRIP:Kb.LINES;eb(d.linewidth),Kb.drawArrays(p,0,f.__webglLineCount),Qb.info.render.calls++}else g instanceof e.ParticleSystem&&(Kb.drawArrays(Kb.POINTS,0,f.__webglParticleCount),Qb.info.render.calls++,Qb.info.render.points+=f.__webglParticleCount)}},this.render=function(a,b,c,d){if(b instanceof e.Camera==!1)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var f,g,h,i,j,k=a.__lights,l=a.fog;for(Vb=-1,vc=!0,a.autoUpdate===!0&&a.updateMatrixWorld(),void 0===b.parent&&b.updateMatrixWorld(),b.matrixWorldInverse.getInverse(b.matrixWorld),rc.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse),qc.setFromMatrix(rc),this.autoUpdateObjects&&this.initWebGLObjects(a),A(this.renderPluginsPre,a,b),Qb.info.render.calls=0,Qb.info.render.vertices=0,Qb.info.render.faces=0,Qb.info.render.points=0,this.setRenderTarget(c),(this.autoClear||d)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),j=a.__webglObjects,f=0,g=j.length;g>f;f++)h=j[f],i=h.object,h.id=f,h.render=!1,i.visible&&((i instanceof e.Mesh||i instanceof e.ParticleSystem)&&i.frustumCulled&&!qc.intersectsObject(i)||(ab(i,b),E(h),h.render=!0,this.sortObjects===!0&&(null!==i.renderDepth?h.z=i.renderDepth:(tc.setFromMatrixPosition(i.matrixWorld),tc.applyProjection(rc),h.z=tc.z))));for(this.sortObjects&&j.sort(y),j=a.__webglObjectsImmediate,f=0,g=j.length;g>f;f++)h=j[f],i=h.object,i.visible&&(ab(i,b),D(h));if(a.overrideMaterial){var m=a.overrideMaterial;this.setBlending(m.blending,m.blendEquation,m.blendSrc,m.blendDst),this.setDepthTest(m.depthTest),this.setDepthWrite(m.depthWrite),fb(m.polygonOffset,m.polygonOffsetFactor,m.polygonOffsetUnits),B(a.__webglObjects,!1,"",b,k,l,!0,m),C(a.__webglObjectsImmediate,"",b,k,l,!1,m)}else{var m=null;this.setBlending(e.NoBlending),B(a.__webglObjects,!0,"opaque",b,k,l,!1,m),C(a.__webglObjectsImmediate,"opaque",b,k,l,!1,m),B(a.__webglObjects,!1,"transparent",b,k,l,!0,m),C(a.__webglObjectsImmediate,"transparent",b,k,l,!0,m)}A(this.renderPluginsPost,a,b),c&&c.generateMipmaps&&c.minFilter!==e.NearestFilter&&c.minFilter!==e.LinearFilter&&sb(c),this.setDepthTest(!0),this.setDepthWrite(!0)},this.renderImmediateObject=function(a,b,c,d,e){var f=P(a,b,c,d,e);Wb=-1,Qb.setMaterialFaces(d),e.immediateRenderCallback?e.immediateRenderCallback(f,Kb,qc):e.render(function(a){Qb.renderBufferImmediate(a,f,d)})},this.initWebGLObjects=function(a){for(a.__webglObjects||(a.__webglObjects=[],a.__webglObjectsImmediate=[],a.__webglSprites=[],a.__webglFlares=[]);a.__objectsAdded.length;)F(a.__objectsAdded[0],a),a.__objectsAdded.splice(0,1);for(;a.__objectsRemoved.length;)L(a.__objectsRemoved[0],a),a.__objectsRemoved.splice(0,1);for(var b=0,c=a.__webglObjects.length;c>b;b++){var d=a.__webglObjects[b].object;void 0===d.__webglInit&&(void 0!==d.__webglActive&&L(d,a),F(d,a)),I(d)}},this.initMaterial=function(a,b,c,d){a.addEventListener("dispose",Mc);var f,g,h,i,j,k,l;a instanceof e.MeshDepthMaterial?l="depth":a instanceof e.MeshNormalMaterial?l="normal":a instanceof e.MeshBasicMaterial?l="basic":a instanceof e.MeshLambertMaterial?l="lambert":a instanceof e.MeshPhongMaterial?l="phong":a instanceof e.LineBasicMaterial?l="basic":a instanceof e.LineDashedMaterial?l="dashed":a instanceof e.ParticleSystemMaterial&&(l="particle_basic"),l&&O(a,e.ShaderLib[l]),i=wb(b),k=xb(b),j=vb(d),h={map:!!a.map,envMap:!!a.envMap,lightMap:!!a.lightMap,bumpMap:!!a.bumpMap,normalMap:!!a.normalMap,specularMap:!!a.specularMap,vertexColors:a.vertexColors,fog:c,useFog:a.fog,fogExp:c instanceof e.FogExp2,sizeAttenuation:a.sizeAttenuation,skinning:a.skinning,maxBones:j,useVertexTexture:Cc&&d&&d.useVertexTexture,morphTargets:a.morphTargets,morphNormals:a.morphNormals,maxMorphTargets:this.maxMorphTargets,maxMorphNormals:this.maxMorphNormals,maxDirLights:i.directional,maxPointLights:i.point,maxSpotLights:i.spot,maxHemiLights:i.hemi,maxShadows:k,shadowMapEnabled:this.shadowMapEnabled&&d.receiveShadow&&k>0,shadowMapType:this.shadowMapType,shadowMapDebug:this.shadowMapDebug,shadowMapCascade:this.shadowMapCascade,alphaTest:a.alphaTest,metal:a.metal,wrapAround:a.wrapAround,doubleSided:a.side===e.DoubleSide,flipSided:a.side===e.BackSide},a.program=hb(l,a.fragmentShader,a.vertexShader,a.uniforms,a.attributes,a.defines,h,a.index0AttributeName);var m=a.program.attributes;if(a.morphTargets){a.numSupportedMorphTargets=0;var n,o="morphTarget";for(g=0;g=0&&a.numSupportedMorphTargets++}if(a.morphNormals){a.numSupportedMorphNormals=0;var n,o="morphNormal";for(g=0;g=0&&a.numSupportedMorphNormals++}a.uniformsList=[];for(f in a.uniforms)a.uniformsList.push([a.uniforms[f],f])},this.setFaceCulling=function(a,b){a===e.CullFaceNone?Kb.disable(Kb.CULL_FACE):(Kb.frontFace(b===e.FrontFaceDirectionCW?Kb.CW:Kb.CCW),Kb.cullFace(a===e.CullFaceBack?Kb.BACK:a===e.CullFaceFront?Kb.FRONT:Kb.FRONT_AND_BACK),Kb.enable(Kb.CULL_FACE))},this.setMaterialFaces=function(a){var b=a.side===e.DoubleSide,c=a.side===e.BackSide;Zb!==b&&(b?Kb.disable(Kb.CULL_FACE):Kb.enable(Kb.CULL_FACE),Zb=b),$b!==c&&(Kb.frontFace(c?Kb.CW:Kb.CCW),$b=c)},this.setDepthTest=function(a){dc!==a&&(a?Kb.enable(Kb.DEPTH_TEST):Kb.disable(Kb.DEPTH_TEST),dc=a)},this.setDepthWrite=function(a){ec!==a&&(Kb.depthMask(a),ec=a)},this.setBlending=function(a,b,c,d){a!==_b&&(a===e.NoBlending?Kb.disable(Kb.BLEND):a===e.AdditiveBlending?(Kb.enable(Kb.BLEND),Kb.blendEquation(Kb.FUNC_ADD),Kb.blendFunc(Kb.SRC_ALPHA,Kb.ONE)):a===e.SubtractiveBlending?(Kb.enable(Kb.BLEND),Kb.blendEquation(Kb.FUNC_ADD),Kb.blendFunc(Kb.ZERO,Kb.ONE_MINUS_SRC_COLOR)):a===e.MultiplyBlending?(Kb.enable(Kb.BLEND),Kb.blendEquation(Kb.FUNC_ADD),Kb.blendFunc(Kb.ZERO,Kb.SRC_COLOR)):a===e.CustomBlending?Kb.enable(Kb.BLEND):(Kb.enable(Kb.BLEND),Kb.blendEquationSeparate(Kb.FUNC_ADD,Kb.FUNC_ADD),Kb.blendFuncSeparate(Kb.SRC_ALPHA,Kb.ONE_MINUS_SRC_ALPHA,Kb.ONE,Kb.ONE_MINUS_SRC_ALPHA)),_b=a),a===e.CustomBlending?(b!==ac&&(Kb.blendEquation(ub(b)),ac=b),(c!==bc||d!==cc)&&(Kb.blendFunc(ub(c),ub(d)),bc=c,cc=d)):(ac=null,bc=null,cc=null)},this.setTexture=function(a,b){if(a.needsUpdate){a.__webglInit||(a.__webglInit=!0,a.addEventListener("dispose",Kc),a.__webglTexture=Kb.createTexture(),Qb.info.memory.textures++),Kb.activeTexture(Kb.TEXTURE0+b),Kb.bindTexture(Kb.TEXTURE_2D,a.__webglTexture),Kb.pixelStorei(Kb.UNPACK_FLIP_Y_WEBGL,a.flipY),Kb.pixelStorei(Kb.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),Kb.pixelStorei(Kb.UNPACK_ALIGNMENT,a.unpackAlignment);var c=a.image,d=e.Math.isPowerOfTwo(c.width)&&e.Math.isPowerOfTwo(c.height),f=ub(a.format),g=ub(a.type);mb(Kb.TEXTURE_2D,a,d);var h,i=a.mipmaps;if(a instanceof e.DataTexture)if(i.length>0&&d){for(var j=0,k=i.length;k>j;j++)h=i[j],Kb.texImage2D(Kb.TEXTURE_2D,j,f,h.width,h.height,0,f,g,h.data);a.generateMipmaps=!1}else Kb.texImage2D(Kb.TEXTURE_2D,0,f,c.width,c.height,0,f,g,c.data);else if(a instanceof e.CompressedTexture)for(var j=0,k=i.length;k>j;j++)h=i[j],a.format!==e.RGBAFormat?Kb.compressedTexImage2D(Kb.TEXTURE_2D,j,f,h.width,h.height,0,h.data):Kb.texImage2D(Kb.TEXTURE_2D,j,f,h.width,h.height,0,f,g,h.data);else if(i.length>0&&d){for(var j=0,k=i.length;k>j;j++)h=i[j],Kb.texImage2D(Kb.TEXTURE_2D,j,f,f,g,h);a.generateMipmaps=!1}else Kb.texImage2D(Kb.TEXTURE_2D,0,f,f,g,a.image);a.generateMipmaps&&d&&Kb.generateMipmap(Kb.TEXTURE_2D),a.needsUpdate=!1,a.onUpdate&&a.onUpdate()}else Kb.activeTexture(Kb.TEXTURE0+b),Kb.bindTexture(Kb.TEXTURE_2D,a.__webglTexture)},this.setRenderTarget=function(a){var b=a instanceof e.WebGLRenderTargetCube;if(a&&!a.__webglFramebuffer){void 0===a.depthBuffer&&(a.depthBuffer=!0),void 0===a.stencilBuffer&&(a.stencilBuffer=!0),a.addEventListener("dispose",Lc),a.__webglTexture=Kb.createTexture(),Qb.info.memory.textures++;var c=e.Math.isPowerOfTwo(a.width)&&e.Math.isPowerOfTwo(a.height),d=ub(a.format),f=ub(a.type);if(b){a.__webglFramebuffer=[],a.__webglRenderbuffer=[],Kb.bindTexture(Kb.TEXTURE_CUBE_MAP,a.__webglTexture),mb(Kb.TEXTURE_CUBE_MAP,a,c);for(var g=0;6>g;g++)a.__webglFramebuffer[g]=Kb.createFramebuffer(),a.__webglRenderbuffer[g]=Kb.createRenderbuffer(),Kb.texImage2D(Kb.TEXTURE_CUBE_MAP_POSITIVE_X+g,0,d,a.width,a.height,0,d,f,null),qb(a.__webglFramebuffer[g],a,Kb.TEXTURE_CUBE_MAP_POSITIVE_X+g),rb(a.__webglRenderbuffer[g],a);c&&Kb.generateMipmap(Kb.TEXTURE_CUBE_MAP)}else a.__webglFramebuffer=Kb.createFramebuffer(),a.__webglRenderbuffer=a.shareDepthFrom?a.shareDepthFrom.__webglRenderbuffer:Kb.createRenderbuffer(),Kb.bindTexture(Kb.TEXTURE_2D,a.__webglTexture),mb(Kb.TEXTURE_2D,a,c),Kb.texImage2D(Kb.TEXTURE_2D,0,d,a.width,a.height,0,d,f,null),qb(a.__webglFramebuffer,a,Kb.TEXTURE_2D),a.shareDepthFrom?a.depthBuffer&&!a.stencilBuffer?Kb.framebufferRenderbuffer(Kb.FRAMEBUFFER,Kb.DEPTH_ATTACHMENT,Kb.RENDERBUFFER,a.__webglRenderbuffer):a.depthBuffer&&a.stencilBuffer&&Kb.framebufferRenderbuffer(Kb.FRAMEBUFFER,Kb.DEPTH_STENCIL_ATTACHMENT,Kb.RENDERBUFFER,a.__webglRenderbuffer):rb(a.__webglRenderbuffer,a),c&&Kb.generateMipmap(Kb.TEXTURE_2D);b?Kb.bindTexture(Kb.TEXTURE_CUBE_MAP,null):Kb.bindTexture(Kb.TEXTURE_2D,null),Kb.bindRenderbuffer(Kb.RENDERBUFFER,null),Kb.bindFramebuffer(Kb.FRAMEBUFFER,null)}var h,i,j,k,l;a?(h=b?a.__webglFramebuffer[a.activeCubeFace]:a.__webglFramebuffer,i=a.width,j=a.height,k=0,l=0):(h=null,i=lc,j=mc,k=jc,l=kc),h!==Ub&&(Kb.bindFramebuffer(Kb.FRAMEBUFFER,h),Kb.viewport(k,l,i,j),Ub=h),nc=i,oc=j},this.shadowMapPlugin=new e.ShadowMapPlugin,this.addPrePlugin(this.shadowMapPlugin),this.addPostPlugin(new e.SpritePlugin),this.addPostPlugin(new e.LensFlarePlugin)},e.WebGLRenderTarget=function(a,b,c){this.width=a,this.height=b,c=c||{},this.wrapS=void 0!==c.wrapS?c.wrapS:e.ClampToEdgeWrapping,this.wrapT=void 0!==c.wrapT?c.wrapT:e.ClampToEdgeWrapping,this.magFilter=void 0!==c.magFilter?c.magFilter:e.LinearFilter,this.minFilter=void 0!==c.minFilter?c.minFilter:e.LinearMipMapLinearFilter,this.anisotropy=void 0!==c.anisotropy?c.anisotropy:1,this.offset=new e.Vector2(0,0),this.repeat=new e.Vector2(1,1),this.format=void 0!==c.format?c.format:e.RGBAFormat,this.type=void 0!==c.type?c.type:e.UnsignedByteType,this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0,this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0,this.generateMipmaps=!0,this.shareDepthFrom=null -},e.WebGLRenderTarget.prototype={constructor:e.WebGLRenderTarget,clone:function(){var a=new e.WebGLRenderTarget(this.width,this.height);return a.wrapS=this.wrapS,a.wrapT=this.wrapT,a.magFilter=this.magFilter,a.minFilter=this.minFilter,a.anisotropy=this.anisotropy,a.offset.copy(this.offset),a.repeat.copy(this.repeat),a.format=this.format,a.type=this.type,a.depthBuffer=this.depthBuffer,a.stencilBuffer=this.stencilBuffer,a.generateMipmaps=this.generateMipmaps,a.shareDepthFrom=this.shareDepthFrom,a},dispose:function(){this.dispatchEvent({type:"dispose"})}},e.EventDispatcher.prototype.apply(e.WebGLRenderTarget.prototype),e.WebGLRenderTargetCube=function(a,b,c){e.WebGLRenderTarget.call(this,a,b,c),this.activeCubeFace=0},e.WebGLRenderTargetCube.prototype=Object.create(e.WebGLRenderTarget.prototype),e.RenderableVertex=function(){this.position=new e.Vector3,this.positionWorld=new e.Vector3,this.positionScreen=new e.Vector4,this.visible=!0},e.RenderableVertex.prototype.copy=function(a){this.positionWorld.copy(a.positionWorld),this.positionScreen.copy(a.positionScreen)},e.RenderableFace=function(){this.id=0,this.v1=new e.RenderableVertex,this.v2=new e.RenderableVertex,this.v3=new e.RenderableVertex,this.centroidModel=new e.Vector3,this.normalModel=new e.Vector3,this.vertexNormalsModel=[new e.Vector3,new e.Vector3,new e.Vector3],this.vertexNormalsLength=0,this.color=null,this.material=null,this.uvs=[[]],this.z=0},e.RenderableObject=function(){this.id=0,this.object=null,this.z=0},e.RenderableSprite=function(){this.id=0,this.object=null,this.x=0,this.y=0,this.z=0,this.rotation=0,this.scale=new e.Vector2,this.material=null},e.RenderableLine=function(){this.id=0,this.v1=new e.RenderableVertex,this.v2=new e.RenderableVertex,this.vertexColors=[new e.Color,new e.Color],this.material=null,this.z=0},e.GeometryUtils={merge:function(a,b,c){var d,f,g=a.vertices.length,h=(a.faceVertexUvs[0].length,b instanceof e.Mesh?b.geometry:b),i=a.vertices,j=h.vertices,k=a.faces,l=h.faces,m=a.faceVertexUvs[0],n=h.faceVertexUvs[0];void 0===c&&(c=0),b instanceof e.Mesh&&(b.matrixAutoUpdate&&b.updateMatrix(),d=b.matrix,f=(new e.Matrix3).getNormalMatrix(d));for(var o=0,p=j.length;p>o;o++){var q=j[o],r=q.clone();d&&r.applyMatrix4(d),i.push(r)}for(o=0,p=l.length;p>o;o++){var s,t,u,v=l[o],w=v.vertexNormals,x=v.vertexColors;s=new e.Face3(v.a+g,v.b+g,v.c+g),s.normal.copy(v.normal),f&&s.normal.applyMatrix3(f).normalize();for(var y=0,z=w.length;z>y;y++)t=w[y].clone(),f&&t.applyMatrix3(f).normalize(),s.vertexNormals.push(t);s.color.copy(v.color);for(var y=0,z=x.length;z>y;y++)u=x[y],s.vertexColors.push(u.clone());s.materialIndex=v.materialIndex+c,s.centroid.copy(v.centroid),d&&s.centroid.applyMatrix4(d),k.push(s)}for(o=0,p=n.length;p>o;o++){for(var A=n[o],B=[],y=0,z=A.length;z>y;y++)B.push(new e.Vector2(A[y].x,A[y].y));m.push(B)}},randomPointInTriangle:function(){var a=new e.Vector3;return function(b,c,d){var f=new e.Vector3,g=e.Math.random16(),h=e.Math.random16();g+h>1&&(g=1-g,h=1-h);var i=1-g-h;return f.copy(b),f.multiplyScalar(g),a.copy(c),a.multiplyScalar(h),f.add(a),a.copy(d),a.multiplyScalar(i),f.add(a),f}}(),randomPointInFace:function(a,b){var c,d,f;return c=b.vertices[a.a],d=b.vertices[a.b],f=b.vertices[a.c],e.GeometryUtils.randomPointInTriangle(c,d,f)},randomPointsInGeometry:function(a,b){function c(a){function b(c,d){if(c>d)return c;var e=c+Math.floor((d-c)/2);return n[e]>a?b(c,e-1):n[e]f;f++)d=j[f],g=k[d.a],h=k[d.b],i=k[d.c],d._area=e.GeometryUtils.triangleArea(g,h,i),m+=d._area,n[f]=m;var o,p,q=[],r={};for(f=0;b>f;f++)o=e.Math.random16()*m,p=c(o),q[f]=e.GeometryUtils.randomPointInFace(j[p],a,!0),r[p]?r[p]+=1:r[p]=1;return q},triangleArea:function(){var a=new e.Vector3,b=new e.Vector3;return function(c,d,e){return a.subVectors(d,c),b.subVectors(e,c),a.cross(b),.5*a.length()}}(),center:function(a){a.computeBoundingBox();var b=a.boundingBox,c=new e.Vector3;return c.addVectors(b.min,b.max),c.multiplyScalar(-.5),a.applyMatrix((new e.Matrix4).makeTranslation(c.x,c.y,c.z)),a.computeBoundingBox(),c},triangulateQuads:function(a){var b,c,d,e,f=[],g=[];for(b=0,c=a.faceVertexUvs.length;c>b;b++)g[b]=[];for(b=0,c=a.faces.length;c>b;b++){var h=a.faces[b];for(f.push(h),d=0,e=a.faceVertexUvs.length;e>d;d++)g[d].push(a.faceVertexUvs[d][b])}a.faces=f,a.faceVertexUvs=g,a.computeCentroids(),a.computeFaceNormals(),a.computeVertexNormals(),a.hasTangents&&a.computeTangents()}},e.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c){var d=new e.ImageLoader;d.crossOrigin=this.crossOrigin;var f=new e.Texture(void 0,b),g=d.load(a,function(){f.needsUpdate=!0,c&&c(f)});return f.image=g,f.sourceFile=a,f},loadCompressedTexture:function(a,b,c,d){var f=new e.CompressedTexture;f.mapping=b;var g=new XMLHttpRequest;return g.onload=function(){var a=g.response,b=e.ImageUtils.parseDDS(a,!0);f.format=b.format,f.mipmaps=b.mipmaps,f.image.width=b.width,f.image.height=b.height,f.generateMipmaps=!1,f.needsUpdate=!0,c&&c(f)},g.onerror=d,g.open("GET",a,!0),g.responseType="arraybuffer",g.send(null),f},loadTextureCube:function(a,b,c,d){var f=[];f.loadCount=0;var g=new e.Texture;g.image=f,void 0!==b&&(g.mapping=b),g.flipY=!1;for(var h=0,i=a.length;i>h;++h){var j=new Image;f[h]=j,j.onload=function(){f.loadCount+=1,6===f.loadCount&&(g.needsUpdate=!0,c&&c(g))},j.onerror=d,j.crossOrigin=this.crossOrigin,j.src=a[h]}return g},loadCompressedTextureCube:function(a,b,c,d){var f=[];f.loadCount=0;var g=new e.CompressedTexture;g.image=f,void 0!==b&&(g.mapping=b),g.flipY=!1,g.generateMipmaps=!1;var h=function(a,b){return function(){var d=a.response,h=e.ImageUtils.parseDDS(d,!0);b.format=h.format,b.mipmaps=h.mipmaps,b.width=h.width,b.height=h.height,f.loadCount+=1,6===f.loadCount&&(g.format=h.format,g.needsUpdate=!0,c&&c(g))}};if(a instanceof Array)for(var i=0,j=a.length;j>i;++i){var k={};f[i]=k;var l=new XMLHttpRequest;l.onload=h(l,k),l.onerror=d;var m=a[i];l.open("GET",m,!0),l.responseType="arraybuffer",l.send(null)}else{var m=a,l=new XMLHttpRequest;l.onload=function(){var a=l.response,b=e.ImageUtils.parseDDS(a,!0);if(b.isCubemap){for(var d=b.mipmaps.length/b.mipmapCount,h=0;d>h;h++){f[h]={mipmaps:[]};for(var i=0;ii;i++){f[i]={mipmaps:[]};for(var j=0;j>8&255,a>>16&255,a>>24&255)}function f(a,b,c,d){for(var e=c*d*4,f=new Uint8Array(a,b,e),g=new Uint8Array(e),h=0,i=0,j=0;d>j;j++)for(var k=0;c>k;k++){var l=f[i];i++;var m=f[i];i++;var n=f[i];i++;var o=f[i];i++,g[h]=n,h++,g[h]=m,h++,g[h]=l,h++,g[h]=o,h++}return g}var g={mipmaps:[],width:0,height:0,format:null,mipmapCount:1},h=542327876,i=131072,j=512,k=4,l=c("DXT1"),m=c("DXT3"),n=c("DXT5"),o=31,p=0,q=1,r=2,s=3,t=4,u=7,v=20,w=21,x=22,y=23,z=24,A=25,B=26,C=28,D=new Int32Array(a,0,o);if(D[p]!==h)return console.error("ImageUtils.parseDDS(): Invalid magic number in DDS header"),g;if(!D[v]&k)return console.error("ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code"),g;var E,F=D[w],G=!1;switch(F){case l:E=8,g.format=e.RGB_S3TC_DXT1_Format;break;case m:E=16,g.format=e.RGBA_S3TC_DXT3_Format;break;case n:E=16,g.format=e.RGBA_S3TC_DXT5_Format;break;default:if(!(32==D[x]&&16711680&D[y]&&65280&D[z]&&255&D[A]&&4278190080&D[B]))return console.error("ImageUtils.parseDDS(): Unsupported FourCC code: ",d(F)),g;G=!0,E=64,g.format=e.RGBAFormat}g.mipmapCount=1,D[r]&i&&b!==!1&&(g.mipmapCount=Math.max(1,D[u])),g.isCubemap=D[C]&j?!0:!1,g.width=D[t],g.height=D[s];for(var H=D[q]+4,I=g.width,J=g.height,K=g.isCubemap?6:1,L=0;K>L;L++){for(var M=0;Mm;m++)for(var n=0;g>n;n++){var o=0>n-1?0:n-1,p=n+1>g-1?g-1:n+1,q=0>m-1?0:m-1,r=m+1>f-1?f-1:m+1,s=[],t=[0,0,j[4*(n*f+m)]/255*b];s.push([-1,0,j[4*(n*f+q)]/255*b]),s.push([-1,-1,j[4*(o*f+q)]/255*b]),s.push([0,-1,j[4*(o*f+m)]/255*b]),s.push([1,-1,j[4*(o*f+r)]/255*b]),s.push([1,0,j[4*(n*f+r)]/255*b]),s.push([1,1,j[4*(p*f+r)]/255*b]),s.push([0,1,j[4*(p*f+m)]/255*b]),s.push([-1,1,j[4*(p*f+q)]/255*b]);for(var u=[],v=s.length,w=0;v>w;w++){var x=s[w],y=s[(w+1)%v];x=d(x,t),y=d(y,t),u.push(e(c(x,y)))}for(var z=[0,0,0],w=0;wj;j++)f[3*j]=g,f[3*j+1]=h,f[3*j+2]=i;var k=new e.DataTexture(f,a,b,e.RGBFormat);return k.needsUpdate=!0,k}},e.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=new e.Object3D,d=0,f=b.length;f>d;d++)c.add(new e.Mesh(a,b[d]));return c},detach:function(a,b,c){a.applyMatrix(b.matrixWorld),b.remove(a),c.add(a)},attach:function(a,b,c){var d=new e.Matrix4;d.getInverse(c.matrixWorld),a.applyMatrix(d),b.remove(a),c.add(a)}},e.FontUtils={faces:{},face:"helvetiker",weight:"normal",style:"normal",size:150,divisions:10,getFace:function(){return this.faces[this.face][this.weight][this.style]},loadFace:function(a){var b=a.familyName.toLowerCase(),c=this;c.faces[b]=c.faces[b]||{},c.faces[b][a.cssFontWeight]=c.faces[b][a.cssFontWeight]||{},c.faces[b][a.cssFontWeight][a.cssFontStyle]=a;c.faces[b][a.cssFontWeight][a.cssFontStyle]=a;return a},drawText:function(a){var b,c=this.getFace(),d=this.size/c.resolution,f=0,g=String(a).split(""),h=g.length,i=[];for(b=0;h>b;b++){var j=new e.Path,k=this.extractGlyphPoints(g[b],c,d,f,j);f+=k.offset,i.push(k.path)}var l=f/2;return{paths:i,offset:l}},extractGlyphPoints:function(a,b,c,d,f){var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z=[],A=b.glyphs[a]||b.glyphs["?"];if(A){if(A.o)for(j=A._cachedOutline||(A._cachedOutline=A.o.split(" ")),l=j.length,m=c,n=c,g=0;l>g;)switch(k=j[g++]){case"m":o=j[g++]*m+d,p=j[g++]*n,f.moveTo(o,p);break;case"l":o=j[g++]*m+d,p=j[g++]*n,f.lineTo(o,p);break;case"q":if(q=j[g++]*m+d,r=j[g++]*n,u=j[g++]*m+d,v=j[g++]*n,f.quadraticCurveTo(u,v,q,r),y=z[z.length-1])for(s=y.x,t=y.y,h=1,i=this.divisions;i>=h;h++){var B=h/i;e.Shape.Utils.b2(B,s,u,q),e.Shape.Utils.b2(B,t,v,r)}break;case"b":if(q=j[g++]*m+d,r=j[g++]*n,u=j[g++]*m+d,v=j[g++]*-n,w=j[g++]*m+d,x=j[g++]*-n,f.bezierCurveTo(q,r,u,v,w,x),y=z[z.length-1])for(s=y.x,t=y.y,h=1,i=this.divisions;i>=h;h++){var B=h/i;e.Shape.Utils.b3(B,s,u,w,q),e.Shape.Utils.b3(B,t,v,x,r)}}return{offset:A.ha*c,path:f}}}},e.FontUtils.generateShapes=function(a,b){b=b||{};var c=void 0!==b.size?b.size:100,d=void 0!==b.curveSegments?b.curveSegments:4,f=void 0!==b.font?b.font:"helvetiker",g=void 0!==b.weight?b.weight:"normal",h=void 0!==b.style?b.style:"normal";e.FontUtils.size=c,e.FontUtils.divisions=d,e.FontUtils.face=f,e.FontUtils.weight=g,e.FontUtils.style=h;for(var i=e.FontUtils.drawText(a),j=i.paths,k=[],l=0,m=j.length;m>l;l++)Array.prototype.push.apply(k,j[l].toShapes());return k},function(a){var b=1e-10,c=function(a,b){var c=a.length;if(3>c)return null;var f,g,h,i=[],j=[],k=[];if(d(a)>0)for(g=0;c>g;g++)j[g]=g;else for(g=0;c>g;g++)j[g]=c-1-g;var l=c,m=2*l;for(g=l-1;l>2;){if(m--<=0)return console.log("Warning, unable to triangulate polygon!"),b?k:i;if(f=g,f>=l&&(f=0),g=f+1,g>=l&&(g=0),h=g+1,h>=l&&(h=0),e(a,f,g,h,l,j)){var n,o,p,q,r;for(n=j[f],o=j[g],p=j[h],i.push([a[n],a[o],a[p]]),k.push([j[f],j[g],j[h]]),q=g,r=g+1;l>r;q++,r++)j[q]=j[r];l--,m=2*l}}return b?k:i},d=function(a){for(var b=a.length,c=0,d=b-1,e=0;b>e;d=e++)c+=a[d].x*a[e].y-a[e].x*a[d].y;return.5*c},e=function(a,c,d,e,f,g){var h,i,j,k,l,m,n,o,p;if(i=a[g[c]].x,j=a[g[c]].y,k=a[g[d]].x,l=a[g[d]].y,m=a[g[e]].x,n=a[g[e]].y,b>(k-i)*(n-j)-(l-j)*(m-i))return!1;var q,r,s,t,u,v,w,x,y,z,A,B,C,D,E;for(q=m-k,r=n-l,s=i-m,t=j-n,u=k-i,v=l-j,h=0;f>h;h++)if(o=a[g[h]].x,p=a[g[h]].y,!(o===i&&p===j||o===k&&p===l||o===m&&p===n)&&(w=o-i,x=p-j,y=o-k,z=p-l,A=o-m,B=p-n,E=q*z-r*y,C=u*x-v*w,D=s*B-t*A,E>=-b&&D>=-b&&C>=-b))return!1;return!0};return a.Triangulate=c,a.Triangulate.area=d,a}(e.FontUtils),d._typeface_js={faces:e.FontUtils.faces,loadFace:e.FontUtils.loadFace},e.typeface_js=d._typeface_js,e.Curve=function(){},e.Curve.prototype.getPoint=function(){return console.log("Warning, getPoint() not implemented!"),null},e.Curve.prototype.getPointAt=function(a){var b=this.getUtoTmapping(a);return this.getPoint(b)},e.Curve.prototype.getPoints=function(a){a||(a=5);var b,c=[];for(b=0;a>=b;b++)c.push(this.getPoint(b/a));return c},e.Curve.prototype.getSpacedPoints=function(a){a||(a=5);var b,c=[];for(b=0;a>=b;b++)c.push(this.getPointAt(b/a));return c},e.Curve.prototype.getLength=function(){var a=this.getLengths();return a[a.length-1]},e.Curve.prototype.getLengths=function(a){if(a||(a=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length==a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b,c,d=[],e=this.getPoint(0),f=0;for(d.push(0),c=1;a>=c;c++)b=this.getPoint(c/a),f+=b.distanceTo(e),d.push(f),e=b;return this.cacheArcLengths=d,d},e.Curve.prototype.updateArcLengths=function(){this.needsUpdate=!0,this.getLengths()},e.Curve.prototype.getUtoTmapping=function(a,b){var c,d=this.getLengths(),e=0,f=d.length;c=b?b:a*d[f-1];for(var g,h=0,i=f-1;i>=h;)if(e=Math.floor(h+(i-h)/2),g=d[e]-c,0>g)h=e+1;else{if(!(g>0)){i=e;break}i=e-1}if(e=i,d[e]==c){var j=e/(f-1);return j}var k=d[e],l=d[e+1],m=l-k,n=(c-k)/m,j=(e+n)/(f-1);return j},e.Curve.prototype.getTangent=function(a){var b=1e-4,c=a-b,d=a+b;0>c&&(c=0),d>1&&(d=1);var e=this.getPoint(c),f=this.getPoint(d),g=f.clone().sub(e);return g.normalize()},e.Curve.prototype.getTangentAt=function(a){var b=this.getUtoTmapping(a);return this.getTangent(b)},e.Curve.Utils={tangentQuadraticBezier:function(a,b,c,d){return 2*(1-a)*(c-b)+2*a*(d-c)},tangentCubicBezier:function(a,b,c,d,e){return-3*b*(1-a)*(1-a)+3*c*(1-a)*(1-a)-6*a*c*(1-a)+6*a*d*(1-a)-3*a*a*d+3*a*a*e},tangentSpline:function(a){var b=6*a*a-6*a,c=3*a*a-4*a+1,d=-6*a*a+6*a,e=3*a*a-2*a;return b+c+d+e},interpolate:function(a,b,c,d,e){var f=.5*(c-a),g=.5*(d-b),h=e*e,i=e*h;return(2*b-2*c+f+g)*i+(-3*b+3*c-2*f-g)*h+f*e+b}},e.Curve.create=function(a,b){return a.prototype=Object.create(e.Curve.prototype),a.prototype.getPoint=b,a},e.CurvePath=function(){this.curves=[],this.bends=[],this.autoClose=!1},e.CurvePath.prototype=Object.create(e.Curve.prototype),e.CurvePath.prototype.add=function(a){this.curves.push(a)},e.CurvePath.prototype.checkConnection=function(){},e.CurvePath.prototype.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 e.LineCurve(b,a))},e.CurvePath.prototype.getPoint=function(a){for(var b,c,d=a*this.getLength(),e=this.getCurveLengths(),f=0;f=d){b=e[f]-d,c=this.curves[f];var g=1-b/c.getLength();return c.getPointAt(g)}f++}return null},e.CurvePath.prototype.getLength=function(){var a=this.getCurveLengths();return a[a.length-1]},e.CurvePath.prototype.getCurveLengths=function(){if(this.cacheLengths&&this.cacheLengths.length==this.curves.length)return this.cacheLengths;var a,b=[],c=0,d=this.curves.length;for(a=0;d>a;a++)c+=this.curves[a].getLength(),b.push(c);return this.cacheLengths=b,b},e.CurvePath.prototype.getBoundingBox=function(){var a,b,c,d,f,g,h=this.getPoints();a=b=Number.NEGATIVE_INFINITY,d=f=Number.POSITIVE_INFINITY;var i,j,k,l,m=h[0]instanceof e.Vector3;for(l=m?new e.Vector3:new e.Vector2,j=0,k=h.length;k>j;j++)i=h[j],i.x>a?a=i.x:i.xb?b=i.y:i.yc?c=i.z:i.zc;c++)e=this.getWrapPoints(e,b[c]);return e},e.CurvePath.prototype.getTransformedSpacedPoints=function(a,b){var c,d,e=this.getSpacedPoints(a);for(b||(b=this.bends),c=0,d=b.length;d>c;c++)e=this.getWrapPoints(e,b[c]);return e},e.CurvePath.prototype.getWrapPoints=function(a,b){var c,d,e,f,g,h,i=this.getBoundingBox();for(c=0,d=a.length;d>c;c++){e=a[c],f=e.x,g=e.y,h=f/i.maxX,h=b.getUtoTmapping(h,f);var j=b.getPoint(h),k=b.getTangent(h);k.set(-k.y,k.x).multiplyScalar(g),e.x=j.x+k.x,e.y=j.y+k.y}return a},e.Gyroscope=function(){e.Object3D.call(this)},e.Gyroscope.prototype=Object.create(e.Object3D.prototype),e.Gyroscope.prototype.updateMatrixWorld=function(a){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||a)&&(this.parent?(this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorld.decompose(this.translationWorld,this.quaternionWorld,this.scaleWorld),this.matrix.decompose(this.translationObject,this.quaternionObject,this.scaleObject),this.matrixWorld.compose(this.translationWorld,this.quaternionObject,this.scaleWorld)):this.matrixWorld.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0);for(var b=0,c=this.children.length;c>b;b++)this.children[b].updateMatrixWorld(a)},e.Gyroscope.prototype.translationWorld=new e.Vector3,e.Gyroscope.prototype.translationObject=new e.Vector3,e.Gyroscope.prototype.quaternionWorld=new e.Quaternion,e.Gyroscope.prototype.quaternionObject=new e.Quaternion,e.Gyroscope.prototype.scaleWorld=new e.Vector3,e.Gyroscope.prototype.scaleObject=new e.Vector3,e.Path=function(a){e.CurvePath.call(this),this.actions=[],a&&this.fromPoints(a)},e.Path.prototype=Object.create(e.CurvePath.prototype),e.PathActions={MOVE_TO:"moveTo",LINE_TO:"lineTo",QUADRATIC_CURVE_TO:"quadraticCurveTo",BEZIER_CURVE_TO:"bezierCurveTo",CSPLINE_THRU:"splineThru",ARC:"arc",ELLIPSE:"ellipse"},e.Path.prototype.fromPoints=function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;c>b;b++)this.lineTo(a[b].x,a[b].y)},e.Path.prototype.moveTo=function(){var a=Array.prototype.slice.call(arguments);this.actions.push({action:e.PathActions.MOVE_TO,args:a})},e.Path.prototype.lineTo=function(a,b){var c=Array.prototype.slice.call(arguments),d=this.actions[this.actions.length-1].args,f=d[d.length-2],g=d[d.length-1],h=new e.LineCurve(new e.Vector2(f,g),new e.Vector2(a,b));this.curves.push(h),this.actions.push({action:e.PathActions.LINE_TO,args:c})},e.Path.prototype.quadraticCurveTo=function(a,b,c,d){var f=Array.prototype.slice.call(arguments),g=this.actions[this.actions.length-1].args,h=g[g.length-2],i=g[g.length-1],j=new e.QuadraticBezierCurve(new e.Vector2(h,i),new e.Vector2(a,b),new e.Vector2(c,d));this.curves.push(j),this.actions.push({action:e.PathActions.QUADRATIC_CURVE_TO,args:f})},e.Path.prototype.bezierCurveTo=function(a,b,c,d,f,g){var h=Array.prototype.slice.call(arguments),i=this.actions[this.actions.length-1].args,j=i[i.length-2],k=i[i.length-1],l=new e.CubicBezierCurve(new e.Vector2(j,k),new e.Vector2(a,b),new e.Vector2(c,d),new e.Vector2(f,g));this.curves.push(l),this.actions.push({action:e.PathActions.BEZIER_CURVE_TO,args:h})},e.Path.prototype.splineThru=function(a){var b=Array.prototype.slice.call(arguments),c=this.actions[this.actions.length-1].args,d=c[c.length-2],f=c[c.length-1],g=[new e.Vector2(d,f)];Array.prototype.push.apply(g,a);var h=new e.SplineCurve(g);this.curves.push(h),this.actions.push({action:e.PathActions.CSPLINE_THRU,args:b})},e.Path.prototype.arc=function(a,b,c,d,e,f){var g=this.actions[this.actions.length-1].args,h=g[g.length-2],i=g[g.length-1];this.absarc(a+h,b+i,c,d,e,f)},e.Path.prototype.absarc=function(a,b,c,d,e,f){this.absellipse(a,b,c,c,d,e,f)},e.Path.prototype.ellipse=function(a,b,c,d,e,f,g){var h=this.actions[this.actions.length-1].args,i=h[h.length-2],j=h[h.length-1];this.absellipse(a+i,b+j,c,d,e,f,g)},e.Path.prototype.absellipse=function(a,b,c,d,f,g,h){var i=Array.prototype.slice.call(arguments),j=new e.EllipseCurve(a,b,c,d,f,g,h);this.curves.push(j);var k=j.getPoint(1);i.push(k.x),i.push(k.y),this.actions.push({action:e.PathActions.ELLIPSE,args:i})},e.Path.prototype.getSpacedPoints=function(a){a||(a=40);for(var b=[],c=0;a>c;c++)b.push(this.getPoint(c/a));return b},e.Path.prototype.getPoints=function(a,b){if(this.useSpacedPoints)return console.log("tata"),this.getSpacedPoints(a,b);a=a||12;var c,d,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v=[];for(c=0,d=this.actions.length;d>c;c++)switch(f=this.actions[c],g=f.action,h=f.args,g){case e.PathActions.MOVE_TO:v.push(new e.Vector2(h[0],h[1]));break;case e.PathActions.LINE_TO:v.push(new e.Vector2(h[0],h[1]));break;case e.PathActions.QUADRATIC_CURVE_TO:for(i=h[2],j=h[3],m=h[0],n=h[1],v.length>0?(q=v[v.length-1],o=q.x,p=q.y):(q=this.actions[c-1].args,o=q[q.length-2],p=q[q.length-1]),r=1;a>=r;r++)s=r/a,t=e.Shape.Utils.b2(s,o,m,i),u=e.Shape.Utils.b2(s,p,n,j),v.push(new e.Vector2(t,u));break;case e.PathActions.BEZIER_CURVE_TO:for(i=h[4],j=h[5],m=h[0],n=h[1],k=h[2],l=h[3],v.length>0?(q=v[v.length-1],o=q.x,p=q.y):(q=this.actions[c-1].args,o=q[q.length-2],p=q[q.length-1]),r=1;a>=r;r++)s=r/a,t=e.Shape.Utils.b3(s,o,m,k,i),u=e.Shape.Utils.b3(s,p,n,l,j),v.push(new e.Vector2(t,u));break;case e.PathActions.CSPLINE_THRU:q=this.actions[c-1].args;var w=new e.Vector2(q[q.length-2],q[q.length-1]),x=[w],y=a*h[0].length;x=x.concat(h[0]);var z=new e.SplineCurve(x);for(r=1;y>=r;r++)v.push(z.getPointAt(r/y));break;case e.PathActions.ARC:var A,B=h[0],C=h[1],D=h[2],E=h[3],F=h[4],G=!!h[5],H=F-E,I=2*a;for(r=1;I>=r;r++)s=r/I,G||(s=1-s),A=E+s*H,t=B+D*Math.cos(A),u=C+D*Math.sin(A),v.push(new e.Vector2(t,u));break;case e.PathActions.ELLIPSE:var A,B=h[0],C=h[1],J=h[2],K=h[3],E=h[4],F=h[5],G=!!h[6],H=F-E,I=2*a;for(r=1;I>=r;r++)s=r/I,G||(s=1-s),A=E+s*H,t=B+J*Math.cos(A),u=C+K*Math.sin(A),v.push(new e.Vector2(t,u))}var L=v[v.length-1],M=1e-10;return Math.abs(L.x-v[0].x)g;f=g++){var h=b[f],i=b[g],j=i.x-h.x,k=i.y-h.y;if(Math.abs(k)>c){if(0>k&&(h=b[g],j=-j,i=b[f],k=-k),a.yi.y)continue;if(a.y==h.y){if(a.x==h.x)return!0}else{var l=k*(a.x-h.x)-j*(a.y-h.y);if(0==l)return!0;if(0>l)continue;e=!e}}else{if(a.y!=h.y)continue;if(i.x<=a.x&&a.x<=h.x||h.x<=a.x&&a.x<=i.x)return!0}}return e}var c,d,f,g,h,i=[],j=new e.Path;for(c=0,d=this.actions.length;d>c;c++)f=this.actions[c],h=f.args,g=f.action,g==e.PathActions.MOVE_TO&&0!=j.actions.length&&(i.push(j),j=new e.Path),j[g].apply(j,h);if(0!=j.actions.length&&i.push(j),0==i.length)return[];var k,l,m,n=[];if(1==i.length)return l=i[0],m=new e.Shape,m.actions=l.actions,m.curves=l.curves,n.push(m),n;var o=!e.Shape.Utils.isClockWise(i[0].getPoints());o=a?!o:o;var p,q=[],r=[],s=[],t=0;for(r[t]=void 0,s[t]=[],c=0,d=i.length;d>c;c++)l=i[c],p=l.getPoints(),k=e.Shape.Utils.isClockWise(p),k=a?!k:k,k?(!o&&r[t]&&t++,r[t]={s:new e.Shape,p:p},r[t].s.actions=l.actions,r[t].s.curves=l.curves,o&&t++,s[t]=[]):s[t].push({h:l,p:p[0]});if(r.length>1){for(var u=!1,v=[],w=0,x=r.length;x>w;w++)q[w]=[];for(var w=0,x=r.length;x>w;w++)for(var y=(r[w],s[w]),z=0;z0&&(u||(s=q))}var D,E,F;for(c=0,d=r.length;d>c;c++)for(m=r[c].s,n.push(m),D=s[c],E=0,F=D.length;F>E;E++)m.holes.push(D[E].h);return n},e.Shape=function(){e.Path.apply(this,arguments),this.holes=[]},e.Shape.prototype=Object.create(e.Path.prototype),e.Shape.prototype.extrude=function(a){var b=new e.ExtrudeGeometry(this,a);return b},e.Shape.prototype.makeGeometry=function(a){var b=new e.ShapeGeometry(this,a);return b},e.Shape.prototype.getPointsHoles=function(a){var b,c=this.holes.length,d=[];for(b=0;c>b;b++)d[b]=this.holes[b].getTransformedPoints(a,this.bends);return d},e.Shape.prototype.getSpacedPointsHoles=function(a){var b,c=this.holes.length,d=[];for(b=0;c>b;b++)d[b]=this.holes[b].getTransformedSpacedPoints(a,this.bends);return d},e.Shape.prototype.extractAllPoints=function(a){return{shape:this.getTransformedPoints(a),holes:this.getPointsHoles(a)}},e.Shape.prototype.extractPoints=function(a){return this.useSpacedPoints?this.extractAllSpacedPoints(a):this.extractAllPoints(a)},e.Shape.prototype.extractAllSpacedPoints=function(a){return{shape:this.getTransformedSpacedPoints(a),holes:this.getSpacedPointsHoles(a)}},e.Shape.Utils={triangulateShape:function(a,b){function c(a,b,c){return a.x!=b.x?a.xg){var p;if(n>0){if(0>o||o>n)return[];if(p=k*l-j*m,0>p||p>n)return[]}else{if(o>0||n>o)return[];if(p=k*l-j*m,p>0||n>p)return[]}if(0==p)return!f||0!=o&&o!=n?[a]:[];if(p==n)return!f||0!=o&&o!=n?[b]:[];if(0==o)return[d];if(o==n)return[e];var q=p/n;return[{x:a.x+q*h,y:a.y+q*i}]}if(0!=o||k*l!=j*m)return[];var r=0==h&&0==i,s=0==j&&0==k;if(r&&s)return a.x!=d.x||a.y!=d.y?[]:[a];if(r)return c(d,e,a)?[a]:[];if(s)return c(a,b,d)?[d]:[];var t,u,v,w,x,y,z,A;return 0!=h?(a.x=v?z>w?[]:w==z?f?[]:[x]:A>=w?[x,u]:[x,y]:v>A?[]:v==A?f?[]:[t]:A>=w?[t,u]:[t,y]}function f(a,b,c,d){var e=1e-10,f=b.x-a.x,g=b.y-a.y,h=c.x-a.x,i=c.y-a.y,j=d.x-a.x,k=d.y-a.y,l=f*i-g*h,m=f*k-g*j;if(Math.abs(l)>e){var n=j*i-k*h;return l>0?m>=0&&n>=0:m>=0||n>=0}return m>0}function g(a,b){function c(a,b){var c=s.length-1,d=a-1;0>d&&(d=c);var e=a+1;e>c&&(e=0);var g=f(s[a],s[d],s[e],h[b]);if(!g)return!1;var i=h.length-1,j=b-1;0>j&&(j=i);var k=b+1;return k>i&&(k=0),g=f(h[b],h[j],h[k],s[a]),g?!0:!1}function e(a,b){var c,e,f;for(c=0;c0)return!0;return!1}function g(a,c){var e,f,g,h,i;for(e=0;e0)return!0;return!1}for(var h,i,j,k,l,m,n,o,p,q,r,s=a.concat(),t=[],u=[],v=0,w=b.length;w>v;v++)t.push(v);for(var x=2*t.length;t.length>0;){if(x--,0>x){console.log("Infinite Loop! Holes left:"+t.length+", Probably Hole outside Shape!");break}for(j=0;j=0)break;u[n]=!0}if(i>=0)break}}return s}for(var h,i,j,k,l,m,n={},o=a.concat(),p=0,q=b.length;q>p;p++)Array.prototype.push.apply(o,b[p]);for(h=0,i=o.length;i>h;h++)l=o[h].x+":"+o[h].y,void 0!==n[l]&&console.log("Duplicate point",l),n[l]=h;var r=g(a,b),s=e.FontUtils.Triangulate(r,!1);for(h=0,i=s.length;i>h;h++)for(k=s[h],j=0;3>j;j++)l=k[j].x+":"+k[j].y,m=n[l],void 0!==m&&(k[j]=m);return s.concat()},isClockWise:function(a){return e.FontUtils.Triangulate.area(a)<0},b2p0:function(a,b){var c=1-a;return c*c*b},b2p1:function(a,b){return 2*(1-a)*a*b},b2p2:function(a,b){return a*a*b},b2:function(a,b,c,d){return this.b2p0(a,b)+this.b2p1(a,c)+this.b2p2(a,d)},b3p0:function(a,b){var c=1-a;return c*c*c*b},b3p1:function(a,b){var c=1-a;return 3*c*c*a*b},b3p2:function(a,b){var c=1-a;return 3*c*a*a*b},b3p3:function(a,b){return a*a*a*b},b3:function(a,b,c,d,e){return this.b3p0(a,b)+this.b3p1(a,c)+this.b3p2(a,d)+this.b3p3(a,e)}},e.LineCurve=function(a,b){this.v1=a,this.v2=b},e.LineCurve.prototype=Object.create(e.Curve.prototype),e.LineCurve.prototype.getPoint=function(a){var b=this.v2.clone().sub(this.v1);return b.multiplyScalar(a).add(this.v1),b},e.LineCurve.prototype.getPointAt=function(a){return this.getPoint(a)},e.LineCurve.prototype.getTangent=function(){var a=this.v2.clone().sub(this.v1);return a.normalize()},e.QuadraticBezierCurve=function(a,b,c){this.v0=a,this.v1=b,this.v2=c},e.QuadraticBezierCurve.prototype=Object.create(e.Curve.prototype),e.QuadraticBezierCurve.prototype.getPoint=function(a){var b,c;return b=e.Shape.Utils.b2(a,this.v0.x,this.v1.x,this.v2.x),c=e.Shape.Utils.b2(a,this.v0.y,this.v1.y,this.v2.y),new e.Vector2(b,c)},e.QuadraticBezierCurve.prototype.getTangent=function(a){var b,c;b=e.Curve.Utils.tangentQuadraticBezier(a,this.v0.x,this.v1.x,this.v2.x),c=e.Curve.Utils.tangentQuadraticBezier(a,this.v0.y,this.v1.y,this.v2.y);var d=new e.Vector2(b,c);return d.normalize(),d},e.CubicBezierCurve=function(a,b,c,d){this.v0=a,this.v1=b,this.v2=c,this.v3=d},e.CubicBezierCurve.prototype=Object.create(e.Curve.prototype),e.CubicBezierCurve.prototype.getPoint=function(a){var b,c;return b=e.Shape.Utils.b3(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),c=e.Shape.Utils.b3(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y),new e.Vector2(b,c)},e.CubicBezierCurve.prototype.getTangent=function(a){var b,c;b=e.Curve.Utils.tangentCubicBezier(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),c=e.Curve.Utils.tangentCubicBezier(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y);var d=new e.Vector2(b,c);return d.normalize(),d},e.SplineCurve=function(a){this.points=void 0==a?[]:a},e.SplineCurve.prototype=Object.create(e.Curve.prototype),e.SplineCurve.prototype.getPoint=function(a){var b,c,d,f=new e.Vector2,g=[],h=this.points;return b=(h.length-1)*a,c=Math.floor(b),d=b-c,g[0]=0==c?c:c-1,g[1]=c,g[2]=c>h.length-2?h.length-1:c+1,g[3]=c>h.length-3?h.length-1:c+2,f.x=e.Curve.Utils.interpolate(h[g[0]].x,h[g[1]].x,h[g[2]].x,h[g[3]].x,d),f.y=e.Curve.Utils.interpolate(h[g[0]].y,h[g[1]].y,h[g[2]].y,h[g[3]].y,d),f},e.EllipseCurve=function(a,b,c,d,e,f,g){this.aX=a,this.aY=b,this.xRadius=c,this.yRadius=d,this.aStartAngle=e,this.aEndAngle=f,this.aClockwise=g},e.EllipseCurve.prototype=Object.create(e.Curve.prototype),e.EllipseCurve.prototype.getPoint=function(a){var b,c=this.aEndAngle-this.aStartAngle;0>c&&(c+=2*Math.PI),c>2*Math.PI&&(c-=2*Math.PI),b=this.aClockwise===!0?this.aEndAngle+(1-a)*(2*Math.PI-c):this.aStartAngle+a*c; -var d=this.aX+this.xRadius*Math.cos(b),f=this.aY+this.yRadius*Math.sin(b);return new e.Vector2(d,f)},e.ArcCurve=function(a,b,c,d,f,g){e.EllipseCurve.call(this,a,b,c,c,d,f,g)},e.ArcCurve.prototype=Object.create(e.EllipseCurve.prototype),e.LineCurve3=e.Curve.create(function(a,b){this.v1=a,this.v2=b},function(a){var b=new e.Vector3;return b.subVectors(this.v2,this.v1),b.multiplyScalar(a),b.add(this.v1),b}),e.QuadraticBezierCurve3=e.Curve.create(function(a,b,c){this.v0=a,this.v1=b,this.v2=c},function(a){var b,c,d;return b=e.Shape.Utils.b2(a,this.v0.x,this.v1.x,this.v2.x),c=e.Shape.Utils.b2(a,this.v0.y,this.v1.y,this.v2.y),d=e.Shape.Utils.b2(a,this.v0.z,this.v1.z,this.v2.z),new e.Vector3(b,c,d)}),e.CubicBezierCurve3=e.Curve.create(function(a,b,c,d){this.v0=a,this.v1=b,this.v2=c,this.v3=d},function(a){var b,c,d;return b=e.Shape.Utils.b3(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),c=e.Shape.Utils.b3(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y),d=e.Shape.Utils.b3(a,this.v0.z,this.v1.z,this.v2.z,this.v3.z),new e.Vector3(b,c,d)}),e.SplineCurve3=e.Curve.create(function(a){this.points=void 0==a?[]:a},function(a){var b,c,d,f=new e.Vector3,g=[],h=this.points;b=(h.length-1)*a,c=Math.floor(b),d=b-c,g[0]=0==c?c:c-1,g[1]=c,g[2]=c>h.length-2?h.length-1:c+1,g[3]=c>h.length-3?h.length-1:c+2;var i=h[g[0]],j=h[g[1]],k=h[g[2]],l=h[g[3]];return f.x=e.Curve.Utils.interpolate(i.x,j.x,k.x,l.x,d),f.y=e.Curve.Utils.interpolate(i.y,j.y,k.y,l.y,d),f.z=e.Curve.Utils.interpolate(i.z,j.z,k.z,l.z,d),f}),e.ClosedSplineCurve3=e.Curve.create(function(a){this.points=void 0==a?[]:a},function(a){var b,c,d,f=new e.Vector3,g=[],h=this.points;return b=(h.length-0)*a,c=Math.floor(b),d=b-c,c+=c>0?0:(Math.floor(Math.abs(c)/h.length)+1)*h.length,g[0]=(c-1)%h.length,g[1]=c%h.length,g[2]=(c+1)%h.length,g[3]=(c+2)%h.length,f.x=e.Curve.Utils.interpolate(h[g[0]].x,h[g[1]].x,h[g[2]].x,h[g[3]].x,d),f.y=e.Curve.Utils.interpolate(h[g[0]].y,h[g[1]].y,h[g[2]].y,h[g[3]].y,d),f.z=e.Curve.Utils.interpolate(h[g[0]].z,h[g[1]].z,h[g[2]].z,h[g[3]].z,d),f}),e.AnimationHandler=function(){var a=[],b={},c={};c.update=function(b){for(var c=0;ca;a++){var c=this.hierarchy[a];c.matrixAutoUpdate=!0,void 0===c.animationCache&&(c.animationCache={},c.animationCache.prevKey={pos:0,rot:0,scl:0},c.animationCache.nextKey={pos:0,rot:0,scl:0},c.animationCache.originalMatrix=c instanceof e.Bone?c.skinMatrix:c.matrix);var d=c.animationCache.prevKey,f=c.animationCache.nextKey;d.pos=this.data.hierarchy[a].keys[0],d.rot=this.data.hierarchy[a].keys[0],d.scl=this.data.hierarchy[a].keys[0],f.pos=this.getNextKeyWith("pos",a,1),f.rot=this.getNextKeyWith("rot",a,1),f.scl=this.getNextKeyWith("scl",a,1)}},e.Animation.prototype.update=function(){var a=[],b=new e.Vector3,c=function(a,b){var c,e,f,g,h,i,j,k,l,m=[],n=[];return c=(a.length-1)*b,e=Math.floor(c),f=c-e,m[0]=0===e?e:e-1,m[1]=e,m[2]=e>a.length-2?e:e+1,m[3]=e>a.length-3?e:e+2,i=a[m[0]],j=a[m[1]],k=a[m[2]],l=a[m[3]],g=f*f,h=f*g,n[0]=d(i[0],j[0],k[0],l[0],f,g,h),n[1]=d(i[1],j[1],k[1],l[1],f,g,h),n[2]=d(i[2],j[2],k[2],l[2],f,g,h),n},d=function(a,b,c,d,e,f,g){var h=.5*(c-a),i=.5*(d-b);return(2*(b-c)+h+i)*g+(-3*(b-c)-2*h-i)*f+h*e+b};return function(d){if(this.isPlaying!==!1){this.currentTime+=d*this.timeScale;var f,g=["pos","rot","scl"],h=this.data.length;if(this.loop===!0&&this.currentTime>h)this.currentTime%=h,this.reset();else if(this.loop===!1&&this.currentTime>h)return void this.stop();this.currentTime=Math.min(this.currentTime,h);for(var i=0,j=this.hierarchy.length;j>i;i++)for(var k=this.hierarchy[i],l=k.animationCache,m=0;3>m;m++){var n=g[m],o=l.prevKey[n],p=l.nextKey[n];if(p.time<=this.currentTime){for(o=this.data.hierarchy[i].keys[0],p=this.getNextKeyWith(n,i,1);p.timeo.index;)o=p,p=this.getNextKeyWith(n,i,p.index+1);l.prevKey[n]=o,l.nextKey[n]=p}k.matrixAutoUpdate=!0,k.matrixWorldNeedsUpdate=!0;var q=(this.currentTime-o.time)/(p.time-o.time),r=o[n],s=p[n];if(0>q&&(q=0),q>1&&(q=1),"pos"===n){if(f=k.position,this.interpolationType===e.AnimationHandler.LINEAR)f.x=r[0]+(s[0]-r[0])*q,f.y=r[1]+(s[1]-r[1])*q,f.z=r[2]+(s[2]-r[2])*q;else if(this.interpolationType===e.AnimationHandler.CATMULLROM||this.interpolationType===e.AnimationHandler.CATMULLROM_FORWARD){a[0]=this.getPrevKeyWith("pos",i,o.index-1).pos,a[1]=r,a[2]=s,a[3]=this.getNextKeyWith("pos",i,p.index+1).pos,q=.33*q+.33;var t=c(a,q);if(f.x=t[0],f.y=t[1],f.z=t[2],this.interpolationType===e.AnimationHandler.CATMULLROM_FORWARD){var u=c(a,1.01*q);b.set(u[0],u[1],u[2]),b.sub(f),b.y=0,b.normalize();var v=Math.atan2(b.x,b.z);k.rotation.set(0,v,0)}}}else"rot"===n?e.Quaternion.slerp(r,s,k.quaternion,q):"scl"===n&&(f=k.scale,f.x=r[0]+(s[0]-r[0])*q,f.y=r[1]+(s[1]-r[1])*q,f.z=r[2]+(s[2]-r[2])*q)}}}}(),e.Animation.prototype.getNextKeyWith=function(a,b,c){var d=this.data.hierarchy[b].keys;for(this.interpolationType===e.AnimationHandler.CATMULLROM||this.interpolationType===e.AnimationHandler.CATMULLROM_FORWARD?c=c0?c:0:c>=0?c:c+d.length;c>=0;c--)if(void 0!==d[c][a])return d[c];return this.data.hierarchy[b].keys[d.length-1]},e.KeyFrameAnimation=function(a,b){this.root=a,this.data=e.AnimationHandler.get(b),this.hierarchy=e.AnimationHandler.parse(a),this.currentTime=0,this.timeScale=.001,this.isPlaying=!1,this.isPaused=!0,this.loop=!0;for(var c=0,d=this.hierarchy.length;d>c;c++){var f=this.data.hierarchy[c].keys,g=this.data.hierarchy[c].sids,h=this.hierarchy[c];if(f.length&&g){for(var i=0;ib;b++){c=this.hierarchy[b],d=this.data.hierarchy[b],void 0===d.animationCache&&(d.animationCache={},d.animationCache.prevKey=null,d.animationCache.nextKey=null,d.animationCache.originalMatrix=c instanceof e.Bone?c.skinMatrix:c.matrix);var g=this.data.hierarchy[b].keys;g.length&&(d.animationCache.prevKey=g[0],d.animationCache.nextKey=g[1],this.startTime=Math.min(g[0].time,this.startTime),this.endTime=Math.max(g[g.length-1].time,this.endTime))}this.update(0)}this.isPaused=!1,e.AnimationHandler.addToUpdate(this)},e.KeyFrameAnimation.prototype.pause=function(){this.isPaused?e.AnimationHandler.addToUpdate(this):e.AnimationHandler.removeFromUpdate(this),this.isPaused=!this.isPaused},e.KeyFrameAnimation.prototype.stop=function(){this.isPlaying=!1,this.isPaused=!1,e.AnimationHandler.removeFromUpdate(this);for(var a=0;ab&&(this.currentTime%=b),this.currentTime=Math.min(this.currentTime,b);for(var c=0,d=this.hierarchy.length;d>c;c++){var e=this.hierarchy[c],f=this.data.hierarchy[c],g=f.keys,h=f.animationCache;if(g.length){var i=h.prevKey,j=h.nextKey;if(j.time<=this.currentTime){for(;j.timei.index;)i=j,j=g[i.index+1];h.prevKey=i,h.nextKey=j}j.time>=this.currentTime?i.interpolate(j,this.currentTime):i.interpolate(j,j.time),this.data.hierarchy[c].node.updateMatrix(),e.matrixWorldNeedsUpdate=!0}}}},e.KeyFrameAnimation.prototype.getNextKeyWith=function(a,b,c){var d=this.data.hierarchy[b].keys;for(c%=d.length;c=0?c:c+d.length;c>=0;c--)if(d[c].hasTarget(a))return d[c];return d[d.length-1]},e.MorphAnimation=function(a){this.mesh=a,this.frames=a.morphTargetInfluences.length,this.currentTime=0,this.duration=1e3,this.loop=!0,this.isPlaying=!1},e.MorphAnimation.prototype={play:function(){this.isPlaying=!0},pause:function(){this.isPlaying=!1},update:function(){var a=0,b=0;return function(c){if(this.isPlaying!==!1){this.currentTime+=c,this.loop===!0&&this.currentTime>this.duration&&(this.currentTime%=this.duration),this.currentTime=Math.min(this.currentTime,this.duration);var d=this.duration/this.frames,e=Math.floor(this.currentTime/d);e!=b&&(this.mesh.morphTargetInfluences[a]=0,this.mesh.morphTargetInfluences[b]=1,this.mesh.morphTargetInfluences[e]=0,a=b,b=e),this.mesh.morphTargetInfluences[e]=this.currentTime%d/d,this.mesh.morphTargetInfluences[a]=1-this.mesh.morphTargetInfluences[e]}}}()},e.CubeCamera=function(a,b,c){e.Object3D.call(this);var d=90,f=1,g=new e.PerspectiveCamera(d,f,a,b);g.up.set(0,-1,0),g.lookAt(new e.Vector3(1,0,0)),this.add(g);var h=new e.PerspectiveCamera(d,f,a,b);h.up.set(0,-1,0),h.lookAt(new e.Vector3(-1,0,0)),this.add(h);var i=new e.PerspectiveCamera(d,f,a,b);i.up.set(0,0,1),i.lookAt(new e.Vector3(0,1,0)),this.add(i);var j=new e.PerspectiveCamera(d,f,a,b);j.up.set(0,0,-1),j.lookAt(new e.Vector3(0,-1,0)),this.add(j);var k=new e.PerspectiveCamera(d,f,a,b);k.up.set(0,-1,0),k.lookAt(new e.Vector3(0,0,1)),this.add(k);var l=new e.PerspectiveCamera(d,f,a,b);l.up.set(0,-1,0),l.lookAt(new e.Vector3(0,0,-1)),this.add(l),this.renderTarget=new e.WebGLRenderTargetCube(c,c,{format:e.RGBFormat,magFilter:e.LinearFilter,minFilter:e.LinearFilter}),this.updateCubeMap=function(a,b){var c=this.renderTarget,d=c.generateMipmaps;c.generateMipmaps=!1,c.activeCubeFace=0,a.render(b,g,c),c.activeCubeFace=1,a.render(b,h,c),c.activeCubeFace=2,a.render(b,i,c),c.activeCubeFace=3,a.render(b,j,c),c.activeCubeFace=4,a.render(b,k,c),c.generateMipmaps=d,c.activeCubeFace=5,a.render(b,l,c)}},e.CubeCamera.prototype=Object.create(e.Object3D.prototype),e.CombinedCamera=function(a,b,c,d,f,g,h){e.Camera.call(this),this.fov=c,this.left=-a/2,this.right=a/2,this.top=b/2,this.bottom=-b/2,this.cameraO=new e.OrthographicCamera(a/-2,a/2,b/2,b/-2,g,h),this.cameraP=new e.PerspectiveCamera(c,a/b,d,f),this.zoom=1,this.toPerspective()},e.CombinedCamera.prototype=Object.create(e.Camera.prototype),e.CombinedCamera.prototype.toPerspective=function(){this.near=this.cameraP.near,this.far=this.cameraP.far,this.cameraP.fov=this.fov/this.zoom,this.cameraP.updateProjectionMatrix(),this.projectionMatrix=this.cameraP.projectionMatrix,this.inPerspectiveMode=!0,this.inOrthographicMode=!1},e.CombinedCamera.prototype.toOrthographic=function(){var a=this.fov,b=this.cameraP.aspect,c=this.cameraP.near,d=this.cameraP.far,e=(c+d)/2,f=Math.tan(a/2)*e,g=2*f,h=g*b,i=h/2;f/=this.zoom,i/=this.zoom,this.cameraO.left=-i,this.cameraO.right=i,this.cameraO.top=f,this.cameraO.bottom=-f,this.cameraO.updateProjectionMatrix(),this.near=this.cameraO.near,this.far=this.cameraO.far,this.projectionMatrix=this.cameraO.projectionMatrix,this.inPerspectiveMode=!1,this.inOrthographicMode=!0},e.CombinedCamera.prototype.setSize=function(a,b){this.cameraP.aspect=a/b,this.left=-a/2,this.right=a/2,this.top=b/2,this.bottom=-b/2},e.CombinedCamera.prototype.setFov=function(a){this.fov=a,this.inPerspectiveMode?this.toPerspective():this.toOrthographic()},e.CombinedCamera.prototype.updateProjectionMatrix=function(){this.inPerspectiveMode?this.toPerspective():(this.toPerspective(),this.toOrthographic())},e.CombinedCamera.prototype.setLens=function(a,b){void 0===b&&(b=24);var c=2*e.Math.radToDeg(Math.atan(b/(2*a)));return this.setFov(c),c},e.CombinedCamera.prototype.setZoom=function(a){this.zoom=a,this.inPerspectiveMode?this.toPerspective():this.toOrthographic()},e.CombinedCamera.prototype.toFrontView=function(){this.rotation.x=0,this.rotation.y=0,this.rotation.z=0,this.rotationAutoUpdate=!1},e.CombinedCamera.prototype.toBackView=function(){this.rotation.x=0,this.rotation.y=Math.PI,this.rotation.z=0,this.rotationAutoUpdate=!1},e.CombinedCamera.prototype.toLeftView=function(){this.rotation.x=0,this.rotation.y=-Math.PI/2,this.rotation.z=0,this.rotationAutoUpdate=!1},e.CombinedCamera.prototype.toRightView=function(){this.rotation.x=0,this.rotation.y=Math.PI/2,this.rotation.z=0,this.rotationAutoUpdate=!1},e.CombinedCamera.prototype.toTopView=function(){this.rotation.x=-Math.PI/2,this.rotation.y=0,this.rotation.z=0,this.rotationAutoUpdate=!1},e.CombinedCamera.prototype.toBottomView=function(){this.rotation.x=Math.PI/2,this.rotation.y=0,this.rotation.z=0,this.rotationAutoUpdate=!1},e.BoxGeometry=function(a,b,c,d,f,g){function h(a,b,c,d,f,g,h,j){var k,l,m,n=i.widthSegments,o=i.heightSegments,p=f/2,q=g/2,r=i.vertices.length;"x"===a&&"y"===b||"y"===a&&"x"===b?k="z":"x"===a&&"z"===b||"z"===a&&"x"===b?(k="y",o=i.depthSegments):("z"===a&&"y"===b||"y"===a&&"z"===b)&&(k="x",n=i.depthSegments);var s=n+1,t=o+1,u=f/n,v=g/o,w=new e.Vector3;for(w[k]=h>0?1:-1,m=0;t>m;m++)for(l=0;s>l;l++){var x=new e.Vector3;x[a]=(l*u-p)*c,x[b]=(m*v-q)*d,x[k]=h,i.vertices.push(x)}for(m=0;o>m;m++)for(l=0;n>l;l++){var y=l+s*m,z=l+s*(m+1),A=l+1+s*(m+1),B=l+1+s*m,C=new e.Vector2(l/n,1-m/o),D=new e.Vector2(l/n,1-(m+1)/o),E=new e.Vector2((l+1)/n,1-(m+1)/o),F=new e.Vector2((l+1)/n,1-m/o),G=new e.Face3(y+r,z+r,B+r);G.normal.copy(w),G.vertexNormals.push(w.clone(),w.clone(),w.clone()),G.materialIndex=j,i.faces.push(G),i.faceVertexUvs[0].push([C,D,F]),G=new e.Face3(z+r,A+r,B+r),G.normal.copy(w),G.vertexNormals.push(w.clone(),w.clone(),w.clone()),G.materialIndex=j,i.faces.push(G),i.faceVertexUvs[0].push([D.clone(),E,F.clone()])}}e.Geometry.call(this);var i=this;this.width=a,this.height=b,this.depth=c,this.widthSegments=d||1,this.heightSegments=f||1,this.depthSegments=g||1;var j=this.width/2,k=this.height/2,l=this.depth/2;h("z","y",-1,-1,this.depth,this.height,j,0),h("z","y",1,-1,this.depth,this.height,-j,1),h("x","z",1,1,this.width,this.depth,k,2),h("x","z",1,-1,this.width,this.depth,-k,3),h("x","y",1,-1,this.width,this.height,l,4),h("x","y",-1,-1,this.width,this.height,-l,5),this.computeCentroids(),this.mergeVertices()},e.BoxGeometry.prototype=Object.create(e.Geometry.prototype),e.CircleGeometry=function(a,b,c,d){e.Geometry.call(this),this.radius=a=a||50,this.segments=b=void 0!==b?Math.max(3,b):8,this.thetaStart=c=void 0!==c?c:0,this.thetaLength=d=void 0!==d?d:2*Math.PI;var f,g=[],h=new e.Vector3,i=new e.Vector2(.5,.5);for(this.vertices.push(h),g.push(i),f=0;b>=f;f++){var j=new e.Vector3,k=c+f/b*d;j.x=a*Math.cos(k),j.y=a*Math.sin(k),this.vertices.push(j),g.push(new e.Vector2((j.x/a+1)/2,(j.y/a+1)/2))}var l=new e.Vector3(0,0,1);for(f=1;b>=f;f++){var m=f,n=f+1,o=0;this.faces.push(new e.Face3(m,n,o,[l.clone(),l.clone(),l.clone()])),this.faceVertexUvs[0].push([g[f].clone(),g[f+1].clone(),i.clone()])}this.computeCentroids(),this.computeFaceNormals(),this.boundingSphere=new e.Sphere(new e.Vector3,a)},e.CircleGeometry.prototype=Object.create(e.Geometry.prototype),e.CubeGeometry=e.BoxGeometry,e.CylinderGeometry=function(a,b,c,d,f,g){e.Geometry.call(this),this.radiusTop=a=void 0!==a?a:20,this.radiusBottom=b=void 0!==b?b:20,this.height=c=void 0!==c?c:100,this.radialSegments=d=d||8,this.heightSegments=f=f||1,this.openEnded=g=void 0!==g?g:!1;var h,i,j=c/2,k=[],l=[];for(i=0;f>=i;i++){var m=[],n=[],o=i/f,p=o*(b-a)+a;for(h=0;d>=h;h++){var q=h/d,r=new e.Vector3;r.x=p*Math.sin(q*Math.PI*2),r.y=-o*c+j,r.z=p*Math.cos(q*Math.PI*2),this.vertices.push(r),m.push(this.vertices.length-1),n.push(new e.Vector2(q,1-o))}k.push(m),l.push(n)}var s,t,u=(b-a)/c;for(h=0;d>h;h++)for(0!==a?(s=this.vertices[k[0][h]].clone(),t=this.vertices[k[0][h+1]].clone()):(s=this.vertices[k[1][h]].clone(),t=this.vertices[k[1][h+1]].clone()),s.setY(Math.sqrt(s.x*s.x+s.z*s.z)*u).normalize(),t.setY(Math.sqrt(t.x*t.x+t.z*t.z)*u).normalize(),i=0;f>i;i++){var v=k[i][h],w=k[i+1][h],x=k[i+1][h+1],y=k[i][h+1],z=s.clone(),A=s.clone(),B=t.clone(),C=t.clone(),D=l[i][h].clone(),E=l[i+1][h].clone(),F=l[i+1][h+1].clone(),G=l[i][h+1].clone();this.faces.push(new e.Face3(v,w,y,[z,A,C])),this.faceVertexUvs[0].push([D,E,G]),this.faces.push(new e.Face3(w,x,y,[A.clone(),B,C.clone()])),this.faceVertexUvs[0].push([E.clone(),F,G.clone()])}if(g===!1&&a>0)for(this.vertices.push(new e.Vector3(0,j,0)),h=0;d>h;h++){var v=k[0][h],w=k[0][h+1],x=this.vertices.length-1,z=new e.Vector3(0,1,0),A=new e.Vector3(0,1,0),B=new e.Vector3(0,1,0),D=l[0][h].clone(),E=l[0][h+1].clone(),F=new e.Vector2(E.x,0);this.faces.push(new e.Face3(v,w,x,[z,A,B])),this.faceVertexUvs[0].push([D,E,F])}if(g===!1&&b>0)for(this.vertices.push(new e.Vector3(0,-j,0)),h=0;d>h;h++){var v=k[i][h+1],w=k[i][h],x=this.vertices.length-1,z=new e.Vector3(0,-1,0),A=new e.Vector3(0,-1,0),B=new e.Vector3(0,-1,0),D=l[i][h+1].clone(),E=l[i][h].clone(),F=new e.Vector2(E.x,1);this.faces.push(new e.Face3(v,w,x,[z,A,B])),this.faceVertexUvs[0].push([D,E,F])}this.computeCentroids(),this.computeFaceNormals()},e.CylinderGeometry.prototype=Object.create(e.Geometry.prototype),e.ExtrudeGeometry=function(a,b){return"undefined"==typeof a?void(a=[]):(e.Geometry.call(this),a=a instanceof Array?a:[a],this.shapebb=a[a.length-1].getBoundingBox(),this.addShapeList(a,b),this.computeCentroids(),void this.computeFaceNormals())},e.ExtrudeGeometry.prototype=Object.create(e.Geometry.prototype),e.ExtrudeGeometry.prototype.addShapeList=function(a,b){for(var c=a.length,d=0;c>d;d++){var e=a[d];this.addShape(e,b)}},e.ExtrudeGeometry.prototype.addShape=function(a,b){function c(a,b,c){return b||console.log("die"),b.clone().multiplyScalar(c).add(a)}function d(a,b,c){var d,f,g=1e-10,h=e.Math.sign,i=1,j=a.x-b.x,k=a.y-b.y,l=c.x-a.x,m=c.y-a.y,n=j*j+k*k,o=j*m-k*l;if(Math.abs(o)>g){var p=Math.sqrt(n),q=Math.sqrt(l*l+m*m),r=b.x-k/p,s=b.y+j/p,t=c.x-m/q,u=c.y+l/q,v=((t-r)*m-(u-s)*l)/(j*m-k*l);d=r+j*v-a.x,f=s+k*v-a.y;var w=d*d+f*f;if(2>=w)return new e.Vector2(d,f);i=Math.sqrt(w/2)}else{var x=!1;j>g?l>g&&(x=!0):-g>j?-g>l&&(x=!0):h(k)==h(m)&&(x=!0),x?(d=-k,f=j,i=Math.sqrt(n)):(d=j,f=k,i=Math.sqrt(n/2))}return new e.Vector2(d/i,f/i)}function f(){if(u){var a=0,b=T*a;for(W=0;U>W;W++)S=L[W],j(S[2]+b,S[1]+b,S[0]+b,!0);for(a=w+2*t,b=T*a,W=0;U>W;W++)S=L[W],j(S[0]+b,S[1]+b,S[2]+b,!1)}else{for(W=0;U>W;W++)S=L[W],j(S[2],S[1],S[0],!0);for(W=0;U>W;W++)S=L[W],j(S[0]+T*w,S[1]+T*w,S[2]+T*w,!1)}}function g(){var a=0;for(h(M,a),a+=M.length,D=0,E=J.length;E>D;D++)C=J[D],h(C,a),a+=C.length}function h(a,b){var c,d;for(W=a.length;--W>=0;){c=W,d=W-1,0>d&&(d=a.length-1);var e=0,f=w+2*t;for(e=0;f>e;e++){var g=T*e,h=T*(e+1),i=b+c+g,j=b+d+g,l=b+d+h,m=b+c+h;k(i,j,l,m,a,e,f,c,d)}}}function i(a,b,c){F.vertices.push(new e.Vector3(a,b,c))}function j(c,d,f,g){c+=G,d+=G,f+=G,F.faces.push(new e.Face3(c,d,f,null,null,z));var h=g?B.generateBottomUV(F,a,b,c,d,f):B.generateTopUV(F,a,b,c,d,f);F.faceVertexUvs[0].push(h)}function k(c,d,f,g,h,i,j,k,l){c+=G,d+=G,f+=G,g+=G,F.faces.push(new e.Face3(c,d,g,null,null,A)),F.faces.push(new e.Face3(d,f,g,null,null,A));var m=B.generateSideWallUV(F,a,h,b,c,d,f,g,i,j,k,l);F.faceVertexUvs[0].push([m[0],m[1],m[3]]),F.faceVertexUvs[0].push([m[1],m[2],m[3]])}{var l,m,n,o,p,q=void 0!==b.amount?b.amount:100,r=void 0!==b.bevelThickness?b.bevelThickness:6,s=void 0!==b.bevelSize?b.bevelSize:r-2,t=void 0!==b.bevelSegments?b.bevelSegments:3,u=void 0!==b.bevelEnabled?b.bevelEnabled:!0,v=void 0!==b.curveSegments?b.curveSegments:12,w=void 0!==b.steps?b.steps:1,x=b.extrudePath,y=!1,z=b.material,A=b.extrudeMaterial,B=void 0!==b.UVGenerator?b.UVGenerator:e.ExtrudeGeometry.WorldUVGenerator;this.shapebb}x&&(l=x.getSpacedPoints(w),y=!0,u=!1,m=void 0!==b.frames?b.frames:new e.TubeGeometry.FrenetFrames(x,w,!1),n=new e.Vector3,o=new e.Vector3,p=new e.Vector3),u||(t=0,r=0,s=0);var C,D,E,F=this,G=this.vertices.length,H=a.extractPoints(v),I=H.shape,J=H.holes,K=!e.Shape.Utils.isClockWise(I);if(K){for(I=I.reverse(),D=0,E=J.length;E>D;D++)C=J[D],e.Shape.Utils.isClockWise(C)&&(J[D]=C.reverse());K=!1}var L=e.Shape.Utils.triangulateShape(I,J),M=I;for(D=0,E=J.length;E>D;D++)C=J[D],I=I.concat(C);for(var N,O,P,Q,R,S,T=I.length,U=L.length,V=(M.length,180/Math.PI,[]),W=0,X=M.length,Y=X-1,Z=W+1;X>W;W++,Y++,Z++){Y===X&&(Y=0),Z===X&&(Z=0);{M[W],M[Y],M[Z]}V[W]=d(M[W],M[Y],M[Z])}var $,_=[],ab=V.concat();for(D=0,E=J.length;E>D;D++){for(C=J[D],$=[],W=0,X=C.length,Y=X-1,Z=W+1;X>W;W++,Y++,Z++)Y===X&&(Y=0),Z===X&&(Z=0),$[W]=d(C[W],C[Y],C[Z]);_.push($),ab=ab.concat($)}for(N=0;t>N;N++){for(P=N/t,Q=r*(1-P),O=s*Math.sin(P*Math.PI/2),W=0,X=M.length;X>W;W++)R=c(M[W],V[W],O),i(R.x,R.y,-Q);for(D=0,E=J.length;E>D;D++)for(C=J[D],$=_[D],W=0,X=C.length;X>W;W++)R=c(C[W],$[W],O),i(R.x,R.y,-Q)}for(O=s,W=0;T>W;W++)R=u?c(I[W],ab[W],O):I[W],y?(o.copy(m.normals[0]).multiplyScalar(R.x),n.copy(m.binormals[0]).multiplyScalar(R.y),p.copy(l[0]).add(o).add(n),i(p.x,p.y,p.z)):i(R.x,R.y,0);var bb;for(bb=1;w>=bb;bb++)for(W=0;T>W;W++)R=u?c(I[W],ab[W],O):I[W],y?(o.copy(m.normals[bb]).multiplyScalar(R.x),n.copy(m.binormals[bb]).multiplyScalar(R.y),p.copy(l[bb]).add(o).add(n),i(p.x,p.y,p.z)):i(R.x,R.y,q/w*bb);for(N=t-1;N>=0;N--){for(P=N/t,Q=r*(1-P),O=s*Math.sin(P*Math.PI/2),W=0,X=M.length;X>W;W++)R=c(M[W],V[W],O),i(R.x,R.y,q+Q);for(D=0,E=J.length;E>D;D++)for(C=J[D],$=_[D],W=0,X=C.length;X>W;W++)R=c(C[W],$[W],O),y?i(R.x,R.y+l[w-1].y,l[w-1].x+Q):i(R.x,R.y,q+Q)}f(),g()},e.ExtrudeGeometry.WorldUVGenerator={generateTopUV:function(a,b,c,d,f,g){var h=a.vertices[d].x,i=a.vertices[d].y,j=a.vertices[f].x,k=a.vertices[f].y,l=a.vertices[g].x,m=a.vertices[g].y;return[new e.Vector2(h,i),new e.Vector2(j,k),new e.Vector2(l,m)]},generateBottomUV:function(a,b,c,d,e,f){return this.generateTopUV(a,b,c,d,e,f)},generateSideWallUV:function(a,b,c,d,f,g,h,i){var j=a.vertices[f].x,k=a.vertices[f].y,l=a.vertices[f].z,m=a.vertices[g].x,n=a.vertices[g].y,o=a.vertices[g].z,p=a.vertices[h].x,q=a.vertices[h].y,r=a.vertices[h].z,s=a.vertices[i].x,t=a.vertices[i].y,u=a.vertices[i].z;return Math.abs(k-n)<.01?[new e.Vector2(j,1-l),new e.Vector2(m,1-o),new e.Vector2(p,1-r),new e.Vector2(s,1-u)]:[new e.Vector2(k,1-l),new e.Vector2(n,1-o),new e.Vector2(q,1-r),new e.Vector2(t,1-u)]}},e.ExtrudeGeometry.__v1=new e.Vector2,e.ExtrudeGeometry.__v2=new e.Vector2,e.ExtrudeGeometry.__v3=new e.Vector2,e.ExtrudeGeometry.__v4=new e.Vector2,e.ExtrudeGeometry.__v5=new e.Vector2,e.ExtrudeGeometry.__v6=new e.Vector2,e.ShapeGeometry=function(a,b){e.Geometry.call(this),a instanceof Array==!1&&(a=[a]),this.shapebb=a[a.length-1].getBoundingBox(),this.addShapeList(a,b),this.computeCentroids(),this.computeFaceNormals()},e.ShapeGeometry.prototype=Object.create(e.Geometry.prototype),e.ShapeGeometry.prototype.addShapeList=function(a,b){for(var c=0,d=a.length;d>c;c++)this.addShape(a[c],b);return this},e.ShapeGeometry.prototype.addShape=function(a,b){void 0===b&&(b={});var c,d,f,g=void 0!==b.curveSegments?b.curveSegments:12,h=b.material,i=void 0===b.UVGenerator?e.ExtrudeGeometry.WorldUVGenerator:b.UVGenerator,j=(this.shapebb,this.vertices.length),k=a.extractPoints(g),l=k.shape,m=k.holes,n=!e.Shape.Utils.isClockWise(l);if(n){for(l=l.reverse(),c=0,d=m.length;d>c;c++)f=m[c],e.Shape.Utils.isClockWise(f)&&(m[c]=f.reverse());n=!1}var o=e.Shape.Utils.triangulateShape(l,m),p=l;for(c=0,d=m.length;d>c;c++)f=m[c],l=l.concat(f);{var q,r,s=l.length,t=o.length;p.length}for(c=0;s>c;c++)q=l[c],this.vertices.push(new e.Vector3(q.x,q.y,0));for(c=0;t>c;c++){r=o[c];var u=r[0]+j,v=r[1]+j,w=r[2]+j;this.faces.push(new e.Face3(u,v,w,null,null,h)),this.faceVertexUvs[0].push(i.generateBottomUV(this,a,b,u,v,w))}},e.LatheGeometry=function(a,b,c,d){e.Geometry.call(this),b=b||12,c=c||0,d=d||2*Math.PI;for(var f=1/(a.length-1),g=1/b,h=0,i=b;i>=h;h++)for(var j=c+h*g*d,k=Math.cos(j),l=Math.sin(j),m=0,n=a.length;n>m;m++){var o=a[m],p=new e.Vector3;p.x=k*o.x-l*o.y,p.y=l*o.x+k*o.y,p.z=o.z,this.vertices.push(p)}for(var q=a.length,h=0,i=b;i>h;h++)for(var m=0,n=a.length-1;n>m;m++){var r=m+q*h,s=r,t=r+q,k=r+1+q,u=r+1,v=h*g,w=m*f,x=v+g,y=w+f;this.faces.push(new e.Face3(s,t,u)),this.faceVertexUvs[0].push([new e.Vector2(v,w),new e.Vector2(x,w),new e.Vector2(v,y)]),this.faces.push(new e.Face3(t,k,u)),this.faceVertexUvs[0].push([new e.Vector2(x,w),new e.Vector2(x,y),new e.Vector2(v,y)])}this.mergeVertices(),this.computeCentroids(),this.computeFaceNormals(),this.computeVertexNormals()},e.LatheGeometry.prototype=Object.create(e.Geometry.prototype),e.PlaneGeometry=function(a,b,c,d){e.Geometry.call(this),this.width=a,this.height=b,this.widthSegments=c||1,this.heightSegments=d||1;var f,g,h=a/2,i=b/2,j=this.widthSegments,k=this.heightSegments,l=j+1,m=k+1,n=this.width/j,o=this.height/k,p=new e.Vector3(0,0,1);for(g=0;m>g;g++)for(f=0;l>f;f++){var q=f*n-h,r=g*o-i;this.vertices.push(new e.Vector3(q,-r,0))}for(g=0;k>g;g++)for(f=0;j>f;f++){var s=f+l*g,t=f+l*(g+1),u=f+1+l*(g+1),v=f+1+l*g,w=new e.Vector2(f/j,1-g/k),x=new e.Vector2(f/j,1-(g+1)/k),y=new e.Vector2((f+1)/j,1-(g+1)/k),z=new e.Vector2((f+1)/j,1-g/k),A=new e.Face3(s,t,v);A.normal.copy(p),A.vertexNormals.push(p.clone(),p.clone(),p.clone()),this.faces.push(A),this.faceVertexUvs[0].push([w,x,z]),A=new e.Face3(t,u,v),A.normal.copy(p),A.vertexNormals.push(p.clone(),p.clone(),p.clone()),this.faces.push(A),this.faceVertexUvs[0].push([x.clone(),y,z.clone()])}this.computeCentroids()},e.PlaneGeometry.prototype=Object.create(e.Geometry.prototype),e.RingGeometry=function(a,b,c,d,f,g){e.Geometry.call(this),a=a||0,b=b||50,f=void 0!==f?f:0,g=void 0!==g?g:2*Math.PI,c=void 0!==c?Math.max(3,c):8,d=void 0!==d?Math.max(3,d):8;var h,i,j=[],k=a,l=(b-a)/d;for(h=0;d>=h;h++){for(i=0;c>=i;i++){var m=new e.Vector3,n=f+i/c*g;m.x=k*Math.cos(n),m.y=k*Math.sin(n),this.vertices.push(m),j.push(new e.Vector2((m.x/b+1)/2,(m.y/b+1)/2))}k+=l}var o=new e.Vector3(0,0,1);for(h=0;d>h;h++){var p=h*c;for(i=0;c>=i;i++){var n=i+p,q=n+h,r=n+c+h,s=n+c+1+h;this.faces.push(new e.Face3(q,r,s,[o.clone(),o.clone(),o.clone()])),this.faceVertexUvs[0].push([j[q].clone(),j[r].clone(),j[s].clone()]),q=n+h,r=n+c+1+h,s=n+1+h,this.faces.push(new e.Face3(q,r,s,[o.clone(),o.clone(),o.clone()])),this.faceVertexUvs[0].push([j[q].clone(),j[r].clone(),j[s].clone()])}}this.computeCentroids(),this.computeFaceNormals(),this.boundingSphere=new e.Sphere(new e.Vector3,k)},e.RingGeometry.prototype=Object.create(e.Geometry.prototype),e.SphereGeometry=function(a,b,c,d,f,g,h){e.Geometry.call(this),this.radius=a=a||50,this.widthSegments=b=Math.max(3,Math.floor(b)||8),this.heightSegments=c=Math.max(2,Math.floor(c)||6),this.phiStart=d=void 0!==d?d:0,this.phiLength=f=void 0!==f?f:2*Math.PI,this.thetaStart=g=void 0!==g?g:0,this.thetaLength=h=void 0!==h?h:Math.PI;var i,j,k=[],l=[];for(j=0;c>=j;j++){var m=[],n=[];for(i=0;b>=i;i++){var o=i/b,p=j/c,q=new e.Vector3;q.x=-a*Math.cos(d+o*f)*Math.sin(g+p*h),q.y=a*Math.cos(g+p*h),q.z=a*Math.sin(d+o*f)*Math.sin(g+p*h),this.vertices.push(q),m.push(this.vertices.length-1),n.push(new e.Vector2(o,1-p))}k.push(m),l.push(n)}for(j=0;jp;p++)for(this.grid[p]=[],k=p/(C-1),o=a.getPointAt(k),h=F[p],i=G[p],j=H[p],q=0;q=h&&(g=h,m.set(1,0,0)),g>=i&&(g=i,m.set(0,1,0)),g>=j&&m.set(0,0,1),q.crossVectors(n[0],m).normalize(),o[0].crossVectors(n[0],q),p[0].crossVectors(n[0],o[0])}var f,g,h,i,j,k,l,m=(new e.Vector3,new e.Vector3),n=(new e.Vector3,[]),o=[],p=[],q=new e.Vector3,r=new e.Matrix4,s=b+1,t=1e-4;for(this.tangents=n,this.normals=o,this.binormals=p,k=0;s>k;k++)l=k/(s-1),n[k]=a.getTangentAt(l),n[k].normalize();for(d(),k=1;s>k;k++)o[k]=o[k-1].clone(),p[k]=p[k-1].clone(),q.crossVectors(n[k-1],n[k]),q.length()>t&&(q.normalize(),f=Math.acos(e.Math.clamp(n[k-1].dot(n[k]),-1,1)),o[k].applyMatrix4(r.makeRotationAxis(q,f))),p[k].crossVectors(n[k],o[k]);if(c)for(f=Math.acos(e.Math.clamp(o[0].dot(o[s-1]),-1,1)),f/=s-1,n[0].dot(q.crossVectors(o[0],o[s-1]))>0&&(f=-f),k=1;s>k;k++)o[k].applyMatrix4(r.makeRotationAxis(n[k],f*k)),p[k].crossVectors(n[k],o[k])},e.PolyhedronGeometry=function(a,b,c,d){function f(a){var b=a.normalize().clone();b.index=l.vertices.push(b)-1;var c=i(a)/2/Math.PI+.5,d=j(a)/Math.PI+.5;return b.uv=new e.Vector2(c,1-d),b}function g(a,b,c){var d=new e.Face3(a.index,b.index,c.index,[a.clone(),b.clone(),c.clone()]);d.centroid.add(a).add(b).add(c).divideScalar(3),l.faces.push(d);var f=i(d.centroid);l.faceVertexUvs[0].push([k(a.uv,a,f),k(b.uv,b,f),k(c.uv,c,f)])}function h(a,b){for(var c=Math.pow(2,b),d=(Math.pow(4,b),f(l.vertices[a.a])),e=f(l.vertices[a.b]),h=f(l.vertices[a.c]),i=[],j=0;c>=j;j++){i[j]=[];for(var k=f(d.clone().lerp(h,j/c)),m=f(e.clone().lerp(h,j/c)),n=c-j,o=0;n>=o;o++)i[j][o]=0==o&&j==c?k:f(k.clone().lerp(m,o/n))}for(var j=0;c>j;j++)for(var o=0;2*(c-j)-1>o;o++){var p=Math.floor(o/2);o%2==0?g(i[j][p+1],i[j+1][p],i[j][p]):g(i[j][p+1],i[j+1][p+1],i[j+1][p])}}function i(a){return Math.atan2(a.z,-a.x)}function j(a){return Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))}function k(a,b,c){return 0>c&&1===a.x&&(a=new e.Vector2(a.x-1,a.y)),0===b.x&&0===b.z&&(a=new e.Vector2(c/2/Math.PI+.5,a.y)),a.clone()}e.Geometry.call(this),c=c||1,d=d||0;for(var l=this,m=0,n=a.length;n>m;m++)f(new e.Vector3(a[m][0],a[m][1],a[m][2]));for(var o=this.vertices,p=[],m=0,n=b.length;n>m;m++){var q=o[b[m][0]],r=o[b[m][1]],s=o[b[m][2]];p[m]=new e.Face3(q.index,r.index,s.index,[q.clone(),r.clone(),s.clone()])}for(var m=0,n=p.length;n>m;m++)h(p[m],d);for(var m=0,n=this.faceVertexUvs[0].length;n>m;m++){var t=this.faceVertexUvs[0][m],u=t[0].x,v=t[1].x,w=t[2].x,x=Math.max(u,Math.max(v,w)),y=Math.min(u,Math.min(v,w));x>.9&&.1>y&&(.2>u&&(t[0].x+=1),.2>v&&(t[1].x+=1),.2>w&&(t[2].x+=1))}for(var m=0,n=this.vertices.length;n>m;m++)this.vertices[m].multiplyScalar(c);this.mergeVertices(),this.computeCentroids(),this.computeFaceNormals(),this.boundingSphere=new e.Sphere(new e.Vector3,c)},e.PolyhedronGeometry.prototype=Object.create(e.Geometry.prototype),e.IcosahedronGeometry=function(a,b){this.radius=a,this.detail=b;var c=(1+Math.sqrt(5))/2,d=[[-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]],f=[[0,11,5],[0,5,1],[0,1,7],[0,7,10],[0,10,11],[1,5,9],[5,11,4],[11,10,2],[10,7,6],[7,1,8],[3,9,4],[3,4,2],[3,2,6],[3,6,8],[3,8,9],[4,9,5],[2,4,11],[6,2,10],[8,6,7],[9,8,1]];e.PolyhedronGeometry.call(this,d,f,a,b)},e.IcosahedronGeometry.prototype=Object.create(e.Geometry.prototype),e.OctahedronGeometry=function(a,b){var c=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]],d=[[0,2,4],[0,4,3],[0,3,5],[0,5,2],[1,2,5],[1,5,3],[1,3,4],[1,4,2]];e.PolyhedronGeometry.call(this,c,d,a,b)},e.OctahedronGeometry.prototype=Object.create(e.Geometry.prototype),e.TetrahedronGeometry=function(a,b){var c=[[1,1,1],[-1,-1,1],[-1,1,-1],[1,-1,-1]],d=[[2,1,0],[0,3,2],[1,3,0],[2,3,1]];e.PolyhedronGeometry.call(this,c,d,a,b)},e.TetrahedronGeometry.prototype=Object.create(e.Geometry.prototype),e.ParametricGeometry=function(a,b,c){e.Geometry.call(this);var d,f,g,h,i,j=this.vertices,k=this.faces,l=this.faceVertexUvs[0],m=b+1;for(d=0;c>=d;d++)for(i=d/c,f=0;b>=f;f++)h=f/b,g=a(h,i),j.push(g);var n,o,p,q,r,s,t,u;for(d=0;c>d;d++)for(f=0;b>f;f++)n=d*m+f,o=d*m+f+1,p=(d+1)*m+f+1,q=(d+1)*m+f,r=new e.Vector2(f/b,d/c),s=new e.Vector2((f+1)/b,d/c),t=new e.Vector2((f+1)/b,(d+1)/c),u=new e.Vector2(f/b,(d+1)/c),k.push(new e.Face3(n,o,q)),l.push([r,s,u]),k.push(new e.Face3(o,p,q)),l.push([s.clone(),t,u.clone()]);this.computeCentroids(),this.computeFaceNormals(),this.computeVertexNormals()},e.ParametricGeometry.prototype=Object.create(e.Geometry.prototype),e.AxisHelper=function(a){a=a||1;var b=new e.Geometry;b.vertices.push(new e.Vector3,new e.Vector3(a,0,0),new e.Vector3,new e.Vector3(0,a,0),new e.Vector3,new e.Vector3(0,0,a)),b.colors.push(new e.Color(16711680),new e.Color(16755200),new e.Color(65280),new e.Color(11206400),new e.Color(255),new e.Color(43775));var c=new e.LineBasicMaterial({vertexColors:e.VertexColors});e.Line.call(this,b,c,e.LinePieces)},e.AxisHelper.prototype=Object.create(e.Line.prototype),e.ArrowHelper=function(a,b,c,d,f,g){e.Object3D.call(this),void 0===d&&(d=16776960),void 0===c&&(c=1),void 0===f&&(f=.2*c),void 0===g&&(g=.2*f),this.position=b;var h=new e.Geometry;h.vertices.push(new e.Vector3(0,0,0)),h.vertices.push(new e.Vector3(0,1,0)),this.line=new e.Line(h,new e.LineBasicMaterial({color:d})),this.line.matrixAutoUpdate=!1,this.add(this.line);var i=new e.CylinderGeometry(0,.5,1,5,1);i.applyMatrix((new e.Matrix4).makeTranslation(0,-.5,0)),this.cone=new e.Mesh(i,new e.MeshBasicMaterial({color:d})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(a),this.setLength(c,f,g)},e.ArrowHelper.prototype=Object.create(e.Object3D.prototype),e.ArrowHelper.prototype.setDirection=function(){var a,b=new e.Vector3;return function(c){c.y>.99999?this.quaternion.set(0,0,0,1):c.y<-.99999?this.quaternion.set(1,0,0,0):(b.set(c.z,0,-c.x).normalize(),a=Math.acos(c.y),this.quaternion.setFromAxisAngle(b,a))}}(),e.ArrowHelper.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a),void 0===c&&(c=.2*b),this.line.scale.set(1,a,1),this.line.updateMatrix(),this.cone.scale.set(c,b,c),this.cone.position.y=a,this.cone.updateMatrix()},e.ArrowHelper.prototype.setColor=function(a){this.line.material.color.setHex(a),this.cone.material.color.setHex(a)},e.BoxHelper=function(a){var b=[new e.Vector3(1,1,1),new e.Vector3(-1,1,1),new e.Vector3(-1,-1,1),new e.Vector3(1,-1,1),new e.Vector3(1,1,-1),new e.Vector3(-1,1,-1),new e.Vector3(-1,-1,-1),new e.Vector3(1,-1,-1)];this.vertices=b;var c=new e.Geometry;c.vertices.push(b[0],b[1],b[1],b[2],b[2],b[3],b[3],b[0],b[4],b[5],b[5],b[6],b[6],b[7],b[7],b[4],b[0],b[4],b[1],b[5],b[2],b[6],b[3],b[7]),e.Line.call(this,c,new e.LineBasicMaterial({color:16776960}),e.LinePieces),void 0!==a&&this.update(a)},e.BoxHelper.prototype=Object.create(e.Line.prototype),e.BoxHelper.prototype.update=function(a){var b=a.geometry;null===b.boundingBox&&b.computeBoundingBox();var c=b.boundingBox.min,d=b.boundingBox.max,e=this.vertices;e[0].set(d.x,d.y,d.z),e[1].set(c.x,d.y,d.z),e[2].set(c.x,c.y,d.z),e[3].set(d.x,c.y,d.z),e[4].set(d.x,d.y,c.z),e[5].set(c.x,d.y,c.z),e[6].set(c.x,c.y,c.z),e[7].set(d.x,c.y,c.z),this.geometry.computeBoundingSphere(),this.geometry.verticesNeedUpdate=!0,this.matrixAutoUpdate=!1,this.matrixWorld=a.matrixWorld},e.BoundingBoxHelper=function(a,b){var c=void 0!==b?b:8947848;this.object=a,this.box=new e.Box3,e.Mesh.call(this,new e.BoxGeometry(1,1,1),new e.MeshBasicMaterial({color:c,wireframe:!0}))},e.BoundingBoxHelper.prototype=Object.create(e.Mesh.prototype),e.BoundingBoxHelper.prototype.update=function(){this.box.setFromObject(this.object),this.box.size(this.scale),this.box.center(this.position)},e.CameraHelper=function(a){function b(a,b,d){c(a,d),c(b,d)}function c(a,b){d.vertices.push(new e.Vector3),d.colors.push(new e.Color(b)),void 0===g[a]&&(g[a]=[]),g[a].push(d.vertices.length-1)}var d=new e.Geometry,f=new e.LineBasicMaterial({color:16777215,vertexColors:e.FaceColors}),g={},h=16755200,i=16711680,j=43775,k=16777215,l=3355443;b("n1","n2",h),b("n2","n4",h),b("n4","n3",h),b("n3","n1",h),b("f1","f2",h),b("f2","f4",h),b("f4","f3",h),b("f3","f1",h),b("n1","f1",h),b("n2","f2",h),b("n3","f3",h),b("n4","f4",h),b("p","n1",i),b("p","n2",i),b("p","n3",i),b("p","n4",i),b("u1","u2",j),b("u2","u3",j),b("u3","u1",j),b("c","t",k),b("p","c",l),b("cn1","cn2",l),b("cn3","cn4",l),b("cf1","cf2",l),b("cf3","cf4",l),e.Line.call(this,d,f,e.LinePieces),this.camera=a,this.matrixWorld=a.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=g,this.update()},e.CameraHelper.prototype=Object.create(e.Line.prototype),e.CameraHelper.prototype.update=function(){var a=new e.Vector3,b=new e.Camera,c=new e.Projector;return function(){function d(d,f,g,h){a.set(f,g,h),c.unprojectVector(a,b);var i=e.pointMap[d];if(void 0!==i)for(var j=0,k=i.length;k>j;j++)e.geometry.vertices[i[j]].copy(a)}var e=this,f=1,g=1;b.projectionMatrix.copy(this.camera.projectionMatrix),d("c",0,0,-1),d("t",0,0,1),d("n1",-f,-g,-1),d("n2",f,-g,-1),d("n3",-f,g,-1),d("n4",f,g,-1),d("f1",-f,-g,1),d("f2",f,-g,1),d("f3",-f,g,1),d("f4",f,g,1),d("u1",.7*f,1.1*g,-1),d("u2",.7*-f,1.1*g,-1),d("u3",0,2*g,-1),d("cf1",-f,0,1),d("cf2",f,0,1),d("cf3",0,-g,1),d("cf4",0,g,1),d("cn1",-f,0,-1),d("cn2",f,0,-1),d("cn3",0,-g,-1),d("cn4",0,g,-1),this.geometry.verticesNeedUpdate=!0}}(),e.DirectionalLightHelper=function(a,b){e.Object3D.call(this),this.light=a,this.light.updateMatrixWorld(),this.matrixWorld=a.matrixWorld,this.matrixAutoUpdate=!1,b=b||1;var c=new e.PlaneGeometry(b,b),d=new e.MeshBasicMaterial({wireframe:!0,fog:!1});d.color.copy(this.light.color).multiplyScalar(this.light.intensity),this.lightPlane=new e.Mesh(c,d),this.add(this.lightPlane),c=new e.Geometry,c.vertices.push(new e.Vector3),c.vertices.push(new e.Vector3),d=new e.LineBasicMaterial({fog:!1}),d.color.copy(this.light.color).multiplyScalar(this.light.intensity),this.targetLine=new e.Line(c,d),this.add(this.targetLine),this.update()},e.DirectionalLightHelper.prototype=Object.create(e.Object3D.prototype),e.DirectionalLightHelper.prototype.dispose=function(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()},e.DirectionalLightHelper.prototype.update=function(){var a=new e.Vector3,b=new e.Vector3,c=new e.Vector3;return function(){a.setFromMatrixPosition(this.light.matrixWorld),b.setFromMatrixPosition(this.light.target.matrixWorld),c.subVectors(b,a),this.lightPlane.lookAt(c),this.lightPlane.material.color.copy(this.light.color).multiplyScalar(this.light.intensity),this.targetLine.geometry.vertices[1].copy(c),this.targetLine.geometry.verticesNeedUpdate=!0,this.targetLine.material.color.copy(this.lightPlane.material.color)}}(),e.EdgesHelper=function(a,b){var c=void 0!==b?b:16777215,d=[0,0],f={},g=function(a,b){return a-b},h=["a","b","c"],i=new e.BufferGeometry,j=a.geometry.clone();j.mergeVertices(),j.computeFaceNormals();for(var k=j.vertices,l=j.faces,m=0,n=0,o=l.length;o>n;n++)for(var p=l[n],q=0;3>q;q++){d[0]=p[h[q]],d[1]=p[h[(q+1)%3]],d.sort(g);var r=d.toString();void 0===f[r]?(f[r]={vert1:d[0],vert2:d[1],face1:n,face2:void 0},m++):f[r].face2=n}i.addAttribute("position",Float32Array,2*m,3);var s=i.attributes.position.array,t=0;for(var r in f){var u=f[r];if(void 0===u.face2||l[u.face1].normal.dot(l[u.face2].normal)<.9999){var v=k[u.vert1];s[t++]=v.x,s[t++]=v.y,s[t++]=v.z,v=k[u.vert2],s[t++]=v.x,s[t++]=v.y,s[t++]=v.z}}e.Line.call(this,i,new e.LineBasicMaterial({color:c}),e.LinePieces),this.matrixAutoUpdate=!1,this.matrixWorld=a.matrixWorld},e.EdgesHelper.prototype=Object.create(e.Line.prototype),e.FaceNormalsHelper=function(a,b,c,d){this.object=a,this.size=void 0!==b?b:1;for(var f=void 0!==c?c:16776960,g=void 0!==d?d:1,h=new e.Geometry,i=this.object.geometry.faces,j=0,k=i.length;k>j;j++)h.vertices.push(new e.Vector3),h.vertices.push(new e.Vector3);e.Line.call(this,h,new e.LineBasicMaterial({color:f,linewidth:g}),e.LinePieces),this.matrixAutoUpdate=!1,this.normalMatrix=new e.Matrix3,this.update()},e.FaceNormalsHelper.prototype=Object.create(e.Line.prototype),e.FaceNormalsHelper.prototype.update=function(){var a=new e.Vector3;return function(){this.object.updateMatrixWorld(!0),this.normalMatrix.getNormalMatrix(this.object.matrixWorld);for(var b=this.geometry.vertices,c=this.object.geometry.faces,d=this.object.matrixWorld,e=0,f=c.length;f>e;e++){var g=c[e];a.copy(g.normal).applyMatrix3(this.normalMatrix).normalize().multiplyScalar(this.size);var h=2*e;b[h].copy(g.centroid).applyMatrix4(d),b[h+1].addVectors(b[h],a)}return this.geometry.verticesNeedUpdate=!0,this}}(),e.GridHelper=function(a,b){var c=new e.Geometry,d=new e.LineBasicMaterial({vertexColors:e.VertexColors});this.color1=new e.Color(4473924),this.color2=new e.Color(8947848);for(var f=-a;a>=f;f+=b){c.vertices.push(new e.Vector3(-a,0,f),new e.Vector3(a,0,f),new e.Vector3(f,0,-a),new e.Vector3(f,0,a));var g=0===f?this.color1:this.color2;c.colors.push(g,g,g,g)}e.Line.call(this,c,d,e.LinePieces)},e.GridHelper.prototype=Object.create(e.Line.prototype),e.GridHelper.prototype.setColors=function(a,b){this.color1.set(a),this.color2.set(b),this.geometry.colorsNeedUpdate=!0},e.HemisphereLightHelper=function(a,b){e.Object3D.call(this),this.light=a,this.light.updateMatrixWorld(),this.matrixWorld=a.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new e.Color,new e.Color];var c=new e.SphereGeometry(b,4,2);c.applyMatrix((new e.Matrix4).makeRotationX(-Math.PI/2));for(var d=0,f=8;f>d;d++)c.faces[d].color=this.colors[4>d?0:1];var g=new e.MeshBasicMaterial({vertexColors:e.FaceColors,wireframe:!0});this.lightSphere=new e.Mesh(c,g),this.add(this.lightSphere),this.update()},e.HemisphereLightHelper.prototype=Object.create(e.Object3D.prototype),e.HemisphereLightHelper.prototype.dispose=function(){this.lightSphere.geometry.dispose(),this.lightSphere.material.dispose()},e.HemisphereLightHelper.prototype.update=function(){var a=new e.Vector3;return function(){this.colors[0].copy(this.light.color).multiplyScalar(this.light.intensity),this.colors[1].copy(this.light.groundColor).multiplyScalar(this.light.intensity),this.lightSphere.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate()),this.lightSphere.geometry.colorsNeedUpdate=!0}}(),e.PointLightHelper=function(a,b){this.light=a,this.light.updateMatrixWorld();var c=new e.SphereGeometry(b,4,2),d=new e.MeshBasicMaterial({wireframe:!0,fog:!1});d.color.copy(this.light.color).multiplyScalar(this.light.intensity),e.Mesh.call(this,c,d),this.matrixWorld=this.light.matrixWorld,this.matrixAutoUpdate=!1},e.PointLightHelper.prototype=Object.create(e.Mesh.prototype),e.PointLightHelper.prototype.dispose=function(){this.geometry.dispose(),this.material.dispose()},e.PointLightHelper.prototype.update=function(){this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)},e.SpotLightHelper=function(a){e.Object3D.call(this),this.light=a,this.light.updateMatrixWorld(),this.matrixWorld=a.matrixWorld,this.matrixAutoUpdate=!1;var b=new e.CylinderGeometry(0,1,1,8,1,!0);b.applyMatrix((new e.Matrix4).makeTranslation(0,-.5,0)),b.applyMatrix((new e.Matrix4).makeRotationX(-Math.PI/2));var c=new e.MeshBasicMaterial({wireframe:!0,fog:!1});this.cone=new e.Mesh(b,c),this.add(this.cone),this.update()},e.SpotLightHelper.prototype=Object.create(e.Object3D.prototype),e.SpotLightHelper.prototype.dispose=function(){this.cone.geometry.dispose(),this.cone.material.dispose()},e.SpotLightHelper.prototype.update=function(){var a=new e.Vector3,b=new e.Vector3;return function(){var c=this.light.distance?this.light.distance:1e4,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c),a.setFromMatrixPosition(this.light.matrixWorld),b.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(b.sub(a)),this.cone.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}}(),e.VertexNormalsHelper=function(a,b,c,d){this.object=a,this.size=void 0!==b?b:1;for(var f=void 0!==c?c:16711680,g=void 0!==d?d:1,h=new e.Geometry,i=(a.geometry.vertices,a.geometry.faces),j=0,k=i.length;k>j;j++)for(var l=i[j],m=0,n=l.vertexNormals.length;n>m;m++)h.vertices.push(new e.Vector3),h.vertices.push(new e.Vector3);e.Line.call(this,h,new e.LineBasicMaterial({color:f,linewidth:g}),e.LinePieces),this.matrixAutoUpdate=!1,this.normalMatrix=new e.Matrix3,this.update()},e.VertexNormalsHelper.prototype=Object.create(e.Line.prototype),e.VertexNormalsHelper.prototype.update=function(){var a=new e.Vector3;return function(){var b=["a","b","c","d"];this.object.updateMatrixWorld(!0),this.normalMatrix.getNormalMatrix(this.object.matrixWorld);for(var c=this.geometry.vertices,d=this.object.geometry.vertices,e=this.object.geometry.faces,f=this.object.matrixWorld,g=0,h=0,i=e.length;i>h;h++)for(var j=e[h],k=0,l=j.vertexNormals.length;l>k;k++){var m=j[b[k]],n=d[m],o=j.vertexNormals[k];c[g].copy(n).applyMatrix4(f),a.copy(o).applyMatrix3(this.normalMatrix).normalize().multiplyScalar(this.size),a.add(c[g]),g+=1,c[g].copy(a),g+=1}return this.geometry.verticesNeedUpdate=!0,this}}(),e.VertexTangentsHelper=function(a,b,c,d){this.object=a,this.size=void 0!==b?b:1;for(var f=void 0!==c?c:255,g=void 0!==d?d:1,h=new e.Geometry,i=(a.geometry.vertices,a.geometry.faces),j=0,k=i.length;k>j;j++)for(var l=i[j],m=0,n=l.vertexTangents.length;n>m;m++)h.vertices.push(new e.Vector3),h.vertices.push(new e.Vector3);e.Line.call(this,h,new e.LineBasicMaterial({color:f,linewidth:g}),e.LinePieces),this.matrixAutoUpdate=!1,this.update()},e.VertexTangentsHelper.prototype=Object.create(e.Line.prototype),e.VertexTangentsHelper.prototype.update=function(){var a=new e.Vector3;return function(){var b=["a","b","c","d"];this.object.updateMatrixWorld(!0);for(var c=this.geometry.vertices,d=this.object.geometry.vertices,e=this.object.geometry.faces,f=this.object.matrixWorld,g=0,h=0,i=e.length;i>h;h++)for(var j=e[h],k=0,l=j.vertexTangents.length;l>k;k++){var m=j[b[k]],n=d[m],o=j.vertexTangents[k];c[g].copy(n).applyMatrix4(f),a.copy(o).transformDirection(f).multiplyScalar(this.size),a.add(c[g]),g+=1,c[g].copy(a),g+=1}return this.geometry.verticesNeedUpdate=!0,this}}(),e.WireframeHelper=function(a,b){var c=void 0!==b?b:16777215,d=[0,0],f={},g=function(a,b){return a-b},h=["a","b","c"],i=new e.BufferGeometry;if(a.geometry instanceof e.Geometry){for(var j=a.geometry.vertices,k=a.geometry.faces,l=0,m=new Uint32Array(6*k.length),n=0,o=k.length;o>n;n++)for(var p=k[n],q=0;3>q;q++){d[0]=p[h[q]],d[1]=p[h[(q+1)%3]],d.sort(g);var r=d.toString();void 0===f[r]&&(m[2*l]=d[0],m[2*l+1]=d[1],f[r]=!0,l++)}i.addAttribute("position",Float32Array,2*l,3);for(var s=i.attributes.position.array,n=0,o=l;o>n;n++)for(var q=0;2>q;q++){var t=j[m[2*n+q]],u=6*n+3*q;s[u+0]=t.x,s[u+1]=t.y,s[u+2]=t.z}}else if(a.geometry instanceof e.BufferGeometry&&void 0!==a.geometry.attributes.index){for(var j=a.geometry.attributes.position.array,v=a.geometry.attributes.index.array,w=a.geometry.offsets,l=0,m=new Uint32Array(2*v.length),x=0,y=w.length;y>x;++x)for(var z=w[x].start,A=w[x].count,u=w[x].index,n=z,B=z+A;B>n;n+=3)for(var q=0;3>q;q++){d[0]=u+v[n+q],d[1]=u+v[n+(q+1)%3],d.sort(g);var r=d.toString();void 0===f[r]&&(m[2*l]=d[0],m[2*l+1]=d[1],f[r]=!0,l++)}i.addAttribute("position",Float32Array,2*l,3);for(var s=i.attributes.position.array,n=0,o=l;o>n;n++)for(var q=0;2>q;q++){var u=6*n+3*q,C=3*m[2*n+q];s[u+0]=j[C],s[u+1]=j[C+1],s[u+2]=j[C+2]}}else if(a.geometry instanceof e.BufferGeometry){var j=a.geometry.attributes.position.array,l=j.length/3,D=l/3;i.addAttribute("position",Float32Array,2*l,3);for(var s=i.attributes.position.array,n=0,o=D;o>n;n++)for(var q=0;3>q;q++){var u=18*n+6*q,E=9*n+3*q;s[u+0]=j[E],s[u+1]=j[E+1],s[u+2]=j[E+2];var C=9*n+3*((q+1)%3);s[u+3]=j[C],s[u+4]=j[C+1],s[u+5]=j[C+2]}}e.Line.call(this,i,new e.LineBasicMaterial({color:c}),e.LinePieces),this.matrixAutoUpdate=!1,this.matrixWorld=a.matrixWorld},e.WireframeHelper.prototype=Object.create(e.Line.prototype),e.ImmediateRenderObject=function(){e.Object3D.call(this),this.render=function(){}},e.ImmediateRenderObject.prototype=Object.create(e.Object3D.prototype),e.LensFlare=function(a,b,c,d,f){e.Object3D.call(this),this.lensFlares=[],this.positionScreen=new e.Vector3,this.customUpdateCallback=void 0,void 0!==a&&this.add(a,b,c,d,f)},e.LensFlare.prototype=Object.create(e.Object3D.prototype),e.LensFlare.prototype.add=function(a,b,c,d,f,g){void 0===b&&(b=-1),void 0===c&&(c=0),void 0===g&&(g=1),void 0===f&&(f=new e.Color(16777215)),void 0===d&&(d=e.NormalBlending),c=Math.min(c,Math.max(0,c)),this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:1,opacity:g,color:f,blending:d})},e.LensFlare.prototype.updateLensFlares=function(){var a,b,c=this.lensFlares.length,d=2*-this.positionScreen.x,e=2*-this.positionScreen.y;for(a=0;c>a;a++)b=this.lensFlares[a],b.x=this.positionScreen.x+d*b.distance,b.y=this.positionScreen.y+e*b.distance,b.wantedRotation=b.x*Math.PI*.25,b.rotation+=.25*(b.wantedRotation-b.rotation)},e.MorphBlendMesh=function(a,b){e.Mesh.call(this,a,b),this.animationsMap={},this.animationsList=[];var c=this.geometry.morphTargets.length,d="__default",f=0,g=c-1,h=c/1;this.createAnimation(d,f,g,h),this.setAnimationWeight(d,1)},e.MorphBlendMesh.prototype=Object.create(e.Mesh.prototype),e.MorphBlendMesh.prototype.createAnimation=function(a,b,c,d){var e={startFrame:b,endFrame:c,length:c-b+1,fps:d,duration:(c-b)/d,lastFrame:0,currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[a]=e,this.animationsList.push(e)},e.MorphBlendMesh.prototype.autoCreateAnimations=function(a){for(var b,c=/([a-z]+)(\d+)/,d={},e=this.geometry,f=0,g=e.morphTargets.length;g>f;f++){var h=e.morphTargets[f],i=h.name.match(c);if(i&&i.length>1){{var j=i[1];i[2]}d[j]||(d[j]={start:1/0,end:-1/0});var k=d[j];fk.end&&(k.end=f),b||(b=j)}}for(var j in d){var k=d[j];this.createAnimation(j,k.start,k.end,a)}this.firstAnimation=b},e.MorphBlendMesh.prototype.setAnimationDirectionForward=function(a){var b=this.animationsMap[a];b&&(b.direction=1,b.directionBackwards=!1)},e.MorphBlendMesh.prototype.setAnimationDirectionBackward=function(a){var b=this.animationsMap[a];b&&(b.direction=-1,b.directionBackwards=!0)},e.MorphBlendMesh.prototype.setAnimationFPS=function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)},e.MorphBlendMesh.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)},e.MorphBlendMesh.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)},e.MorphBlendMesh.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)},e.MorphBlendMesh.prototype.getAnimationTime=function(a){var b=0,c=this.animationsMap[a];return c&&(b=c.time),b},e.MorphBlendMesh.prototype.getAnimationDuration=function(a){var b=-1,c=this.animationsMap[a];return c&&(b=c.duration),b},e.MorphBlendMesh.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("animation["+a+"] undefined")},e.MorphBlendMesh.prototype.stopAnimation=function(a){var b=this.animationsMap[a];b&&(b.active=!1)},e.MorphBlendMesh.prototype.update=function(a){for(var b=0,c=this.animationsList.length;c>b;b++){var d=this.animationsList[b];if(d.active){var f=d.duration/d.length;d.time+=d.direction*a,d.mirroredLoop?(d.time>d.duration||d.time<0)&&(d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),d.time<0&&(d.time=0,d.directionBackwards=!1)):(d.time=d.time%d.duration,d.time<0&&(d.time+=d.duration));var g=d.startFrame+e.Math.clamp(Math.floor(d.time/f),0,d.length-1),h=d.weight;g!==d.currentFrame&&(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*h,this.morphTargetInfluences[g]=0,d.lastFrame=d.currentFrame,d.currentFrame=g);var i=d.time%f/f;d.directionBackwards&&(i=1-i),this.morphTargetInfluences[d.currentFrame]=i*h,this.morphTargetInfluences[d.lastFrame]=(1-i)*h}}},e.LensFlarePlugin=function(){function a(a,c){var d=b.createProgram(),e=b.createShader(b.FRAGMENT_SHADER),f=b.createShader(b.VERTEX_SHADER),g="precision "+c+" float;\n";return b.shaderSource(e,g+a.fragmentShader),b.shaderSource(f,g+a.vertexShader),b.compileShader(e),b.compileShader(f),b.attachShader(d,e),b.attachShader(d,f),b.linkProgram(d),d}var b,c,d,f={};this.init=function(g){b=g.context,c=g,d=g.getPrecision(),f.vertices=new Float32Array(16),f.faces=new Uint16Array(6);var h=0;f.vertices[h++]=-1,f.vertices[h++]=-1,f.vertices[h++]=0,f.vertices[h++]=0,f.vertices[h++]=1,f.vertices[h++]=-1,f.vertices[h++]=1,f.vertices[h++]=0,f.vertices[h++]=1,f.vertices[h++]=1,f.vertices[h++]=1,f.vertices[h++]=1,f.vertices[h++]=-1,f.vertices[h++]=1,f.vertices[h++]=0,f.vertices[h++]=1,h=0,f.faces[h++]=0,f.faces[h++]=1,f.faces[h++]=2,f.faces[h++]=0,f.faces[h++]=2,f.faces[h++]=3,f.vertexBuffer=b.createBuffer(),f.elementBuffer=b.createBuffer(),b.bindBuffer(b.ARRAY_BUFFER,f.vertexBuffer),b.bufferData(b.ARRAY_BUFFER,f.vertices,b.STATIC_DRAW),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,f.elementBuffer),b.bufferData(b.ELEMENT_ARRAY_BUFFER,f.faces,b.STATIC_DRAW),f.tempTexture=b.createTexture(),f.occlusionTexture=b.createTexture(),b.bindTexture(b.TEXTURE_2D,f.tempTexture),b.texImage2D(b.TEXTURE_2D,0,b.RGB,16,16,0,b.RGB,b.UNSIGNED_BYTE,null),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST),b.bindTexture(b.TEXTURE_2D,f.occlusionTexture),b.texImage2D(b.TEXTURE_2D,0,b.RGBA,16,16,0,b.RGBA,b.UNSIGNED_BYTE,null),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST),b.getParameter(b.MAX_VERTEX_TEXTURE_IMAGE_UNITS)<=0?(f.hasVertexTexture=!1,f.program=a(e.ShaderFlares.lensFlare,d)):(f.hasVertexTexture=!0,f.program=a(e.ShaderFlares.lensFlareVertexTexture,d)),f.attributes={},f.uniforms={},f.attributes.vertex=b.getAttribLocation(f.program,"position"),f.attributes.uv=b.getAttribLocation(f.program,"uv"),f.uniforms.renderType=b.getUniformLocation(f.program,"renderType"),f.uniforms.map=b.getUniformLocation(f.program,"map"),f.uniforms.occlusionMap=b.getUniformLocation(f.program,"occlusionMap"),f.uniforms.opacity=b.getUniformLocation(f.program,"opacity"),f.uniforms.color=b.getUniformLocation(f.program,"color"),f.uniforms.scale=b.getUniformLocation(f.program,"scale"),f.uniforms.rotation=b.getUniformLocation(f.program,"rotation"),f.uniforms.screenPosition=b.getUniformLocation(f.program,"screenPosition")},this.render=function(a,d,g,h){var i=a.__webglFlares,j=i.length;if(j){var k=new e.Vector3,l=h/g,m=.5*g,n=.5*h,o=16/h,p=new e.Vector2(o*l,o),q=new e.Vector3(1,1,0),r=new e.Vector2(1,1),s=f.uniforms,t=f.attributes;b.useProgram(f.program),b.enableVertexAttribArray(f.attributes.vertex),b.enableVertexAttribArray(f.attributes.uv),b.uniform1i(s.occlusionMap,0),b.uniform1i(s.map,1),b.bindBuffer(b.ARRAY_BUFFER,f.vertexBuffer),b.vertexAttribPointer(t.vertex,2,b.FLOAT,!1,16,0),b.vertexAttribPointer(t.uv,2,b.FLOAT,!1,16,8),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,f.elementBuffer),b.disable(b.CULL_FACE),b.depthMask(!1);var u,v,w,x,y;for(u=0;j>u;u++)if(o=16/h,p.set(o*l,o),x=i[u],k.set(x.matrixWorld.elements[12],x.matrixWorld.elements[13],x.matrixWorld.elements[14]),k.applyMatrix4(d.matrixWorldInverse),k.applyProjection(d.projectionMatrix),q.copy(k),r.x=q.x*m+m,r.y=q.y*n+n,f.hasVertexTexture||r.x>0&&r.x0&&r.yv;v++)y=x.lensFlares[v],y.opacity>.001&&y.scale>.001&&(q.x=y.x,q.y=y.y,q.z=y.z,o=y.size*y.scale/h,p.x=o*l,p.y=o,b.uniform3f(s.screenPosition,q.x,q.y,q.z),b.uniform2f(s.scale,p.x,p.y),b.uniform1f(s.rotation,y.rotation),b.uniform1f(s.opacity,y.opacity),b.uniform3f(s.color,y.color.r,y.color.g,y.color.b),c.setBlending(y.blending,y.blendEquation,y.blendSrc,y.blendDst),c.setTexture(y.texture,1),b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0)); -b.enable(b.CULL_FACE),b.enable(b.DEPTH_TEST),b.depthMask(!0)}}},e.ShadowMapPlugin=function(){function a(a,b){var c=new e.DirectionalLight;c.isVirtual=!0,c.onlyShadow=!0,c.castShadow=!0,c.shadowCameraNear=a.shadowCameraNear,c.shadowCameraFar=a.shadowCameraFar,c.shadowCameraLeft=a.shadowCameraLeft,c.shadowCameraRight=a.shadowCameraRight,c.shadowCameraBottom=a.shadowCameraBottom,c.shadowCameraTop=a.shadowCameraTop,c.shadowCameraVisible=a.shadowCameraVisible,c.shadowDarkness=a.shadowDarkness,c.shadowBias=a.shadowCascadeBias[b],c.shadowMapWidth=a.shadowCascadeWidth[b],c.shadowMapHeight=a.shadowCascadeHeight[b],c.pointsWorld=[],c.pointsFrustum=[];for(var d=c.pointsWorld,f=c.pointsFrustum,g=0;8>g;g++)d[g]=new e.Vector3,f[g]=new e.Vector3;var h=a.shadowCascadeNearZ[b],i=a.shadowCascadeFarZ[b];return f[0].set(-1,-1,h),f[1].set(1,-1,h),f[2].set(-1,1,h),f[3].set(1,1,h),f[4].set(-1,-1,i),f[5].set(1,-1,i),f[6].set(-1,1,i),f[7].set(1,1,i),c}function b(a,b){var c=a.shadowCascadeArray[b];c.position.copy(a.position),c.target.position.copy(a.target.position),c.lookAt(c.target),c.shadowCameraVisible=a.shadowCameraVisible,c.shadowDarkness=a.shadowDarkness,c.shadowBias=a.shadowCascadeBias[b];var d=a.shadowCascadeNearZ[b],e=a.shadowCascadeFarZ[b],f=c.pointsFrustum;f[0].z=d,f[1].z=d,f[2].z=d,f[3].z=d,f[4].z=e,f[5].z=e,f[6].z=e,f[7].z=e}function c(a,b){var c=b.shadowCamera,d=b.pointsFrustum,f=b.pointsWorld;n.set(1/0,1/0,1/0),o.set(-1/0,-1/0,-1/0);for(var g=0;8>g;g++){var h=f[g];h.copy(d[g]),e.ShadowMapPlugin.__projector.unprojectVector(h,a),h.applyMatrix4(c.matrixWorldInverse),h.xo.x&&(o.x=h.x),h.yo.y&&(o.y=h.y),h.zo.z&&(o.z=h.z)}c.left=n.x,c.right=o.x,c.top=o.y,c.bottom=n.y,c.updateProjectionMatrix()}function d(a){return a.material instanceof e.MeshFaceMaterial?a.material.materials[0]:a.material}var f,g,h,i,j,k,l=new e.Frustum,m=new e.Matrix4,n=new e.Vector3,o=new e.Vector3,p=new e.Vector3;this.init=function(a){f=a.context,g=a;var b=e.ShaderLib.depthRGBA,c=e.UniformsUtils.clone(b.uniforms);h=new e.ShaderMaterial({fragmentShader:b.fragmentShader,vertexShader:b.vertexShader,uniforms:c}),i=new e.ShaderMaterial({fragmentShader:b.fragmentShader,vertexShader:b.vertexShader,uniforms:c,morphTargets:!0}),j=new e.ShaderMaterial({fragmentShader:b.fragmentShader,vertexShader:b.vertexShader,uniforms:c,skinning:!0}),k=new e.ShaderMaterial({fragmentShader:b.fragmentShader,vertexShader:b.vertexShader,uniforms:c,morphTargets:!0,skinning:!0}),h._shadowPass=!0,i._shadowPass=!0,j._shadowPass=!0,k._shadowPass=!0},this.render=function(a,b){g.shadowMapEnabled&&g.shadowMapAutoUpdate&&this.update(a,b)},this.update=function(n,o){var q,r,s,t,u,v,w,x,y,z,A,B,C,D,E=[],F=0,G=null;for(f.clearColor(1,1,1,1),f.disable(f.BLEND),f.enable(f.CULL_FACE),f.frontFace(f.CCW),f.cullFace(g.shadowMapCullFace===e.CullFaceFront?f.FRONT:f.BACK),g.setDepthTest(!0),q=0,r=n.__lights.length;r>q;q++)if(C=n.__lights[q],C.castShadow)if(C instanceof e.DirectionalLight&&C.shadowCascade)for(u=0;uq;q++){if(C=E[q],!C.shadowMap){var J=e.LinearFilter;g.shadowMapType===e.PCFSoftShadowMap&&(J=e.NearestFilter);var K={minFilter:J,magFilter:J,format:e.RGBAFormat};C.shadowMap=new e.WebGLRenderTarget(C.shadowMapWidth,C.shadowMapHeight,K),C.shadowMapSize=new e.Vector2(C.shadowMapWidth,C.shadowMapHeight),C.shadowMatrix=new e.Matrix4}if(!C.shadowCamera){if(C instanceof e.SpotLight)C.shadowCamera=new e.PerspectiveCamera(C.shadowCameraFov,C.shadowMapWidth/C.shadowMapHeight,C.shadowCameraNear,C.shadowCameraFar);else{if(!(C instanceof e.DirectionalLight)){console.error("Unsupported light type for shadow");continue}C.shadowCamera=new e.OrthographicCamera(C.shadowCameraLeft,C.shadowCameraRight,C.shadowCameraTop,C.shadowCameraBottom,C.shadowCameraNear,C.shadowCameraFar)}n.add(C.shadowCamera),n.autoUpdate===!0&&n.updateMatrixWorld()}for(C.shadowCameraVisible&&!C.cameraHelper&&(C.cameraHelper=new e.CameraHelper(C.shadowCamera),C.shadowCamera.add(C.cameraHelper)),C.isVirtual&&H.originalCamera==o&&c(o,C),v=C.shadowMap,w=C.shadowMatrix,x=C.shadowCamera,x.position.setFromMatrixPosition(C.matrixWorld),p.setFromMatrixPosition(C.target.matrixWorld),x.lookAt(p),x.updateMatrixWorld(),x.matrixWorldInverse.getInverse(x.matrixWorld),C.cameraHelper&&(C.cameraHelper.visible=C.shadowCameraVisible),C.shadowCameraVisible&&C.cameraHelper.update(),w.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),w.multiply(x.projectionMatrix),w.multiply(x.matrixWorldInverse),m.multiplyMatrices(x.projectionMatrix,x.matrixWorldInverse),l.setFromMatrix(m),g.setRenderTarget(v),g.clear(),D=n.__webglObjects,s=0,t=D.length;t>s;s++)A=D[s],B=A.object,A.render=!1,B.visible&&B.castShadow&&((B instanceof e.Mesh||B instanceof e.ParticleSystem)&&B.frustumCulled&&!l.intersectsObject(B)||(B._modelViewMatrix.multiplyMatrices(x.matrixWorldInverse,B.matrixWorld),A.render=!0));var L,M,N;for(s=0,t=D.length;t>s;s++)A=D[s],A.render&&(B=A.object,y=A.buffer,L=d(B),M=void 0!==B.geometry.morphTargets&&B.geometry.morphTargets.length>0&&L.morphTargets,N=B instanceof e.SkinnedMesh&&L.skinning,z=B.customDepthMaterial?B.customDepthMaterial:N?M?k:j:M?i:h,y instanceof e.BufferGeometry?g.renderBufferDirect(x,n.__lights,G,z,y,B):g.renderBuffer(x,n.__lights,G,z,y,B));for(D=n.__webglObjectsImmediate,s=0,t=D.length;t>s;s++)A=D[s],B=A.object,B.visible&&B.castShadow&&(B._modelViewMatrix.multiplyMatrices(x.matrixWorldInverse,B.matrixWorld),g.renderImmediateObject(x,n.__lights,G,h,B))}var O=g.getClearColor(),P=g.getClearAlpha();f.clearColor(O.r,O.g,O.b,P),f.enable(f.BLEND),g.shadowMapCullFace===e.CullFaceFront&&f.cullFace(f.BACK)}},e.ShadowMapPlugin.__projector=new e.Projector,e.SpritePlugin=function(){function a(){var a=c.createProgram(),b=c.createShader(c.VERTEX_SHADER),e=c.createShader(c.FRAGMENT_SHADER);return c.shaderSource(b,["precision "+d.getPrecision()+" float;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uvOffset + uv * uvScale;","vec2 alignedPosition = position * scale;","vec2 rotatedPosition;","rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","vec4 finalPosition;","finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","finalPosition.xy += rotatedPosition;","finalPosition = projectionMatrix * finalPosition;","gl_Position = finalPosition;","}"].join("\n")),c.shaderSource(e,["precision "+d.getPrecision()+" float;","uniform vec3 color;","uniform sampler2D map;","uniform float opacity;","uniform int fogType;","uniform vec3 fogColor;","uniform float fogDensity;","uniform float fogNear;","uniform float fogFar;","uniform float alphaTest;","varying vec2 vUV;","void main() {","vec4 texture = texture2D( map, vUV );","if ( texture.a < alphaTest ) discard;","gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","if ( fogType > 0 ) {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","if ( fogType == 1 ) {","fogFactor = smoothstep( fogNear, fogFar, depth );","} else {","const float LOG2 = 1.442695;","float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","}","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}","}"].join("\n")),c.compileShader(b),c.compileShader(e),c.attachShader(a,b),c.attachShader(a,e),c.linkProgram(a),a}function b(a,b){return a.z!==b.z?b.z-a.z:b.id-a.id}var c,d,f,g,h,i,j,k,l,m;this.init=function(b){c=b.context,d=b,g=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),h=new Uint16Array([0,1,2,0,2,3]),i=c.createBuffer(),j=c.createBuffer(),c.bindBuffer(c.ARRAY_BUFFER,i),c.bufferData(c.ARRAY_BUFFER,g,c.STATIC_DRAW),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,j),c.bufferData(c.ELEMENT_ARRAY_BUFFER,h,c.STATIC_DRAW),k=a(),l={position:c.getAttribLocation(k,"position"),uv:c.getAttribLocation(k,"uv")},m={uvOffset:c.getUniformLocation(k,"uvOffset"),uvScale:c.getUniformLocation(k,"uvScale"),rotation:c.getUniformLocation(k,"rotation"),scale:c.getUniformLocation(k,"scale"),color:c.getUniformLocation(k,"color"),map:c.getUniformLocation(k,"map"),opacity:c.getUniformLocation(k,"opacity"),modelViewMatrix:c.getUniformLocation(k,"modelViewMatrix"),projectionMatrix:c.getUniformLocation(k,"projectionMatrix"),fogType:c.getUniformLocation(k,"fogType"),fogDensity:c.getUniformLocation(k,"fogDensity"),fogNear:c.getUniformLocation(k,"fogNear"),fogFar:c.getUniformLocation(k,"fogFar"),fogColor:c.getUniformLocation(k,"fogColor"),alphaTest:c.getUniformLocation(k,"alphaTest")};var n=document.createElement("canvas");n.width=8,n.height=8;var o=n.getContext("2d");o.fillStyle="#ffffff",o.fillRect(0,0,n.width,n.height),f=new e.Texture(n),f.needsUpdate=!0},this.render=function(a,g){var h=a.__webglSprites,n=h.length;if(n){c.useProgram(k),c.enableVertexAttribArray(l.position),c.enableVertexAttribArray(l.uv),c.disable(c.CULL_FACE),c.enable(c.BLEND),c.bindBuffer(c.ARRAY_BUFFER,i),c.vertexAttribPointer(l.position,2,c.FLOAT,!1,16,0),c.vertexAttribPointer(l.uv,2,c.FLOAT,!1,16,8),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,j),c.uniformMatrix4fv(m.projectionMatrix,!1,g.projectionMatrix.elements),c.activeTexture(c.TEXTURE0),c.uniform1i(m.map,0);var o=0,p=0,q=a.fog;q?(c.uniform3f(m.fogColor,q.color.r,q.color.g,q.color.b),q instanceof e.Fog?(c.uniform1f(m.fogNear,q.near),c.uniform1f(m.fogFar,q.far),c.uniform1i(m.fogType,1),o=1,p=1):q instanceof e.FogExp2&&(c.uniform1f(m.fogDensity,q.density),c.uniform1i(m.fogType,2),o=2,p=2)):(c.uniform1i(m.fogType,0),o=0,p=0);var r,s,t,u,v=[];for(r=0;n>r;r++)s=h[r],t=s.material,s.visible!==!1&&(s._modelViewMatrix.multiplyMatrices(g.matrixWorldInverse,s.matrixWorld),s.z=-s._modelViewMatrix.elements[14]);for(h.sort(b),r=0;n>r;r++)s=h[r],s.visible!==!1&&(t=s.material,c.uniform1f(m.alphaTest,t.alphaTest),c.uniformMatrix4fv(m.modelViewMatrix,!1,s._modelViewMatrix.elements),v[0]=s.scale.x,v[1]=s.scale.y,u=a.fog&&t.fog?p:0,o!==u&&(c.uniform1i(m.fogType,u),o=u),null!==t.map?(c.uniform2f(m.uvOffset,t.map.offset.x,t.map.offset.y),c.uniform2f(m.uvScale,t.map.repeat.x,t.map.repeat.y)):(c.uniform2f(m.uvOffset,0,0),c.uniform2f(m.uvScale,1,1)),c.uniform1f(m.opacity,t.opacity),c.uniform3f(m.color,t.color.r,t.color.g,t.color.b),c.uniform1f(m.rotation,t.rotation),c.uniform2fv(m.scale,v),d.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst),d.setDepthTest(t.depthTest),d.setDepthWrite(t.depthWrite),t.map&&t.map.image&&t.map.image.width?d.setTexture(t.map,0):d.setTexture(f,0),c.drawElements(c.TRIANGLES,6,c.UNSIGNED_SHORT,0));c.enable(c.CULL_FACE)}}},e.DepthPassPlugin=function(){function a(a){return a.material instanceof e.MeshFaceMaterial?a.material.materials[0]:a.material}this.enabled=!1,this.renderTarget=null;var b,c,d,f,g,h,i=new e.Frustum,j=new e.Matrix4;this.init=function(a){b=a.context,c=a;var i=e.ShaderLib.depthRGBA,j=e.UniformsUtils.clone(i.uniforms);d=new e.ShaderMaterial({fragmentShader:i.fragmentShader,vertexShader:i.vertexShader,uniforms:j}),f=new e.ShaderMaterial({fragmentShader:i.fragmentShader,vertexShader:i.vertexShader,uniforms:j,morphTargets:!0}),g=new e.ShaderMaterial({fragmentShader:i.fragmentShader,vertexShader:i.vertexShader,uniforms:j,skinning:!0}),h=new e.ShaderMaterial({fragmentShader:i.fragmentShader,vertexShader:i.vertexShader,uniforms:j,morphTargets:!0,skinning:!0}),d._shadowPass=!0,f._shadowPass=!0,g._shadowPass=!0,h._shadowPass=!0},this.render=function(a,b){this.enabled&&this.update(a,b)},this.update=function(k,l){var m,n,o,p,q,r,s,t=null;for(b.clearColor(1,1,1,1),b.disable(b.BLEND),c.setDepthTest(!0),k.autoUpdate===!0&&k.updateMatrixWorld(),l.matrixWorldInverse.getInverse(l.matrixWorld),j.multiplyMatrices(l.projectionMatrix,l.matrixWorldInverse),i.setFromMatrix(j),c.setRenderTarget(this.renderTarget),c.clear(),s=k.__webglObjects,m=0,n=s.length;n>m;m++)q=s[m],r=q.object,q.render=!1,r.visible&&((r instanceof e.Mesh||r instanceof e.ParticleSystem)&&r.frustumCulled&&!i.intersectsObject(r)||(r._modelViewMatrix.multiplyMatrices(l.matrixWorldInverse,r.matrixWorld),q.render=!0));var u,v,w;for(m=0,n=s.length;n>m;m++)if(q=s[m],q.render){if(r=q.object,o=q.buffer,r instanceof e.ParticleSystem&&!r.customDepthMaterial)continue;u=a(r),u&&c.setMaterialFaces(r.material),v=r.geometry.morphTargets.length>0&&u.morphTargets,w=r instanceof e.SkinnedMesh&&u.skinning,p=r.customDepthMaterial?r.customDepthMaterial:w?v?h:g:v?f:d,o instanceof e.BufferGeometry?c.renderBufferDirect(l,k.__lights,t,p,o,r):c.renderBuffer(l,k.__lights,t,p,o,r)}for(s=k.__webglObjectsImmediate,m=0,n=s.length;n>m;m++)q=s[m],r=q.object,r.visible&&(r._modelViewMatrix.multiplyMatrices(l.matrixWorldInverse,r.matrixWorld),c.renderImmediateObject(l,k.__lights,t,d,r));var x=c.getClearColor(),y=c.getClearAlpha();b.clearColor(x.r,x.g,x.b,y),b.enable(b.BLEND)}},e.ShaderFlares={lensFlareVertexTexture:{vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","uniform sampler2D occlusionMap;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float vVisibility;","void main() {","vUV = uv;","vec2 pos = position;","if( renderType == 2 ) {","vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );","vVisibility = visibility.r / 9.0;","vVisibility *= 1.0 - visibility.g / 9.0;","vVisibility *= visibility.b / 9.0;","vVisibility *= 1.0 - visibility.a / 9.0;","pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["uniform lowp int renderType;","uniform sampler2D map;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","varying float vVisibility;","void main() {","if( renderType == 0 ) {","gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );","} else if( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * vVisibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")},lensFlare:{vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uv;","vec2 pos = position;","if( renderType == 2 ) {","pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["precision mediump float;","uniform lowp int renderType;","uniform sampler2D map;","uniform sampler2D occlusionMap;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","void main() {","if( renderType == 0 ) {","gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );","} else if( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;","visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;","visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;","visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;","visibility = ( 1.0 - visibility / 4.0 );","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * visibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")}},"undefined"!=typeof c?("undefined"!=typeof b&&b.exports&&(c=b.exports=e),c.THREE=e):this.THREE=e},{}],13:[function(a,b){void 0===Date.now&&(Date.now=function(){return(new Date).valueOf()});var c=c||function(){var a=[];return{REVISION:"13",getAll:function(){return a},removeAll:function(){a=[]},add:function(b){a.push(b)},remove:function(b){var c=a.indexOf(b);-1!==c&&a.splice(c,1)},update:function(b){if(0===a.length)return!1;var c=0;for(b=void 0!==b?b:"undefined"!=typeof window&&void 0!==window.performance&&void 0!==window.performance.now?window.performance.now():Date.now();ca;a++)p[a].stop()},this.delay=function(a){return l=a,this},this.repeat=function(a){return h=a,this},this.yoyo=function(a){return i=a,this},this.easing=function(a){return n=a,this},this.interpolation=function(a){return o=a,this},this.chain=function(){return p=arguments,this},this.onStart=function(a){return q=a,this},this.onUpdate=function(a){return s=a,this},this.onComplete=function(a){return t=a,this},this.onStop=function(a){return u=a,this},this.update=function(a){var c;if(m>a)return!0;r===!1&&(null!==q&&q.call(b),r=!0);var j=(a-m)/g;j=j>1?1:j;var u=n(j);for(c in e){var v=d[c]||0,w=e[c];w instanceof Array?b[c]=o(w,u):("string"==typeof w&&(w=v+parseFloat(w,10)),"number"==typeof w&&(b[c]=v+(w-v)*u))}if(null!==s&&s.call(b,u),1==j){if(h>0){isFinite(h)&&h--;for(c in f){if("string"==typeof e[c]&&(f[c]=f[c]+parseFloat(e[c],10)),i){var x=f[c];f[c]=e[c],e[c]=x}d[c]=f[c]}return i&&(k=!k),m=a+l,!0}null!==t&&t.call(b);for(var y=0,z=p.length;z>y;y++)p[y].start(a);return!1}return!0}},c.Easing={Linear:{None:function(a){return a}},Quadratic:{In:function(a){return a*a},Out:function(a){return a*(2-a)},InOut:function(a){return(a*=2)<1?.5*a*a:-.5*(--a*(a-2)-1)}},Cubic:{In:function(a){return a*a*a},Out:function(a){return--a*a*a+1},InOut:function(a){return(a*=2)<1?.5*a*a*a:.5*((a-=2)*a*a+2)}},Quartic:{In:function(a){return a*a*a*a},Out:function(a){return 1- --a*a*a*a},InOut:function(a){return(a*=2)<1?.5*a*a*a*a:-.5*((a-=2)*a*a*a-2)}},Quintic:{In:function(a){return a*a*a*a*a},Out:function(a){return--a*a*a*a*a+1},InOut:function(a){return(a*=2)<1?.5*a*a*a*a*a:.5*((a-=2)*a*a*a*a+2)}},Sinusoidal:{In:function(a){return 1-Math.cos(a*Math.PI/2)},Out:function(a){return Math.sin(a*Math.PI/2)},InOut:function(a){return.5*(1-Math.cos(Math.PI*a))}},Exponential:{In:function(a){return 0===a?0:Math.pow(1024,a-1)},Out:function(a){return 1===a?1:1-Math.pow(2,-10*a)},InOut:function(a){return 0===a?0:1===a?1:(a*=2)<1?.5*Math.pow(1024,a-1):.5*(-Math.pow(2,-10*(a-1))+2)}},Circular:{In:function(a){return 1-Math.sqrt(1-a*a)},Out:function(a){return Math.sqrt(1- --a*a)},InOut:function(a){return(a*=2)<1?-.5*(Math.sqrt(1-a*a)-1):.5*(Math.sqrt(1-(a-=2)*a)+1)}},Elastic:{In:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),-(c*Math.pow(2,10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d)))},Out:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),c*Math.pow(2,-10*a)*Math.sin(2*(a-b)*Math.PI/d)+1)},InOut:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),(a*=2)<1?-.5*c*Math.pow(2,10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d):c*Math.pow(2,-10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d)*.5+1)}},Back:{In:function(a){var b=1.70158;return a*a*((b+1)*a-b)},Out:function(a){var b=1.70158;return--a*a*((b+1)*a+b)+1},InOut:function(a){var b=2.5949095;return(a*=2)<1?.5*a*a*((b+1)*a-b):.5*((a-=2)*a*((b+1)*a+b)+2)}},Bounce:{In:function(a){return 1-c.Easing.Bounce.Out(1-a)},Out:function(a){return 1/2.75>a?7.5625*a*a:2/2.75>a?7.5625*(a-=1.5/2.75)*a+.75:2.5/2.75>a?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375},InOut:function(a){return.5>a?.5*c.Easing.Bounce.In(2*a):.5*c.Easing.Bounce.Out(2*a-1)+.5}}},c.Interpolation={Linear:function(a,b){var d=a.length-1,e=d*b,f=Math.floor(e),g=c.Interpolation.Utils.Linear;return 0>b?g(a[0],a[1],e):b>1?g(a[d],a[d-1],d-e):g(a[f],a[f+1>d?d:f+1],e-f)},Bezier:function(a,b){var d,e=0,f=a.length-1,g=Math.pow,h=c.Interpolation.Utils.Bernstein;for(d=0;f>=d;d++)e+=g(1-b,f-d)*g(b,d)*a[d]*h(f,d);return e},CatmullRom:function(a,b){var d=a.length-1,e=d*b,f=Math.floor(e),g=c.Interpolation.Utils.CatmullRom;return a[0]===a[d]?(0>b&&(f=Math.floor(e=d*(1+b))),g(a[(f-1+d)%d],a[f],a[(f+1)%d],a[(f+2)%d],e-f)):0>b?a[0]-(g(a[0],a[0],a[1],a[1],-e)-a[0]):b>1?a[d]-(g(a[d],a[d],a[d-1],a[d-1],e-d)-a[d]):g(a[f?f-1:0],a[f],a[f+1>d?d:f+1],a[f+2>d?d:f+2],e-f)},Utils:{Linear:function(a,b,c){return(b-a)*c+a},Bernstein:function(a,b){var d=c.Interpolation.Utils.Factorial;return d(a)/d(b)/d(a-b)},Factorial:function(){var a=[1];return function(b){var c,d=1;if(a[b])return a[b];for(c=b;c>1;c--)d*=c;return a[b]=d}}(),CatmullRom:function(a,b,c,d,e){var f=.5*(c-a),g=.5*(d-b),h=e*e,i=e*h;return(2*b-2*c+f+g)*i+(-3*b+3*c-2*f-g)*h+f*e+b}}},b.exports=c},{}],14:[function(a,b){!function c(a,d,e){function f(a,b){return this instanceof f?(g(a)?(b=a[1],a=a[0]):"object"==typeof a&&a&&(b=a.y,a=a.x),this.x=f.clean(a||0),void(this.y=f.clean(b||0))):new f(a,b)}var g=function(a){return"[object Array]"===Object.prototype.toString.call(a)};f.prototype={change:function(a){if("function"==typeof a)this.observers?this.observers.push(a):this.observers=[a];else if(this.observers&&this.observers.length)for(var b=this.observers.length-1;b>=0;b--)this.observers[b](this,a);return this},ignore:function(a){if(this.observers)if(a)for(var b=this.observers,c=b.length;c--;)b[c]===a&&b.splice(c,1);else this.observers=[];return this},set:function(a,b,c){if("number"!=typeof a&&(c=b,b=a.y,a=a.x),this.x===a&&this.y===b)return this;var d=null;return c!==!1&&this.observers&&this.observers.length&&(d=this.clone()),this.x=f.clean(a),this.y=f.clean(b),c!==!1?this.change(d):void 0},zero:function(){return this.set(0,0)},clone:function(){return new this.constructor(this.x,this.y)},negate:function(a){return a?new this.constructor(-this.x,-this.y):this.set(-this.x,-this.y)},add:function(a,b,c){return"number"!=typeof a&&(c=b,g(a)?(b=a[1],a=a[0]):(b=a.y,a=a.x)),a+=this.x,b+=this.y,c?new this.constructor(a,b):this.set(a,b)},subtract:function(a,b,c){return"number"!=typeof a&&(c=b,g(a)?(b=a[1],a=a[0]):(b=a.y,a=a.x)),a=this.x-a,b=this.y-b,c?new this.constructor(a,b):this.set(a,b)},multiply:function(a,b,c){return"number"!=typeof a?(c=b,g(a)?(b=a[1],a=a[0]):(b=a.y,a=a.x)):"number"!=typeof b&&(c=b,b=a),a*=this.x,b*=this.y,c?new this.constructor(a,b):this.set(a,b)},rotate:function(a,b,c){var d,e,f=this.x,g=this.y,h=Math.cos(a),i=Math.sin(a);return b=b?-1:1,d=h*f-b*i*g,e=b*i*f+h*g,c?new this.constructor(d,e):this.set(d,e)},length:function(){var a=this.x,b=this.y;return Math.sqrt(a*a+b*b)},lengthSquared:function(){var a=this.x,b=this.y;return a*a+b*b},distance:function(a){var b=this.x-a.x,c=this.y-a.y;return Math.sqrt(b*b+c*c)},normalize:function(a){var b=this.length(),c=bc?c:e,h=f>d?d:f;return b?new this.constructor(g,h):this.set(g,h)},max:function(a,b){var c=this.x,d=this.y,e=a.x,f=a.y,g=c>e?c:e,h=d>f?d:f;return b?new this.constructor(g,h):this.set(g,h)},clamp:function(a,b,c){var d=this.min(b,!0).max(a);return c?d:this.set(d.x,d.y)},lerp:function(a,b,c){return this.add(a.subtract(this,!0).multiply(b),c)},skew:function(a){return a?new this.constructor(-this.y,this.x):this.set(-this.y,this.x)},dot:function(a){return f.clean(this.x*a.x+a.y*this.y)},perpDot:function(a){return f.clean(this.x*a.y-this.y*a.x)},angleTo:function(a){return Math.atan2(this.perpDot(a),this.dot(a))},divide:function(a,b,c){if("number"!=typeof a?(c=b,g(a)?(b=a[1],a=a[0]):(b=a.y,a=a.x)):"number"!=typeof b&&(c=b,b=a),0===a||0===b)throw new Error("division by zero");if(isNaN(a)||isNaN(b))throw new Error("NaN detected");return c?new this.constructor(this.x/a,this.y/b):this.set(this.x/a,this.y/b)},isPointOnLine:function(a,b){return(a.y-this.y)*(a.x-b.x)===(a.y-b.y)*(a.x-this.x)},toArray:function(){return[this.x,this.y]},fromArray:function(a){return this.set(a[0],a[1])},toJSON:function(){return{x:this.x,y:this.y}},toString:function(){return"("+this.x+", "+this.y+")"},constructor:f},f.fromArray=function(a,b){return new(b||f)(a[0],a[1])},f.precision=d||8;var h=Math.pow(10,f.precision);return f.clean=a||function(a){if(isNaN(a))throw new Error("NaN detected");if(!isFinite(a))throw new Error("Infinity detected");return Math.round(a)===a?a:Math.round(a*h)/h},f.inject=c,a||(f.fast=c(function(a){return a}),"undefined"!=typeof b&&"object"==typeof b.exports?b.exports=f:window.Vec2=window.Vec2||f),f}()},{}],15:[function(a,b){function c(a,b,c){c||(c={}),this.width=a,this.height=b,this.points=[],this.introLines=new e.Object3D,this.pins=[],this.markers=[],this.satelliteAnimations=[],this.satelliteMeshes=[],this.satellites={},this.quadtree=new f(new g(180,360),5),this.active=!0;var d={font:"Inconsolata",baseColor:"#ffcc00",markerColor:"#ffcc00",pinColor:"#00eeee",satelliteColor:"#ff0000",blankPercentage:0,thinAntarctica:.01,mapUrl:"resources/equirectangle_projection.png",introLinesAltitude:1.1,introLinesDuration:2e3,introLinesColor:"#8FD8D8",introLinesCount:60,scale:1,dayLength:28e3,pointsPerDegree:1.1,pointSize:.6,pointsVariance:.2,maxPins:500,maxMarkers:4,data:[],tiles:[],viewAngle:0};for(var h in d)this[h]||(this[h]=d[h],c[h]&&(this[h]=c[h]));this.setScale(this.scale),this.renderer=new e.WebGLRenderer({antialias:!0}),this.renderer.setSize(this.width,this.height),this.renderer.gammaInput=!0,this.renderer.gammaOutput=!0,this.domElement=this.renderer.domElement,this.data.sort(function(a,b){return b.lng-2*b.label.length-(a.lng-2*a.label.length)});for(var h=0;h0&&this.firstRunTime+(next=this.data.pop()).when=Date.now()&&this.data.push(next)}},p=function(){this.hexGrid&&this.scene.remove(this.hexGrid);var a=["#define PI 3.141592653589793238462643","#define DISTANCE 500.0","#define INTRODURATION "+(parseFloat(this.introLinesDuration)+1e-5),"#define INTROALTITUDE "+(parseFloat(this.introLinesAltitude)+1e-5),"attribute float lng;","uniform float currentTime;","varying vec4 vColor;","","void main()","{"," vec3 newPos = position;"," float opacityVal = 0.0;"," float introStart = INTRODURATION * ((180.0 + lng)/360.0);"," if(currentTime > introStart){"," opacityVal = 1.0;"," }"," if(currentTime > introStart && currentTime < introStart + INTRODURATION / 8.0){"," newPos = position * INTROALTITUDE;"," opacityVal = .3;"," }"," if(currentTime > introStart + INTRODURATION / 8.0 && currentTime < introStart + INTRODURATION / 8.0 + 200.0){"," newPos = position * (1.0 + ((INTROALTITUDE-1.0) * (1.0-(currentTime - introStart-(INTRODURATION/8.0))/200.0)));"," }"," vColor = vec4( color, opacityVal );"," gl_Position = projectionMatrix * modelViewMatrix * vec4(newPos, 1.0);","}"].join("\n"),b=["varying vec4 vColor;","void main()","{"," gl_FragColor = vColor;"," float depth = gl_FragCoord.z / gl_FragCoord.w;"," float fogFactor = smoothstep("+parseInt(this.cameraDistance)+".0,"+parseInt(this.cameraDistance+300)+".0, depth );"," vec3 fogColor = vec3(0.0);"," gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}"].join("\n"),c={lng:{type:"f",value:null}};this.pointUniforms={currentTime:{type:"f",value:0}};var d=new e.ShaderMaterial({uniforms:this.pointUniforms,attributes:c,vertexShader:a,fragmentShader:b,transparent:!0,vertexColors:e.VertexColors,side:e.DoubleSide}),f=4*this.tiles.length,g=new e.BufferGeometry;g.addAttribute("index",Uint16Array,3*f,1),g.addAttribute("position",Float32Array,3*f,3),g.addAttribute("normal",Float32Array,3*f,3),g.addAttribute("color",Float32Array,3*f,3),g.addAttribute("lng",Float32Array,3*f,1);for(var h=g.attributes.lng.array,i=l(this.baseColor).hueSet(),j=[],k=0;k5&&q(s+3,r.b[0].x,r.b[0].y,r.b[0].z,r.b[5].x,r.b[5].y,r.b[5].z,r.b[4].x,r.b[4].y,r.b[4].z,r.lat,r.lon,v)}g.offsets=[];for(var w=f/m,k=0;w>k;k++){var x={start:k*m*3,index:k*m*3,count:3*Math.min(f-k*m,m)};g.offsets.push(x)}g.computeBoundingSphere(),this.hexGrid=new e.Mesh(g,d),this.scene.add(this.hexGrid)},q=function(){for(var a,b=new e.LineBasicMaterial({color:this.introLinesColor,transparent:!0,linewidth:2,opacity:.5}),c=0;ci;i++){var j=m.mapPoint(f,g-5*i);a=new e.Vector3(j.x*this.introLinesAltitude,j.y*this.introLinesAltitude,j.z*this.introLinesAltitude),d.vertices.push(a)}this.introLines.add(new e.Line(d,b))}this.scene.add(this.introLines)};c.prototype.init=function(a){this.camera=new e.PerspectiveCamera(50,this.width/this.height,1,this.cameraDistance+300),this.camera.position.z=this.cameraDistance,this.cameraAngle=Math.PI,this.scene=new e.Scene,this.scene.fog=new e.Fog(0,this.cameraDistance,this.cameraDistance+300),q.call(this),this.smokeProvider=new k(this.scene),p.call(this),setTimeout(a,500) -},c.prototype.destroy=function(a){var b=this;this.active=!1,setTimeout(function(){for(;b.scene.children.length>0;)b.scene.remove(b.scene.children[0]);"function"==typeof a&&a()},1e3)},c.prototype.addPin=function(a,b,c){a=parseFloat(a),b=parseFloat(b);var d={lineColor:this.pinColor,topColor:this.pinColor},e=1.2;("string"!=typeof c||0===c.length)&&(e-=.05+.05*Math.random());var f=new h(a,b,c,e,this.scene,this.smokeProvider,d);this.pins.push(f);var i=n(a,b);if(f.pos_=new g(parseInt(i.x),parseInt(i.y)),f.rad_=c.length>0?i.rad:1,this.quadtree.addObject(f),c.length>0){var j=this.quadtree.getCollisionsForObject(f),k=0,l=0,m=[];for(var o in j)j[o].text.length>0&&(k++,j[o].age()>5e3?m.push(j[o]):l++);if(k>0&&0==l)for(var o=0;o0&&(f.hideLabel(),f.hideSmoke(),f.hideTop(),f.changeAltitude(.05*Math.random()+1.1))}if(this.pins.length>this.maxPins){var p=this.pins.shift();this.quadtree.removeObject(p),p.remove()}return f},c.prototype.addMarker=function(a,b,c,d){var e,f={markerColor:this.markerColor,lineColor:this.markerColor};return e="boolean"==typeof d&&d?new i(a,b,c,1.2,this.markers[this.markers.length-1],this.scene,f):"object"==typeof d?new i(a,b,c,1.2,d,this.scene,f):new i(a,b,c,1.2,null,this.scene,f),this.markers.push(e),this.markers.length>this.maxMarkers&&this.markers.shift().remove(),e},c.prototype.addSatellite=function(a,b,c,d,e,f){d||(d={}),void 0==d.coreColor&&(d.coreColor=this.satelliteColor);var g=new j(a,b,c,this.scene,d,e,f);return this.satellites[g.toString()]||(this.satellites[g.toString()]=g),g.onRemove(function(){delete this.satellites[g.toString()]}.bind(this)),g},c.prototype.addConstellation=function(a,b){for(var c,d=[],e=0;ethis.maxPins;){var b=this.pins.shift();this.quadtree.removeObject(b),b.remove()}},c.prototype.setMaxMarkers=function(a){for(this.maxMarkers=a;this.markers.length>this.maxMarkers;)this.markers.shift().remove()},c.prototype.setBaseColor=function(a){this.baseColor=a,p.call(this)},c.prototype.setMarkerColor=function(a){this.markerColor=a,this.scene._encom_markerTexture=null},c.prototype.setPinColor=function(a){this.pinColor=a},c.prototype.setScale=function(a){this.scale=a,this.cameraDistance=1700/a,this.scene&&this.scene.fog&&(this.scene.fog.near=this.cameraDistance,this.scene.fog.far=this.cameraDistance+300,p.call(this),this.camera.far=this.cameraDistance+300,this.camera.updateProjectionMatrix())},c.prototype.tick=function(){if(this.camera){this.firstRunTime||(this.firstRunTime=Date.now()),o.call(this),d.update(),this.lastRenderDate||(this.lastRenderDate=new Date),this.firstRenderDate||(this.firstRenderDate=new Date),this.totalRunTime=new Date-this.firstRenderDate;var a=new Date-this.lastRenderDate;this.lastRenderDate=new Date;var b=2*Math.PI/(this.dayLength/a);this.cameraAngle+=b,this.active||(this.cameraDistance+=1e3*a/1e3),this.camera.position.x=this.cameraDistance*Math.cos(this.cameraAngle)*Math.cos(this.viewAngle),this.camera.position.y=Math.sin(this.viewAngle)*this.cameraDistance,this.camera.position.z=this.cameraDistance*Math.sin(this.cameraAngle)*Math.cos(this.viewAngle);for(var c in this.satellites)this.satellites[c].tick(this.camera.position,this.cameraAngle,a);for(var c=0;cthis.totalRunTime?(this.totalRunTime/this.introLinesDuration<.1&&(this.introLines.children[0].material.opacity=this.totalRunTime/this.introLinesDuration*10-.2),this.introLines.children[0].material.opacity=this.totalRunTime/this.introLinesDuration>.8?5*Math.max(1-this.totalRunTime/this.introLinesDuration,0):1,this.introLines.rotateY(2*Math.PI/(this.introLinesDuration/a))):this.introLines&&(this.scene.remove(this.introLines),delete[this.introLines]),this.pointUniforms.currentTime.value=this.totalRunTime,this.smokeProvider.tick(this.totalRunTime),this.camera.lookAt(this.scene.position),this.renderer.render(this.scene,this.camera)}},b.exports=c},{"./Marker":16,"./Pin":17,"./Satellite":18,"./SmokeProvider":19,"./utils":21,"hexasphere.js":3,"pusher.color":6,quadtree2:8,three:12,"tween.js":13,vec2:14}],16:[function(a,b){var c=a("three"),d=a("tween.js"),e=a("./utils"),f=function(a){var b,d,f=30,g=30;return b=e.renderToCanvas(f,g,function(b){b.fillStyle=a,b.strokeStyle=a,b.lineWidth=3,b.beginPath(),b.arc(f/2,g/2,f/3,0,2*Math.PI),b.stroke(),b.beginPath(),b.arc(f/2,g/2,f/5,0,2*Math.PI),b.fill()}),d=new c.Texture(b),d.needsUpdate=!0,d},g=function(a,b,g,h,i,j,k){var l,m,n,o,p,q,r={lineColor:"#FFCC00",lineWidth:1,markerColor:"#FFCC00",labelColor:"#FFF",font:"Inconsolata",fontSize:20,drawTime:2e3,lineSegments:150};if(this.lat=parseFloat(a),this.lon=parseFloat(b),this.text=g,this.altitude=parseFloat(h),this.scene=j,this.previous=i,this.next=[],this.previous&&this.previous.next.push(this),k)for(var s in r)void 0!=k[s]&&(r[s]=k[s]);this.opts=r,l=e.mapPoint(a,b),i&&(m=e.mapPoint(i.lat,i.lon)),j._encom_markerTexture||(j._encom_markerTexture=f(this.opts.markerColor)),n=new c.SpriteMaterial({map:j._encom_markerTexture,opacity:.7,depthTest:!0,fog:!0}),this.marker=new c.Sprite(n),this.marker.scale.set(0,0),this.marker.position.set(l.x*h,l.y*h,l.z*h),o=e.createLabel(g.toUpperCase(),this.opts.fontSize,this.opts.labelColor,this.opts.font,this.opts.markerColor),p=new c.Texture(o),p.needsUpdate=!0,q=new c.SpriteMaterial({map:p,useScreenCoordinates:!1,opacity:0,depthTest:!0,fog:!0}),this.labelSprite=new c.Sprite(q),this.labelSprite.position={x:l.x*h*1.1,y:l.y*h*1.05+(l.y<0?-15:30),z:l.z*h*1.1},this.labelSprite.scale.set(o.width,o.height),new d.Tween({opacity:0}).to({opacity:1},500).onUpdate(function(){q.opacity=this.opacity}).start();var t=this;if(new d.Tween({x:0,y:0}).to({x:50,y:50},2e3).easing(d.Easing.Elastic.Out).onUpdate(function(){t.marker.scale.set(this.x,this.y)}).delay(this.previous?t.opts.drawTime:0).start(),this.previous){var u,v,w,x,y,z,A,B,C,D,E,F,G=[],H=[];t.geometrySpline=new c.Geometry,u=new c.LineBasicMaterial({color:this.opts.lineColor,transparent:!0,linewidth:3,opacity:.5}),t.geometrySplineDotted=new c.Geometry,v=new c.LineBasicMaterial({color:this.opts.lineColor,linewidth:1,transparent:!0,opacity:.5}),w=(a-i.lat)/t.opts.lineSegments,x=(b-i.lon)/t.opts.lineSegments,y=e.mapPoint(i.lat,i.lon),G=[],H=[];for(var I=0;I=a.index&&(E.set(1.2*D.x,1.2*D.y,1.2*D.z),currentVert2.set(1.19*currentPoint2.x,1.19*currentPoint2.y,1.19*currentPoint2.z)),t.geometrySpline.verticesNeedUpdate=!0,t.geometrySplineDotted.verticesNeedUpdate=!0;G.length>0&&setTimeout(F,t.opts.drawTime/t.opts.lineSegments)},F(),this.scene.add(new c.Line(t.geometrySpline,u)),this.scene.add(new c.Line(t.geometrySplineDotted,v,c.LinePieces))}this.scene.add(this.marker),this.scene.add(this.labelSprite)};g.prototype.remove=function(){for(var a=0,b=this,c=function(d){for(var e=0;a>e;e++)d.geometrySpline.vertices[e].set(d.geometrySpline.vertices[e+1]),d.geometrySplineDotted.vertices[e].set(d.geometrySplineDotted.vertices[e+1]),d.geometrySpline.verticesNeedUpdate=!0,d.geometrySplineDotted.verticesNeedUpdate=!0;a++,a0,showTop:g.length>0,showSmoke:g.length>0};if(this.lat=a,this.lon=b,this.text=g,this.altitude=h,this.scene=i,this.smokeProvider=j,this.dateCreated=Date.now(),k)for(var t in s)void 0!=k[t]&&(s[t]=k[t]);this.opts=s,this.topVisible=s.showTop,this.smokeVisible=s.showSmoke,this.labelVisible=s.showLabel,this.lineGeometry=new c.Geometry,l=new c.LineBasicMaterial({color:s.lineColor,linewidth:s.lineWidth}),r=e.mapPoint(a,b),this.lineGeometry.vertices.push(new c.Vector3(r.x,r.y,r.z)),this.lineGeometry.vertices.push(new c.Vector3(r.x,r.y,r.z)),this.line=new c.Line(this.lineGeometry,l),m=e.createLabel(g,18,s.labelColor,s.font),n=new c.Texture(m),n.needsUpdate=!0,o=new c.SpriteMaterial({map:n,useScreenCoordinates:!1,opacity:0,depthTest:!0,fog:!0}),this.labelSprite=new c.Sprite(o),this.labelSprite.position={x:r.x*h*1.1,y:r.y*h+(r.y<0?-15:30),z:r.z*h*1.1},this.labelSprite.scale.set(m.width,m.height),p=new c.Texture(f(s.topColor)),p.needsUpdate=!0,q=new c.SpriteMaterial({map:p,depthTest:!0,fog:!0,opacity:0}),this.topSprite=new c.Sprite(q),this.topSprite.scale.set(20,20),this.topSprite.position.set(r.x*h,r.y*h,r.z*h),this.smokeVisible&&(this.smokeId=j.setFire(a,b,h));var u=this;(s.showTop||s.showLabel)&&new d.Tween({opacity:0}).to({opacity:1},500).onUpdate(function(){q.opacity=u.topVisible?this.opacity:0,o.opacity=u.labelVisible?this.opacity:0}).delay(1e3).start(),new d.Tween(r).to({x:r.x*h,y:r.y*h,z:r.z*h},1500).easing(d.Easing.Elastic.Out).onUpdate(function(){u.lineGeometry.vertices[1].x=this.x,u.lineGeometry.vertices[1].y=this.y,u.lineGeometry.vertices[1].z=this.z,u.lineGeometry.verticesNeedUpdate=!0}).start(),this.scene.add(this.labelSprite),this.scene.add(this.line),this.scene.add(this.topSprite)};g.prototype.toString=function(){return""+this.lat+"_"+this.lon},g.prototype.changeAltitude=function(a){var b=e.mapPoint(this.lat,this.lon),c=this;new d.Tween({altitude:this.altitude}).to({altitude:a},1500).easing(d.Easing.Elastic.Out).onUpdate(function(){c.smokeVisible&&c.smokeProvider.changeAltitude(this.altitude,c.smokeId),c.topVisible&&c.topSprite.position.set(b.x*this.altitude,b.y*this.altitude,b.z*this.altitude),c.labelVisible&&(c.labelSprite.position={x:b.x*this.altitude*1.1,y:b.y*this.altitude+(b.y<0?-15:30),z:b.z*this.altitude*1.1}),c.lineGeometry.vertices[1].x=b.x*this.altitude,c.lineGeometry.vertices[1].y=b.y*this.altitude,c.lineGeometry.vertices[1].z=b.z*this.altitude,c.lineGeometry.verticesNeedUpdate=!0}).onComplete(function(){c.altitude=a}).start()},g.prototype.hideTop=function(){this.topVisible&&(this.topSprite.material.opacity=0,this.topVisible=!1)},g.prototype.showTop=function(){this.topVisible||(this.topSprite.material.opacity=1,this.topVisible=!0)},g.prototype.hideLabel=function(){this.labelVisible&&(this.labelSprite.material.opacity=0,this.labelVisible=!1)},g.prototype.showLabel=function(){this.labelVisible||(this.labelSprite.material.opacity=1,this.labelVisible=!0)},g.prototype.hideSmoke=function(){this.smokeVisible&&(this.smokeProvider.extinguish(this.smokeId),this.smokeVisible=!1)},g.prototype.showSmoke=function(){this.smokeVisible||(this.smokeId=this.smokeProvider.setFire(this.lat,this.lon,this.altitude),this.smokeVisible=!0)},g.prototype.age=function(){return Date.now()-this.dateCreated},g.prototype.remove=function(){this.scene.remove(this.labelSprite),this.scene.remove(this.line),this.scene.remove(this.topSprite),this.smokeVisible&&this.smokeProvider.extinguish(this.smokeId)},b.exports=g},{"./utils":21,three:12,"tween.js":13}],18:[function(a,b){var c=a("./TextureAnimator"),d=a("three"),e=a("./utils"),f=function(a,b,c,d,f,g,h,i){var j=a/c,k=Math.floor((a-d)/f),l=b-25,m=l/(a-d),n=0,o=0,p=0,q=e.hexToRgb(g);return e.renderToCanvas(a*b/c,b*c,function(c){for(var e=0;a>e;e++){e-p*j>=j&&(n=0,o+=b,p++);var g=n+25,l=o+Math.floor(b/2);c.lineWidth=2,c.strokeStyle=i;var r=Math.PI/16,s=-Math.PI+Math.PI/4,t=8,u=Math.floor(a-2*(a-d)/f)+1;d>e&&(t=t*e/d);for(var v=Math.floor((u-d)/2)+d,w=0;4>w;w++){if(c.beginPath(),d>e||e>=a)c.arc(g,l,t,w*Math.PI/2+s+r,w*Math.PI/2+s+Math.PI/2-2*r);else if(e>d&&v>e){var x=v-d,y=3*Math.PI/2,z=e-d,A=y/x,B=-Math.PI+Math.PI/4+r+A*z;c.arc(g,l,t,Math.max(w*Math.PI/2+s,B),Math.max(w*Math.PI/2+s+Math.PI/2-2*r,B+Math.PI/2-2*r))}else if(e>=v&&u>e){var x=u-v,y=2*w*Math.PI/4,z=e-v,A=y/x,B=Math.PI/2+Math.PI/4+r+A*z;c.arc(g,l,t,B,B+Math.PI/2-2*r)}else if(e>=u&&(a-u)/2+u>e){var x=(a-u)/2,y=Math.PI/2,z=e-u,A=y/x,B=w*(Math.PI/2)+Math.PI/4+r+A*z;c.arc(g,l,t,B,B+Math.PI/2-2*r)}else c.arc(g,l,t,w*Math.PI/2+s+r,w*Math.PI/2+s+Math.PI/2-2*r);c.stroke()}for(var C,D=0;f>D;D++)C=e-k*D-d,C>0&&b-25>C*m&&(c.strokeStyle="rgba("+q.r+","+q.g+","+q.b+","+(.9-C*m/(b-25))+")",c.lineWidth=2,c.beginPath(),c.arc(g,l,C*m,-Math.PI/12,Math.PI/12),c.stroke());c.fillStyle="#000",c.beginPath(),c.arc(g,l,3,0,2*Math.PI),c.fill(),c.strokeStyle=h,c.lineWidth=2,c.beginPath(),d>e?c.arc(g,l,3*e/d,0,2*Math.PI):c.arc(g,l,3,0,2*Math.PI),c.stroke(),n+=b}})},g=function(a,b,g,h,i,j,k){var l,m,n,o,p,q,r,s=e.mapPoint(a,b);s.x*=g,s.y*=g,s.z*=g;var m={numWaves:8,waveColor:"#FFF",coreColor:"#FF0000",shieldColor:"#FFF",size:1};if(this.lat=a,this.lon=b,this.altitude=g,this.scene=h,this.onRemoveList=[],n=50,o=100,p=10,q=Math.floor(n/8),i)for(var t in m)void 0!=i[t]&&(m[t]=i[t]);this.opts=m,j?(this.canvas=j,k?this.texture=k:(this.texture=new d.Texture(this.canvas),this.texture.needsUpdate=!0,r=Math.floor(n-2*(n-q)/m.numWaves)+1,this.animator=new c(this.texture,p,n/p,n,80,r))):(this.canvas=f(n,o,p,q,m.numWaves,m.waveColor,m.coreColor,m.shieldColor),this.texture=new d.Texture(this.canvas),this.texture.needsUpdate=!0,r=Math.floor(n-2*(n-q)/m.numWaves)+1,this.animator=new c(this.texture,p,n/p,n,80,r)),l=new d.PlaneGeometry(150*m.size,150*m.size,1,1),this.material=new d.MeshBasicMaterial({map:this.texture,depthTest:!1,transparent:!0}),this.mesh=new d.Mesh(l,this.material),this.mesh.tiltMultiplier=Math.PI/2*(1-Math.abs(a/90)),this.mesh.tiltDirection=a>0?-1:1,this.mesh.lon=b,this.mesh.position.set(s.x,s.y,s.z),this.mesh.rotation.z=-1*(a/90)*Math.PI/2,this.mesh.rotation.y=b/180*Math.PI,h.add(this.mesh)};g.prototype.changeAltitude=function(a){var b=e.mapPoint(this.lat,this.lon);b.x*=a,b.y*=a,b.z*=a,this.altitude=a,this.mesh.position.set(b.x,b.y,b.z)},g.prototype.changeCanvas=function(a,b,e,g){numFrames=50,pixels=100,rows=10,waveStart=Math.floor(numFrames/8),a?this.opts.numWaves=a:a=this.opts.numWaves,b?this.opts.waveColor=b:b=this.opts.waveColor,e?this.opts.coreColor=e:e=this.opts.coreColor,g?this.opts.shieldColor=g:g=this.opts.shieldColor,this.canvas=f(numFrames,pixels,rows,waveStart,a,b,e,g),this.texture=new d.Texture(this.canvas),this.texture.needsUpdate=!0,repeatAt=Math.floor(numFrames-2*(numFrames-waveStart)/a)+1,this.animator=new c(this.texture,rows,numFrames/rows,numFrames,80,repeatAt),this.material.map=this.texture},g.prototype.tick=function(a,b,c){this.mesh.lookAt(a),this.mesh.rotateZ(this.mesh.tiltDirection*Math.PI/2),this.mesh.rotateZ(Math.sin(b+this.mesh.lon/180*Math.PI)*this.mesh.tiltMultiplier*this.mesh.tiltDirection*-1),this.animator&&this.animator.update(c)},g.prototype.remove=function(){this.scene.remove(this.mesh);for(var a=0;a 0.0 && active > 0.0) {"," dt = mod(dt,1500.0);"," }"," float opacity = 1.0 - dt/ 1500.0;"," if (dt == 0.0 || active == 0.0){"," opacity = 0.0;"," }"," vec3 newPos = getPos(myStartLat, myStartLon - ( dt / 50.0));"," vColor = vec4( color, opacity );"," vec4 mvPosition = modelViewMatrix * vec4( newPos, 1.0 );"," gl_PointSize = 2.5 - (dt / 1500.0);"," gl_Position = projectionMatrix * mvPosition;","}"].join("\n"),f=["varying vec4 vColor;","void main()","{"," gl_FragColor = vColor;"," float depth = gl_FragCoord.z / gl_FragCoord.w;"," float fogFactor = smoothstep(1500.0, 1800.0, depth );"," vec3 fogColor = vec3(0.0);"," gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w), fogFactor );","}"].join("\n"),g=function(a,b){var d={smokeCount:5e3,smokePerPin:30,smokePerSecond:20};if(b)for(var g in d)void 0!==b[g]&&(d[g]=b[g]);this.opts=d,this.geometry=new c.Geometry,this.attributes={myStartTime:{type:"f",value:[]},myStartLat:{type:"f",value:[]},myStartLon:{type:"f",value:[]},altitude:{type:"f",value:[]},active:{type:"f",value:[]}},this.uniforms={currentTime:{type:"f",value:0},color:{type:"c",value:new c.Color("#aaa")}};for(var h=new c.ShaderMaterial({uniforms:this.uniforms,attributes:this.attributes,vertexShader:e,fragmentShader:f,transparent:!0}),g=0;gthis.tileDisplayDuration;)if(this.shutDownFlag&&this.currentTile>=e)this.done=!0,this.shutDownCb();else{this.currentDisplayTime-=this.tileDisplayDuration,this.currentTile++,this.currentTile!=e||this.shutDownFlag||(this.currentTile=g);var c=this.currentTile%this.tilesHorizontal;a.offset.x=c/this.tilesHorizontal;var d=Math.floor(this.currentTile/this.tilesHorizontal);a.offset.y=1-d/this.tilesVertical-1/this.tilesVertical}},this.shutDown=function(a){_this.shutDownFlag=!0,_this.shutDownCb=a}};b.exports=d},{three:12}],21:[function(a,b){var c={renderToCanvas:function(a,b,c){var d=document.createElement("canvas");return d.width=a,d.height=b,c(d.getContext("2d")),d},mapPoint:function(a,b,c){c||(c=500);var d=(90-a)*Math.PI/180,e=(180-b)*Math.PI/180,f=c*Math.sin(d)*Math.cos(e),g=c*Math.cos(d),h=c*Math.sin(d)*Math.sin(e);return{x:f,y:g,z:h}},hexToRgb:function(a){var b=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;a=a.replace(b,function(a,b,c,d){return b+b+c+c+d+d});var c=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);return c?{r:parseInt(c[1],16),g:parseInt(c[2],16),b:parseInt(c[3],16)}:null},createLabel:function(a,b,c,d,e){var f=document.createElement("canvas"),g=f.getContext("2d");g.font=b+"pt "+d;var h=g.measureText(a).width;return f.width=h,f.height=b+10,f.width%2&&f.width++,f.height%2&&f.height++,e&&(f.height+=30),g.font=b+"pt "+d,g.textAlign="center",g.textBaseline="middle",g.strokeStyle="black",g.miterLimit=2,g.lineJoin="circle",g.lineWidth=6,g.strokeText(a,f.width/2,f.height/2),g.lineWidth=2,g.fillStyle=c,g.fillText(a,f.width/2,f.height/2),e&&(g.strokeStyle=e,g.lineWidth=4,g.beginPath(),g.moveTo(0,f.height-10),g.lineTo(f.width-1,f.height-10),g.stroke()),f}};b.exports=c},{}]},{},[1]); \ No newline at end of file +var _encomBundle=(function(){function qp(vt){return vt&&vt.__esModule&&Object.prototype.hasOwnProperty.call(vt,"default")?vt.default:vt}var hu={},vn={},uu;function Hl(){if(uu)return vn;uu=1,Object.defineProperty(vn,"__esModule",{value:!0});var vt=Object.freeze({Linear:Object.freeze({None:function(A){return A},In:function(A){return A},Out:function(A){return A},InOut:function(A){return A}}),Quadratic:Object.freeze({In:function(A){return A*A},Out:function(A){return A*(2-A)},InOut:function(A){return(A*=2)<1?.5*A*A:-.5*(--A*(A-2)-1)}}),Cubic:Object.freeze({In:function(A){return A*A*A},Out:function(A){return--A*A*A+1},InOut:function(A){return(A*=2)<1?.5*A*A*A:.5*((A-=2)*A*A+2)}}),Quartic:Object.freeze({In:function(A){return A*A*A*A},Out:function(A){return 1- --A*A*A*A},InOut:function(A){return(A*=2)<1?.5*A*A*A*A:-.5*((A-=2)*A*A*A-2)}}),Quintic:Object.freeze({In:function(A){return A*A*A*A*A},Out:function(A){return--A*A*A*A*A+1},InOut:function(A){return(A*=2)<1?.5*A*A*A*A*A:.5*((A-=2)*A*A*A*A+2)}}),Sinusoidal:Object.freeze({In:function(A){return 1-Math.sin((1-A)*Math.PI/2)},Out:function(A){return Math.sin(A*Math.PI/2)},InOut:function(A){return .5*(1-Math.sin(Math.PI*(.5-A)))}}),Exponential:Object.freeze({In:function(A){return A===0?0:Math.pow(1024,A-1)},Out:function(A){return A===1?1:1-Math.pow(2,-10*A)},InOut:function(A){return A===0?0:A===1?1:(A*=2)<1?.5*Math.pow(1024,A-1):.5*(-Math.pow(2,-10*(A-1))+2)}}),Circular:Object.freeze({In:function(A){return 1-Math.sqrt(1-A*A)},Out:function(A){return Math.sqrt(1- --A*A)},InOut:function(A){return(A*=2)<1?-.5*(Math.sqrt(1-A*A)-1):.5*(Math.sqrt(1-(A-=2)*A)+1)}}),Elastic:Object.freeze({In:function(A){return A===0?0:A===1?1:-Math.pow(2,10*(A-1))*Math.sin((A-1.1)*5*Math.PI)},Out:function(A){return A===0?0:A===1?1:Math.pow(2,-10*A)*Math.sin((A-.1)*5*Math.PI)+1},InOut:function(A){return A===0?0:A===1?1:(A*=2,A<1?-.5*Math.pow(2,10*(A-1))*Math.sin((A-1.1)*5*Math.PI):.5*Math.pow(2,-10*(A-1))*Math.sin((A-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(A){var F=1.70158;return A===1?1:A*A*((F+1)*A-F)},Out:function(A){var F=1.70158;return A===0?0:--A*A*((F+1)*A+F)+1},InOut:function(A){var F=2.5949095;return(A*=2)<1?.5*(A*A*((F+1)*A-F)):.5*((A-=2)*A*((F+1)*A+F)+2)}}),Bounce:Object.freeze({In:function(A){return 1-vt.Bounce.Out(1-A)},Out:function(A){return A<1/2.75?7.5625*A*A:A<2/2.75?7.5625*(A-=1.5/2.75)*A+.75:A<2.5/2.75?7.5625*(A-=2.25/2.75)*A+.9375:7.5625*(A-=2.625/2.75)*A+.984375},InOut:function(A){return A<.5?vt.Bounce.In(A*2)*.5:vt.Bounce.Out(A*2-1)*.5+.5}}),generatePow:function(A){return A===void 0&&(A=4),A=A1e4?1e4:A,{In:function(F){return Math.pow(F,A)},Out:function(F){return 1-Math.pow(1-F,A)},InOut:function(F){return F<.5?Math.pow(F*2,A)/2:(1-Math.pow(2-F*2,A))/2+.5}}}}),at=function(){return performance.now()},Y=(function(){function A(){for(var F=[],C=0;C0;){this._tweensAddedDuringUpdate={};for(var nt=0;nt1?ct(A[C],A[C-1],C-L):ct(A[nt],A[nt+1>C?C:nt+1],L-nt)},Bezier:function(A,F){for(var C=0,L=A.length-1,nt=Math.pow,ct=Z.Utils.Bernstein,ft=0;ft<=L;ft++)C+=nt(1-F,L-ft)*nt(F,ft)*A[ft]*ct(L,ft);return C},CatmullRom:function(A,F){var C=A.length-1,L=C*F,nt=Math.floor(L),ct=Z.Utils.CatmullRom;return A[0]===A[C]?(F<0&&(nt=Math.floor(L=C*(1+F))),ct(A[(nt-1+C)%C],A[nt],A[(nt+1)%C],A[(nt+2)%C],L-nt)):F<0?A[0]-(ct(A[0],A[0],A[1],A[1],-L)-A[0]):F>1?A[C]-(ct(A[C],A[C],A[C-1],A[C-1],L-C)-A[C]):ct(A[nt?nt-1:0],A[nt],A[C1;L--)C*=L;return A[F]=C,C}})(),CatmullRom:function(A,F,C,L,nt){var ct=(C-A)*.5,ft=(L-F)*.5,ne=nt*nt,le=nt*ne;return(2*F-2*C+ct+ft)*le+(-3*F+3*C-2*ct-ft)*ne+ct*nt+F}}},J=(function(){function A(){}return A.nextId=function(){return A._nextId++},A._nextId=0,A})(),X=new Y,H=(function(){function A(F,C){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=vt.Linear.None,this._interpolationFunction=Z.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=J.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=F,typeof C=="object"?(this._group=C,C.add(this)):C===!0&&(this._group=X,X.add(this))}return A.prototype.getId=function(){return this._id},A.prototype.isPlaying=function(){return this._isPlaying},A.prototype.isPaused=function(){return this._isPaused},A.prototype.getDuration=function(){return this._duration},A.prototype.to=function(F,C){if(C===void 0&&(C=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=F,this._propertiesAreSetUp=!1,this._duration=C<0?0:C,this},A.prototype.duration=function(F){return F===void 0&&(F=1e3),this._duration=F<0?0:F,this},A.prototype.dynamic=function(F){return F===void 0&&(F=!1),this._isDynamic=F,this},A.prototype.start=function(F,C){if(F===void 0&&(F=at()),C===void 0&&(C=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var L in this._valuesStartRepeat)this._swapEndStartRepeatValues(L),this._valuesStart[L]=this._valuesStartRepeat[L]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=F,this._startTime+=this._delayTime,!this._propertiesAreSetUp||C){if(this._propertiesAreSetUp=!0,!this._isDynamic){var nt={};for(var ct in this._valuesEnd)nt[ct]=this._valuesEnd[ct];this._valuesEnd=nt}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,C)}return this},A.prototype.startFromCurrentValues=function(F){return this.start(F,!0)},A.prototype._setupProperties=function(F,C,L,nt,ct){for(var ft in L){var ne=F[ft],le=Array.isArray(ne),de=le?"array":typeof ne,ye=!le&&Array.isArray(L[ft]);if(!(de==="undefined"||de==="function")){if(ye){var Le=L[ft];if(Le.length===0)continue;for(var Kt=[ne],je=0,Je=Le.length;je"u"||ct)&&(C[ft]=ne),le||(C[ft]*=1),ye?nt[ft]=L[ft].slice().reverse():nt[ft]=C[ft]||0}}},A.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},A.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},A.prototype.pause=function(F){return F===void 0&&(F=at()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=F,this)},A.prototype.resume=function(F){return F===void 0&&(F=at()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=F-this._pauseStart,this._pauseStart=0,this)},A.prototype.stopChainedTweens=function(){for(var F=0,C=this._chainedTweens.length;Fle)return 1;var Qe=Math.trunc(ft/ne),on=ft-Qe*ne,Ue=Math.min(on/L._duration,1);return Ue===0&&ft===L._duration?1:Ue},ye=de(),Le=this._easingFunction(ye);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,Le),this._onUpdateCallback&&this._onUpdateCallback(this._object,ye),this._duration===0||ft>=this._duration)if(this._repeat>0){var Kt=Math.min(Math.trunc((ft-this._duration)/ne)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=Kt);for(ct in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[ct]=="string"&&(this._valuesStartRepeat[ct]=this._valuesStartRepeat[ct]+parseFloat(this._valuesEnd[ct])),this._yoyo&&this._swapEndStartRepeatValues(ct),this._valuesStart[ct]=this._valuesStartRepeat[ct];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=ne*Kt,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var je=0,Je=this._chainedTweens.length;je=0;--t)if(r[t]>=65535)return!0;return!1}const Jm={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function kr(r,t){return new Jm[r](t)}function Yu(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function Vs(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function Zu(){const r=Vs("canvas");return r.style.display="block",r}const $u={};let Hi=null;function Km(r){Hi=r}function jm(){return Hi}function Gs(...r){const t="THREE."+r.shift();Hi?Hi("log",t,...r):console.log(t,...r)}function Ju(r){const t=r[0];if(typeof t=="string"&&t.startsWith("TSL:")){const e=r[1];e&&e.isStackTrace?r[0]+=" "+e.getLocation():r[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return r}function Ft(...r){r=Ju(r);const t="THREE."+r.shift();if(Hi)Hi("warn",t,...r);else{const e=r[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...r)}}function ie(...r){r=Ju(r);const t="THREE."+r.shift();if(Hi)Hi("error",t,...r);else{const e=r[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...r)}}function go(...r){const t=r.join(" ");t in $u||($u[t]=!0,Ft(...r))}function Qm(r,t,e){return new Promise(function(n,i){function s(){switch(r.clientWaitSync(t,r.SYNC_FLUSH_COMMANDS_BIT,0)){case r.WAIT_FAILED:i();break;case r.TIMEOUT_EXPIRED:setTimeout(s,e);break;default:n()}}setTimeout(s,e)})}const tg={[Nr]:Ss,[zi]:Aa,[wi]:wa,[Sn]:en,[Ss]:Nr,[Aa]:zi,[wa]:wi,[en]:Sn};class ri{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[t]===void 0&&(n[t]=[]),n[t].indexOf(e)===-1&&n[t].push(e)}hasEventListener(t,e){const n=this._listeners;return n===void 0?!1:n[t]!==void 0&&n[t].indexOf(e)!==-1}removeEventListener(t,e){const n=this._listeners;if(n===void 0)return;const i=n[t];if(i!==void 0){const s=i.indexOf(e);s!==-1&&i.splice(s,1)}}dispatchEvent(t){const e=this._listeners;if(e===void 0)return;const n=e[t.type];if(n!==void 0){t.target=this;const i=n.slice(0);for(let s=0,a=i.length;s>8&255]+An[r>>16&255]+An[r>>24&255]+"-"+An[t&255]+An[t>>8&255]+"-"+An[t>>16&15|64]+An[t>>24&255]+"-"+An[e&63|128]+An[e>>8&255]+"-"+An[e>>16&255]+An[e>>24&255]+An[n&255]+An[n>>8&255]+An[n>>16&255]+An[n>>24&255]).toLowerCase()}function pe(r,t,e){return Math.max(t,Math.min(e,r))}function Ec(r,t){return(r%t+t)%t}function eg(r,t,e,n,i){return n+(r-t)*(i-n)/(e-t)}function ng(r,t,e){return r!==t?(e-r)/(t-r):0}function Hs(r,t,e){return(1-e)*r+e*t}function ig(r,t,e,n){return Hs(r,t,1-Math.exp(-e*n))}function rg(r,t=1){return t-Math.abs(Ec(r,t*2)-t)}function sg(r,t,e){return r<=t?0:r>=e?1:(r=(r-t)/(e-t),r*r*(3-2*r))}function ag(r,t,e){return r<=t?0:r>=e?1:(r=(r-t)/(e-t),r*r*r*(r*(r*6-15)+10))}function og(r,t){return r+Math.floor(Math.random()*(t-r+1))}function lg(r,t){return r+Math.random()*(t-r)}function cg(r){return r*(.5-Math.random())}function hg(r){r!==void 0&&(Ku=r);let t=Ku+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function ug(r){return r*ur}function dg(r){return r*Vr}function fg(r){return(r&r-1)===0&&r!==0}function pg(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function mg(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))}function gg(r,t,e,n,i){const s=Math.cos,a=Math.sin,o=s(e/2),l=a(e/2),c=s((t+n)/2),h=a((t+n)/2),d=s((t-n)/2),u=a((t-n)/2),f=s((n-t)/2),p=a((n-t)/2);switch(i){case"XYX":r.set(o*h,l*d,l*u,o*c);break;case"YZY":r.set(l*u,o*h,l*d,o*c);break;case"ZXZ":r.set(l*d,l*u,o*h,o*c);break;case"XZX":r.set(o*h,l*p,l*f,o*c);break;case"YXY":r.set(l*f,o*h,l*p,o*c);break;case"ZYZ":r.set(l*p,l*f,o*h,o*c);break;default:Ft("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Dn(r,t){switch(t.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("Invalid component type.")}}function we(r,t){switch(t.constructor){case Float32Array:return r;case Uint32Array:return Math.round(r*4294967295);case Uint16Array:return Math.round(r*65535);case Uint8Array:return Math.round(r*255);case Int32Array:return Math.round(r*2147483647);case Int16Array:return Math.round(r*32767);case Int8Array:return Math.round(r*127);default:throw new Error("Invalid component type.")}}const _g={DEG2RAD:ur,RAD2DEG:Vr,generateUUID:qn,clamp:pe,euclideanModulo:Ec,mapLinear:eg,inverseLerp:ng,lerp:Hs,damp:ig,pingpong:rg,smoothstep:sg,smootherstep:ag,randInt:og,randFloat:lg,randFloatSpread:cg,seededRandom:hg,degToRad:ug,radToDeg:dg,isPowerOfTwo:fg,ceilPowerOfTwo:pg,floorPowerOfTwo:mg,setQuaternionFromProperEuler:gg,normalize:we,denormalize:Dn},iu=class iu{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,n=this.y,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6],this.y=i[1]*e+i[4]*n+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=pe(this.x,t.x,e.x),this.y=pe(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=pe(this.x,t,e),this.y=pe(this.y,t,e),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(pe(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(pe(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),s=this.x-t.x,a=this.y-t.y;return this.x=s*n-a*i+t.x,this.y=s*i+a*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};iu.prototype.isVector2=!0;let Mt=iu;class Un{constructor(t=0,e=0,n=0,i=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=n,this._w=i}static slerpFlat(t,e,n,i,s,a,o){let l=n[i+0],c=n[i+1],h=n[i+2],d=n[i+3],u=s[a+0],f=s[a+1],p=s[a+2],_=s[a+3];if(d!==_||l!==u||c!==f||h!==p){let g=l*u+c*f+h*p+d*_;g<0&&(u=-u,f=-f,p=-p,_=-_,g=-g);let m=1-o;if(g<.9995){const x=Math.acos(g),S=Math.sin(x);m=Math.sin(m*x)/S,o=Math.sin(o*x)/S,l=l*m+u*o,c=c*m+f*o,h=h*m+p*o,d=d*m+_*o}else{l=l*m+u*o,c=c*m+f*o,h=h*m+p*o,d=d*m+_*o;const x=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=x,c*=x,h*=x,d*=x}}t[e]=l,t[e+1]=c,t[e+2]=h,t[e+3]=d}static multiplyQuaternionsFlat(t,e,n,i,s,a){const o=n[i],l=n[i+1],c=n[i+2],h=n[i+3],d=s[a],u=s[a+1],f=s[a+2],p=s[a+3];return t[e]=o*p+h*d+l*f-c*u,t[e+1]=l*p+h*u+c*d-o*f,t[e+2]=c*p+h*f+o*u-l*d,t[e+3]=h*p-o*d-l*u-c*f,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const n=t._x,i=t._y,s=t._z,a=t._order,o=Math.cos,l=Math.sin,c=o(n/2),h=o(i/2),d=o(s/2),u=l(n/2),f=l(i/2),p=l(s/2);switch(a){case"XYZ":this._x=u*h*d+c*f*p,this._y=c*f*d-u*h*p,this._z=c*h*p+u*f*d,this._w=c*h*d-u*f*p;break;case"YXZ":this._x=u*h*d+c*f*p,this._y=c*f*d-u*h*p,this._z=c*h*p-u*f*d,this._w=c*h*d+u*f*p;break;case"ZXY":this._x=u*h*d-c*f*p,this._y=c*f*d+u*h*p,this._z=c*h*p+u*f*d,this._w=c*h*d-u*f*p;break;case"ZYX":this._x=u*h*d-c*f*p,this._y=c*f*d+u*h*p,this._z=c*h*p-u*f*d,this._w=c*h*d+u*f*p;break;case"YZX":this._x=u*h*d+c*f*p,this._y=c*f*d+u*h*p,this._z=c*h*p-u*f*d,this._w=c*h*d-u*f*p;break;case"XZY":this._x=u*h*d-c*f*p,this._y=c*f*d-u*h*p,this._z=c*h*p+u*f*d,this._w=c*h*d+u*f*p;break;default:Ft("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const n=e/2,i=Math.sin(n);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,n=e[0],i=e[4],s=e[8],a=e[1],o=e[5],l=e[9],c=e[2],h=e[6],d=e[10],u=n+o+d;if(u>0){const f=.5/Math.sqrt(u+1);this._w=.25/f,this._x=(h-l)*f,this._y=(s-c)*f,this._z=(a-i)*f}else if(n>o&&n>d){const f=2*Math.sqrt(1+n-o-d);this._w=(h-l)/f,this._x=.25*f,this._y=(i+a)/f,this._z=(s+c)/f}else if(o>d){const f=2*Math.sqrt(1+o-n-d);this._w=(s-c)/f,this._x=(i+a)/f,this._y=.25*f,this._z=(l+h)/f}else{const f=2*Math.sqrt(1+d-n-o);this._w=(a-i)/f,this._x=(s+c)/f,this._y=(l+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return n<1e-8?(n=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(pe(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(n===0)return this;const i=Math.min(1,e/n);return this.slerp(t,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,s=t._z,a=t._w,o=e._x,l=e._y,c=e._z,h=e._w;return this._x=n*h+a*o+i*c-s*l,this._y=i*h+a*l+s*o-n*c,this._z=s*h+a*c+n*l-i*o,this._w=a*h-n*o-i*l-s*c,this._onChangeCallback(),this}slerp(t,e){let n=t._x,i=t._y,s=t._z,a=t._w,o=this.dot(t);o<0&&(n=-n,i=-i,s=-s,a=-a,o=-o);let l=1-e;if(o<.9995){const c=Math.acos(o),h=Math.sin(c);l=Math.sin(l*c)/h,e=Math.sin(e*c)/h,this._x=this._x*l+n*e,this._y=this._y*l+i*e,this._z=this._z*l+s*e,this._w=this._w*l+a*e,this._onChangeCallback()}else this._x=this._x*l+n*e,this._y=this._y*l+i*e,this._z=this._z*l+s*e,this._w=this._w*l+a*e,this.normalize();return this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(i*Math.sin(t),i*Math.cos(t),s*Math.sin(e),s*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}const ru=class ru{constructor(t=0,e=0,n=0){this.x=t,this.y=e,this.z=n}set(t,e,n){return n===void 0&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(ju.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(ju.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,s=t.elements;return this.x=s[0]*e+s[3]*n+s[6]*i,this.y=s[1]*e+s[4]*n+s[7]*i,this.z=s[2]*e+s[5]*n+s[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,s=t.elements,a=1/(s[3]*e+s[7]*n+s[11]*i+s[15]);return this.x=(s[0]*e+s[4]*n+s[8]*i+s[12])*a,this.y=(s[1]*e+s[5]*n+s[9]*i+s[13])*a,this.z=(s[2]*e+s[6]*n+s[10]*i+s[14])*a,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,s=t.x,a=t.y,o=t.z,l=t.w,c=2*(a*i-o*n),h=2*(o*e-s*i),d=2*(s*n-a*e);return this.x=e+l*c+a*d-o*h,this.y=n+l*h+o*c-s*d,this.z=i+l*d+s*h-a*c,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,n=this.y,i=this.z,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i,this.y=s[1]*e+s[5]*n+s[9]*i,this.z=s[2]*e+s[6]*n+s[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=pe(this.x,t.x,e.x),this.y=pe(this.y,t.y,e.y),this.z=pe(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=pe(this.x,t,e),this.y=pe(this.y,t,e),this.z=pe(this.z,t,e),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(pe(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,s=t.z,a=e.x,o=e.y,l=e.z;return this.x=i*l-s*o,this.y=s*a-n*l,this.z=n*o-i*a,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Cc.copy(this).projectOnVector(t),this.sub(Cc)}reflect(t){return this.sub(Cc.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(pe(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){const i=Math.sin(e)*t;return this.x=i*Math.sin(n),this.y=Math.cos(e)*t,this.z=i*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=Math.random()*2-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};ru.prototype.isVector3=!0;let D=ru;const Cc=new D,ju=new Un,su=class su{constructor(t,e,n,i,s,a,o,l,c){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,n,i,s,a,o,l,c)}set(t,e,n,i,s,a,o,l,c){const h=this.elements;return h[0]=t,h[1]=i,h[2]=o,h[3]=e,h[4]=s,h[5]=l,h[6]=n,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,s=this.elements,a=n[0],o=n[3],l=n[6],c=n[1],h=n[4],d=n[7],u=n[2],f=n[5],p=n[8],_=i[0],g=i[3],m=i[6],x=i[1],S=i[4],b=i[7],P=i[2],E=i[5],O=i[8];return s[0]=a*_+o*x+l*P,s[3]=a*g+o*S+l*E,s[6]=a*m+o*b+l*O,s[1]=c*_+h*x+d*P,s[4]=c*g+h*S+d*E,s[7]=c*m+h*b+d*O,s[2]=u*_+f*x+p*P,s[5]=u*g+f*S+p*E,s[8]=u*m+f*b+p*O,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],c=t[7],h=t[8];return e*a*h-e*o*c-n*s*h+n*o*l+i*s*c-i*a*l}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],c=t[7],h=t[8],d=h*a-o*c,u=o*l-h*s,f=c*s-a*l,p=e*d+n*u+i*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const _=1/p;return t[0]=d*_,t[1]=(i*c-h*n)*_,t[2]=(o*n-i*a)*_,t[3]=u*_,t[4]=(h*e-i*l)*_,t[5]=(i*s-o*e)*_,t[6]=f*_,t[7]=(n*l-c*e)*_,t[8]=(a*e-n*s)*_,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,i,s,a,o){const l=Math.cos(s),c=Math.sin(s);return this.set(n*l,n*c,-n*(l*a+c*o)+a+t,-i*c,i*l,-i*(-c*a+l*o)+o+e,0,0,1),this}scale(t,e){return this.premultiply(Rc.makeScale(t,e)),this}rotate(t){return this.premultiply(Rc.makeRotation(-t)),this}translate(t,e){return this.premultiply(Rc.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,n=t.elements;for(let i=0;i<9;i++)if(e[i]!==n[i])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return new this.constructor().fromArray(this.elements)}};su.prototype.isMatrix3=!0;let Me=su;const Rc=new Me,Qu=new Me().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),td=new Me().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function xg(){const r={enabled:!0,workingColorSpace:Bs,spaces:{},convert:function(i,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===Ge&&(i.r=Ri(i.r),i.g=Ri(i.g),i.b=Ri(i.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(i.applyMatrix3(this.spaces[s].toXYZ),i.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Ge&&(i.r=Gr(i.r),i.g=Gr(i.g),i.b=Gr(i.b))),i},workingToColorSpace:function(i,s){return this.convert(i,this.workingColorSpace,s)},colorSpaceToWorking:function(i,s){return this.convert(i,s,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===Ci?zs:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,s=this.workingColorSpace){return i.fromArray(this.spaces[s].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,s,a){return i.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,s){return go("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),r.workingToColorSpace(i,s)},toWorkingColorSpace:function(i,s){return go("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),r.colorSpaceToWorking(i,s)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],n=[.3127,.329];return r.define({[Bs]:{primaries:t,whitePoint:n,transfer:zs,toXYZ:Qu,fromXYZ:td,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:kn},outputColorSpaceConfig:{drawingBufferColorSpace:kn}},[kn]:{primaries:t,whitePoint:n,transfer:Ge,toXYZ:Qu,fromXYZ:td,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:kn}}}),r}const Ne=xg();function Ri(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function Gr(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}let Hr;class ed{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let n;if(t instanceof HTMLCanvasElement)n=t;else{Hr===void 0&&(Hr=Vs("canvas")),Hr.width=t.width,Hr.height=t.height;const i=Hr.getContext("2d");t instanceof ImageData?i.putImageData(t,0,0):i.drawImage(t,0,0,t.width,t.height),n=Hr}return n.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){const e=Vs("canvas");e.width=t.width,e.height=t.height;const n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);const i=n.getImageData(0,0,t.width,t.height),s=i.data;for(let a=0;a1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Pc).x}get height(){return this.source.getSize(Pc).y}get depth(){return this.source.getSize(Pc).z}get image(){return this.source.data}set image(t){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(const e in t){const n=t[e];if(n===void 0){Ft(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const i=this[e];if(i===void 0){Ft(`Texture.setValues(): property '${e}' does not exist.`);continue}i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[e]=n}}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,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,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==Ea)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case ws:t.x=t.x-Math.floor(t.x);break;case Bn:t.x=t.x<0?0:1;break;case Es:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case ws:t.y=t.y-Math.floor(t.y);break;case Bn:t.y=t.y<0?0:1;break;case Es:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}}nn.DEFAULT_IMAGE=null,nn.DEFAULT_MAPPING=Ea,nn.DEFAULT_ANISOTROPY=1;const au=class au{constructor(t=0,e=0,n=0,i=1){this.x=t,this.y=e,this.z=n,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,i){return this.x=t,this.y=e,this.z=n,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,s=this.w,a=t.elements;return this.x=a[0]*e+a[4]*n+a[8]*i+a[12]*s,this.y=a[1]*e+a[5]*n+a[9]*i+a[13]*s,this.z=a[2]*e+a[6]*n+a[10]*i+a[14]*s,this.w=a[3]*e+a[7]*n+a[11]*i+a[15]*s,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,i,s;const l=t.elements,c=l[0],h=l[4],d=l[8],u=l[1],f=l[5],p=l[9],_=l[2],g=l[6],m=l[10];if(Math.abs(h-u)<.01&&Math.abs(d-_)<.01&&Math.abs(p-g)<.01){if(Math.abs(h+u)<.1&&Math.abs(d+_)<.1&&Math.abs(p+g)<.1&&Math.abs(c+f+m-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const S=(c+1)/2,b=(f+1)/2,P=(m+1)/2,E=(h+u)/4,O=(d+_)/4,y=(p+g)/4;return S>b&&S>P?S<.01?(n=0,i=.707106781,s=.707106781):(n=Math.sqrt(S),i=E/n,s=O/n):b>P?b<.01?(n=.707106781,i=0,s=.707106781):(i=Math.sqrt(b),n=E/i,s=y/i):P<.01?(n=.707106781,i=.707106781,s=0):(s=Math.sqrt(P),n=O/s,i=y/s),this.set(n,i,s,e),this}let x=Math.sqrt((g-p)*(g-p)+(d-_)*(d-_)+(u-h)*(u-h));return Math.abs(x)<.001&&(x=1),this.x=(g-p)/x,this.y=(d-_)/x,this.z=(u-h)/x,this.w=Math.acos((c+f+m-1)/2),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=pe(this.x,t.x,e.x),this.y=pe(this.y,t.y,e.y),this.z=pe(this.z,t.z,e.z),this.w=pe(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=pe(this.x,t,e),this.y=pe(this.y,t,e),this.z=pe(this.z,t,e),this.w=pe(this.w,t,e),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(pe(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this.w=t.w+(e.w-t.w)*n,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};au.prototype.isVector4=!0;let We=au;class Lc extends ri{constructor(t=1,e=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:tn,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=n.depth,this.scissor=new We(0,0,t,e),this.scissorTest=!1,this.viewport=new We(0,0,t,e),this.textures=[];const i={width:t,height:e,depth:n.depth},s=new nn(i),a=n.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,n=t.textures.length;e>>0}enable(t){this.mask|=1<1){for(let e=0;e1){for(let n=0;n0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.pivot!==null&&(i.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(o=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(t),i.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(t)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(t.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){i.children=[];for(let o=0;o0){i.animations=[];for(let o=0;o0&&(n.geometries=o),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),d.length>0&&(n.shapes=d),u.length>0&&(n.skeletons=u),f.length>0&&(n.animations=f),p.length>0&&(n.nodes=p)}return n.object=i,n;function a(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=t.pivot!==null?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let n=0;nf+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!c.inputState.pinching&&u<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else l!==null&&t.gripSpace&&(s=e.getPose(t.gripSpace,n),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:t,target:this})));o!==null&&(i=e.getPose(t.targetRaySpace,n),i===null&&s!==null&&(i=s),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Rg)))}return o!==null&&(o.visible=i!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){const n=new Yr;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}}const cd={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,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,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},qi={h:0,s:0,l:0},bo={h:0,s:0,l:0};function Uc(r,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<.16666666666666666?r+(t-r)*6*e:e<.5?t:e<.6666666666666666?r+(t-r)*6*(.6666666666666666-e):r}class $t{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(e===void 0&&n===void 0){const i=t;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=kn){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,Ne.colorSpaceToWorking(this,e),this}setRGB(t,e,n,i=Ne.workingColorSpace){return this.r=t,this.g=e,this.b=n,Ne.colorSpaceToWorking(this,i),this}setHSL(t,e,n,i=Ne.workingColorSpace){if(t=Ec(t,1),e=pe(e,0,1),n=pe(n,0,1),e===0)this.r=this.g=this.b=n;else{const s=n<=.5?n*(1+e):n+e-n*e,a=2*n-s;this.r=Uc(a,s,t+.3333333333333333),this.g=Uc(a,s,t),this.b=Uc(a,s,t-.3333333333333333)}return Ne.colorSpaceToWorking(this,i),this}setStyle(t,e=kn){function n(s){s!==void 0&&parseFloat(s)<1&&Ft("Color: Alpha component of "+t+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(t)){let s;const a=i[1],o=i[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,e);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,e);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,e);break;default:Ft("Color: Unknown color model "+t)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(t)){const s=i[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,e);if(a===6)return this.setHex(parseInt(s,16),e);Ft("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=kn){const n=cd[t.toLowerCase()];return n!==void 0?this.setHex(n,e):Ft("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Ri(t.r),this.g=Ri(t.g),this.b=Ri(t.b),this}copyLinearToSRGB(t){return this.r=Gr(t.r),this.g=Gr(t.g),this.b=Gr(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=kn){return Ne.workingToColorSpace(wn.copy(this),t),Math.round(pe(wn.r*255,0,255))*65536+Math.round(pe(wn.g*255,0,255))*256+Math.round(pe(wn.b*255,0,255))}getHexString(t=kn){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Ne.workingColorSpace){Ne.workingToColorSpace(wn.copy(this),e);const n=wn.r,i=wn.g,s=wn.b,a=Math.max(n,i,s),o=Math.min(n,i,s);let l,c;const h=(o+a)/2;if(o===a)l=0,c=0;else{const d=a-o;switch(c=h<=.5?d/(a+o):d/(2-a-o),a){case n:l=(i-s)/d+(i0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}const oi=new D,Pi=new D,Nc=new D,Li=new D,Zr=new D,$r=new D,ud=new D,Fc=new D,Oc=new D,Bc=new D,zc=new We,kc=new We,Vc=new We;class Vn{constructor(t=new D,e=new D,n=new D){this.a=t,this.b=e,this.c=n}static getNormal(t,e,n,i){i.subVectors(n,e),oi.subVectors(t,e),i.cross(oi);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(t,e,n,i,s){oi.subVectors(i,e),Pi.subVectors(n,e),Nc.subVectors(t,e);const a=oi.dot(oi),o=oi.dot(Pi),l=oi.dot(Nc),c=Pi.dot(Pi),h=Pi.dot(Nc),d=a*c-o*o;if(d===0)return s.set(0,0,0),null;const u=1/d,f=(c*l-o*h)*u,p=(a*h-o*l)*u;return s.set(1-f-p,p,f)}static containsPoint(t,e,n,i){return this.getBarycoord(t,e,n,i,Li)===null?!1:Li.x>=0&&Li.y>=0&&Li.x+Li.y<=1}static getInterpolation(t,e,n,i,s,a,o,l){return this.getBarycoord(t,e,n,i,Li)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,Li.x),l.addScaledVector(a,Li.y),l.addScaledVector(o,Li.z),l)}static getInterpolatedAttribute(t,e,n,i,s,a){return zc.setScalar(0),kc.setScalar(0),Vc.setScalar(0),zc.fromBufferAttribute(t,e),kc.fromBufferAttribute(t,n),Vc.fromBufferAttribute(t,i),a.setScalar(0),a.addScaledVector(zc,s.x),a.addScaledVector(kc,s.y),a.addScaledVector(Vc,s.z),a}static isFrontFacing(t,e,n,i){return oi.subVectors(n,e),Pi.subVectors(t,e),oi.cross(Pi).dot(i)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this}setFromAttributeAndIndices(t,e,n,i){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,i),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return oi.subVectors(this.c,this.b),Pi.subVectors(this.a,this.b),oi.cross(Pi).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(.3333333333333333)}getNormal(t){return Vn.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Vn.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,i,s){return Vn.getInterpolation(t,this.a,this.b,this.c,e,n,i,s)}containsPoint(t){return Vn.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Vn.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,s=this.c;let a,o;Zr.subVectors(i,n),$r.subVectors(s,n),Fc.subVectors(t,n);const l=Zr.dot(Fc),c=$r.dot(Fc);if(l<=0&&c<=0)return e.copy(n);Oc.subVectors(t,i);const h=Zr.dot(Oc),d=$r.dot(Oc);if(h>=0&&d<=h)return e.copy(i);const u=l*d-h*c;if(u<=0&&l>=0&&h<=0)return a=l/(l-h),e.copy(n).addScaledVector(Zr,a);Bc.subVectors(t,s);const f=Zr.dot(Bc),p=$r.dot(Bc);if(p>=0&&f<=p)return e.copy(s);const _=f*c-l*p;if(_<=0&&c>=0&&p<=0)return o=c/(c-p),e.copy(n).addScaledVector($r,o);const g=h*p-f*d;if(g<=0&&d-h>=0&&f-p>=0)return ud.subVectors(s,i),o=(d-h)/(d-h+(f-p)),e.copy(i).addScaledVector(ud,o);const m=1/(g+_+u);return a=_*m,o=u*m,e.copy(n).addScaledVector(Zr,a).addScaledVector($r,o)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}class En{constructor(t=new D(1/0,1/0,1/0),e=new D(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,li),li.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Xs),Eo.subVectors(this.max,Xs),Jr.subVectors(t.a,Xs),Kr.subVectors(t.b,Xs),jr.subVectors(t.c,Xs),Yi.subVectors(Kr,Jr),Zi.subVectors(jr,Kr),dr.subVectors(Jr,jr);let e=[0,-Yi.z,Yi.y,0,-Zi.z,Zi.y,0,-dr.z,dr.y,Yi.z,0,-Yi.x,Zi.z,0,-Zi.x,dr.z,0,-dr.x,-Yi.y,Yi.x,0,-Zi.y,Zi.x,0,-dr.y,dr.x,0];return!Gc(e,Jr,Kr,jr,Eo)||(e=[1,0,0,0,1,0,0,0,1],!Gc(e,Jr,Kr,jr,Eo))?!1:(Co.crossVectors(Yi,Zi),e=[Co.x,Co.y,Co.z],Gc(e,Jr,Kr,jr,Eo))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,li).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(li).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(Di[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Di[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Di[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Di[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Di[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Di[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Di[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Di[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Di),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}}const Di=[new D,new D,new D,new D,new D,new D,new D,new D],li=new D,wo=new En,Jr=new D,Kr=new D,jr=new D,Yi=new D,Zi=new D,dr=new D,Xs=new D,Eo=new D,Co=new D,fr=new D;function Gc(r,t,e,n,i){for(let s=0,a=r.length-3;s<=a;s+=3){fr.fromArray(r,s);const o=i.x*Math.abs(fr.x)+i.y*Math.abs(fr.y)+i.z*Math.abs(fr.z),l=t.dot(fr),c=e.dot(fr),h=n.dot(fr);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const Ui=Ig();function Ig(){const r=new ArrayBuffer(4),t=new Float32Array(r),e=new Uint32Array(r),n=new Uint32Array(512),i=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(n[l]=0,n[l|256]=32768,i[l]=24,i[l|256]=24):c<-14?(n[l]=1024>>-c-14,n[l|256]=1024>>-c-14|32768,i[l]=-c-1,i[l|256]=-c-1):c<=15?(n[l]=c+15<<10,n[l|256]=c+15<<10|32768,i[l]=13,i[l|256]=13):c<128?(n[l]=31744,n[l|256]=64512,i[l]=24,i[l|256]=24):(n[l]=31744,n[l|256]=64512,i[l]=13,i[l|256]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;(c&8388608)===0;)c<<=1,h-=8388608;c&=-8388609,h+=947912704,s[l]=c|h}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:t,uint32View:e,baseTable:n,shiftTable:i,mantissaTable:s,exponentTable:a,offsetTable:o}}function Gn(r){Math.abs(r)>65504&&Ft("DataUtils.toHalfFloat(): Value out of range."),r=pe(r,-65504,65504),Ui.floatView[0]=r;const t=Ui.uint32View[0],e=t>>23&511;return Ui.baseTable[e]+((t&8388607)>>Ui.shiftTable[e])}function qs(r){const t=r>>10;return Ui.uint32View[0]=Ui.mantissaTable[Ui.offsetTable[t]+(r&1023)]+Ui.exponentTable[t],Ui.floatView[0]}class Pg{static toHalfFloat(t){return Gn(t)}static fromHalfFloat(t){return qs(t)}}const fn=new D,Ro=new Mt;let Lg=0;class Xe extends ri{constructor(t,e,n=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Lg++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=n,this.usage=ks,this.updateRanges=[],this.gpuType=Pn,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,s=this.itemSize;ithis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Ys.subVectors(t,this.center);const e=Ys.lengthSq();if(e>this.radius*this.radius){const n=Math.sqrt(e),i=(n-this.radius)*.5;this.center.addScaledVector(Ys,i/n),this.radius+=i}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(Xc.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Ys.copy(t.center).add(Xc)),this.expandByPoint(Ys.copy(t.center).sub(Xc))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}}let kg=0;const jn=new ge,qc=new Fe,Qr=new D,$n=new En,Zs=new En,xn=new D;class Se extends ri{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:kg++}),this.uuid=qn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new($m(t)?Wc:Hc)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,n=0){this.groups.push({start:t,count:e,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const s=new Me().getNormalMatrix(t);n.applyNormalMatrix(s),n.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(t),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(t){return jn.makeRotationFromQuaternion(t),this.applyMatrix4(jn),this}rotateX(t){return jn.makeRotationX(t),this.applyMatrix4(jn),this}rotateY(t){return jn.makeRotationY(t),this.applyMatrix4(jn),this}rotateZ(t){return jn.makeRotationZ(t),this.applyMatrix4(jn),this}translate(t,e,n){return jn.makeTranslation(t,e,n),this.applyMatrix4(jn),this}scale(t,e,n){return jn.makeScale(t,e,n),this.applyMatrix4(jn),this}lookAt(t){return qc.lookAt(t),qc.updateMatrix(),this.applyMatrix4(qc.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Qr).negate(),this.translate(Qr.x,Qr.y,Qr.z),this}setFromPoints(t){const e=this.getAttribute("position");if(e===void 0){const n=[];for(let i=0,s=t.length;ie.count&&Ft("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new En);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){ie("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new D(-1/0,-1/0,-1/0),new D(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let n=0,i=e.length;n0&&(t.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(t[c]=l[c]);return t}t.data={attributes:{}};const e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const l in n){const c=n[l];t.data.attributes[l]=c.toJSON(t.data)}const i={};let s=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let d=0,u=c.length;d0&&(i[l]=h,s=!0)}s&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(t.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(t.data.boundingSphere=o.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const n=t.index;n!==null&&this.setIndex(n.clone());const i=t.attributes;for(const c in i){const h=i[c];this.setAttribute(c,h.clone(e))}const s=t.morphAttributes;for(const c in s){const h=[],d=s[c];for(let u=0,f=d.length;u0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(const e in t){const n=t[e];if(n===void 0){Ft(`Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];if(i===void 0){Ft(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n}}toJSON(t){const e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Ut&&(n.blending=this.blending),this.side!==_t&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Je&&(n.blendSrc=this.blendSrc),this.blendDst!==Qe&&(n.blendDst=this.blendDst),this.blendEquation!==ct&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Sn&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Ac&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==cr&&(n.stencilFail=this.stencilFail),this.stencilZFail!==cr&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==cr&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function i(s){const a=[];for(const o in s){const l=s[o];delete l.metadata,a.push(l)}return a}if(e){const s=i(t.textures),a=i(t.images);s.length>0&&(n.textures=s),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let n=null;if(e!==null){const i=e.length;n=new Array(i);for(let s=0;s!==i;++s)n[s]=e[s].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}}class Yc extends Cn{constructor(t){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new $t(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.rotation=t.rotation,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}let ts;const $s=new D,es=new D,ns=new D,is=new Mt,Js=new Mt,dd=new ge,Po=new D,Ks=new D,Lo=new D,fd=new Mt,Zc=new Mt,pd=new Mt;class md extends Fe{constructor(t=new Yc){if(super(),this.isSprite=!0,this.type="Sprite",ts===void 0){ts=new Se;const e=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),n=new Io(e,5);ts.setIndex([0,1,2,0,2,3]),ts.setAttribute("position",new pr(n,3,0,!1)),ts.setAttribute("uv",new pr(n,2,3,!1))}this.geometry=ts,this.material=t,this.center=new Mt(.5,.5),this.count=1}raycast(t,e){t.camera===null&&ie('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),es.setFromMatrixScale(this.matrixWorld),dd.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),ns.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&es.multiplyScalar(-ns.z);const n=this.material.rotation;let i,s;n!==0&&(s=Math.cos(n),i=Math.sin(n));const a=this.center;Do(Po.set(-.5,-.5,0),ns,a,es,i,s),Do(Ks.set(.5,-.5,0),ns,a,es,i,s),Do(Lo.set(.5,.5,0),ns,a,es,i,s),fd.set(0,0),Zc.set(1,0),pd.set(1,1);let o=t.ray.intersectTriangle(Po,Ks,Lo,!1,$s);if(o===null&&(Do(Ks.set(-.5,.5,0),ns,a,es,i,s),Zc.set(0,1),o=t.ray.intersectTriangle(Po,Lo,Ks,!1,$s),o===null))return;const l=t.ray.origin.distanceTo($s);lt.far||e.push({distance:l,point:$s.clone(),uv:Vn.getInterpolation($s,Po,Ks,Lo,fd,Zc,pd,new Mt),face:null,object:this})}copy(t,e){return super.copy(t,e),t.center!==void 0&&this.center.copy(t.center),this.material=t.material,this}}function Do(r,t,e,n,i,s){is.subVectors(r,e).addScalar(.5).multiply(n),i!==void 0?(Js.x=s*is.x-i*is.y,Js.y=i*is.x+s*is.y):Js.copy(is),r.copy(t),r.x+=Js.x,r.y+=Js.y,r.applyMatrix4(dd)}const Uo=new D,gd=new D;class _d extends Fe{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let n=0,i=e.length;n0){let n,i;for(n=1,i=e.length;n0){Uo.setFromMatrixPosition(this.matrixWorld);const i=t.ray.origin.distanceTo(Uo);this.getObjectForDistance(i).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){Uo.setFromMatrixPosition(t.matrixWorld),gd.setFromMatrixPosition(this.matrixWorld);const n=Uo.distanceTo(gd)/t.zoom;e[0].object.visible=!0;let i,s;for(i=1,s=e.length;i=a)e[i-1].object.visible=!1,e[i].object.visible=!0;else break}for(this._currentLevel=i-1;i0)if(d=a*l-o,u=a*o-l,p=s*h,d>=0)if(u>=-p)if(u<=p){const _=1/h;d*=_,u*=_,f=d*(d+a*u+2*o)+u*(a*d+u+2*l)+c}else u=s,d=Math.max(0,-(a*u+o)),f=-d*d+u*(u+2*l)+c;else u=-s,d=Math.max(0,-(a*u+o)),f=-d*d+u*(u+2*l)+c;else u<=-p?(d=Math.max(0,-(-a*s+o)),u=d>0?-s:Math.min(Math.max(-s,-l),s),f=-d*d+u*(u+2*l)+c):u<=p?(d=0,u=Math.min(Math.max(-s,-l),s),f=u*(u+2*l)+c):(d=Math.max(0,-(a*s+o)),u=d>0?s:Math.min(Math.max(-s,-l),s),f=-d*d+u*(u+2*l)+c);else u=a>0?-s:s,d=Math.max(0,-(a*u+o)),f=-d*d+u*(u+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,d),i&&i.copy($c).addScaledVector(No,u),f}intersectSphere(t,e){Ni.subVectors(t.center,this.origin);const n=Ni.dot(this.direction),i=Ni.dot(Ni)-n*n,s=t.radius*t.radius;if(i>s)return null;const a=Math.sqrt(s-i),o=n-a,l=n+a;return l<0?null:o<0?this.at(l,e):this.at(o,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){const n=this.distanceToPlane(t);return n===null?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,s,a,o,l;const c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,u=this.origin;return c>=0?(n=(t.min.x-u.x)*c,i=(t.max.x-u.x)*c):(n=(t.max.x-u.x)*c,i=(t.min.x-u.x)*c),h>=0?(s=(t.min.y-u.y)*h,a=(t.max.y-u.y)*h):(s=(t.max.y-u.y)*h,a=(t.min.y-u.y)*h),n>a||s>i||((s>n||isNaN(n))&&(n=s),(a=0?(o=(t.min.z-u.z)*d,l=(t.max.z-u.z)*d):(o=(t.max.z-u.z)*d,l=(t.min.z-u.z)*d),n>l||o>i)||((o>n||n!==n)&&(n=o),(l=0?n:i,e)}intersectsBox(t){return this.intersectBox(t,Ni)!==null}intersectTriangle(t,e,n,i,s){Jc.subVectors(e,t),Fo.subVectors(n,t),Kc.crossVectors(Jc,Fo);let a=this.direction.dot(Kc),o;if(a>0){if(i)return null;o=1}else if(a<0)o=-1,a=-a;else return null;$i.subVectors(this.origin,t);const l=o*this.direction.dot(Fo.crossVectors($i,Fo));if(l<0)return null;const c=o*this.direction.dot(Jc.cross($i));if(c<0||l+c>a)return null;const h=-o*$i.dot(Kc);return h<0?null:this.at(h/a,s)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ji extends Cn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new $t(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ai,this.combine=bs,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const xd=new ge,mr=new rs,Oo=new bn,vd=new D,Bo=new D,zo=new D,ko=new D,jc=new D,Vo=new D,yd=new D,Go=new D;class pn extends Fe{constructor(t=new Se,e=new Ji){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),t.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),t.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,n=Object.keys(e);if(n.length>0){const i=e[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=i.length;s(t.far-t.near)**2))&&(xd.copy(s).invert(),mr.copy(t.ray).applyMatrix4(xd),!(n.boundingBox!==null&&mr.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(t,e,mr)))}_computeIntersections(t,e,n){let i;const s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,h=s.attributes.uv1,d=s.attributes.normal,u=s.groups,f=s.drawRange;if(o!==null)if(Array.isArray(a))for(let p=0,_=u.length;p<_;p++){const g=u[p],m=a[g.materialIndex],x=Math.max(g.start,f.start),S=Math.min(o.count,Math.min(g.start+g.count,f.start+f.count));for(let b=x,P=S;be.far?null:{distance:c,point:Go.clone(),object:r}}function Ho(r,t,e,n,i,s,a,o,l,c){r.getVertexPosition(o,Bo),r.getVertexPosition(l,zo),r.getVertexPosition(c,ko);const h=Gg(r,t,e,n,Bo,zo,ko,yd);if(h){const d=new D;Vn.getBarycoord(yd,Bo,zo,ko,d),i&&(h.uv=Vn.getInterpolatedAttribute(i,o,l,c,d,new Mt)),s&&(h.uv1=Vn.getInterpolatedAttribute(s,o,l,c,d,new Mt)),a&&(h.normal=Vn.getInterpolatedAttribute(a,o,l,c,d,new D),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));const u={a:o,b:l,c,normal:new D,materialIndex:0};Vn.getNormal(Bo,zo,ko,u.normal),h.face=u,h.barycoord=d}return h}const js=new We,Md=new We,Sd=new We,Hg=new We,bd=new ge,Wo=new D,Qc=new bn,Td=new ge,th=new rs;class Ad extends pn{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=mc,this.bindMatrix=new ge,this.bindMatrixInverse=new ge,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;this.boundingBox===null&&(this.boundingBox=new En),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let n=0;n1)?null:e.copy(t.start).addScaledVector(i,a)}intersectsLine(t){const e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const n=e||Yg.getNormalMatrix(t),i=this.coplanarPoint(nh).applyMatrix4(t),s=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(s),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}}const gr=new bn,Zg=new Mt(.5,.5),Yo=new D;class os{constructor(t=new Ki,e=new Ki,n=new Ki,i=new Ki,s=new Ki,a=new Ki){this.planes=[t,e,n,i,s,a]}set(t,e,n,i,s,a){const o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(n),o[3].copy(i),o[4].copy(s),o[5].copy(a),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=Xn,n=!1){const i=this.planes,s=t.elements,a=s[0],o=s[1],l=s[2],c=s[3],h=s[4],d=s[5],u=s[6],f=s[7],p=s[8],_=s[9],g=s[10],m=s[11],x=s[12],S=s[13],b=s[14],P=s[15];if(i[0].setComponents(c-a,f-h,m-p,P-x).normalize(),i[1].setComponents(c+a,f+h,m+p,P+x).normalize(),i[2].setComponents(c+o,f+d,m+_,P+S).normalize(),i[3].setComponents(c-o,f-d,m-_,P-S).normalize(),n)i[4].setComponents(l,u,g,b).normalize(),i[5].setComponents(c-l,f-u,m-g,P-b).normalize();else if(i[4].setComponents(c-l,f-u,m-g,P-b).normalize(),e===Xn)i[5].setComponents(c+l,f+u,m+g,P+b).normalize();else if(e===hr)i[5].setComponents(l,u,g,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(t){if(t.boundingSphere!==void 0)t.boundingSphere===null&&t.computeBoundingSphere(),gr.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),gr.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(gr)}intersectsSprite(t){gr.center.set(0,0,0);const e=Zg.distanceTo(t.center);return gr.radius=.7071067811865476+e,gr.applyMatrix4(t.matrixWorld),this.intersectsSphere(gr)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let s=0;s<6;s++)if(e[s].distanceToPoint(n)0?t.max.x:t.min.x,Yo.y=i.normal.y>0?t.max.y:t.min.y,Yo.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(Yo)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const xi=new ge,vi=new os;class Zo{constructor(){this.coordinateSystem=Xn}intersectsObject(t,e){if(!e.isArrayCamera||e.cameras.length===0)return!1;for(let n=0;n=s.length&&s.push({start:-1,count:-1,z:-1,index:-1});const o=s[this.index];a.push(o),this.index++,o.start=t,o.count=e,o.z=n,o.index=i}reset(){this.list.length=0,this.index=0}}const Hn=new ge,jg=new $t(1,1,1),Id=new os,Qg=new Zo,$o=new En,_r=new bn,ea=new D,Pd=new D,t0=new D,rh=new Kg,Rn=new pn,Jo=[];function e0(r,t,e=0){const n=t.itemSize;if(r.isInterleavedBufferAttribute||r.array.constructor!==t.array.constructor){const i=r.count;for(let s=0;s65535?new Uint32Array(i):new Uint16Array(i);e.setIndex(new Xe(s,1))}this._geometryInitialized=!0}}_validateGeometry(t){const e=this.geometry;if(!!t.getIndex()!=!!e.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const n in e.attributes){if(!t.hasAttribute(n))throw new Error(`THREE.BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);const i=t.getAttribute(n),s=e.getAttribute(n);if(i.itemSize!==s.itemSize||i.normalized!==s.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(t){const e=this._instanceInfo;if(t<0||t>=e.length||e[t].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${t}. Instance is either out of range or has been deleted.`)}validateGeometryId(t){const e=this._geometryInfo;if(t<0||t>=e.length||e[t].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${t}. Geometry is either out of range or has been deleted.`)}setCustomSort(t){return this.customSort=t,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new En);const t=this.boundingBox,e=this._instanceInfo;t.makeEmpty();for(let n=0,i=e.length;n=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const n={visible:!0,active:!0,geometryIndex:t};let i=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(ih),i=this._availableInstanceIds.shift(),this._instanceInfo[i]=n):(i=this._instanceInfo.length,this._instanceInfo.push(n));const s=this._matricesTexture;Hn.identity().toArray(s.image.data,i*16),s.needsUpdate=!0;const a=this._colorsTexture;return a&&(jg.toArray(a.image.data,i*4),a.needsUpdate=!0),this._visibilityChanged=!0,i}addGeometry(t,e=-1,n=-1){this._initializeGeometry(t),this._validateGeometry(t);const i={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},s=this._geometryInfo;i.vertexStart=this._nextVertexStart,i.reservedVertexCount=e===-1?t.getAttribute("position").count:e;const a=t.getIndex();if(a!==null&&(i.indexStart=this._nextIndexStart,i.reservedIndexCount=n===-1?a.count:n),i.indexStart!==-1&&i.indexStart+i.reservedIndexCount>this._maxIndexCount||i.vertexStart+i.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(ih),l=this._availableGeometryIds.shift(),s[l]=i):(l=this._geometryCount,this._geometryCount++,s.push(i)),this.setGeometryAt(l,t),this._nextIndexStart=i.indexStart+i.reservedIndexCount,this._nextVertexStart=i.vertexStart+i.reservedVertexCount,l}setGeometryAt(t,e){if(t>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(e);const n=this.geometry,i=n.getIndex()!==null,s=n.getIndex(),a=e.getIndex(),o=this._geometryInfo[t];if(i&&a.count>o.reservedIndexCount||e.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=e.getAttribute("position").count;for(const h in n.attributes){const d=e.getAttribute(h),u=n.getAttribute(h);e0(d,u,l);const f=d.itemSize;for(let p=d.count,_=c;p<_;p++){const g=l+p;for(let m=0;m=e.length||e[t].active===!1)return this;const n=this._instanceInfo;for(let i=0,s=n.length;io).sort((a,o)=>n[a].vertexStart-n[o].vertexStart),s=this.geometry;for(let a=0,o=n.length;a=this._geometryCount)return null;const n=this.geometry,i=this._geometryInfo[t];if(i.boundingBox===null){const s=new En,a=n.index,o=n.attributes.position;for(let l=i.start,c=i.start+i.count;l=this._geometryCount)return null;const n=this.geometry,i=this._geometryInfo[t];if(i.boundingSphere===null){const s=new bn;this.getBoundingBoxAt(t,$o),$o.getCenter(s.center);const a=n.index,o=n.attributes.position;let l=0;for(let c=i.start,h=i.start+i.count;co.active);if(Math.max(...n.map(o=>o.vertexStart+o.reservedVertexCount))>t)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${e}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...n.map(l=>l.indexStart+l.reservedIndexCount))>e)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${e}. Cannot shrink further.`);const s=this.geometry;s.dispose(),this._maxVertexCount=t,this._maxIndexCount=e,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Se,this._initializeGeometry(s));const a=this.geometry;s.index&&xr(s.index.array,a.index.array);for(const o in s.attributes)xr(s.attributes[o].array,a.attributes[o].array)}raycast(t,e){const n=this._instanceInfo,i=this._geometryInfo,s=this.matrixWorld,a=this.geometry;Rn.material=this.material,Rn.geometry.index=a.index,Rn.geometry.attributes=a.attributes,Rn.geometry.boundingBox===null&&(Rn.geometry.boundingBox=new En),Rn.geometry.boundingSphere===null&&(Rn.geometry.boundingSphere=new bn);for(let o=0,l=n.length;o({...e,boundingBox:e.boundingBox!==null?e.boundingBox.clone():null,boundingSphere:e.boundingSphere!==null?e.boundingSphere.clone():null})),this._instanceInfo=t._instanceInfo.map(e=>({...e})),this._availableInstanceIds=t._availableInstanceIds.slice(),this._availableGeometryIds=t._availableGeometryIds.slice(),this._nextIndexStart=t._nextIndexStart,this._nextVertexStart=t._nextVertexStart,this._geometryCount=t._geometryCount,this._maxInstanceCount=t._maxInstanceCount,this._maxVertexCount=t._maxVertexCount,this._maxIndexCount=t._maxIndexCount,this._geometryInitialized=t._geometryInitialized,this._multiDrawCounts=t._multiDrawCounts.slice(),this._multiDrawStarts=t._multiDrawStarts.slice(),this._indirectTexture=t._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=t._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=t._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(t,e,n,i,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const a=i.getIndex();let o=a===null?1:a.array.BYTES_PER_ELEMENT,l=1;s.wireframe&&(l=2,o=i.attributes.position.count>65535?4:2);const c=this._instanceInfo,h=this._multiDrawStarts,d=this._multiDrawCounts,u=this._geometryInfo,f=this.perObjectFrustumCulled,p=this._indirectTexture,_=p.image.data,g=n.isArrayCamera?Qg:Id;f&&!n.isArrayCamera&&(Hn.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),Id.setFromProjectionMatrix(Hn,n.coordinateSystem,n.reversedDepth));let m=0;if(this.sortObjects){Hn.copy(this.matrixWorld).invert(),ea.setFromMatrixPosition(n.matrixWorld).applyMatrix4(Hn),Pd.set(0,0,-1).transformDirection(n.matrixWorld).transformDirection(Hn);for(let b=0,P=c.length;b0){const i=e[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=i.length;sn)return;sh.applyMatrix4(r.matrixWorld);const c=t.ray.origin.distanceTo(sh);if(!(ct.far))return{distance:c,point:Ud.clone().applyMatrix4(r.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:r}}const Nd=new D,Fd=new D;class yi extends ji{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,n=[];for(let i=0,s=e.count;i0){const i=e[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=i.length;si.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:t,face:null,faceIndex:null,barycoord:null,object:a})}}class Vd extends nn{constructor(t,e,n,i,s=tn,a=tn,o,l,c){super(t,e,n,i,s,a,o,l,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const h=this;function d(){h.needsUpdate=!0,h._requestVideoFrameCallbackId=t.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in t&&(this._requestVideoFrameCallbackId=t.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;"requestVideoFrameCallback"in t===!1&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}}class n0 extends Vd{constructor(t,e,n,i,s,a,o,l){super({},t,e,n,i,s,a,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(t){this.image=t,this.needsUpdate=!0}}class i0 extends nn{constructor(t,e){super({width:t,height:e}),this.isFramebufferTexture=!0,this.magFilter=ln,this.minFilter=ln,this.generateMipmaps=!1,this.needsUpdate=!0}}class il extends nn{constructor(t,e,n,i,s,a,o,l,c,h,d,u){super(null,a,o,l,c,h,i,s,d,u),this.isCompressedTexture=!0,this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}class r0 extends il{constructor(t,e,n,i,s,a){super(t,e,n,s,a),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=Bn,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class s0 extends il{constructor(t,e,n){super(void 0,t[0].width,t[0].height,e,n,pi),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class ia extends nn{constructor(t=[],e=pi,n,i,s,a,o,l,c,h){super(t,e,n,i,s,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class a0 extends nn{constructor(t,e,n,i,s,a,o,l,c){super(t,e,n,i,s,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class o0 extends nn{constructor(t,e,n,i,s,a,o,l,c){super(t,e,n,i,s,a,o,l,c),this.isHTMLTexture=!0,this.generateMipmaps=!1,this.needsUpdate=!0;const h=t?t.parentNode:null;h!==null&&"requestPaint"in h&&(h.onpaint=()=>{this.needsUpdate=!0},h.requestPaint())}dispose(){const t=this.image?this.image.parentNode:null;t!==null&&"onpaint"in t&&(t.onpaint=null),super.dispose()}}class vr extends nn{constructor(t,e,n=Kn,i,s,a,o=ln,l=ln,c,h=_i,d=1){if(h!==_i&&h!==Vi)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const u={width:t,height:e,depth:d};super(u,i,s,a,o,l,h,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new Wi(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return this.compareFunction!==null&&(e.compareFunction=this.compareFunction),e}}class Gd extends vr{constructor(t,e=Kn,n=pi,i,s,a=ln,o=ln,l,c=_i){const h={width:t,height:t,depth:1},d=[h,h,h,h,h,h];super(t,t,e,n,i,s,a,o,l,c),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}}class lh extends nn{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}}class yr extends Se{constructor(t=1,e=1,n=1,i=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:s,depthSegments:a};const o=this;i=Math.floor(i),s=Math.floor(s),a=Math.floor(a);const l=[],c=[],h=[],d=[];let u=0,f=0;p("z","y","x",-1,-1,n,e,t,a,s,0),p("z","y","x",1,-1,n,e,-t,a,s,1),p("x","z","y",1,1,t,n,e,i,a,2),p("x","z","y",1,-1,t,n,-e,i,a,3),p("x","y","z",1,-1,t,e,n,i,s,4),p("x","y","z",-1,-1,t,e,-n,i,s,5),this.setIndex(l),this.setAttribute("position",new Qt(c,3)),this.setAttribute("normal",new Qt(h,3)),this.setAttribute("uv",new Qt(d,2));function p(_,g,m,x,S,b,P,E,O,y,I){const k=b/O,z=P/y,K=b/2,lt=P/2,ut=E/2,$=O+1,st=y+1;let tt=0,wt=0;const Et=new D;for(let kt=0;kt0?1:-1,h.push(Et.x,Et.y,Et.z),d.push(re/O),d.push(1-kt/y),tt+=1}}for(let kt=0;kt0){const I=(x-1)*_;for(let k=0;k0&&S(!0),e>0&&S(!1)),this.setIndex(h),this.setAttribute("position",new Qt(d,3)),this.setAttribute("normal",new Qt(u,3)),this.setAttribute("uv",new Qt(f,2));function x(){const b=new D,P=new D;let E=0;const O=(e-t)/n;for(let y=0;y<=s;y++){const I=[],k=y/s,z=k*(e-t)+t;for(let K=0;K<=i;K++){const lt=K/i,ut=lt*l+o,$=Math.sin(ut),st=Math.cos(ut);P.x=z*$,P.y=-k*n+g,P.z=z*st,d.push(P.x,P.y,P.z),b.set($,O,st).normalize(),u.push(b.x,b.y,b.z),f.push(lt,1-k),I.push(p++)}_.push(I)}for(let y=0;y0||I!==0)&&(h.push(k,z,lt),E+=3),(e>0||I!==s-1)&&(h.push(z,K,lt),E+=3)}c.addGroup(m,E,0),m+=E}function S(b){const P=p,E=new Mt,O=new D;let y=0;const I=b===!0?t:e,k=b===!0?1:-1;for(let K=1;K<=i;K++)d.push(0,g*k,0),u.push(0,k,0),f.push(.5,.5),p++;const z=p;for(let K=0;K<=i;K++){const ut=K/i*l+o,$=Math.cos(ut),st=Math.sin(ut);O.x=I*st,O.y=g*k,O.z=I*$,d.push(O.x,O.y,O.z),u.push(0,k,0),E.x=$*.5+.5,E.y=st*.5*k+.5,f.push(E.x,E.y),p++}for(let K=0;K.9&&O<.1&&(S<.2&&(a[x+0]+=1),b<.2&&(a[x+2]+=1),P<.2&&(a[x+4]+=1))}}function u(x){s.push(x.x,x.y,x.z)}function f(x,S){const b=x*3;S.x=t[b+0],S.y=t[b+1],S.z=t[b+2]}function p(){const x=new D,S=new D,b=new D,P=new D,E=new Mt,O=new Mt,y=new Mt;for(let I=0,k=0;I0)l=i-1;else{l=i;break}if(i=l,n[i]===a)return i/(s-1);const h=n[i],u=n[i+1]-h,f=(a-h)/u;return(i+f)/(s-1)}getTangent(t,e){let i=t-1e-4,s=t+1e-4;i<0&&(i=0),s>1&&(s=1);const a=this.getPoint(i),o=this.getPoint(s),l=e||(a.isVector2?new Mt:new D);return l.copy(o).sub(a).normalize(),l}getTangentAt(t,e){const n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e=!1){const n=new D,i=[],s=[],a=[],o=new D,l=new ge;for(let f=0;f<=t;f++){const p=f/t;i[f]=this.getTangentAt(p,new D)}s[0]=new D,a[0]=new D;let c=Number.MAX_VALUE;const h=Math.abs(i[0].x),d=Math.abs(i[0].y),u=Math.abs(i[0].z);h<=c&&(c=h,n.set(1,0,0)),d<=c&&(c=d,n.set(0,1,0)),u<=c&&n.set(0,0,1),o.crossVectors(i[0],n).normalize(),s[0].crossVectors(i[0],o),a[0].crossVectors(i[0],s[0]);for(let f=1;f<=t;f++){if(s[f]=s[f-1].clone(),a[f]=a[f-1].clone(),o.crossVectors(i[f-1],i[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(pe(i[f-1].dot(i[f]),-1,1));s[f].applyMatrix4(l.makeRotationAxis(o,p))}a[f].crossVectors(i[f],s[f])}if(e===!0){let f=Math.acos(pe(s[0].dot(s[t]),-1,1));f/=t,i[0].dot(o.crossVectors(s[0],s[t]))>0&&(f=-f);for(let p=1;p<=t;p++)s[p].applyMatrix4(l.makeRotationAxis(i[p],f*p)),a[p].crossVectors(i[p],s[p])}return{tangents:i,normals:s,binormals:a}}clone(){return new this.constructor().copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class hl extends hi{constructor(t=0,e=0,n=1,i=1,s=0,a=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=s,this.aEndAngle=a,this.aClockwise=o,this.aRotation=l}getPoint(t,e=new Mt){const n=e,i=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const a=Math.abs(s)i;)s-=i;s0?0:(Math.floor(Math.abs(o)/s)+1)*s:l===0&&o===s-1&&(o=s-2,l=1);let c,h;this.closed||o>0?c=i[(o-1)%s]:(qd.subVectors(i[0],i[1]).add(i[0]),c=qd);const d=i[o%s],u=i[(o+1)%s];if(this.closed||o+2i.length-2?i.length-1:a+1],d=i[a>i.length-3?i.length-1:a+2];return n.set(Zd(o,l.x,c.x,h.x,d.x),Zd(o,l.y,c.y,h.y,d.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e=n){const a=i[s]-n,o=this.curves[s],l=o.getLength(),c=l===0?0:1-a/l;return o.getPointAt(c,e)}s++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let n=0,i=this.curves.length;n1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,n=t.curves.length;e0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const h=c.getPoint(1);return this.currentPoint.copy(h),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class Mr extends dl{constructor(t){super(t),this.uuid=qn(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let n=0,i=this.holes.length;n80*e){o=r[0],l=r[1];let h=o,d=l;for(let u=e;uh&&(h=f),p>d&&(d=p)}c=Math.max(h-o,d-l),c=c!==0?32767/c:0}return la(s,a,e,o,l,c,0),a}function jd(r,t,e,n,i){let s;if(i===P0(r,t,e,n)>0)for(let a=t;a=t;a-=n)s=nf(a/n|0,r[a],r[a+1],s);return s&&ls(s,s.next)&&(ua(s),s=s.next),s}function Sr(r,t){if(!r)return r;t||(t=r);let e=r,n;do if(n=!1,!e.steiner&&(ls(e,e.next)||rn(e.prev,e,e.next)===0)){if(ua(e),e=t=e.prev,e===e.next)break;n=!0}else e=e.next;while(n||e!==t);return t}function la(r,t,e,n,i,s,a){if(!r)return;!a&&s&&A0(r,n,i,s);let o=r;for(;r.prev!==r.next;){const l=r.prev,c=r.next;if(s?_0(r,n,i,s):g0(r)){t.push(l.i,r.i,c.i),ua(r),r=c.next,o=c.next;continue}if(r=c,r===o){a?a===1?(r=x0(Sr(r),t),la(r,t,e,n,i,s,2)):a===2&&v0(r,t,e,n,i,s):la(Sr(r),t,e,n,i,s,1);break}}}function g0(r){const t=r.prev,e=r,n=r.next;if(rn(t,e,n)>=0)return!1;const i=t.x,s=e.x,a=n.x,o=t.y,l=e.y,c=n.y,h=Math.min(i,s,a),d=Math.min(o,l,c),u=Math.max(i,s,a),f=Math.max(o,l,c);let p=n.next;for(;p!==t;){if(p.x>=h&&p.x<=u&&p.y>=d&&p.y<=f&&ca(i,o,s,l,a,c,p.x,p.y)&&rn(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function _0(r,t,e,n){const i=r.prev,s=r,a=r.next;if(rn(i,s,a)>=0)return!1;const o=i.x,l=s.x,c=a.x,h=i.y,d=s.y,u=a.y,f=Math.min(o,l,c),p=Math.min(h,d,u),_=Math.max(o,l,c),g=Math.max(h,d,u),m=vh(f,p,t,e,n),x=vh(_,g,t,e,n);let S=r.prevZ,b=r.nextZ;for(;S&&S.z>=m&&b&&b.z<=x;){if(S.x>=f&&S.x<=_&&S.y>=p&&S.y<=g&&S!==i&&S!==a&&ca(o,h,l,d,c,u,S.x,S.y)&&rn(S.prev,S,S.next)>=0||(S=S.prevZ,b.x>=f&&b.x<=_&&b.y>=p&&b.y<=g&&b!==i&&b!==a&&ca(o,h,l,d,c,u,b.x,b.y)&&rn(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;S&&S.z>=m;){if(S.x>=f&&S.x<=_&&S.y>=p&&S.y<=g&&S!==i&&S!==a&&ca(o,h,l,d,c,u,S.x,S.y)&&rn(S.prev,S,S.next)>=0)return!1;S=S.prevZ}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=_&&b.y>=p&&b.y<=g&&b!==i&&b!==a&&ca(o,h,l,d,c,u,b.x,b.y)&&rn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function x0(r,t){let e=r;do{const n=e.prev,i=e.next.next;!ls(n,i)&&tf(n,e,e.next,i)&&ha(n,i)&&ha(i,n)&&(t.push(n.i,e.i,i.i),ua(e),ua(e.next),e=r=i),e=e.next}while(e!==r);return Sr(e)}function v0(r,t,e,n,i,s){let a=r;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&C0(a,o)){let l=ef(a,o);a=Sr(a,a.next),l=Sr(l,l.next),la(a,t,e,n,i,s,0),la(l,t,e,n,i,s,0);return}o=o.next}a=a.next}while(a!==r)}function y0(r,t,e,n){const i=[];for(let s=0,a=t.length;s=e.next.y&&e.next.y!==e.y){const d=e.x+(i-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(d<=n&&d>s&&(s=d,a=e.x=e.x&&e.x>=l&&n!==e.x&&Qd(ia.x||e.x===a.x&&T0(a,e)))&&(a=e,h=d)}e=e.next}while(e!==o);return a}function T0(r,t){return rn(r.prev,r,t.prev)<0&&rn(t.next,r,r.next)<0}function A0(r,t,e,n){let i=r;do i.z===0&&(i.z=vh(i.x,i.y,t,e,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==r);i.prevZ.nextZ=null,i.prevZ=null,w0(i)}function w0(r){let t,e=1;do{let n=r,i;r=null;let s=null;for(t=0;n;){t++;let a=n,o=0;for(let c=0;c0||l>0&&a;)o!==0&&(l===0||!a||n.z<=a.z)?(i=n,n=n.nextZ,o--):(i=a,a=a.nextZ,l--),s?s.nextZ=i:r=i,i.prevZ=s,s=i;n=a}s.nextZ=null,e*=2}while(t>1);return r}function vh(r,t,e,n,i){return r=(r-e)*i|0,t=(t-n)*i|0,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,r|t<<1}function E0(r){let t=r,e=r;do(t.x=(r-a)*(s-o)&&(r-a)*(n-o)>=(e-a)*(t-o)&&(e-a)*(s-o)>=(i-a)*(n-o)}function ca(r,t,e,n,i,s,a,o){return!(r===a&&t===o)&&Qd(r,t,e,n,i,s,a,o)}function C0(r,t){return r.next.i!==t.i&&r.prev.i!==t.i&&!R0(r,t)&&(ha(r,t)&&ha(t,r)&&I0(r,t)&&(rn(r.prev,r,t.prev)||rn(r,t.prev,t))||ls(r,t)&&rn(r.prev,r,r.next)>0&&rn(t.prev,t,t.next)>0)}function rn(r,t,e){return(t.y-r.y)*(e.x-t.x)-(t.x-r.x)*(e.y-t.y)}function ls(r,t){return r.x===t.x&&r.y===t.y}function tf(r,t,e,n){const i=pl(rn(r,t,e)),s=pl(rn(r,t,n)),a=pl(rn(e,n,r)),o=pl(rn(e,n,t));return!!(i!==s&&a!==o||i===0&&fl(r,e,t)||s===0&&fl(r,n,t)||a===0&&fl(e,r,n)||o===0&&fl(e,t,n))}function fl(r,t,e){return t.x<=Math.max(r.x,e.x)&&t.x>=Math.min(r.x,e.x)&&t.y<=Math.max(r.y,e.y)&&t.y>=Math.min(r.y,e.y)}function pl(r){return r>0?1:r<0?-1:0}function R0(r,t){let e=r;do{if(e.i!==r.i&&e.next.i!==r.i&&e.i!==t.i&&e.next.i!==t.i&&tf(e,e.next,r,t))return!0;e=e.next}while(e!==r);return!1}function ha(r,t){return rn(r.prev,r,r.next)<0?rn(r,t,r.next)>=0&&rn(r,r.prev,t)>=0:rn(r,t,r.prev)<0||rn(r,r.next,t)<0}function I0(r,t){let e=r,n=!1;const i=(r.x+t.x)/2,s=(r.y+t.y)/2;do e.y>s!=e.next.y>s&&e.next.y!==e.y&&i<(e.next.x-e.x)*(s-e.y)/(e.next.y-e.y)+e.x&&(n=!n),e=e.next;while(e!==r);return n}function ef(r,t){const e=yh(r.i,r.x,r.y),n=yh(t.i,t.x,t.y),i=r.next,s=t.prev;return r.next=t,t.prev=r,e.next=i,i.prev=e,n.next=e,e.prev=n,s.next=n,n.prev=s,n}function nf(r,t,e,n){const i=yh(r,t,e);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function ua(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function yh(r,t,e){return{i:r,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function P0(r,t,e,n){let i=0;for(let s=t,a=e-n;s2&&r[t-1].equals(r[0])&&r.pop()}function sf(r,t){for(let e=0;eNumber.EPSILON){const R=Math.sqrt(Rt),T=Math.sqrt(se*se+ve*ve),Q=Ct.x-Te/R,mt=Ct.y+G/R,Tt=bt.x-ve/T,It=bt.y+se/T,Nt=((Tt-Q)*ve-(It-mt)*se)/(G*ve-Te*se);Xt=Q+G*Nt-St.x,zt=mt+Te*Nt-St.y;const ht=Xt*Xt+zt*zt;if(ht<=2)return new Mt(Xt,zt);xe=Math.sqrt(ht/2)}else{let R=!1;G>Number.EPSILON?se>Number.EPSILON&&(R=!0):G<-Number.EPSILON?se<-Number.EPSILON&&(R=!0):Math.sign(Te)===Math.sign(ve)&&(R=!0),R?(Xt=-Te,zt=G,xe=Math.sqrt(Rt)):(Xt=G,zt=Te,xe=Math.sqrt(Rt/2))}return new Mt(Xt/xe,zt/xe)}const Et=[];for(let St=0,Ct=$.length,bt=Ct-1,Xt=St+1;St=0;St--){const Ct=St/g,bt=f*Math.cos(Ct*Math.PI/2),Xt=p*Math.sin(Ct*Math.PI/2)+_;for(let zt=0,xe=$.length;zt=0;){const Xt=bt;let zt=bt-1;zt<0&&(zt=St.length-1);for(let xe=0,G=h+g*2;xe0)&&f.push(S,b,E),(m!==n-1||l0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const n={};for(const i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}class Mh extends Qn{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Sh extends Cn{constructor(t){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new $t(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $t(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ai,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class ff extends Sh{constructor(t){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Mt(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return pe(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new $t(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new $t(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new $t(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(t)}get anisotropy(){return this._anisotropy}set anisotropy(t){this._anisotropy>0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class pf extends Cn{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new $t(16777215),this.specular=new $t(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $t(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ai,this.combine=bs,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class mf extends Cn{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new $t(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $t(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}class gf extends Cn{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}}class _f extends Cn{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new $t(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $t(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ai,this.combine=bs,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class bh extends Cn{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=zu,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class Th extends Cn{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}class xf extends Cn{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new $t(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this.fog=t.fog,this}}class vf extends Fn{constructor(t){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}}function br(r,t){return!r||r.constructor===t?r:typeof t.BYTES_PER_ELEMENT=="number"?new t(r):Array.prototype.slice.call(r)}function yf(r){function t(i,s){return r[i]-r[s]}const e=r.length,n=new Array(e);for(let i=0;i!==e;++i)n[i]=i;return n.sort(t),n}function Ah(r,t,e){const n=r.length,i=new r.constructor(n);for(let s=0,a=0;a!==n;++s){const o=e[s]*t;for(let l=0;l!==t;++l)i[a++]=r[o+l]}return i}function wh(r,t,e,n){let i=1,s=r[0];for(;s!==void 0&&s[n]===void 0;)s=r[i++];if(s===void 0)return;let a=s[n];if(a!==void 0)if(Array.isArray(a))do a=s[n],a!==void 0&&(t.push(s.time),e.push(...a)),s=r[i++];while(s!==void 0);else if(a.toArray!==void 0)do a=s[n],a!==void 0&&(t.push(s.time),a.toArray(e,e.length)),s=r[i++];while(s!==void 0);else do a=s[n],a!==void 0&&(t.push(s.time),e.push(a)),s=r[i++];while(s!==void 0)}function z0(r,t,e,n,i=30){const s=r.clone();s.name=t;const a=[];for(let l=0;l=n)){d.push(c.times[f]);for(let _=0;_s.tracks[l].times[0]&&(o=s.tracks[l].times[0]);for(let l=0;l=o.times[p]){const m=p*d+h,x=m+d-h;_=o.values.slice(m,x)}else{const m=o.createInterpolant(),x=h,S=d-h;m.evaluate(s),_=m.resultBuffer.slice(x,S)}l==="quaternion"&&new Un().fromArray(_).normalize().conjugate().toArray(_);const g=c.times.length;for(let m=0;m=s)){const o=e[1];t=s)break e}a=n,n=0;break n}break t}for(;n>>1;te;)--a;if(++a,s!==0||a!==i){s>=a&&(a=Math.max(a,1),s=a-1);const o=this.getValueSize();this.times=n.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!==0&&(ie("KeyframeTrack: Invalid value size in track.",this),t=!1);const n=this.times,i=this.values,s=n.length;s===0&&(ie("KeyframeTrack: Track is empty.",this),t=!1);let a=null;for(let o=0;o!==s;o++){const l=n[o];if(typeof l=="number"&&isNaN(l)){ie("KeyframeTrack: Time is not a valid number.",this,o,l),t=!1;break}if(a!==null&&a>l){ie("KeyframeTrack: Out of order keys.",this,o,l,a),t=!1;break}a=l}if(i!==void 0&&Yu(i))for(let o=0,l=i.length;o!==l;++o){const c=i[o];if(isNaN(c)){ie("KeyframeTrack: Value is not a valid number.",this,o,c),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===uo,s=t.length-1;let a=1;for(let o=1;o0){t[a]=t[s];for(let o=s*n,l=a*n,c=0;c!==n;++c)e[l+c]=e[o+c];++a}return a!==t.length?(this.times=t.slice(0,a),this.values=e.slice(0,a*n)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),n=this.constructor,i=new n(this.name,t,e);return i.createInterpolant=this.createInterpolant,i}}ti.prototype.ValueTypeName="",ti.prototype.TimeBufferType=Float32Array,ti.prototype.ValueBufferType=Float32Array,ti.prototype.DefaultInterpolation=ho;class Tr extends ti{constructor(t,e,n){super(t,e,n)}}Tr.prototype.ValueTypeName="bool",Tr.prototype.ValueBufferType=Array,Tr.prototype.DefaultInterpolation=Fs,Tr.prototype.InterpolantFactoryMethodLinear=void 0,Tr.prototype.InterpolantFactoryMethodSmooth=void 0;class Ch extends ti{constructor(t,e,n,i){super(t,e,n,i)}}Ch.prototype.ValueTypeName="color";class pa extends ti{constructor(t,e,n,i){super(t,e,n,i)}}pa.prototype.ValueTypeName="number";class Tf extends us{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(n-e)/(i-e);let c=t*o;for(let h=c+o;c!==h;c+=4)Un.slerpFlat(s,0,a,c-o,a,c,l);return s}}class ma extends ti{constructor(t,e,n,i){super(t,e,n,i)}InterpolantFactoryMethodLinear(t){return new Tf(this.times,this.values,this.getValueSize(),t)}}ma.prototype.ValueTypeName="quaternion",ma.prototype.InterpolantFactoryMethodSmooth=void 0;class Ar extends ti{constructor(t,e,n){super(t,e,n)}}Ar.prototype.ValueTypeName="string",Ar.prototype.ValueBufferType=Array,Ar.prototype.DefaultInterpolation=Fs,Ar.prototype.InterpolantFactoryMethodLinear=void 0,Ar.prototype.InterpolantFactoryMethodSmooth=void 0;class ga extends ti{constructor(t,e,n,i){super(t,e,n,i)}}ga.prototype.ValueTypeName="vector";class _a{constructor(t="",e=-1,n=[],i=fo){this.name=t,this.tracks=n,this.duration=e,this.blendMode=i,this.uuid=qn(),this.userData={},this.duration<0&&this.resetDuration()}static parse(t){const e=[],n=t.tracks,i=1/(t.fps||1);for(let a=0,o=n.length;a!==o;++a)e.push(H0(n[a]).scale(i));const s=new this(t.name,t.duration,e,t.blendMode);return s.uuid=t.uuid,s.userData=JSON.parse(t.userData||"{}"),s}static toJSON(t){const e=[],n=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode,userData:JSON.stringify(t.userData)};for(let s=0,a=n.length;s!==a;++s)e.push(ti.toJSON(n[s]));return i}static CreateFromMorphTargetSequence(t,e,n,i){const s=e.length,a=[];for(let o=0;o1){const d=h[1];let u=i[d];u||(i[d]=u=[]),u.push(c)}}const a=[];for(const o in i)a.push(this.CreateFromMorphTargetSequence(o,i[o],e,n));return a}static parseAnimation(t,e){if(Ft("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!t)return ie("AnimationClip: No animation in JSONLoader data."),null;const n=function(d,u,f,p,_){if(f.length!==0){const g=[],m=[];wh(f,g,m,p),g.length!==0&&_.push(new d(u,g,m))}},i=[],s=t.name||"default",a=t.fps||30,o=t.blendMode;let l=t.length||-1;const c=t.hierarchy||[];for(let d=0;d{e&&e(s),this.manager.itemEnd(t)},0);return}if(Fi[t]!==void 0){Fi[t].push({onLoad:e,onProgress:n,onError:i});return}Fi[t]=[],Fi[t].push({onLoad:e,onProgress:n,onError:i});const a=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(a).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&Ft("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const h=Fi[t],d=c.body.getReader(),u=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=u?parseInt(u):0,p=f!==0;let _=0;const g=new ReadableStream({start(m){x();function x(){d.read().then(({done:S,value:b})=>{if(S)m.close();else{_+=b.byteLength;const P=new ProgressEvent("progress",{lengthComputable:p,loaded:_,total:f});for(let E=0,O=h.length;E{m.error(S)})}}});return new Response(g)}else throw new W0(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return c.json();default:if(o==="")return c.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),u=d&&d[1]?d[1].toLowerCase():void 0,f=new TextDecoder(u);return c.arrayBuffer().then(p=>f.decode(p))}}}).then(c=>{Mi.add(`file:${t}`,c);const h=Fi[t];delete Fi[t];for(let d=0,u=h.length;d{const h=Fi[t];if(h===void 0)throw this.manager.itemError(t),c;delete Fi[t];for(let d=0,u=h.length;d{this.manager.itemEnd(t)}),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class X0 extends Wn{constructor(t){super(t)}load(t,e,n,i){const s=this,a=new Oi(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(t,function(o){try{e(s.parse(JSON.parse(o)))}catch(l){i?i(l):ie(l),s.manager.itemError(t)}},n,i)}parse(t){const e=[];for(let n=0;n0:i.vertexColors=t.vertexColors),t.uniforms!==void 0)for(const s in t.uniforms){const a=t.uniforms[s];switch(i.uniforms[s]={},a.type){case"t":i.uniforms[s].value=n(a.value);break;case"c":i.uniforms[s].value=new $t().setHex(a.value);break;case"v2":i.uniforms[s].value=new Mt().fromArray(a.value);break;case"v3":i.uniforms[s].value=new D().fromArray(a.value);break;case"v4":i.uniforms[s].value=new We().fromArray(a.value);break;case"m3":i.uniforms[s].value=new Me().fromArray(a.value);break;case"m4":i.uniforms[s].value=new ge().fromArray(a.value);break;default:i.uniforms[s].value=a.value}}if(t.defines!==void 0&&(i.defines=t.defines),t.vertexShader!==void 0&&(i.vertexShader=t.vertexShader),t.fragmentShader!==void 0&&(i.fragmentShader=t.fragmentShader),t.glslVersion!==void 0&&(i.glslVersion=t.glslVersion),t.extensions!==void 0)for(const s in t.extensions)i.extensions[s]=t.extensions[s];if(t.lights!==void 0&&(i.lights=t.lights),t.clipping!==void 0&&(i.clipping=t.clipping),t.size!==void 0&&(i.size=t.size),t.sizeAttenuation!==void 0&&(i.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(i.map=n(t.map)),t.matcap!==void 0&&(i.matcap=n(t.matcap)),t.alphaMap!==void 0&&(i.alphaMap=n(t.alphaMap)),t.bumpMap!==void 0&&(i.bumpMap=n(t.bumpMap)),t.bumpScale!==void 0&&(i.bumpScale=t.bumpScale),t.normalMap!==void 0&&(i.normalMap=n(t.normalMap)),t.normalMapType!==void 0&&(i.normalMapType=t.normalMapType),t.normalScale!==void 0){let s=t.normalScale;Array.isArray(s)===!1&&(s=[s,s]),i.normalScale=new Mt().fromArray(s)}return t.displacementMap!==void 0&&(i.displacementMap=n(t.displacementMap)),t.displacementScale!==void 0&&(i.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(i.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(i.roughnessMap=n(t.roughnessMap)),t.metalnessMap!==void 0&&(i.metalnessMap=n(t.metalnessMap)),t.emissiveMap!==void 0&&(i.emissiveMap=n(t.emissiveMap)),t.emissiveIntensity!==void 0&&(i.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(i.specularMap=n(t.specularMap)),t.specularIntensityMap!==void 0&&(i.specularIntensityMap=n(t.specularIntensityMap)),t.specularColorMap!==void 0&&(i.specularColorMap=n(t.specularColorMap)),t.envMap!==void 0&&(i.envMap=n(t.envMap)),t.envMapRotation!==void 0&&i.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(i.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(i.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(i.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(i.lightMap=n(t.lightMap)),t.lightMapIntensity!==void 0&&(i.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(i.aoMap=n(t.aoMap)),t.aoMapIntensity!==void 0&&(i.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(i.gradientMap=n(t.gradientMap)),t.clearcoatMap!==void 0&&(i.clearcoatMap=n(t.clearcoatMap)),t.clearcoatRoughnessMap!==void 0&&(i.clearcoatRoughnessMap=n(t.clearcoatRoughnessMap)),t.clearcoatNormalMap!==void 0&&(i.clearcoatNormalMap=n(t.clearcoatNormalMap)),t.clearcoatNormalScale!==void 0&&(i.clearcoatNormalScale=new Mt().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(i.iridescenceMap=n(t.iridescenceMap)),t.iridescenceThicknessMap!==void 0&&(i.iridescenceThicknessMap=n(t.iridescenceThicknessMap)),t.transmissionMap!==void 0&&(i.transmissionMap=n(t.transmissionMap)),t.thicknessMap!==void 0&&(i.thicknessMap=n(t.thicknessMap)),t.anisotropyMap!==void 0&&(i.anisotropyMap=n(t.anisotropyMap)),t.sheenColorMap!==void 0&&(i.sheenColorMap=n(t.sheenColorMap)),t.sheenRoughnessMap!==void 0&&(i.sheenRoughnessMap=n(t.sheenRoughnessMap)),i}setTextures(t){return this.textures=t,this}createMaterialFromType(t){return El.createMaterialFromType(t)}static createMaterialFromType(t){const e={ShadowMaterial:cf,SpriteMaterial:Yc,RawShaderMaterial:Mh,ShaderMaterial:Qn,PointsMaterial:ah,MeshPhysicalMaterial:ff,MeshStandardMaterial:Sh,MeshPhongMaterial:pf,MeshToonMaterial:mf,MeshNormalMaterial:gf,MeshLambertMaterial:_f,MeshDepthMaterial:bh,MeshDistanceMaterial:Th,MeshBasicMaterial:Ji,MeshMatcapMaterial:xf,LineDashedMaterial:vf,LineBasicMaterial:Fn,Material:Cn};return new e[t]}}class Dh{static extractUrlBase(t){const e=t.lastIndexOf("/");return e===-1?"./":t.slice(0,e+1)}static resolveURL(t,e){return typeof t!="string"||t===""?"":(/^https?:\/\//i.test(e)&&/^\//.test(t)&&(e=e.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(t)||/^data:.*,.*$/i.test(t)||/^blob:.*$/i.test(t)?t:e+t)}}class Bf extends Se{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(t){return super.copy(t),this.instanceCount=t.instanceCount,this}toJSON(){const t=super.toJSON();return t.instanceCount=this.instanceCount,t.isInstancedBufferGeometry=!0,t}}class zf extends Wn{constructor(t){super(t)}load(t,e,n,i){const s=this,a=new Oi(s.manager);a.setPath(s.path),a.setRequestHeader(s.requestHeader),a.setWithCredentials(s.withCredentials),a.load(t,function(o){try{e(s.parse(JSON.parse(o)))}catch(l){i?i(l):ie(l),s.manager.itemError(t)}},n,i)}parse(t){const e={},n={};function i(f,p){if(e[p]!==void 0)return e[p];const g=f.interleavedBuffers[p],m=s(f,g.buffer),x=kr(g.type,m),S=new Io(x,g.stride);return S.uuid=g.uuid,e[p]=S,S}function s(f,p){if(n[p]!==void 0)return n[p];const g=f.arrayBuffers[p],m=new Uint32Array(g).buffer;return n[p]=m,m}const a=t.isInstancedBufferGeometry?new Bf:new Se,o=t.data.index;if(o!==void 0){const f=kr(o.type,o.array);a.setIndex(new Xe(f,1))}const l=t.data.attributes;for(const f in l){const p=l[f];let _;if(p.isInterleavedBufferAttribute){const g=i(t.data,p.data);_=new pr(g,p.itemSize,p.offset,p.normalized)}else{const g=kr(p.type,p.array),m=p.isInstancedBufferAttribute?ss:Xe;_=new m(g,p.itemSize,p.normalized)}p.name!==void 0&&(_.name=p.name),p.usage!==void 0&&_.setUsage(p.usage),a.setAttribute(f,_)}const c=t.data.morphAttributes;if(c)for(const f in c){const p=c[f],_=[];for(let g=0,m=p.length;g0){const l=new Rh(e);s=new xa(l),s.setCrossOrigin(this.crossOrigin);for(let c=0,h=t.length;c0){i=new xa(this.manager),i.setCrossOrigin(this.crossOrigin);for(let a=0,o=t.length;a{let m=null,x=null;return g.boundingBox!==void 0&&(m=new En().fromJSON(g.boundingBox)),g.boundingSphere!==void 0&&(x=new bn().fromJSON(g.boundingSphere)),{...g,boundingBox:m,boundingSphere:x}}),a._instanceInfo=t.instanceInfo,a._availableInstanceIds=t._availableInstanceIds,a._availableGeometryIds=t._availableGeometryIds,a._nextIndexStart=t.nextIndexStart,a._nextVertexStart=t.nextVertexStart,a._geometryCount=t.geometryCount,a._maxInstanceCount=t.maxInstanceCount,a._maxVertexCount=t.maxVertexCount,a._maxIndexCount=t.maxIndexCount,a._geometryInitialized=t.geometryInitialized,a._matricesTexture=c(t.matricesTexture.uuid),a._indirectTexture=c(t.indirectTexture.uuid),t.colorsTexture!==void 0&&(a._colorsTexture=c(t.colorsTexture.uuid)),t.boundingSphere!==void 0&&(a.boundingSphere=new bn().fromJSON(t.boundingSphere)),t.boundingBox!==void 0&&(a.boundingBox=new En().fromJSON(t.boundingBox));break;case"LOD":a=new _d;break;case"Line":a=new ji(o(t.geometry),l(t.material));break;case"LineLoop":a=new Od(o(t.geometry),l(t.material));break;case"LineSegments":a=new yi(o(t.geometry),l(t.material));break;case"PointCloud":case"Points":a=new zd(o(t.geometry),l(t.material));break;case"Sprite":a=new md(l(t.material));break;case"Group":a=new Yr;break;case"Bone":a=new eh;break;default:a=new Fe}if(a.uuid=t.uuid,t.name!==void 0&&(a.name=t.name),t.matrix!==void 0?(a.matrix.fromArray(t.matrix),t.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=t.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)):(t.position!==void 0&&a.position.fromArray(t.position),t.rotation!==void 0&&a.rotation.fromArray(t.rotation),t.quaternion!==void 0&&a.quaternion.fromArray(t.quaternion),t.scale!==void 0&&a.scale.fromArray(t.scale)),t.up!==void 0&&a.up.fromArray(t.up),t.pivot!==void 0&&(a.pivot=new D().fromArray(t.pivot)),t.morphTargetDictionary!==void 0&&(a.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),t.morphTargetInfluences!==void 0&&(a.morphTargetInfluences=t.morphTargetInfluences.slice()),t.castShadow!==void 0&&(a.castShadow=t.castShadow),t.receiveShadow!==void 0&&(a.receiveShadow=t.receiveShadow),t.shadow&&(t.shadow.intensity!==void 0&&(a.shadow.intensity=t.shadow.intensity),t.shadow.bias!==void 0&&(a.shadow.bias=t.shadow.bias),t.shadow.normalBias!==void 0&&(a.shadow.normalBias=t.shadow.normalBias),t.shadow.radius!==void 0&&(a.shadow.radius=t.shadow.radius),t.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(t.shadow.mapSize),t.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(t.shadow.camera))),t.visible!==void 0&&(a.visible=t.visible),t.frustumCulled!==void 0&&(a.frustumCulled=t.frustumCulled),t.renderOrder!==void 0&&(a.renderOrder=t.renderOrder),t.static!==void 0&&(a.static=t.static),t.userData!==void 0&&(a.userData=t.userData),t.layers!==void 0&&(a.layers.mask=t.layers),t.children!==void 0){const u=t.children;for(let f=0;f"u"&&Ft("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&Ft("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(t){return this.options=t,this}load(t,e,n,i){t===void 0&&(t=""),this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=this,a=Mi.get(`image-bitmap:${t}`);if(a!==void 0){if(s.manager.itemStart(t),a.then){a.then(c=>{Nh.has(a)===!0?(i&&i(Nh.get(a)),s.manager.itemError(t),s.manager.itemEnd(t)):(e&&e(c),s.manager.itemEnd(t))});return}setTimeout(function(){e&&e(a),s.manager.itemEnd(t)},0);return}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(t,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){Mi.add(`image-bitmap:${t}`,c),e&&e(c),s.manager.itemEnd(t)}).catch(function(c){i&&i(c),Nh.set(l,c),Mi.remove(`image-bitmap:${t}`),s.manager.itemError(t),s.manager.itemEnd(t)});Mi.add(`image-bitmap:${t}`,l),s.manager.itemStart(t)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let Cl;class Fh{static getContext(){return Cl===void 0&&(Cl=new(window.AudioContext||window.webkitAudioContext)),Cl}static setContext(t){Cl=t}}class n_ extends Wn{constructor(t){super(t)}load(t,e,n,i){const s=this,a=new Oi(this.manager);a.setResponseType("arraybuffer"),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(t,function(l){try{const c=l.slice(0),h=Fh.getContext(),d=t+"#decode";s.manager.itemStart(d),h.decodeAudioData(c,function(u){e(u),s.manager.itemEnd(d)}).catch(function(u){o(u),s.manager.itemEnd(d)})}catch(c){o(c)}},n,i);function o(l){i?i(l):ie(l),s.manager.itemError(t)}}}const Gf=new ge,Hf=new ge,wr=new ge;class i_{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Tn,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Tn,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(t){const e=this._cache;if(e.focus!==t.focus||e.fov!==t.fov||e.aspect!==t.aspect*this.aspect||e.near!==t.near||e.far!==t.far||e.zoom!==t.zoom||e.eyeSep!==this.eyeSep){e.focus=t.focus,e.fov=t.fov,e.aspect=t.aspect*this.aspect,e.near=t.near,e.far=t.far,e.zoom=t.zoom,e.eyeSep=this.eyeSep,wr.copy(t.projectionMatrix);const i=e.eyeSep/2,s=i*e.near/e.focus,a=e.near*Math.tan(ur*e.fov*.5)/e.zoom;let o,l;Hf.elements[12]=-i,Gf.elements[12]=i,o=-a*e.aspect+s,l=a*e.aspect+s,wr.elements[0]=2*e.near/(l-o),wr.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(wr),o=-a*e.aspect-s,l=a*e.aspect-s,wr.elements[0]=2*e.near/(l-o),wr.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(wr)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(Hf),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(Gf)}}const fs=-90,ps=1;class Wf extends Fe{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Tn(fs,ps,t,e);i.layers=this.layers,this.add(i);const s=new Tn(fs,ps,t,e);s.layers=this.layers,this.add(s);const a=new Tn(fs,ps,t,e);a.layers=this.layers,this.add(a);const o=new Tn(fs,ps,t,e);o.layers=this.layers,this.add(o);const l=new Tn(fs,ps,t,e);l.layers=this.layers,this.add(l);const c=new Tn(fs,ps,t,e);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[n,i,s,a,o,l]=e;for(const c of e)this.remove(c);if(t===Xn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(t===hr)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);for(const c of e)this.add(c),c.updateMatrixWorld()}update(t,e){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[s,a,o,l,c,h]=this.children,d=t.getRenderTarget(),u=t.getActiveCubeFace(),f=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const _=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let g=!1;t.isWebGLRenderer===!0?g=t.state.buffers.depth.getReversed():g=t.reversedDepthBuffer,t.setRenderTarget(n,0,i),g&&t.autoClear===!1&&t.clearDepth(),t.render(e,s),t.setRenderTarget(n,1,i),g&&t.autoClear===!1&&t.clearDepth(),t.render(e,a),t.setRenderTarget(n,2,i),g&&t.autoClear===!1&&t.clearDepth(),t.render(e,o),t.setRenderTarget(n,3,i),g&&t.autoClear===!1&&t.clearDepth(),t.render(e,l),t.setRenderTarget(n,4,i),g&&t.autoClear===!1&&t.clearDepth(),t.render(e,c),n.texture.generateMipmaps=_,t.setRenderTarget(n,5,i),g&&t.autoClear===!1&&t.clearDepth(),t.render(e,h),t.setRenderTarget(d,u,f),t.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Xf extends Tn{constructor(t=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=t}}class qf{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(t){this._document=t,t.hidden!==void 0&&(this._pageVisibilityHandler=r_.bind(this),t.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(t){return this._timescale=t,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(t){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(t!==void 0?t:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}}function r_(){this._document.hidden===!1&&this.reset()}const Er=new D,Oh=new Un,s_=new D,Cr=new D,Rr=new D;class a_ extends Fe{constructor(){super(),this.type="AudioListener",this.context=Fh.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._timer=new qf}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(t){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=t,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(t){return this.gain.gain.setTargetAtTime(t,this.context.currentTime,.01),this}updateMatrixWorld(t){super.updateMatrixWorld(t),this._timer.update();const e=this.context.listener;if(this.timeDelta=this._timer.getDelta(),this.matrixWorld.decompose(Er,Oh,s_),Cr.set(0,0,-1).applyQuaternion(Oh),Rr.set(0,1,0).applyQuaternion(Oh),e.positionX){const n=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(Er.x,n),e.positionY.linearRampToValueAtTime(Er.y,n),e.positionZ.linearRampToValueAtTime(Er.z,n),e.forwardX.linearRampToValueAtTime(Cr.x,n),e.forwardY.linearRampToValueAtTime(Cr.y,n),e.forwardZ.linearRampToValueAtTime(Cr.z,n),e.upX.linearRampToValueAtTime(Rr.x,n),e.upY.linearRampToValueAtTime(Rr.y,n),e.upZ.linearRampToValueAtTime(Rr.z,n)}else e.setPosition(Er.x,Er.y,Er.z),e.setOrientation(Cr.x,Cr.y,Cr.z,Rr.x,Rr.y,Rr.z)}}class Yf extends Fe{constructor(t){super(),this.type="Audio",this.listener=t,this.context=t.context,this.gain=this.context.createGain(),this.gain.connect(t.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(t){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=t,this.connect(),this}setMediaElementSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(t),this.connect(),this}setMediaStreamSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(t),this.connect(),this}setBuffer(t){return this.buffer=t,this.sourceType="buffer",this.autoplay&&this.play(),this}play(t=0){if(this.isPlaying===!0){Ft("Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){Ft("Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+t;const e=this.context.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd,e.onended=this.onEnded.bind(this),e.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=e,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){Ft("Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(t=0){if(this.hasPlaybackControl===!1){Ft("Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+t),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t0&&this._mixBufferRegionAdditive(n,i,this._addIndex*e,1,e);for(let l=e,c=e+e;l!==c;++l)if(n[l]!==n[l+e]){o.setValue(n,i);break}}saveOriginalState(){const t=this.binding,e=this.buffer,n=this.valueSize,i=n*this._origIndex;t.getValue(e,i);for(let s=n,a=i;s!==a;++s)e[s]=e[i+s%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=this.valueSize*3;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let n=t;n=.5)for(let a=0;a!==s;++a)t[e+a]=t[n+a]}_slerp(t,e,n,i){Un.slerpFlat(t,e,t,e,t,n,i)}_slerpAdditive(t,e,n,i,s){const a=this._workIndex*s;Un.multiplyQuaternionsFlat(t,a,t,e,t,n),Un.slerpFlat(t,e,t,e,t,a,i)}_lerp(t,e,n,i,s){const a=1-i;for(let o=0;o!==s;++o){const l=e+o;t[l]=t[l]*a+t[n+o]*i}}_lerpAdditive(t,e,n,i,s){for(let a=0;a!==s;++a){const o=e+a;t[o]=t[o]+t[n+a]*i}}}const Bh="\\[\\]\\.:\\/",h_=new RegExp("["+Bh+"]","g"),zh="[^"+Bh+"]",u_="[^"+Bh.replace("\\.","")+"]",d_=/((?:WC+[\/:])*)/.source.replace("WC",zh),f_=/(WCOD+)?/.source.replace("WCOD",u_),p_=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",zh),m_=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",zh),g_=new RegExp("^"+d_+f_+p_+m_+"$"),__=["material","materials","bones","map"];class x_{constructor(t,e,n){const i=n||Oe.parseTrackName(e);this._targetGroup=t,this._bindings=t.subscribe_(e,i)}getValue(t,e){this.bind();const n=this._targetGroup.nCachedObjects_,i=this._bindings[n];i!==void 0&&i.getValue(t,e)}setValue(t,e){const n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,s=n.length;i!==s;++i)n[i].setValue(t,e)}bind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,n=t.length;e!==n;++e)t[e].bind()}unbind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,n=t.length;e!==n;++e)t[e].unbind()}}class Oe{constructor(t,e,n){this.path=e,this.parsedPath=n||Oe.parseTrackName(e),this.node=Oe.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new Oe.Composite(t,e,n):new Oe(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(h_,"")}static parseTrackName(t){const e=g_.exec(t);if(e===null)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const n={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){const s=n.nodeName.substring(i+1);__.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(e===void 0||e===""||e==="."||e===-1||e===t.name||e===t.uuid)return t;if(t.skeleton){const n=t.skeleton.getBoneByName(e);if(n!==void 0)return n}if(t.children){const n=function(s){for(let a=0;a=s){const d=s++,u=t[d];e[u.uuid]=h,t[h]=u,e[c]=d,t[d]=l;for(let f=0,p=i;f!==p;++f){const _=n[f],g=_[d],m=_[h];_[h]=g,_[d]=m}}}this.nCachedObjects_=s}uncache(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let s=this.nCachedObjects_,a=t.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],h=c.uuid,d=e[h];if(d!==void 0)if(delete e[h],d0&&(e[f.uuid]=d),t[d]=f,t.pop();for(let p=0,_=i;p!==_;++p){const g=n[p];g[d]=g[u],g.pop()}}}this.nCachedObjects_=s}subscribe_(t,e){const n=this._bindingsIndicesByPath;let i=n[t];const s=this._bindings;if(i!==void 0)return s[i];const a=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,h=this.nCachedObjects_,d=new Array(c);i=s.length,n[t]=i,a.push(t),o.push(e),s.push(d);for(let u=h,f=l.length;u!==f;++u){const p=l[u];d[u]=new Oe(p,t,e)}return d}unsubscribe_(t){const e=this._bindingsIndicesByPath,n=e[t];if(n!==void 0){const i=this._paths,s=this._parsedPaths,a=this._bindings,o=a.length-1,l=a[o],c=t[o];e[c]=n,a[n]=l,a.pop(),s[n]=s[o],s.pop(),i[n]=i[o],i.pop()}}}class Jf{constructor(t,e,n=null,i=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=n,this.blendMode=i;const s=e.tracks,a=s.length,o=new Array(a),l={endingStart:or,endingEnd:or};for(let c=0;c!==a;++c){const h=s[c].createInterpolant(null);o[c]=h,h.settings&&Object.assign(l,h.settings),h.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=Ou,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(t){return this._startTime=t,this}setLoop(t,e){return this.loop=t,this.repetitions=e,this}setEffectiveWeight(t){return this.weight=t,this._effectiveWeight=this.enabled?t:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(t){return this._scheduleFading(t,0,1)}fadeOut(t){return this._scheduleFading(t,1,0)}crossFadeFrom(t,e,n=!1){if(t.fadeOut(e),this.fadeIn(e),n===!0){const i=this._clip.duration,s=t._clip.duration,a=s/i,o=i/s;t.warp(1,a,e),this.warp(o,1,e)}return this}crossFadeTo(t,e,n=!1){return t.crossFadeFrom(this,e,n)}stopFading(){const t=this._weightInterpolant;return t!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}setEffectiveTimeScale(t){return this.timeScale=t,this._effectiveTimeScale=this.paused?0:t,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(t){return this.timeScale=this._clip.duration/t,this.stopWarping()}syncWith(t){return this.time=t.time,this.timeScale=t.timeScale,this.stopWarping()}halt(t){return this.warp(this._effectiveTimeScale,0,t)}warp(t,e,n){const i=this._mixer,s=i.time,a=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=i._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=s,l[1]=s+n,c[0]=t/a,c[1]=e/a,this}stopWarping(){const t=this._timeScaleInterpolant;return t!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(t,e,n,i){if(!this.enabled){this._updateWeight(t);return}const s=this._startTime;if(s!==null){const l=(t-s)*n;l<0||n===0?e=0:(this._startTime=null,e=n*l)}e*=this._updateTimeScale(t);const a=this._updateTime(e),o=this._updateWeight(t);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case Tc:for(let h=0,d=l.length;h!==d;++h)l[h].evaluate(a),c[h].accumulateAdditive(o);break;case fo:default:for(let h=0,d=l.length;h!==d;++h)l[h].evaluate(a),c[h].accumulate(i,o)}}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const n=this._weightInterpolant;if(n!==null){const i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),i===0&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const n=this._timeScaleInterpolant;if(n!==null){const i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopWarping(),e===0?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,n=this.loop;let i=this.time+t,s=this._loopCount;const a=n===Bu;if(t===0)return s===-1?i:a&&(s&1)===1?e-i:i;if(n===Fu){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(i>=e)i=e;else if(i<0)i=0;else{this.time=i;break t}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(s===-1&&(t>=0?(s=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),i>=e||i<0){const o=Math.floor(i/e);i-=e*o,s+=Math.abs(o);const l=this.repetitions-s;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=t>0?e:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(l===1){const c=t<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=s,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this._loopCount=s,this.time=i;if(a&&(s&1)===1)return e-i}return i}_setEndings(t,e,n){const i=this._interpolantSettings;n?(i.endingStart=lr,i.endingEnd=lr):(t?i.endingStart=this.zeroSlopeAtStart?lr:or:i.endingStart=Os,e?i.endingEnd=this.zeroSlopeAtEnd?lr:or:i.endingEnd=Os)}_scheduleFading(t,e,n){const i=this._mixer,s=i.time;let a=this._weightInterpolant;a===null&&(a=i._lendControlInterpolant(),this._weightInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=s,l[0]=e,o[1]=s+t,l[1]=n,this}}const y_=new Float32Array(1);class M_ extends ri{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(t,e){const n=t._localRoot||this._root,i=t._clip.tracks,s=i.length,a=t._propertyBindings,o=t._interpolants,l=n.uuid,c=this._bindingsByRootAndName;let h=c[l];h===void 0&&(h={},c[l]=h);for(let d=0;d!==s;++d){const u=i[d],f=u.name;let p=h[f];if(p!==void 0)++p.referenceCount,a[d]=p;else{if(p=a[d],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,l,f));continue}const _=e&&e._propertyBindings[d].binding.parsedPath;p=new $f(Oe.create(n,f,_),u.ValueTypeName,u.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,l,f),a[d]=p}o[d].resultBuffer=p.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(t._cacheIndex===null){const n=(t._localRoot||this._root).uuid,i=t._clip.uuid,s=this._actionsByClip[i];this._bindAction(t,s&&s.knownActions[0]),this._addInactiveAction(t,i,n)}const e=t._propertyBindings;for(let n=0,i=e.length;n!==i;++n){const s=e[n];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let n=0,i=e.length;n!==i;++n){const s=e[n];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(t)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}}_isActiveAction(t){const e=t._cacheIndex;return e!==null&&e=0;--n)t[n].stop();return this}update(t){t*=this.timeScale;const e=this._actions,n=this._nActiveActions,i=this.time+=t,s=Math.sign(t),a=this._accuIndex^=1;for(let c=0;c!==n;++c)e[c]._update(i,t,s,a);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(t){this.time=0;for(let e=0;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Qf).distanceTo(t)}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const tp=new D,Rl=new D,ms=new D,gs=new D,Hh=new D,L_=new D,D_=new D;class U_{constructor(t=new D,e=new D){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){tp.subVectors(t,this.start),Rl.subVectors(this.end,this.start);const n=Rl.dot(Rl);if(n===0)return 0;let s=Rl.dot(tp)/n;return e&&(s=pe(s,0,1)),s}closestPointToPoint(t,e,n){const i=this.closestPointToPointParameter(t,e);return this.delta(n).multiplyScalar(i).add(this.start)}distanceSqToLine3(t,e=L_,n=D_){const i=10000000000000001e-32;let s,a;const o=this.start,l=t.start,c=this.end,h=t.end;ms.subVectors(c,o),gs.subVectors(h,l),Hh.subVectors(o,l);const d=ms.dot(ms),u=gs.dot(gs),f=gs.dot(Hh);if(d<=i&&u<=i)return e.copy(o),n.copy(l),e.sub(n),e.dot(e);if(d<=i)s=0,a=f/u,a=pe(a,0,1);else{const p=ms.dot(Hh);if(u<=i)a=0,s=pe(-p/d,0,1);else{const _=ms.dot(gs),g=d*u-_*_;g!==0?s=pe((_*f-p*u)/g,0,1):s=0,a=(_*s+f)/u,a<0?(a=0,s=pe(-p/d,0,1)):a>1&&(a=1,s=pe((_-p)/d,0,1))}}return e.copy(o).addScaledVector(ms,s),n.copy(l).addScaledVector(gs,a),e.distanceToSquared(n)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const ep=new D;class N_ extends Fe{constructor(t,e){super(),this.light=t,this.matrixAutoUpdate=!1,this.color=e,this.type="SpotLightHelper";const n=new Se,i=[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(let a=0,o=1,l=32;a1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{op.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(op,e)}}setLength(t,e=t*.2,n=e*.2){this.line.scale.set(1,Math.max(1e-4,t-e),1),this.line.updateMatrix(),this.cone.scale.set(n,e,n),this.cone.position.y=t,this.cone.updateMatrix()}setColor(t){this.line.material.color.set(t),this.cone.material.color.set(t)}copy(t){return super.copy(t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class Z_ extends yi{constructor(t=1){const e=[0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],i=new Se;i.setAttribute("position",new Qt(e,3)),i.setAttribute("color",new Qt(n,3));const s=new Fn({vertexColors:!0,toneMapped:!1});super(i,s),this.type="AxesHelper"}setColors(t,e,n){const i=new $t,s=this.geometry.attributes.color.array;return i.set(t),i.toArray(s,0),i.toArray(s,3),i.set(e),i.toArray(s,6),i.toArray(s,9),i.set(n),i.toArray(s,12),i.toArray(s,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class $_{constructor(){this.type="ShapePath",this.color=new $t,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new dl,this.subPaths.push(this.currentPath),this.currentPath.moveTo(t,e),this}lineTo(t,e){return this.currentPath.lineTo(t,e),this}quadraticCurveTo(t,e,n,i){return this.currentPath.quadraticCurveTo(t,e,n,i),this}bezierCurveTo(t,e,n,i,s,a){return this.currentPath.bezierCurveTo(t,e,n,i,s,a),this}splineThru(t){return this.currentPath.splineThru(t),this}toShapes(t){function e(m){const x=[];for(let S=0,b=m.length;SNumber.EPSILON){if(k<0&&(O=x[E],I=-I,y=x[P],k=-k),m.yy.y)continue;if(m.y===O.y){if(m.x===O.x)return!0}else{const z=k*(m.x-O.x)-I*(m.y-O.y);if(z===0)return!0;if(z<0)continue;b=!b}}else{if(m.y!==O.y)continue;if(y.x<=m.x&&m.x<=O.x||O.x<=m.x&&m.x<=y.x)return!0}}return b}const i=ui.isClockWise,s=this.subPaths;if(s.length===0)return[];let a,o,l;const c=[];if(s.length===1)return o=s[0],l=new Mr,l.curves=o.curves,c.push(l),c;let h=!i(s[0].getPoints());h=t?!h:h;const d=[],u=[];let f=[],p=0,_;u[p]=void 0,f[p]=[];for(let m=0,x=s.length;m1){let m=!1,x=0;for(let S=0,b=u.length;S0&&m===!1&&(f=d)}let g;for(let m=0,x=u.length;mt?(r.repeat.x=1,r.repeat.y=e/t,r.offset.x=0,r.offset.y=(1-r.repeat.y)/2):(r.repeat.x=t/e,r.repeat.y=1,r.offset.x=(1-r.repeat.x)/2,r.offset.y=0),r}function j_(r,t){const e=r.image&&r.image.width?r.image.width/r.image.height:1;return e>t?(r.repeat.x=t/e,r.repeat.y=1,r.offset.x=(1-r.repeat.x)/2,r.offset.y=0):(r.repeat.x=1,r.repeat.y=e/t,r.offset.x=0,r.offset.y=(1-r.repeat.y)/2),r}function Q_(r){return r.repeat.x=1,r.repeat.y=1,r.offset.x=0,r.offset.y=0,r}function qh(r,t,e,n){const i=tx(n);switch(e){case Mc:return r*t;case Pa:return r*t/i.components*i.byteLength;case Rs:return r*t/i.components*i.byteLength;case Gi:return r*t*2/i.components*i.byteLength;case La:return r*t*2/i.components*i.byteLength;case Sc:return r*t*3/i.components*i.byteLength;case Ln:return r*t*4/i.components*i.byteLength;case Da:return r*t*4/i.components*i.byteLength;case Is:case Ps:return Math.floor((r+3)/4)*Math.floor((t+3)/4)*8;case Ls:case Ds:return Math.floor((r+3)/4)*Math.floor((t+3)/4)*16;case Na:case Oa:return Math.max(r,16)*Math.max(t,8)/4;case Ua:case Fa:return Math.max(r,8)*Math.max(t,8)/2;case Ba:case za:case Va:case Ga:return Math.floor((r+3)/4)*Math.floor((t+3)/4)*8;case ka:case Us:case Ha:return Math.floor((r+3)/4)*Math.floor((t+3)/4)*16;case Wa:return Math.floor((r+3)/4)*Math.floor((t+3)/4)*16;case Xa:return Math.floor((r+4)/5)*Math.floor((t+3)/4)*16;case qa:return Math.floor((r+4)/5)*Math.floor((t+4)/5)*16;case Ya:return Math.floor((r+5)/6)*Math.floor((t+4)/5)*16;case Za:return Math.floor((r+5)/6)*Math.floor((t+5)/6)*16;case $a:return Math.floor((r+7)/8)*Math.floor((t+4)/5)*16;case Ja:return Math.floor((r+7)/8)*Math.floor((t+5)/6)*16;case Ka:return Math.floor((r+7)/8)*Math.floor((t+7)/8)*16;case ja:return Math.floor((r+9)/10)*Math.floor((t+4)/5)*16;case Qa:return Math.floor((r+9)/10)*Math.floor((t+5)/6)*16;case to:return Math.floor((r+9)/10)*Math.floor((t+7)/8)*16;case eo:return Math.floor((r+9)/10)*Math.floor((t+9)/10)*16;case no:return Math.floor((r+11)/12)*Math.floor((t+9)/10)*16;case io:return Math.floor((r+11)/12)*Math.floor((t+11)/12)*16;case ro:case so:case ao:return Math.ceil(r/4)*Math.ceil(t/4)*16;case oo:case lo:return Math.ceil(r/4)*Math.ceil(t/4)*8;case Ns:case co:return Math.ceil(r/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${e} format.`)}function tx(r){switch(r){case zn:case _c:return{byteLength:1,components:1};case Br:case xc:case gi:return{byteLength:2,components:1};case Ra:case Ia:return{byteLength:2,components:4};case Kn:case Ca:case Pn:return{byteLength:4,components:1};case vc:case yc:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${r}.`)}class ex{static contain(t,e){return K_(t,e)}static cover(t,e){return j_(t,e)}static fill(t){return Q_(t)}static getByteLength(t,e,n,i){return qh(t,e,n,i)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:vt}})),typeof window<"u"&&(window.__THREE__?Ft("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=vt);function lp(){let r=null,t=!1,e=null,n=null;function i(s,a){e(s,a),n=r.requestAnimationFrame(i)}return{start:function(){t!==!0&&e!==null&&r!==null&&(n=r.requestAnimationFrame(i),t=!0)},stop:function(){r!==null&&r.cancelAnimationFrame(n),t=!1},setAnimationLoop:function(s){e=s},setContext:function(s){r=s}}}function nx(r){const t=new WeakMap;function e(o,l){const c=o.array,h=o.usage,d=c.byteLength,u=r.createBuffer();r.bindBuffer(l,u),r.bufferData(l,c,h),o.onUploadCallback();let f;if(c instanceof Float32Array)f=r.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)f=r.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?f=r.HALF_FLOAT:f=r.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=r.SHORT;else if(c instanceof Uint32Array)f=r.UNSIGNED_INT;else if(c instanceof Int32Array)f=r.INT;else if(c instanceof Int8Array)f=r.BYTE;else if(c instanceof Uint8Array)f=r.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=r.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:u,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function n(o,l,c){const h=l.array,d=l.updateRanges;if(r.bindBuffer(c,o),d.length===0)r.bufferSubData(c,0,h);else{d.sort((f,p)=>f.start-p.start);let u=0;for(let f=1;f 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,vx=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,yx=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,Mx=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,Sx=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#endif`,bx=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#endif`,Tx=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec4 vColor; +#endif`,Ax=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec4( 1.0 ); +#endif +#ifdef USE_COLOR_ALPHA + vColor *= color; +#elif defined( USE_COLOR ) + vColor.rgb *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.rgb *= instanceColor.rgb; +#endif +#ifdef USE_BATCHING_COLOR + vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); +#endif`,wx=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,Ex=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,Cx=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,Rx=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,Ix=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,Px=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,Lx=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,Dx="gl_FragColor = linearToOutputTexel( gl_FragColor );",Ux=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,Nx=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * reflectVec ); + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif + #endif +#endif`,Fx=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif +#endif`,Ox=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,Bx=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,zx=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,kx=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,Vx=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,Gx=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,Hx=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,Wx=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,Xx=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,qx=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,Yx=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Zx=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif +#include `,$x=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,Jx=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,Kx=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,jx=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,Qx=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,tv=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +material.metalness = metalnessFactor; +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; + material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = vec3( 0.04 ); + material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,ev=`uniform sampler2D dfgLUT; +struct PhysicalMaterial { + vec3 diffuseColor; + vec3 diffuseContribution; + vec3 specularColor; + vec3 specularColorBlended; + float roughness; + float metalness; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + vec3 iridescenceFresnelDielectric; + vec3 iridescenceFresnelMetallic; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColorBlended; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float rInv = 1.0 / ( roughness + 0.1 ); + float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; + float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; + float DG = exp( a * dotNV + b ); + return saturate( DG ); +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; + vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; + vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; + vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; + float Ess_V = dfgV.x + dfgV.y; + float Ess_L = dfgL.x + dfgL.y; + float Ems_V = 1.0 - Ess_V; + float Ems_L = 1.0 - Ess_L; + vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; + vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); + float compensationFactor = Ems_V * Ems_L; + vec3 multiScatter = Fms * compensationFactor; + return singleScatter + multiScatter; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + #ifdef USE_CLEARCOAT + vec3 Ncc = geometryClearcoatNormal; + vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); + vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); + vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); + mat3 mInvClearcoat = mat3( + vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), + vec3( 0, 1, 0 ), + vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) + ); + vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; + clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); + #endif + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + + float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); + + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); + + irradiance *= sheenEnergyComp; + + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); + #ifdef USE_SHEEN + float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; + diffuse *= sheenEnergyComp; + #endif + reflectedLight.indirectDiffuse += diffuse; +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; + #endif + vec3 singleScatteringDielectric = vec3( 0.0 ); + vec3 multiScatteringDielectric = vec3( 0.0 ); + vec3 singleScatteringMetallic = vec3( 0.0 ); + vec3 multiScatteringMetallic = vec3( 0.0 ); + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); + computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); + #endif + vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); + vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); + vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; + vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + vec3 indirectSpecular = radiance * singleScattering; + indirectSpecular += multiScattering * cosineWeightedIrradiance; + vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; + #ifdef USE_SHEEN + float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; + indirectSpecular *= sheenEnergyComp; + indirectDiffuse *= sheenEnergyComp; + #endif + reflectedLight.indirectSpecular += indirectSpecular; + reflectedLight.indirectDiffuse += indirectDiffuse; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,nv=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); + material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif + #ifdef USE_LIGHT_PROBES_GRID + vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz; + vec3 probeWorldNormal = inverseTransformDirection( geometryNormal, viewMatrix ); + irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal ); + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,iv=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) + #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,rv=`#if defined( RE_IndirectDiffuse ) + #if defined( LAMBERT ) || defined( PHONG ) + irradiance += iblIrradiance; + #endif + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,sv=`#ifdef USE_LIGHT_PROBES_GRID +uniform highp sampler3D probesSH; +uniform vec3 probesMin; +uniform vec3 probesMax; +uniform vec3 probesResolution; +vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { + vec3 res = probesResolution; + vec3 gridRange = probesMax - probesMin; + vec3 resMinusOne = res - 1.0; + vec3 probeSpacing = gridRange / resMinusOne; + vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5; + vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 ); + uvw = uvw * resMinusOne / res + 0.5 / res; + float nz = res.z; + float paddedSlices = nz + 2.0; + float atlasDepth = 7.0 * paddedSlices; + float uvZBase = uvw.z * nz + 1.0; + vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) ); + vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) ); + vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) ); + vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) ); + vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) ); + vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) ); + vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) ); + vec3 c0 = s0.xyz; + vec3 c1 = vec3( s0.w, s1.xy ); + vec3 c2 = vec3( s1.zw, s2.x ); + vec3 c3 = s2.yzw; + vec3 c4 = s3.xyz; + vec3 c5 = vec3( s3.w, s4.xy ); + vec3 c6 = vec3( s4.zw, s5.x ); + vec3 c7 = s5.yzw; + vec3 c8 = s6.xyz; + float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z; + vec3 result = c0 * 0.886227; + result += c1 * 2.0 * 0.511664 * y; + result += c2 * 2.0 * 0.511664 * z; + result += c3 * 2.0 * 0.511664 * x; + result += c4 * 2.0 * 0.429043 * x * y; + result += c5 * 2.0 * 0.429043 * y * z; + result += c6 * ( 0.743125 * z * z - 0.247708 ); + result += c7 * 2.0 * 0.429043 * x * z; + result += c8 * 0.429043 * ( x * x - y * y ); + return max( result, vec3( 0.0 ) ); +} +#endif`,av=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,ov=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,lv=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,cv=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,hv=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,uv=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,dv=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,fv=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,pv=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,mv=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,gv=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,_v=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,xv=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,vv=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,yv=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,Mv=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,Sv=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #if defined( USE_PACKED_NORMALMAP ) + mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) ); + #endif + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,bv=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Tv=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Av=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,wv=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,Ev=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,Cv=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,Rv=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,Iv=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,Pv=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Lv=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + #ifdef USE_REVERSED_DEPTH_BUFFER + + return depth * ( far - near ) - far; + #else + return depth * ( near - far ) - near; + #endif +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + + #ifdef USE_REVERSED_DEPTH_BUFFER + return ( near * far ) / ( ( near - far ) * depth - near ); + #else + return ( near * far ) / ( ( far - near ) * depth - far ); + #endif +}`,Dv=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,Uv=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,Nv=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,Fv=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,Ov=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,Bv=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,zv=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + #else + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + #else + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + #elif defined( SHADOWMAP_TYPE_BASIC ) + uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + #if defined( SHADOWMAP_TYPE_PCF ) + float interleavedGradientNoise( vec2 position ) { + return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); + } + vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { + const float goldenAngle = 2.399963229728653; + float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); + float theta = float( sampleIndex ) * goldenAngle + phi; + return vec2( cos( theta ), sin( theta ) ) * r; + } + #endif + #if defined( SHADOWMAP_TYPE_PCF ) + float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float radius = shadowRadius * texelSize.x; + float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; + shadow = ( + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) + ) * 0.2; + } + return mix( 1.0, shadow, shadowIntensity ); + } + #elif defined( SHADOWMAP_TYPE_VSM ) + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadowCoord.z -= shadowBias; + #else + shadowCoord.z += shadowBias; + #endif + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; + float mean = distribution.x; + float variance = distribution.y * distribution.y; + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( mean, shadowCoord.z ); + #else + float hard_shadow = step( shadowCoord.z, mean ); + #endif + + if ( hard_shadow == 1.0 ) { + shadow = 1.0; + } else { + variance = max( variance, 0.0000001 ); + float d = shadowCoord.z - mean; + float p_max = variance / ( variance + d * d ); + p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); + shadow = max( hard_shadow, p_max ); + } + } + return mix( 1.0, shadow, shadowIntensity ); + } + #else + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadowCoord.z -= shadowBias; + #else + shadowCoord.z += shadowBias; + #endif + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + float depth = texture2D( shadowMap, shadowCoord.xy ).r; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadow = step( depth, shadowCoord.z ); + #else + shadow = step( shadowCoord.z, depth ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + vec3 bd3D = normalize( lightToPosition ); + vec3 absVec = abs( lightToPosition ); + float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); + if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { + #ifdef USE_REVERSED_DEPTH_BUFFER + float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp -= shadowBias; + #else + float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp += shadowBias; + #endif + float texelSize = shadowRadius / shadowMapSize.x; + vec3 absDir = abs( bd3D ); + vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); + tangent = normalize( cross( bd3D, tangent ) ); + vec3 bitangent = cross( bd3D, tangent ); + float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; + vec2 sample0 = vogelDiskSample( 0, 5, phi ); + vec2 sample1 = vogelDiskSample( 1, 5, phi ); + vec2 sample2 = vogelDiskSample( 2, 5, phi ); + vec2 sample3 = vogelDiskSample( 3, 5, phi ); + vec2 sample4 = vogelDiskSample( 4, 5, phi ); + shadow = ( + texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) + ) * 0.2; + } + return mix( 1.0, shadow, shadowIntensity ); + } + #elif defined( SHADOWMAP_TYPE_BASIC ) + float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + vec3 absVec = abs( lightToPosition ); + float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); + if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { + float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + float depth = textureCube( shadowMap, bd3D ).r; + #ifdef USE_REVERSED_DEPTH_BUFFER + depth = 1.0 - depth; + #endif + shadow = step( dp, depth ); + } + return mix( 1.0, shadow, shadowIntensity ); + } + #endif + #endif +#endif`,kv=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,Vv=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + #ifdef HAS_NORMAL + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #else + vec3 shadowWorldNormal = vec3( 0.0 ); + #endif + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,Gv=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,Hv=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,Wv=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,Xv=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,qv=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,Yv=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,Zv=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,$v=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,Jv=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,Kv=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,jv=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,Qv=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,ty=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,ey=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,ny=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`;const Re={alphahash_fragment:ix,alphahash_pars_fragment:rx,alphamap_fragment:sx,alphamap_pars_fragment:ax,alphatest_fragment:ox,alphatest_pars_fragment:lx,aomap_fragment:cx,aomap_pars_fragment:hx,batching_pars_vertex:ux,batching_vertex:dx,begin_vertex:fx,beginnormal_vertex:px,bsdfs:mx,iridescence_fragment:gx,bumpmap_pars_fragment:_x,clipping_planes_fragment:xx,clipping_planes_pars_fragment:vx,clipping_planes_pars_vertex:yx,clipping_planes_vertex:Mx,color_fragment:Sx,color_pars_fragment:bx,color_pars_vertex:Tx,color_vertex:Ax,common:wx,cube_uv_reflection_fragment:Ex,defaultnormal_vertex:Cx,displacementmap_pars_vertex:Rx,displacementmap_vertex:Ix,emissivemap_fragment:Px,emissivemap_pars_fragment:Lx,colorspace_fragment:Dx,colorspace_pars_fragment:Ux,envmap_fragment:Nx,envmap_common_pars_fragment:Fx,envmap_pars_fragment:Ox,envmap_pars_vertex:Bx,envmap_physical_pars_fragment:$x,envmap_vertex:zx,fog_vertex:kx,fog_pars_vertex:Vx,fog_fragment:Gx,fog_pars_fragment:Hx,gradientmap_pars_fragment:Wx,lightmap_pars_fragment:Xx,lights_lambert_fragment:qx,lights_lambert_pars_fragment:Yx,lights_pars_begin:Zx,lights_toon_fragment:Jx,lights_toon_pars_fragment:Kx,lights_phong_fragment:jx,lights_phong_pars_fragment:Qx,lights_physical_fragment:tv,lights_physical_pars_fragment:ev,lights_fragment_begin:nv,lights_fragment_maps:iv,lights_fragment_end:rv,lightprobes_pars_fragment:sv,logdepthbuf_fragment:av,logdepthbuf_pars_fragment:ov,logdepthbuf_pars_vertex:lv,logdepthbuf_vertex:cv,map_fragment:hv,map_pars_fragment:uv,map_particle_fragment:dv,map_particle_pars_fragment:fv,metalnessmap_fragment:pv,metalnessmap_pars_fragment:mv,morphinstance_vertex:gv,morphcolor_vertex:_v,morphnormal_vertex:xv,morphtarget_pars_vertex:vv,morphtarget_vertex:yv,normal_fragment_begin:Mv,normal_fragment_maps:Sv,normal_pars_fragment:bv,normal_pars_vertex:Tv,normal_vertex:Av,normalmap_pars_fragment:wv,clearcoat_normal_fragment_begin:Ev,clearcoat_normal_fragment_maps:Cv,clearcoat_pars_fragment:Rv,iridescence_pars_fragment:Iv,opaque_fragment:Pv,packing:Lv,premultiplied_alpha_fragment:Dv,project_vertex:Uv,dithering_fragment:Nv,dithering_pars_fragment:Fv,roughnessmap_fragment:Ov,roughnessmap_pars_fragment:Bv,shadowmap_pars_fragment:zv,shadowmap_pars_vertex:kv,shadowmap_vertex:Vv,shadowmask_pars_fragment:Gv,skinbase_vertex:Hv,skinning_pars_vertex:Wv,skinning_vertex:Xv,skinnormal_vertex:qv,specularmap_fragment:Yv,specularmap_pars_fragment:Zv,tonemapping_fragment:$v,tonemapping_pars_fragment:Jv,transmission_fragment:Kv,transmission_pars_fragment:jv,uv_pars_fragment:Qv,uv_pars_vertex:ty,uv_vertex:ey,worldpos_vertex:ny,background_vert:`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,background_frag:`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,backgroundCube_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,cube_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,cube_frag:`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,depth_vert:`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,depth_frag:`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #ifdef USE_REVERSED_DEPTH_BUFFER + float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; + #else + float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; + #endif + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,distance_vert:`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,distance_frag:`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); +}`,equirect_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,equirect_frag:`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,linedashed_vert:`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,linedashed_frag:`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,meshbasic_vert:`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,meshbasic_frag:`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,meshlambert_vert:`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,meshlambert_frag:`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,meshmatcap_vert:`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,meshmatcap_frag:`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,meshnormal_vert:`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,meshnormal_frag:`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,meshphong_vert:`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,meshphong_frag:`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,meshphysical_vert:`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,meshphysical_frag:`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + + outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; + + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,meshtoon_vert:`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,meshtoon_frag:`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,points_vert:`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,points_frag:`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,shadow_vert:`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,shadow_frag:`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include + #include +}`,sprite_vert:`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,sprite_frag:`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`},Vt={common:{diffuse:{value:new $t(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Me},alphaMap:{value:null},alphaMapTransform:{value:new Me},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Me}},envmap:{envMap:{value:null},envMapRotation:{value:new Me},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Me}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Me}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Me},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Me},normalScale:{value:new Mt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Me},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Me}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Me}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Me}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new $t(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new D},probesMax:{value:new D},probesResolution:{value:new D}},points:{diffuse:{value:new $t(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Me},alphaTest:{value:0},uvTransform:{value:new Me}},sprite:{diffuse:{value:new $t(16777215)},opacity:{value:1},center:{value:new Mt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Me},alphaMap:{value:null},alphaMapTransform:{value:new Me},alphaTest:{value:0}}},di={basic:{uniforms:On([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.fog]),vertexShader:Re.meshbasic_vert,fragmentShader:Re.meshbasic_frag},lambert:{uniforms:On([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,Vt.lights,{emissive:{value:new $t(0)},envMapIntensity:{value:1}}]),vertexShader:Re.meshlambert_vert,fragmentShader:Re.meshlambert_frag},phong:{uniforms:On([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,Vt.lights,{emissive:{value:new $t(0)},specular:{value:new $t(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Re.meshphong_vert,fragmentShader:Re.meshphong_frag},standard:{uniforms:On([Vt.common,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.roughnessmap,Vt.metalnessmap,Vt.fog,Vt.lights,{emissive:{value:new $t(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Re.meshphysical_vert,fragmentShader:Re.meshphysical_frag},toon:{uniforms:On([Vt.common,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.gradientmap,Vt.fog,Vt.lights,{emissive:{value:new $t(0)}}]),vertexShader:Re.meshtoon_vert,fragmentShader:Re.meshtoon_frag},matcap:{uniforms:On([Vt.common,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,{matcap:{value:null}}]),vertexShader:Re.meshmatcap_vert,fragmentShader:Re.meshmatcap_frag},points:{uniforms:On([Vt.points,Vt.fog]),vertexShader:Re.points_vert,fragmentShader:Re.points_frag},dashed:{uniforms:On([Vt.common,Vt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Re.linedashed_vert,fragmentShader:Re.linedashed_frag},depth:{uniforms:On([Vt.common,Vt.displacementmap]),vertexShader:Re.depth_vert,fragmentShader:Re.depth_frag},normal:{uniforms:On([Vt.common,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,{opacity:{value:1}}]),vertexShader:Re.meshnormal_vert,fragmentShader:Re.meshnormal_frag},sprite:{uniforms:On([Vt.sprite,Vt.fog]),vertexShader:Re.sprite_vert,fragmentShader:Re.sprite_frag},background:{uniforms:{uvTransform:{value:new Me},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Re.background_vert,fragmentShader:Re.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Me}},vertexShader:Re.backgroundCube_vert,fragmentShader:Re.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Re.cube_vert,fragmentShader:Re.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Re.equirect_vert,fragmentShader:Re.equirect_frag},distance:{uniforms:On([Vt.common,Vt.displacementmap,{referencePosition:{value:new D},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Re.distance_vert,fragmentShader:Re.distance_frag},shadow:{uniforms:On([Vt.lights,Vt.fog,{color:{value:new $t(0)},opacity:{value:1}}]),vertexShader:Re.shadow_vert,fragmentShader:Re.shadow_frag}};di.physical={uniforms:On([di.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Me},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Me},clearcoatNormalScale:{value:new Mt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Me},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Me},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Me},sheen:{value:0},sheenColor:{value:new $t(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Me},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Me},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Me},transmissionSamplerSize:{value:new Mt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Me},attenuationDistance:{value:0},attenuationColor:{value:new $t(0)},specularColor:{value:new $t(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Me},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Me},anisotropyVector:{value:new Mt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Me}}]),vertexShader:Re.meshphysical_vert,fragmentShader:Re.meshphysical_frag};const Nl={r:0,b:0,g:0},iy=new ge,cp=new Me;cp.set(-1,0,0,0,1,0,0,0,1);function ry(r,t,e,n,i,s){const a=new $t(0);let o=i===!0?0:1,l,c,h=null,d=0,u=null;function f(x){let S=x.isScene===!0?x.background:null;if(S&&S.isTexture){const b=x.backgroundBlurriness>0;S=t.get(S,b)}return S}function p(x){let S=!1;const b=f(x);b===null?g(a,o):b&&b.isColor&&(g(b,1),S=!0);const P=r.xr.getEnvironmentBlendMode();P==="additive"?e.buffers.color.setClear(0,0,0,1,s):P==="alpha-blend"&&e.buffers.color.setClear(0,0,0,0,s),(r.autoClear||S)&&(e.buffers.depth.setTest(!0),e.buffers.depth.setMask(!0),e.buffers.color.setMask(!0),r.clear(r.autoClearColor,r.autoClearDepth,r.autoClearStencil))}function _(x,S){const b=f(S);b&&(b.isCubeTexture||b.mapping===Fr)?(c===void 0&&(c=new pn(new yr(1,1,1),new Qn({name:"BackgroundCubeMaterial",uniforms:hs(di.backgroundCube.uniforms),vertexShader:di.backgroundCube.vertexShader,fragmentShader:di.backgroundCube.fragmentShader,side:yt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(P,E,O){this.matrixWorld.copyPosition(O.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(c)),c.material.uniforms.envMap.value=b,c.material.uniforms.backgroundBlurriness.value=S.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=S.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(iy.makeRotationFromEuler(S.backgroundRotation)).transpose(),b.isCubeTexture&&b.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(cp),c.material.toneMapped=Ne.getTransfer(b.colorSpace)!==Ge,(h!==b||d!==b.version||u!==r.toneMapping)&&(c.material.needsUpdate=!0,h=b,d=b.version,u=r.toneMapping),c.layers.enableAll(),x.unshift(c,c.geometry,c.material,0,0,null)):b&&b.isTexture&&(l===void 0&&(l=new pn(new cs(2,2),new Qn({name:"BackgroundMaterial",uniforms:hs(di.background.uniforms),vertexShader:di.background.vertexShader,fragmentShader:di.background.fragmentShader,side:_t,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(l)),l.material.uniforms.t2D.value=b,l.material.uniforms.backgroundIntensity.value=S.backgroundIntensity,l.material.toneMapped=Ne.getTransfer(b.colorSpace)!==Ge,b.matrixAutoUpdate===!0&&b.updateMatrix(),l.material.uniforms.uvTransform.value.copy(b.matrix),(h!==b||d!==b.version||u!==r.toneMapping)&&(l.material.needsUpdate=!0,h=b,d=b.version,u=r.toneMapping),l.layers.enableAll(),x.unshift(l,l.geometry,l.material,0,0,null))}function g(x,S){x.getRGB(Nl,uf(r)),e.buffers.color.setClear(Nl.r,Nl.g,Nl.b,S,s)}function m(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(x,S=1){a.set(x),o=S,g(a,o)},getClearAlpha:function(){return o},setClearAlpha:function(x){o=x,g(a,o)},render:p,addToRenderList:_,dispose:m}}function sy(r,t){const e=r.getParameter(r.MAX_VERTEX_ATTRIBS),n={},i=u(null);let s=i,a=!1;function o(z,K,lt,ut,$){let st=!1;const tt=d(z,ut,lt,K);s!==tt&&(s=tt,c(s.object)),st=f(z,ut,lt,$),st&&p(z,ut,lt,$),$!==null&&t.update($,r.ELEMENT_ARRAY_BUFFER),(st||a)&&(a=!1,b(z,K,lt,ut),$!==null&&r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t.get($).buffer))}function l(){return r.createVertexArray()}function c(z){return r.bindVertexArray(z)}function h(z){return r.deleteVertexArray(z)}function d(z,K,lt,ut){const $=ut.wireframe===!0;let st=n[K.id];st===void 0&&(st={},n[K.id]=st);const tt=z.isInstancedMesh===!0?z.id:0;let wt=st[tt];wt===void 0&&(wt={},st[tt]=wt);let Et=wt[lt.id];Et===void 0&&(Et={},wt[lt.id]=Et);let kt=Et[$];return kt===void 0&&(kt=u(l()),Et[$]=kt),kt}function u(z){const K=[],lt=[],ut=[];for(let $=0;$=0){const Zt=$[Et];let re=st[Et];if(re===void 0&&(Et==="instanceMatrix"&&z.instanceMatrix&&(re=z.instanceMatrix),Et==="instanceColor"&&z.instanceColor&&(re=z.instanceColor)),Zt===void 0||Zt.attribute!==re||re&&Zt.data!==re.data)return!0;tt++}return s.attributesNum!==tt||s.index!==ut}function p(z,K,lt,ut){const $={},st=K.attributes;let tt=0;const wt=lt.getAttributes();for(const Et in wt)if(wt[Et].location>=0){let Zt=st[Et];Zt===void 0&&(Et==="instanceMatrix"&&z.instanceMatrix&&(Zt=z.instanceMatrix),Et==="instanceColor"&&z.instanceColor&&(Zt=z.instanceColor));const re={};re.attribute=Zt,Zt&&Zt.data&&(re.data=Zt.data),$[Et]=re,tt++}s.attributes=$,s.attributesNum=tt,s.index=ut}function _(){const z=s.newAttributes;for(let K=0,lt=z.length;K=0){let kt=$[wt];if(kt===void 0&&(wt==="instanceMatrix"&&z.instanceMatrix&&(kt=z.instanceMatrix),wt==="instanceColor"&&z.instanceColor&&(kt=z.instanceColor)),kt!==void 0){const Zt=kt.normalized,re=kt.itemSize,Ie=t.get(kt);if(Ie===void 0)continue;const Be=Ie.buffer,be=Ie.type,xt=Ie.bytesPerElement,Ht=be===r.INT||be===r.UNSIGNED_INT||kt.gpuType===Ca;if(kt.isInterleavedBufferAttribute){const Pt=kt.data,oe=Pt.stride,me=kt.offset;if(Pt.isInstancedInterleavedBuffer){for(let fe=0;fe0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision>0)return"highp";O="mediump"}return O==="mediump"&&r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=e.precision!==void 0?e.precision:"highp";const h=l(c);h!==c&&(Ft("WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);const d=e.logarithmicDepthBuffer===!0,u=e.reversedDepthBuffer===!0&&t.has("EXT_clip_control");e.reversedDepthBuffer===!0&&u===!1&&Ft("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");const f=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),p=r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS),_=r.getParameter(r.MAX_TEXTURE_SIZE),g=r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE),m=r.getParameter(r.MAX_VERTEX_ATTRIBS),x=r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS),S=r.getParameter(r.MAX_VARYING_VECTORS),b=r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS),P=r.getParameter(r.MAX_SAMPLES),E=r.getParameter(r.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:u,maxTextures:f,maxVertexTextures:p,maxTextureSize:_,maxCubemapSize:g,maxAttributes:m,maxVertexUniforms:x,maxVaryings:S,maxFragmentUniforms:b,maxSamples:P,samples:E}}function ly(r){const t=this;let e=null,n=0,i=!1,s=!1;const a=new Ki,o=new Me,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,u){const f=d.length!==0||u||n!==0||i;return i=u,n=d.length,f},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(d,u){e=h(d,u,0)},this.setState=function(d,u,f){const p=d.clippingPlanes,_=d.clipIntersection,g=d.clipShadows,m=r.get(d);if(!i||p===null||p.length===0||s&&!g)s?h(null):c();else{const x=s?0:n,S=x*4;let b=m.clippingState||null;l.value=b,b=h(p,u,S,f);for(let P=0;P!==S;++P)b[P]=e[P];m.clippingState=b,this.numIntersection=_?this.numPlanes:0,this.numPlanes+=x}};function c(){l.value!==e&&(l.value=e,l.needsUpdate=n>0),t.numPlanes=n,t.numIntersection=0}function h(d,u,f,p){const _=d!==null?d.length:0;let g=null;if(_!==0){if(g=l.value,p!==!0||g===null){const m=f+_*4,x=u.matrixWorldInverse;o.getNormalMatrix(x),(g===null||g.length0&&this._blur(l,0,0,e),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=pp(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=fp(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t2?P:0,P,P),d.setRenderTarget(i),m&&d.render(_,l),d.render(t,l)}d.toneMapping=f,d.autoClear=u,t.background=x}_textureToCubeUV(t,e){const n=this._renderer,i=t.mapping===pi||t.mapping===ki;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=pp()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=fp());const s=i?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=s;const o=s.uniforms;o.envMap.value=t;const l=this._cubeSize;_s(e,0,0,3*l,2*l),n.setRenderTarget(e),n.render(a,ya)}_applyPMREM(t){const e=this._renderer,n=e.autoClear;e.autoClear=!1;const i=this._lodMeshes.length;for(let s=1;sp-ir?n-p+ir:0),m=4*(this._cubeSize-_);l.envMap.value=t.texture,l.roughness.value=f,l.mipInt.value=p-e,_s(s,g,m,3*_,2*_),i.setRenderTarget(s),i.render(o,ya),l.envMap.value=s.texture,l.roughness.value=0,l.mipInt.value=p-n,_s(t,g,m,3*_,2*_),i.setRenderTarget(t),i.render(o,ya)}_blur(t,e,n,i,s){const a=this._pingPongRenderTarget;this._halfBlur(t,a,e,n,i,"latitudinal",s),this._halfBlur(a,t,n,n,i,"longitudinal",s)}_halfBlur(t,e,n,i,s,a,o){const l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&ie("blur direction must be either latitudinal or longitudinal!");const h=3,d=this._lodMeshes[i];d.material=c;const u=c.uniforms,f=this._sizeLods[n]-1,p=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*Lr-1),_=s/p,g=isFinite(s)?1+Math.floor(h*_):Lr;g>Lr&&Ft(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${Lr}`);const m=[];let x=0;for(let O=0;OS-ir?i-S+ir:0),E=4*(this._cubeSize-b);_s(e,P,E,3*b,2*b),l.setRenderTarget(e),l.render(d,ya)}}function uy(r){const t=[],e=[],n=[];let i=r;const s=r-ir+1+hp.length;for(let a=0;ar-ir?l=hp[a-r+ir-1]:a===0&&(l=0),e.push(l);const c=1/(o-2),h=-c,d=1+c,u=[h,h,d,h,d,d,h,h,d,d,h,d],f=6,p=6,_=3,g=2,m=1,x=new Float32Array(_*p*f),S=new Float32Array(g*p*f),b=new Float32Array(m*p*f);for(let E=0;E2?0:-1,I=[O,y,0,O+2/3,y,0,O+2/3,y+1,0,O,y,0,O+2/3,y+1,0,O,y+1,0];x.set(I,_*p*E),S.set(u,g*p*E);const k=[E,E,E,E,E,E];b.set(k,m*p*E)}const P=new Se;P.setAttribute("position",new Xe(x,_)),P.setAttribute("uv",new Xe(S,g)),P.setAttribute("faceIndex",new Xe(b,m)),n.push(new pn(P,null)),i>ir&&i--}return{lodMeshes:n,sizeLods:t,sigmas:e}}function dp(r,t,e){const n=new Yn(r,t,e);return n.texture.mapping=Fr,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function _s(r,t,e,n,i){r.viewport.set(t,e,n,i),r.scissor.set(t,e,n,i)}function dy(r,t,e){return new Qn({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:cy,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${r}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Fl(),fragmentShader:` + + precision highp float; + precision highp int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform float roughness; + uniform float mipInt; + + #define ENVMAP_TYPE_CUBE_UV + #include + + #define PI 3.14159265359 + + // Van der Corput radical inverse + float radicalInverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 + } + + // Hammersley sequence + vec2 hammersley(uint i, uint N) { + return vec2(float(i) / float(N), radicalInverse_VdC(i)); + } + + // GGX VNDF importance sampling (Eric Heitz 2018) + // "Sampling the GGX Distribution of Visible Normals" + // https://jcgt.org/published/0007/04/01/ + vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { + float alpha = roughness * roughness; + + // Section 4.1: Orthonormal basis + vec3 T1 = vec3(1.0, 0.0, 0.0); + vec3 T2 = cross(V, T1); + + // Section 4.2: Parameterization of projected area + float r = sqrt(Xi.x); + float phi = 2.0 * PI * Xi.y; + float t1 = r * cos(phi); + float t2 = r * sin(phi); + float s = 0.5 * (1.0 + V.z); + t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; + + // Section 4.3: Reprojection onto hemisphere + vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; + + // Section 3.4: Transform back to ellipsoid configuration + return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); + } + + void main() { + vec3 N = normalize(vOutputDirection); + vec3 V = N; // Assume view direction equals normal for pre-filtering + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + // For very low roughness, just sample the environment directly + if (roughness < 0.001) { + gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); + return; + } + + // Tangent space basis for VNDF sampling + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + + for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { + vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); + + // For PMREM, V = N, so in tangent space V is always (0, 0, 1) + vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); + + // Transform H back to world space + vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); + vec3 L = normalize(2.0 * dot(V, H) * H - V); + + float NdotL = max(dot(N, L), 0.0); + + if(NdotL > 0.0) { + // Sample environment at fixed mip level + // VNDF importance sampling handles the distribution filtering + vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); + + // Weight by NdotL for the split-sum approximation + // VNDF PDF naturally accounts for the visible microfacet distribution + prefilteredColor += sampleColor * NdotL; + totalWeight += NdotL; + } + } + + if (totalWeight > 0.0) { + prefilteredColor = prefilteredColor / totalWeight; + } + + gl_FragColor = vec4(prefilteredColor, 1.0); + } + `,blending:et,depthTest:!1,depthWrite:!1})}function fy(r,t,e){const n=new Float32Array(Lr),i=new D(0,1,0);return new Qn({name:"SphericalGaussianBlur",defines:{n:Lr,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${r}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Fl(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:et,depthTest:!1,depthWrite:!1})}function fp(){return new Qn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Fl(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:et,depthTest:!1,depthWrite:!1})}function pp(){return new Qn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Fl(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:et,depthTest:!1,depthWrite:!1})}function Fl(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}class jh extends Yn{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const n={width:t,height:t,depth:1},i=[n,n,n,n,n,n];this.texture=new ia(i),this._setTextureOptions(e),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},i=new yr(5,5,5),s=new Qn({name:"CubemapFromEquirect",uniforms:hs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:yt,blending:et});s.uniforms.tEquirect.value=e;const a=new pn(i,s),o=e.minFilter;return e.minFilter===mi&&(e.minFilter=tn),new Wf(1,10,this).update(t,a),e.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(t,e=!0,n=!0,i=!0){const s=t.getRenderTarget();for(let a=0;a<6;a++)t.setRenderTarget(this,a),t.clear(e,n,i);t.setRenderTarget(s)}}function py(r){let t=new WeakMap,e=new WeakMap,n=null;function i(u,f=!1){return u==null?null:f?a(u):s(u)}function s(u){if(u&&u.isTexture){const f=u.mapping;if(f===Ts||f===As)if(t.has(u)){const p=t.get(u).texture;return o(p,u.mapping)}else{const p=u.image;if(p&&p.height>0){const _=new jh(p.height);return _.fromEquirectangularTexture(r,u),t.set(u,_),u.addEventListener("dispose",c),o(_.texture,u.mapping)}else return null}}return u}function a(u){if(u&&u.isTexture){const f=u.mapping,p=f===Ts||f===As,_=f===pi||f===ki;if(p||_){let g=e.get(u);const m=g!==void 0?g.texture.pmremVersion:0;if(u.isRenderTargetTexture&&u.pmremVersion!==m)return n===null&&(n=new Kh(r)),g=p?n.fromEquirectangular(u,g):n.fromCubemap(u,g),g.texture.pmremVersion=u.pmremVersion,e.set(u,g),g.texture;if(g!==void 0)return g.texture;{const x=u.image;return p&&x&&x.height>0||_&&x&&l(x)?(n===null&&(n=new Kh(r)),g=p?n.fromEquirectangular(u):n.fromCubemap(u),g.texture.pmremVersion=u.pmremVersion,e.set(u,g),u.addEventListener("dispose",h),g.texture):null}}}return u}function o(u,f){return f===Ts?u.mapping=pi:f===As&&(u.mapping=ki),u}function l(u){let f=0;const p=6;for(let _=0;_=65535?Wc:Hc)(u,1);g.version=_;const m=s.get(d);m&&t.remove(m),s.set(d,g)}function h(d){const u=s.get(d);if(u){const f=d.index;f!==null&&u.versiont.maxTextureSize&&(E=Math.ceil(P/t.maxTextureSize),P=t.maxTextureSize);const O=new Float32Array(P*E*4*d),y=new _o(O,P,E,d);y.type=Pn,y.needsUpdate=!0;const I=b*4;for(let z=0;z + #include + + void main() { + gl_FragColor = texture2D( tDiffuse, vUv ); + + #ifdef LINEAR_TONE_MAPPING + gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); + #elif defined( REINHARD_TONE_MAPPING ) + gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); + #elif defined( CINEON_TONE_MAPPING ) + gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); + #elif defined( ACES_FILMIC_TONE_MAPPING ) + gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); + #elif defined( AGX_TONE_MAPPING ) + gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); + #elif defined( NEUTRAL_TONE_MAPPING ) + gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); + #elif defined( CUSTOM_TONE_MAPPING ) + gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); + #endif + + #ifdef SRGB_TRANSFER + gl_FragColor = sRGBTransferOETF( gl_FragColor ); + #endif + }`,depthTest:!1,depthWrite:!1}),c=new pn(o,l),h=new va(-1,1,1,-1,0,1);let d=null,u=null,f=!1,p,_=null,g=[],m=!1;this.setSize=function(x,S){s.setSize(x,S),a.setSize(x,S);for(let b=0;b0&&g[0].isRenderPass===!0;const S=s.width,b=s.height;for(let P=0;P0)return r;const i=t*e;let s=vp[i];if(s===void 0&&(s=new Float32Array(i),vp[i]=s),t!==0){n.toArray(s,0);for(let a=1,o=0;a!==t;++a)o+=e,r[a].toArray(s,o)}return s}function gn(r,t){if(r.length!==t.length)return!1;for(let e=0,n=r.length;e0&&(this.seq=i.concat(s))}setValue(t,e,n,i){const s=this.map[e];s!==void 0&&s.setValue(t,n,i)}setOptional(t,e,n){const i=e[n];i!==void 0&&this.setValue(t,n,i)}static upload(t,e,n,i){for(let s=0,a=e.length;s!==a;++s){const o=e[s],l=n[o.id];l.needsUpdate!==!1&&o.setValue(t,l.value,i)}}static seqWithValue(t,e){const n=[];for(let i=0,s=t.length;i!==s;++i){const a=t[i];a.id in e&&n.push(a)}return n}}function Ap(r,t,e){const n=r.createShader(t);return r.shaderSource(n,e),r.compileShader(n),n}const fM=37297;let pM=0;function mM(r,t){const e=r.split(` +`),n=[],i=Math.max(t-6,0),s=Math.min(t+6,e.length);for(let a=i;a":" "} ${o}: ${e[a]}`)}return n.join(` +`)}const wp=new Me;function gM(r){Ne._getMatrix(wp,Ne.workingColorSpace,r);const t=`mat3( ${wp.elements.map(e=>e.toFixed(4))} )`;switch(Ne.getTransfer(r)){case zs:return[t,"LinearTransferOETF"];case Ge:return[t,"sRGBTransferOETF"];default:return Ft("WebGLProgram: Unsupported color space: ",r),[t,"LinearTransferOETF"]}}function Ep(r,t,e){const n=r.getShaderParameter(t,r.COMPILE_STATUS),s=(r.getShaderInfoLog(t)||"").trim();if(n&&s==="")return"";const a=/ERROR: 0:(\d+)/.exec(s);if(a){const o=parseInt(a[1]);return e.toUpperCase()+` + +`+s+` + +`+mM(r.getShaderSource(t),o)}else return s}function _M(r,t){const e=gM(t);return[`vec4 ${r}( vec4 value ) {`,` return ${e[1]}( vec4( value.rgb * ${e[0]}, value.a ) );`,"}"].join(` +`)}const xM={[lc]:"Linear",[cc]:"Reinhard",[hc]:"Cineon",[uc]:"ACESFilmic",[fc]:"AgX",[pc]:"Neutral",[dc]:"Custom"};function vM(r,t){const e=xM[t];return e===void 0?(Ft("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+r+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+r+"( vec3 color ) { return "+e+"ToneMapping( color ); }"}const zl=new D;function yM(){Ne.getLuminanceCoefficients(zl);const r=zl.x.toFixed(4),t=zl.y.toFixed(4),e=zl.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${r}, ${t}, ${e} );`," return dot( weights, rgb );","}"].join(` +`)}function MM(r){return[r.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",r.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Ma).join(` +`)}function SM(r){const t=[];for(const e in r){const n=r[e];n!==!1&&t.push("#define "+e+" "+n)}return t.join(` +`)}function bM(r,t){const e={},n=r.getProgramParameter(t,r.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function eu(r){return r.replace(TM,wM)}const AM=new Map;function wM(r,t){let e=Re[t];if(e===void 0){const n=AM.get(t);if(n!==void 0)e=Re[n],Ft('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,n);else throw new Error("Can not resolve #include <"+t+">")}return eu(e)}const EM=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Ip(r){return r.replace(EM,CM)}function CM(r,t,e,n){let i="";for(let s=parseInt(t);s0&&(g+=` +`),m=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,p].filter(Ma).join(` +`),m.length>0&&(m+=` +`)):(g=[Pp(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,p,e.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",e.batching?"#define USE_BATCHING":"",e.batchingColor?"#define USE_BATCHING_COLOR":"",e.instancing?"#define USE_INSTANCING":"",e.instancingColor?"#define USE_INSTANCING_COLOR":"",e.instancingMorph?"#define USE_INSTANCING_MORPH":"",e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+h:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.displacementMap?"#define USE_DISPLACEMENTMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.mapUv?"#define MAP_UV "+e.mapUv:"",e.alphaMapUv?"#define ALPHAMAP_UV "+e.alphaMapUv:"",e.lightMapUv?"#define LIGHTMAP_UV "+e.lightMapUv:"",e.aoMapUv?"#define AOMAP_UV "+e.aoMapUv:"",e.emissiveMapUv?"#define EMISSIVEMAP_UV "+e.emissiveMapUv:"",e.bumpMapUv?"#define BUMPMAP_UV "+e.bumpMapUv:"",e.normalMapUv?"#define NORMALMAP_UV "+e.normalMapUv:"",e.displacementMapUv?"#define DISPLACEMENTMAP_UV "+e.displacementMapUv:"",e.metalnessMapUv?"#define METALNESSMAP_UV "+e.metalnessMapUv:"",e.roughnessMapUv?"#define ROUGHNESSMAP_UV "+e.roughnessMapUv:"",e.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+e.anisotropyMapUv:"",e.clearcoatMapUv?"#define CLEARCOATMAP_UV "+e.clearcoatMapUv:"",e.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+e.clearcoatNormalMapUv:"",e.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+e.clearcoatRoughnessMapUv:"",e.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+e.iridescenceMapUv:"",e.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+e.iridescenceThicknessMapUv:"",e.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+e.sheenColorMapUv:"",e.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+e.sheenRoughnessMapUv:"",e.specularMapUv?"#define SPECULARMAP_UV "+e.specularMapUv:"",e.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+e.specularColorMapUv:"",e.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+e.specularIntensityMapUv:"",e.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+e.transmissionMapUv:"",e.thicknessMapUv?"#define THICKNESSMAP_UV "+e.thicknessMapUv:"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexNormals?"#define HAS_NORMAL":"",e.vertexColors?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.flatShading?"#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&e.flatShading===!1?"#define USE_MORPHNORMALS":"",e.morphColors?"#define USE_MORPHCOLORS":"",e.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+e.morphTextureStride:"",e.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+e.morphTargetsCount:"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(Ma).join(` +`),m=[Pp(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,p,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",e.map?"#define USE_MAP":"",e.matcap?"#define USE_MATCAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+c:"",e.envMap?"#define "+h:"",e.envMap?"#define "+d:"",u?"#define CUBEUV_TEXEL_WIDTH "+u.texelWidth:"",u?"#define CUBEUV_TEXEL_HEIGHT "+u.texelHeight:"",u?"#define CUBEUV_MAX_MIP "+u.maxMip+".0":"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoat?"#define USE_CLEARCOAT":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.dispersion?"#define USE_DISPERSION":"",e.iridescence?"#define USE_IRIDESCENCE":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaTest?"#define USE_ALPHATEST":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.sheen?"#define USE_SHEEN":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors||e.instancingColor?"#define USE_COLOR":"",e.vertexAlphas||e.batchingColor?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",e.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",e.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",e.toneMapping!==ii?"#define TONE_MAPPING":"",e.toneMapping!==ii?Re.tonemapping_pars_fragment:"",e.toneMapping!==ii?vM("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.opaque?"#define OPAQUE":"",Re.colorspace_pars_fragment,_M("linearToOutputTexel",e.outputColorSpace),yM(),e.useDepthPacking?"#define DEPTH_PACKING "+e.depthPacking:"",` +`].filter(Ma).join(` +`)),a=eu(a),a=Cp(a,e),a=Rp(a,e),o=eu(o),o=Cp(o,e),o=Rp(o,e),a=Ip(a),o=Ip(o),e.isRawShaderMaterial!==!0&&(x=`#version 300 es +`,g=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+g,m=["#define varying in",e.glslVersion===wc?"":"layout(location = 0) out highp vec4 pc_fragColor;",e.glslVersion===wc?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+m);const S=x+g+a,b=x+m+o,P=Ap(i,i.VERTEX_SHADER,S),E=Ap(i,i.FRAGMENT_SHADER,b);i.attachShader(_,P),i.attachShader(_,E),e.index0AttributeName!==void 0?i.bindAttribLocation(_,0,e.index0AttributeName):e.morphTargets===!0&&i.bindAttribLocation(_,0,"position"),i.linkProgram(_);function O(z){if(r.debug.checkShaderErrors){const K=i.getProgramInfoLog(_)||"",lt=i.getShaderInfoLog(P)||"",ut=i.getShaderInfoLog(E)||"",$=K.trim(),st=lt.trim(),tt=ut.trim();let wt=!0,Et=!0;if(i.getProgramParameter(_,i.LINK_STATUS)===!1)if(wt=!1,typeof r.debug.onShaderError=="function")r.debug.onShaderError(i,_,P,E);else{const kt=Ep(i,P,"vertex"),Zt=Ep(i,E,"fragment");ie("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(_,i.VALIDATE_STATUS)+` + +Material Name: `+z.name+` +Material Type: `+z.type+` + +Program Info Log: `+$+` +`+kt+` +`+Zt)}else $!==""?Ft("WebGLProgram: Program Info Log:",$):(st===""||tt==="")&&(Et=!1);Et&&(z.diagnostics={runnable:wt,programLog:$,vertexShader:{log:st,prefix:g},fragmentShader:{log:tt,prefix:m}})}i.deleteShader(P),i.deleteShader(E),y=new Bl(i,_),I=bM(i,_)}let y;this.getUniforms=function(){return y===void 0&&O(this),y};let I;this.getAttributes=function(){return I===void 0&&O(this),I};let k=e.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return k===!1&&(k=i.getProgramParameter(_,fM)),k},this.destroy=function(){n.releaseStatesOfProgram(this),i.deleteProgram(_),this.program=void 0},this.type=e.shaderType,this.name=e.shaderName,this.id=pM++,this.cacheKey=t,this.usedTimes=1,this.program=_,this.vertexShader=P,this.fragmentShader=E,this}let zM=0;class kM{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){const e=t.vertexShader,n=t.fragmentShader,i=this._getShaderStage(e),s=this._getShaderStage(n),a=this._getShaderCacheForMaterial(t);return a.has(i)===!1&&(a.add(i),i.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(t){const e=this.materialCache.get(t);for(const n of e)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){const e=this.materialCache;let n=e.get(t);return n===void 0&&(n=new Set,e.set(t,n)),n}_getShaderStage(t){const e=this.shaderCache;let n=e.get(t);return n===void 0&&(n=new VM(t),e.set(t,n)),n}}class VM{constructor(t){this.id=zM++,this.code=t,this.usedTimes=0}}function GM(r){return r===Gi||r===Us||r===Ns}function HM(r,t,e,n,i,s){const a=new yo,o=new kM,l=new Set,c=[],h=new Map,d=n.logarithmicDepthBuffer;let u=n.precision;const f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function p(y){return l.add(y),y===0?"uv":`uv${y}`}function _(y,I,k,z,K,lt){const ut=z.fog,$=K.geometry,st=y.isMeshStandardMaterial||y.isMeshLambertMaterial||y.isMeshPhongMaterial?z.environment:null,tt=y.isMeshStandardMaterial||y.isMeshLambertMaterial&&!y.envMap||y.isMeshPhongMaterial&&!y.envMap,wt=t.get(y.envMap||st,tt),Et=wt&&wt.mapping===Fr?wt.image.height:null,kt=f[y.type];y.precision!==null&&(u=n.getMaxPrecision(y.precision),u!==y.precision&&Ft("WebGLProgram.getParameters:",y.precision,"not supported, using",u,"instead."));const Zt=$.morphAttributes.position||$.morphAttributes.normal||$.morphAttributes.color,re=Zt!==void 0?Zt.length:0;let Ie=0;$.morphAttributes.position!==void 0&&(Ie=1),$.morphAttributes.normal!==void 0&&(Ie=2),$.morphAttributes.color!==void 0&&(Ie=3);let Be,be,xt,Ht;if(kt){const Ee=di[kt];Be=Ee.vertexShader,be=Ee.fragmentShader}else Be=y.vertexShader,be=y.fragmentShader,o.update(y),xt=o.getVertexShaderID(y),Ht=o.getFragmentShaderID(y);const Pt=r.getRenderTarget(),oe=r.state.buffers.depth.getReversed(),me=K.isInstancedMesh===!0,fe=K.isBatchedMesh===!0,ze=!!y.map,_e=!!y.matcap,St=!!wt,Ct=!!y.aoMap,bt=!!y.lightMap,Xt=!!y.bumpMap,zt=!!y.normalMap,xe=!!y.displacementMap,G=!!y.emissiveMap,Te=!!y.metalnessMap,se=!!y.roughnessMap,ve=y.anisotropy>0,Rt=y.clearcoat>0,He=y.dispersion>0,R=y.iridescence>0,T=y.sheen>0,Q=y.transmission>0,mt=ve&&!!y.anisotropyMap,Tt=Rt&&!!y.clearcoatMap,It=Rt&&!!y.clearcoatNormalMap,Nt=Rt&&!!y.clearcoatRoughnessMap,ht=R&&!!y.iridescenceMap,gt=R&&!!y.iridescenceThicknessMap,Yt=T&&!!y.sheenColorMap,te=T&&!!y.sheenRoughnessMap,Ot=!!y.specularMap,Lt=!!y.specularColorMap,Ae=!!y.specularIntensityMap,Pe=Q&&!!y.transmissionMap,Ve=Q&&!!y.thicknessMap,q=!!y.gradientMap,Dt=!!y.alphaMap,pt=y.alphaTest>0,Jt=!!y.alphaHash,Bt=!!y.extensions;let At=ii;y.toneMapped&&(Pt===null||Pt.isXRRenderTarget===!0)&&(At=r.toneMapping);const ce={shaderID:kt,shaderType:y.type,shaderName:y.name,vertexShader:Be,fragmentShader:be,defines:y.defines,customVertexShaderID:xt,customFragmentShaderID:Ht,isRawShaderMaterial:y.isRawShaderMaterial===!0,glslVersion:y.glslVersion,precision:u,batching:fe,batchingColor:fe&&K._colorsTexture!==null,instancing:me,instancingColor:me&&K.instanceColor!==null,instancingMorph:me&&K.morphTexture!==null,outputColorSpace:Pt===null?r.outputColorSpace:Pt.isXRRenderTarget===!0?Pt.texture.colorSpace:Ne.workingColorSpace,alphaToCoverage:!!y.alphaToCoverage,map:ze,matcap:_e,envMap:St,envMapMode:St&&wt.mapping,envMapCubeUVHeight:Et,aoMap:Ct,lightMap:bt,bumpMap:Xt,normalMap:zt,displacementMap:xe,emissiveMap:G,normalMapObjectSpace:zt&&y.normalMapType===ku,normalMapTangentSpace:zt&&y.normalMapType===Ei,packedNormalMap:zt&&y.normalMapType===Ei&&GM(y.normalMap.format),metalnessMap:Te,roughnessMap:se,anisotropy:ve,anisotropyMap:mt,clearcoat:Rt,clearcoatMap:Tt,clearcoatNormalMap:It,clearcoatRoughnessMap:Nt,dispersion:He,iridescence:R,iridescenceMap:ht,iridescenceThicknessMap:gt,sheen:T,sheenColorMap:Yt,sheenRoughnessMap:te,specularMap:Ot,specularColorMap:Lt,specularIntensityMap:Ae,transmission:Q,transmissionMap:Pe,thicknessMap:Ve,gradientMap:q,opaque:y.transparent===!1&&y.blending===Ut&&y.alphaToCoverage===!1,alphaMap:Dt,alphaTest:pt,alphaHash:Jt,combine:y.combine,mapUv:ze&&p(y.map.channel),aoMapUv:Ct&&p(y.aoMap.channel),lightMapUv:bt&&p(y.lightMap.channel),bumpMapUv:Xt&&p(y.bumpMap.channel),normalMapUv:zt&&p(y.normalMap.channel),displacementMapUv:xe&&p(y.displacementMap.channel),emissiveMapUv:G&&p(y.emissiveMap.channel),metalnessMapUv:Te&&p(y.metalnessMap.channel),roughnessMapUv:se&&p(y.roughnessMap.channel),anisotropyMapUv:mt&&p(y.anisotropyMap.channel),clearcoatMapUv:Tt&&p(y.clearcoatMap.channel),clearcoatNormalMapUv:It&&p(y.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Nt&&p(y.clearcoatRoughnessMap.channel),iridescenceMapUv:ht&&p(y.iridescenceMap.channel),iridescenceThicknessMapUv:gt&&p(y.iridescenceThicknessMap.channel),sheenColorMapUv:Yt&&p(y.sheenColorMap.channel),sheenRoughnessMapUv:te&&p(y.sheenRoughnessMap.channel),specularMapUv:Ot&&p(y.specularMap.channel),specularColorMapUv:Lt&&p(y.specularColorMap.channel),specularIntensityMapUv:Ae&&p(y.specularIntensityMap.channel),transmissionMapUv:Pe&&p(y.transmissionMap.channel),thicknessMapUv:Ve&&p(y.thicknessMap.channel),alphaMapUv:Dt&&p(y.alphaMap.channel),vertexTangents:!!$.attributes.tangent&&(zt||ve),vertexNormals:!!$.attributes.normal,vertexColors:y.vertexColors,vertexAlphas:y.vertexColors===!0&&!!$.attributes.color&&$.attributes.color.itemSize===4,pointsUvs:K.isPoints===!0&&!!$.attributes.uv&&(ze||Dt),fog:!!ut,useFog:y.fog===!0,fogExp2:!!ut&&ut.isFogExp2,flatShading:y.wireframe===!1&&(y.flatShading===!0||$.attributes.normal===void 0&&zt===!1&&(y.isMeshLambertMaterial||y.isMeshPhongMaterial||y.isMeshStandardMaterial||y.isMeshPhysicalMaterial)),sizeAttenuation:y.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:oe,skinning:K.isSkinnedMesh===!0,morphTargets:$.morphAttributes.position!==void 0,morphNormals:$.morphAttributes.normal!==void 0,morphColors:$.morphAttributes.color!==void 0,morphTargetsCount:re,morphTextureStride:Ie,numDirLights:I.directional.length,numPointLights:I.point.length,numSpotLights:I.spot.length,numSpotLightMaps:I.spotLightMap.length,numRectAreaLights:I.rectArea.length,numHemiLights:I.hemi.length,numDirLightShadows:I.directionalShadowMap.length,numPointLightShadows:I.pointShadowMap.length,numSpotLightShadows:I.spotShadowMap.length,numSpotLightShadowsWithMaps:I.numSpotLightShadowsWithMaps,numLightProbes:I.numLightProbes,numLightProbeGrids:lt.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:y.dithering,shadowMapEnabled:r.shadowMap.enabled&&k.length>0,shadowMapType:r.shadowMap.type,toneMapping:At,decodeVideoTexture:ze&&y.map.isVideoTexture===!0&&Ne.getTransfer(y.map.colorSpace)===Ge,decodeVideoTextureEmissive:G&&y.emissiveMap.isVideoTexture===!0&&Ne.getTransfer(y.emissiveMap.colorSpace)===Ge,premultipliedAlpha:y.premultipliedAlpha,doubleSided:y.side===Gt,flipSided:y.side===yt,useDepthPacking:y.depthPacking>=0,depthPacking:y.depthPacking||0,index0AttributeName:y.index0AttributeName,extensionClipCullDistance:Bt&&y.extensions.clipCullDistance===!0&&e.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Bt&&y.extensions.multiDraw===!0||fe)&&e.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:e.has("KHR_parallel_shader_compile"),customProgramCacheKey:y.customProgramCacheKey()};return ce.vertexUv1s=l.has(1),ce.vertexUv2s=l.has(2),ce.vertexUv3s=l.has(3),l.clear(),ce}function g(y){const I=[];if(y.shaderID?I.push(y.shaderID):(I.push(y.customVertexShaderID),I.push(y.customFragmentShaderID)),y.defines!==void 0)for(const k in y.defines)I.push(k),I.push(y.defines[k]);return y.isRawShaderMaterial===!1&&(m(I,y),x(I,y),I.push(r.outputColorSpace)),I.push(y.customProgramCacheKey),I.join()}function m(y,I){y.push(I.precision),y.push(I.outputColorSpace),y.push(I.envMapMode),y.push(I.envMapCubeUVHeight),y.push(I.mapUv),y.push(I.alphaMapUv),y.push(I.lightMapUv),y.push(I.aoMapUv),y.push(I.bumpMapUv),y.push(I.normalMapUv),y.push(I.displacementMapUv),y.push(I.emissiveMapUv),y.push(I.metalnessMapUv),y.push(I.roughnessMapUv),y.push(I.anisotropyMapUv),y.push(I.clearcoatMapUv),y.push(I.clearcoatNormalMapUv),y.push(I.clearcoatRoughnessMapUv),y.push(I.iridescenceMapUv),y.push(I.iridescenceThicknessMapUv),y.push(I.sheenColorMapUv),y.push(I.sheenRoughnessMapUv),y.push(I.specularMapUv),y.push(I.specularColorMapUv),y.push(I.specularIntensityMapUv),y.push(I.transmissionMapUv),y.push(I.thicknessMapUv),y.push(I.combine),y.push(I.fogExp2),y.push(I.sizeAttenuation),y.push(I.morphTargetsCount),y.push(I.morphAttributeCount),y.push(I.numDirLights),y.push(I.numPointLights),y.push(I.numSpotLights),y.push(I.numSpotLightMaps),y.push(I.numHemiLights),y.push(I.numRectAreaLights),y.push(I.numDirLightShadows),y.push(I.numPointLightShadows),y.push(I.numSpotLightShadows),y.push(I.numSpotLightShadowsWithMaps),y.push(I.numLightProbes),y.push(I.shadowMapType),y.push(I.toneMapping),y.push(I.numClippingPlanes),y.push(I.numClipIntersection),y.push(I.depthPacking)}function x(y,I){a.disableAll(),I.instancing&&a.enable(0),I.instancingColor&&a.enable(1),I.instancingMorph&&a.enable(2),I.matcap&&a.enable(3),I.envMap&&a.enable(4),I.normalMapObjectSpace&&a.enable(5),I.normalMapTangentSpace&&a.enable(6),I.clearcoat&&a.enable(7),I.iridescence&&a.enable(8),I.alphaTest&&a.enable(9),I.vertexColors&&a.enable(10),I.vertexAlphas&&a.enable(11),I.vertexUv1s&&a.enable(12),I.vertexUv2s&&a.enable(13),I.vertexUv3s&&a.enable(14),I.vertexTangents&&a.enable(15),I.anisotropy&&a.enable(16),I.alphaHash&&a.enable(17),I.batching&&a.enable(18),I.dispersion&&a.enable(19),I.batchingColor&&a.enable(20),I.gradientMap&&a.enable(21),I.packedNormalMap&&a.enable(22),I.vertexNormals&&a.enable(23),y.push(a.mask),a.disableAll(),I.fog&&a.enable(0),I.useFog&&a.enable(1),I.flatShading&&a.enable(2),I.logarithmicDepthBuffer&&a.enable(3),I.reversedDepthBuffer&&a.enable(4),I.skinning&&a.enable(5),I.morphTargets&&a.enable(6),I.morphNormals&&a.enable(7),I.morphColors&&a.enable(8),I.premultipliedAlpha&&a.enable(9),I.shadowMapEnabled&&a.enable(10),I.doubleSided&&a.enable(11),I.flipSided&&a.enable(12),I.useDepthPacking&&a.enable(13),I.dithering&&a.enable(14),I.transmission&&a.enable(15),I.sheen&&a.enable(16),I.opaque&&a.enable(17),I.pointsUvs&&a.enable(18),I.decodeVideoTexture&&a.enable(19),I.decodeVideoTextureEmissive&&a.enable(20),I.alphaToCoverage&&a.enable(21),I.numLightProbeGrids>0&&a.enable(22),y.push(a.mask)}function S(y){const I=f[y.type];let k;if(I){const z=di[I];k=df.clone(z.uniforms)}else k=y.uniforms;return k}function b(y,I){let k=h.get(I);return k!==void 0?++k.usedTimes:(k=new BM(r,I,y,i),c.push(k),h.set(I,k)),k}function P(y){if(--y.usedTimes===0){const I=c.indexOf(y);c[I]=c[c.length-1],c.pop(),h.delete(y.cacheKey),y.destroy()}}function E(y){o.remove(y)}function O(){o.dispose()}return{getParameters:_,getProgramCacheKey:g,getUniforms:S,acquireProgram:b,releaseProgram:P,releaseShaderCache:E,programs:c,dispose:O}}function WM(){let r=new WeakMap;function t(a){return r.has(a)}function e(a){let o=r.get(a);return o===void 0&&(o={},r.set(a,o)),o}function n(a){r.delete(a)}function i(a,o,l){r.get(a)[o]=l}function s(){r=new WeakMap}return{has:t,get:e,remove:n,update:i,dispose:s}}function XM(r,t){return r.groupOrder!==t.groupOrder?r.groupOrder-t.groupOrder:r.renderOrder!==t.renderOrder?r.renderOrder-t.renderOrder:r.material.id!==t.material.id?r.material.id-t.material.id:r.materialVariant!==t.materialVariant?r.materialVariant-t.materialVariant:r.z!==t.z?r.z-t.z:r.id-t.id}function Lp(r,t){return r.groupOrder!==t.groupOrder?r.groupOrder-t.groupOrder:r.renderOrder!==t.renderOrder?r.renderOrder-t.renderOrder:r.z!==t.z?t.z-r.z:r.id-t.id}function Dp(){const r=[];let t=0;const e=[],n=[],i=[];function s(){t=0,e.length=0,n.length=0,i.length=0}function a(u){let f=0;return u.isInstancedMesh&&(f+=2),u.isSkinnedMesh&&(f+=1),f}function o(u,f,p,_,g,m){let x=r[t];return x===void 0?(x={id:u.id,object:u,geometry:f,material:p,materialVariant:a(u),groupOrder:_,renderOrder:u.renderOrder,z:g,group:m},r[t]=x):(x.id=u.id,x.object=u,x.geometry=f,x.material=p,x.materialVariant=a(u),x.groupOrder=_,x.renderOrder=u.renderOrder,x.z=g,x.group=m),t++,x}function l(u,f,p,_,g,m){const x=o(u,f,p,_,g,m);p.transmission>0?n.push(x):p.transparent===!0?i.push(x):e.push(x)}function c(u,f,p,_,g,m){const x=o(u,f,p,_,g,m);p.transmission>0?n.unshift(x):p.transparent===!0?i.unshift(x):e.unshift(x)}function h(u,f){e.length>1&&e.sort(u||XM),n.length>1&&n.sort(f||Lp),i.length>1&&i.sort(f||Lp)}function d(){for(let u=t,f=r.length;u=s.length?(a=new Dp,s.push(a)):a=s[i],a}function e(){r=new WeakMap}return{get:t,dispose:e}}function YM(){const r={};return{get:function(t){if(r[t.id]!==void 0)return r[t.id];let e;switch(t.type){case"DirectionalLight":e={direction:new D,color:new $t};break;case"SpotLight":e={position:new D,direction:new D,color:new $t,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":e={position:new D,color:new $t,distance:0,decay:0};break;case"HemisphereLight":e={direction:new D,skyColor:new $t,groundColor:new $t};break;case"RectAreaLight":e={color:new $t,position:new D,halfWidth:new D,halfHeight:new D};break}return r[t.id]=e,e}}}function ZM(){const r={};return{get:function(t){if(r[t.id]!==void 0)return r[t.id];let e;switch(t.type){case"DirectionalLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Mt};break;case"SpotLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Mt};break;case"PointLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Mt,shadowCameraNear:1,shadowCameraFar:1e3};break}return r[t.id]=e,e}}}let $M=0;function JM(r,t){return(t.castShadow?2:0)-(r.castShadow?2:0)+(t.map?1:0)-(r.map?1:0)}function KM(r){const t=new YM,e=ZM(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)n.probe.push(new D);const i=new D,s=new ge,a=new ge;function o(c){let h=0,d=0,u=0;for(let I=0;I<9;I++)n.probe[I].set(0,0,0);let f=0,p=0,_=0,g=0,m=0,x=0,S=0,b=0,P=0,E=0,O=0;c.sort(JM);for(let I=0,k=c.length;I0&&(r.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=Vt.LTC_FLOAT_1,n.rectAreaLTC2=Vt.LTC_FLOAT_2):(n.rectAreaLTC1=Vt.LTC_HALF_1,n.rectAreaLTC2=Vt.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=d,n.ambient[2]=u;const y=n.hash;(y.directionalLength!==f||y.pointLength!==p||y.spotLength!==_||y.rectAreaLength!==g||y.hemiLength!==m||y.numDirectionalShadows!==x||y.numPointShadows!==S||y.numSpotShadows!==b||y.numSpotMaps!==P||y.numLightProbes!==O)&&(n.directional.length=f,n.spot.length=_,n.rectArea.length=g,n.point.length=p,n.hemi.length=m,n.directionalShadow.length=x,n.directionalShadowMap.length=x,n.pointShadow.length=S,n.pointShadowMap.length=S,n.spotShadow.length=b,n.spotShadowMap.length=b,n.directionalShadowMatrix.length=x,n.pointShadowMatrix.length=S,n.spotLightMatrix.length=b+P-E,n.spotLightMap.length=P,n.numSpotLightShadowsWithMaps=E,n.numLightProbes=O,y.directionalLength=f,y.pointLength=p,y.spotLength=_,y.rectAreaLength=g,y.hemiLength=m,y.numDirectionalShadows=x,y.numPointShadows=S,y.numSpotShadows=b,y.numSpotMaps=P,y.numLightProbes=O,n.version=$M++)}function l(c,h){let d=0,u=0,f=0,p=0,_=0;const g=h.matrixWorldInverse;for(let m=0,x=c.length;m=a.length?(o=new Up(r),a.push(o)):o=a[s],o}function n(){t=new WeakMap}return{get:e,dispose:n}}const QM=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,tS=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); + gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); +}`,eS=[new D(1,0,0),new D(-1,0,0),new D(0,1,0),new D(0,-1,0),new D(0,0,1),new D(0,0,-1)],nS=[new D(0,-1,0),new D(0,-1,0),new D(0,0,1),new D(0,0,-1),new D(0,-1,0),new D(0,-1,0)],Np=new ge,Sa=new D,nu=new D;function iS(r,t,e){let n=new os;const i=new Mt,s=new Mt,a=new We,o=new bh,l=new Th,c={},h=e.maxTextureSize,d={[_t]:yt,[yt]:_t,[Gt]:Gt},u=new Qn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Mt},radius:{value:4}},vertexShader:QM,fragmentShader:tS}),f=u.clone();f.defines.HORIZONTAL_PASS=1;const p=new Se;p.setAttribute("position",new Xe(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const _=new pn(p,u),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=M;let m=this.type;this.render=function(E,O,y){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||E.length===0)return;this.type===B&&(Ft("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=M);const I=r.getRenderTarget(),k=r.getActiveCubeFace(),z=r.getActiveMipmapLevel(),K=r.state;K.setBlending(et),K.buffers.depth.getReversed()===!0?K.buffers.color.setClear(0,0,0,0):K.buffers.color.setClear(1,1,1,1),K.buffers.depth.setTest(!0),K.setScissorTest(!1);const lt=m!==this.type;lt&&O.traverse(function(ut){ut.material&&(Array.isArray(ut.material)?ut.material.forEach($=>$.needsUpdate=!0):ut.material.needsUpdate=!0)});for(let ut=0,$=E.length;ut<$;ut++){const st=E[ut],tt=st.shadow;if(tt===void 0){Ft("WebGLShadowMap:",st,"has no shadow.");continue}if(tt.autoUpdate===!1&&tt.needsUpdate===!1)continue;i.copy(tt.mapSize);const wt=tt.getFrameExtents();i.multiply(wt),s.copy(tt.mapSize),(i.x>h||i.y>h)&&(i.x>h&&(s.x=Math.floor(h/wt.x),i.x=s.x*wt.x,tt.mapSize.x=s.x),i.y>h&&(s.y=Math.floor(h/wt.y),i.y=s.y*wt.y,tt.mapSize.y=s.y));const Et=r.state.buffers.depth.getReversed();if(tt.camera._reversedDepth=Et,tt.map===null||lt===!0){if(tt.map!==null&&(tt.map.depthTexture!==null&&(tt.map.depthTexture.dispose(),tt.map.depthTexture=null),tt.map.dispose()),this.type===W){if(st.isPointLight){Ft("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}tt.map=new Yn(i.x,i.y,{format:Gi,type:gi,minFilter:tn,magFilter:tn,generateMipmaps:!1}),tt.map.texture.name=st.name+".shadowMap",tt.map.depthTexture=new vr(i.x,i.y,Pn),tt.map.depthTexture.name=st.name+".shadowMapDepth",tt.map.depthTexture.format=_i,tt.map.depthTexture.compareFunction=null,tt.map.depthTexture.minFilter=ln,tt.map.depthTexture.magFilter=ln}else st.isPointLight?(tt.map=new jh(i.x),tt.map.depthTexture=new Gd(i.x,Kn)):(tt.map=new Yn(i.x,i.y),tt.map.depthTexture=new vr(i.x,i.y,Kn)),tt.map.depthTexture.name=st.name+".shadowMap",tt.map.depthTexture.format=_i,this.type===M?(tt.map.depthTexture.compareFunction=Et?mo:po,tt.map.depthTexture.minFilter=tn,tt.map.depthTexture.magFilter=tn):(tt.map.depthTexture.compareFunction=null,tt.map.depthTexture.minFilter=ln,tt.map.depthTexture.magFilter=ln);tt.camera.updateProjectionMatrix()}const kt=tt.map.isWebGLCubeRenderTarget?6:1;for(let Zt=0;Zt0||O.map&&O.alphaTest>0||O.alphaToCoverage===!0){const K=k.uuid,lt=O.uuid;let ut=c[K];ut===void 0&&(ut={},c[K]=ut);let $=ut[lt];$===void 0&&($=k.clone(),ut[lt]=$,O.addEventListener("dispose",P)),k=$}if(k.visible=O.visible,k.wireframe=O.wireframe,I===W?k.side=O.shadowSide!==null?O.shadowSide:O.side:k.side=O.shadowSide!==null?O.shadowSide:d[O.side],k.alphaMap=O.alphaMap,k.alphaTest=O.alphaToCoverage===!0?.5:O.alphaTest,k.map=O.map,k.clipShadows=O.clipShadows,k.clippingPlanes=O.clippingPlanes,k.clipIntersection=O.clipIntersection,k.displacementMap=O.displacementMap,k.displacementScale=O.displacementScale,k.displacementBias=O.displacementBias,k.wireframeLinewidth=O.wireframeLinewidth,k.linewidth=O.linewidth,y.isPointLight===!0&&k.isMeshDistanceMaterial===!0){const K=r.properties.get(k);K.light=y}return k}function b(E,O,y,I,k){if(E.visible===!1)return;if(E.layers.test(O.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&k===W)&&(!E.frustumCulled||n.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(y.matrixWorldInverse,E.matrixWorld);const lt=t.update(E),ut=E.material;if(Array.isArray(ut)){const $=lt.groups;for(let st=0,tt=$.length;st=1):Et.indexOf("OpenGL ES")!==-1&&(wt=parseFloat(/^OpenGL ES (\d)/.exec(Et)[1]),tt=wt>=2);let kt=null,Zt={};const re=r.getParameter(r.SCISSOR_BOX),Ie=r.getParameter(r.VIEWPORT),Be=new We().fromArray(re),be=new We().fromArray(Ie);function xt(q,Dt,pt,Jt){const Bt=new Uint8Array(4),At=r.createTexture();r.bindTexture(q,At),r.texParameteri(q,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(q,r.TEXTURE_MAG_FILTER,r.NEAREST);for(let ce=0;ce"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new Mt,h=new WeakMap,d=new Set;let u;const f=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(R,T){return p?new OffscreenCanvas(R,T):Vs("canvas")}function g(R,T,Q){let mt=1;const Tt=He(R);if((Tt.width>Q||Tt.height>Q)&&(mt=Q/Math.max(Tt.width,Tt.height)),mt<1)if(typeof HTMLImageElement<"u"&&R instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&R instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&R instanceof ImageBitmap||typeof VideoFrame<"u"&&R instanceof VideoFrame){const It=Math.floor(mt*Tt.width),Nt=Math.floor(mt*Tt.height);u===void 0&&(u=_(It,Nt));const ht=T?_(It,Nt):u;return ht.width=It,ht.height=Nt,ht.getContext("2d").drawImage(R,0,0,It,Nt),Ft("WebGLRenderer: Texture has been resized from ("+Tt.width+"x"+Tt.height+") to ("+It+"x"+Nt+")."),ht}else return"data"in R&&Ft("WebGLRenderer: Image in DataTexture is too big ("+Tt.width+"x"+Tt.height+")."),R;return R}function m(R){return R.generateMipmaps}function x(R){r.generateMipmap(R)}function S(R){return R.isWebGLCubeRenderTarget?r.TEXTURE_CUBE_MAP:R.isWebGL3DRenderTarget?r.TEXTURE_3D:R.isWebGLArrayRenderTarget||R.isCompressedArrayTexture?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D}function b(R,T,Q,mt,Tt,It=!1){if(R!==null){if(r[R]!==void 0)return r[R];Ft("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+R+"'")}let Nt;mt&&(Nt=t.get("EXT_texture_norm16"),Nt||Ft("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let ht=T;if(T===r.RED&&(Q===r.FLOAT&&(ht=r.R32F),Q===r.HALF_FLOAT&&(ht=r.R16F),Q===r.UNSIGNED_BYTE&&(ht=r.R8),Q===r.UNSIGNED_SHORT&&Nt&&(ht=Nt.R16_EXT),Q===r.SHORT&&Nt&&(ht=Nt.R16_SNORM_EXT)),T===r.RED_INTEGER&&(Q===r.UNSIGNED_BYTE&&(ht=r.R8UI),Q===r.UNSIGNED_SHORT&&(ht=r.R16UI),Q===r.UNSIGNED_INT&&(ht=r.R32UI),Q===r.BYTE&&(ht=r.R8I),Q===r.SHORT&&(ht=r.R16I),Q===r.INT&&(ht=r.R32I)),T===r.RG&&(Q===r.FLOAT&&(ht=r.RG32F),Q===r.HALF_FLOAT&&(ht=r.RG16F),Q===r.UNSIGNED_BYTE&&(ht=r.RG8),Q===r.UNSIGNED_SHORT&&Nt&&(ht=Nt.RG16_EXT),Q===r.SHORT&&Nt&&(ht=Nt.RG16_SNORM_EXT)),T===r.RG_INTEGER&&(Q===r.UNSIGNED_BYTE&&(ht=r.RG8UI),Q===r.UNSIGNED_SHORT&&(ht=r.RG16UI),Q===r.UNSIGNED_INT&&(ht=r.RG32UI),Q===r.BYTE&&(ht=r.RG8I),Q===r.SHORT&&(ht=r.RG16I),Q===r.INT&&(ht=r.RG32I)),T===r.RGB_INTEGER&&(Q===r.UNSIGNED_BYTE&&(ht=r.RGB8UI),Q===r.UNSIGNED_SHORT&&(ht=r.RGB16UI),Q===r.UNSIGNED_INT&&(ht=r.RGB32UI),Q===r.BYTE&&(ht=r.RGB8I),Q===r.SHORT&&(ht=r.RGB16I),Q===r.INT&&(ht=r.RGB32I)),T===r.RGBA_INTEGER&&(Q===r.UNSIGNED_BYTE&&(ht=r.RGBA8UI),Q===r.UNSIGNED_SHORT&&(ht=r.RGBA16UI),Q===r.UNSIGNED_INT&&(ht=r.RGBA32UI),Q===r.BYTE&&(ht=r.RGBA8I),Q===r.SHORT&&(ht=r.RGBA16I),Q===r.INT&&(ht=r.RGBA32I)),T===r.RGB&&(Q===r.UNSIGNED_SHORT&&Nt&&(ht=Nt.RGB16_EXT),Q===r.SHORT&&Nt&&(ht=Nt.RGB16_SNORM_EXT),Q===r.UNSIGNED_INT_5_9_9_9_REV&&(ht=r.RGB9_E5),Q===r.UNSIGNED_INT_10F_11F_11F_REV&&(ht=r.R11F_G11F_B10F)),T===r.RGBA){const gt=It?zs:Ne.getTransfer(Tt);Q===r.FLOAT&&(ht=r.RGBA32F),Q===r.HALF_FLOAT&&(ht=r.RGBA16F),Q===r.UNSIGNED_BYTE&&(ht=gt===Ge?r.SRGB8_ALPHA8:r.RGBA8),Q===r.UNSIGNED_SHORT&&Nt&&(ht=Nt.RGBA16_EXT),Q===r.SHORT&&Nt&&(ht=Nt.RGBA16_SNORM_EXT),Q===r.UNSIGNED_SHORT_4_4_4_4&&(ht=r.RGBA4),Q===r.UNSIGNED_SHORT_5_5_5_1&&(ht=r.RGB5_A1)}return(ht===r.R16F||ht===r.R32F||ht===r.RG16F||ht===r.RG32F||ht===r.RGBA16F||ht===r.RGBA32F)&&t.get("EXT_color_buffer_float"),ht}function P(R,T){let Q;return R?T===null||T===Kn||T===zr?Q=r.DEPTH24_STENCIL8:T===Pn?Q=r.DEPTH32F_STENCIL8:T===Br&&(Q=r.DEPTH24_STENCIL8,Ft("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):T===null||T===Kn||T===zr?Q=r.DEPTH_COMPONENT24:T===Pn?Q=r.DEPTH_COMPONENT32F:T===Br&&(Q=r.DEPTH_COMPONENT16),Q}function E(R,T){return m(R)===!0||R.isFramebufferTexture&&R.minFilter!==ln&&R.minFilter!==tn?Math.log2(Math.max(T.width,T.height))+1:R.mipmaps!==void 0&&R.mipmaps.length>0?R.mipmaps.length:R.isCompressedTexture&&Array.isArray(R.image)?T.mipmaps.length:1}function O(R){const T=R.target;T.removeEventListener("dispose",O),I(T),T.isVideoTexture&&h.delete(T),T.isHTMLTexture&&d.delete(T)}function y(R){const T=R.target;T.removeEventListener("dispose",y),z(T)}function I(R){const T=n.get(R);if(T.__webglInit===void 0)return;const Q=R.source,mt=f.get(Q);if(mt){const Tt=mt[T.__cacheKey];Tt.usedTimes--,Tt.usedTimes===0&&k(R),Object.keys(mt).length===0&&f.delete(Q)}n.remove(R)}function k(R){const T=n.get(R);r.deleteTexture(T.__webglTexture);const Q=R.source,mt=f.get(Q);delete mt[T.__cacheKey],a.memory.textures--}function z(R){const T=n.get(R);if(R.depthTexture&&(R.depthTexture.dispose(),n.remove(R.depthTexture)),R.isWebGLCubeRenderTarget)for(let mt=0;mt<6;mt++){if(Array.isArray(T.__webglFramebuffer[mt]))for(let Tt=0;Tt=i.maxTextures&&Ft("WebGLTextures: Trying to use "+R+" texture units while this GPU supports only "+i.maxTextures),K+=1,R}function tt(R){const T=[];return T.push(R.wrapS),T.push(R.wrapT),T.push(R.wrapR||0),T.push(R.magFilter),T.push(R.minFilter),T.push(R.anisotropy),T.push(R.internalFormat),T.push(R.format),T.push(R.type),T.push(R.generateMipmaps),T.push(R.premultiplyAlpha),T.push(R.flipY),T.push(R.unpackAlignment),T.push(R.colorSpace),T.join()}function wt(R,T){const Q=n.get(R);if(R.isVideoTexture&&ve(R),R.isRenderTargetTexture===!1&&R.isExternalTexture!==!0&&R.version>0&&Q.__version!==R.version){const mt=R.image;if(mt===null)Ft("WebGLRenderer: Texture marked for update but no image data found.");else if(mt.complete===!1)Ft("WebGLRenderer: Texture marked for update but image is incomplete");else{oe(Q,R,T);return}}else R.isExternalTexture&&(Q.__webglTexture=R.sourceTexture?R.sourceTexture:null);e.bindTexture(r.TEXTURE_2D,Q.__webglTexture,r.TEXTURE0+T)}function Et(R,T){const Q=n.get(R);if(R.isRenderTargetTexture===!1&&R.version>0&&Q.__version!==R.version){oe(Q,R,T);return}else R.isExternalTexture&&(Q.__webglTexture=R.sourceTexture?R.sourceTexture:null);e.bindTexture(r.TEXTURE_2D_ARRAY,Q.__webglTexture,r.TEXTURE0+T)}function kt(R,T){const Q=n.get(R);if(R.isRenderTargetTexture===!1&&R.version>0&&Q.__version!==R.version){oe(Q,R,T);return}e.bindTexture(r.TEXTURE_3D,Q.__webglTexture,r.TEXTURE0+T)}function Zt(R,T){const Q=n.get(R);if(R.isCubeDepthTexture!==!0&&R.version>0&&Q.__version!==R.version){me(Q,R,T);return}e.bindTexture(r.TEXTURE_CUBE_MAP,Q.__webglTexture,r.TEXTURE0+T)}const re={[ws]:r.REPEAT,[Bn]:r.CLAMP_TO_EDGE,[Es]:r.MIRRORED_REPEAT},Ie={[ln]:r.NEAREST,[gc]:r.NEAREST_MIPMAP_NEAREST,[Or]:r.NEAREST_MIPMAP_LINEAR,[tn]:r.LINEAR,[Cs]:r.LINEAR_MIPMAP_NEAREST,[mi]:r.LINEAR_MIPMAP_LINEAR},Be={[Vu]:r.NEVER,[qu]:r.ALWAYS,[Gu]:r.LESS,[po]:r.LEQUAL,[Hu]:r.EQUAL,[mo]:r.GEQUAL,[Wu]:r.GREATER,[Xu]:r.NOTEQUAL};function be(R,T){if(T.type===Pn&&t.has("OES_texture_float_linear")===!1&&(T.magFilter===tn||T.magFilter===Cs||T.magFilter===Or||T.magFilter===mi||T.minFilter===tn||T.minFilter===Cs||T.minFilter===Or||T.minFilter===mi)&&Ft("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),r.texParameteri(R,r.TEXTURE_WRAP_S,re[T.wrapS]),r.texParameteri(R,r.TEXTURE_WRAP_T,re[T.wrapT]),(R===r.TEXTURE_3D||R===r.TEXTURE_2D_ARRAY)&&r.texParameteri(R,r.TEXTURE_WRAP_R,re[T.wrapR]),r.texParameteri(R,r.TEXTURE_MAG_FILTER,Ie[T.magFilter]),r.texParameteri(R,r.TEXTURE_MIN_FILTER,Ie[T.minFilter]),T.compareFunction&&(r.texParameteri(R,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(R,r.TEXTURE_COMPARE_FUNC,Be[T.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(T.magFilter===ln||T.minFilter!==Or&&T.minFilter!==mi||T.type===Pn&&t.has("OES_texture_float_linear")===!1)return;if(T.anisotropy>1||n.get(T).__currentAnisotropy){const Q=t.get("EXT_texture_filter_anisotropic");r.texParameterf(R,Q.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(T.anisotropy,i.getMaxAnisotropy())),n.get(T).__currentAnisotropy=T.anisotropy}}}function xt(R,T){let Q=!1;R.__webglInit===void 0&&(R.__webglInit=!0,T.addEventListener("dispose",O));const mt=T.source;let Tt=f.get(mt);Tt===void 0&&(Tt={},f.set(mt,Tt));const It=tt(T);if(It!==R.__cacheKey){Tt[It]===void 0&&(Tt[It]={texture:r.createTexture(),usedTimes:0},a.memory.textures++,Q=!0),Tt[It].usedTimes++;const Nt=Tt[R.__cacheKey];Nt!==void 0&&(Tt[R.__cacheKey].usedTimes--,Nt.usedTimes===0&&k(T)),R.__cacheKey=It,R.__webglTexture=Tt[It].texture}return Q}function Ht(R,T,Q){return Math.floor(Math.floor(R/Q)/T)}function Pt(R,T,Q,mt){const It=R.updateRanges;if(It.length===0)e.texSubImage2D(r.TEXTURE_2D,0,0,0,T.width,T.height,Q,mt,T.data);else{It.sort((te,Ot)=>te.start-Ot.start);let Nt=0;for(let te=1;te0){Pe&&Ve&&e.texStorage2D(r.TEXTURE_2D,Dt,Ot,Ae[0].width,Ae[0].height);for(let pt=0,Jt=Ae.length;pt0){const Bt=qh(Lt.width,Lt.height,T.format,T.type);for(const At of T.layerUpdates){const ce=Lt.data.subarray(At*Bt/Lt.data.BYTES_PER_ELEMENT,(At+1)*Bt/Lt.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,pt,0,0,At,Lt.width,Lt.height,1,Yt,ce)}T.clearLayerUpdates()}else e.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,pt,0,0,0,Lt.width,Lt.height,gt.depth,Yt,Lt.data)}else e.compressedTexImage3D(r.TEXTURE_2D_ARRAY,pt,Ot,Lt.width,Lt.height,gt.depth,0,Lt.data,0,0);else Ft("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Pe?q&&e.texSubImage3D(r.TEXTURE_2D_ARRAY,pt,0,0,0,Lt.width,Lt.height,gt.depth,Yt,te,Lt.data):e.texImage3D(r.TEXTURE_2D_ARRAY,pt,Ot,Lt.width,Lt.height,gt.depth,0,Yt,te,Lt.data)}else{Pe&&Ve&&e.texStorage2D(r.TEXTURE_2D,Dt,Ot,Ae[0].width,Ae[0].height);for(let pt=0,Jt=Ae.length;pt0){const pt=qh(gt.width,gt.height,T.format,T.type);for(const Jt of T.layerUpdates){const Bt=gt.data.subarray(Jt*pt/gt.data.BYTES_PER_ELEMENT,(Jt+1)*pt/gt.data.BYTES_PER_ELEMENT);e.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,Jt,gt.width,gt.height,1,Yt,te,Bt)}T.clearLayerUpdates()}else e.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,gt.width,gt.height,gt.depth,Yt,te,gt.data)}else e.texImage3D(r.TEXTURE_2D_ARRAY,0,Ot,gt.width,gt.height,gt.depth,0,Yt,te,gt.data);else if(T.isData3DTexture)Pe?(Ve&&e.texStorage3D(r.TEXTURE_3D,Dt,Ot,gt.width,gt.height,gt.depth),q&&e.texSubImage3D(r.TEXTURE_3D,0,0,0,0,gt.width,gt.height,gt.depth,Yt,te,gt.data)):e.texImage3D(r.TEXTURE_3D,0,Ot,gt.width,gt.height,gt.depth,0,Yt,te,gt.data);else if(T.isFramebufferTexture){if(Ve)if(Pe)e.texStorage2D(r.TEXTURE_2D,Dt,Ot,gt.width,gt.height);else{let pt=gt.width,Jt=gt.height;for(let Bt=0;Bt>=1,Jt>>=1}}else if(T.isHTMLTexture){if("texElementImage2D"in r){const pt=r.canvas;if(pt.hasAttribute("layoutsubtree")||pt.setAttribute("layoutsubtree","true"),gt.parentNode!==pt){pt.appendChild(gt),d.add(T),pt.onpaint=Ee=>{const hn=Ee.changedElements;for(const qe of d)hn.includes(qe.image)&&(qe.needsUpdate=!0)},pt.requestPaint();return}const Jt=0,Bt=r.RGBA,At=r.RGBA,ce=r.UNSIGNED_BYTE;r.texElementImage2D(r.TEXTURE_2D,Jt,Bt,At,ce,gt),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)}}else if(Ae.length>0){if(Pe&&Ve){const pt=He(Ae[0]);e.texStorage2D(r.TEXTURE_2D,Dt,Ot,pt.width,pt.height)}for(let pt=0,Jt=Ae.length;pt0&&Jt++;const At=He(Ot[0]);e.texStorage2D(r.TEXTURE_CUBE_MAP,Jt,Ve,At.width,At.height)}for(let At=0;At<6;At++)if(te){q?pt&&e.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+At,0,0,0,Ot[At].width,Ot[At].height,Ae,Pe,Ot[At].data):e.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+At,0,Ve,Ot[At].width,Ot[At].height,0,Ae,Pe,Ot[At].data);for(let ce=0;ce>It),Lt=Math.max(1,T.height>>It);Tt===r.TEXTURE_3D||Tt===r.TEXTURE_2D_ARRAY?e.texImage3D(Tt,It,gt,Ot,Lt,T.depth,0,Nt,ht,null):e.texImage2D(Tt,It,gt,Ot,Lt,0,Nt,ht,null)}e.bindFramebuffer(r.FRAMEBUFFER,R),se(T)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,mt,Tt,te.__webglTexture,0,Te(T)):(Tt===r.TEXTURE_2D||Tt>=r.TEXTURE_CUBE_MAP_POSITIVE_X&&Tt<=r.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&r.framebufferTexture2D(r.FRAMEBUFFER,mt,Tt,te.__webglTexture,It),e.bindFramebuffer(r.FRAMEBUFFER,null)}function ze(R,T,Q){if(r.bindRenderbuffer(r.RENDERBUFFER,R),T.depthBuffer){const mt=T.depthTexture,Tt=mt&&mt.isDepthTexture?mt.type:null,It=P(T.stencilBuffer,Tt),Nt=T.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT;se(T)?o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,Te(T),It,T.width,T.height):Q?r.renderbufferStorageMultisample(r.RENDERBUFFER,Te(T),It,T.width,T.height):r.renderbufferStorage(r.RENDERBUFFER,It,T.width,T.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,Nt,r.RENDERBUFFER,R)}else{const mt=T.textures;for(let Tt=0;Tt{delete T.__boundDepthTexture,delete T.__depthDisposeCallback,mt.removeEventListener("dispose",Tt)};mt.addEventListener("dispose",Tt),T.__depthDisposeCallback=Tt}T.__boundDepthTexture=mt}if(R.depthTexture&&!T.__autoAllocateDepthBuffer)if(Q)for(let mt=0;mt<6;mt++)_e(T.__webglFramebuffer[mt],R,mt);else{const mt=R.texture.mipmaps;mt&&mt.length>0?_e(T.__webglFramebuffer[0],R,0):_e(T.__webglFramebuffer,R,0)}else if(Q){T.__webglDepthbuffer=[];for(let mt=0;mt<6;mt++)if(e.bindFramebuffer(r.FRAMEBUFFER,T.__webglFramebuffer[mt]),T.__webglDepthbuffer[mt]===void 0)T.__webglDepthbuffer[mt]=r.createRenderbuffer(),ze(T.__webglDepthbuffer[mt],R,!1);else{const Tt=R.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,It=T.__webglDepthbuffer[mt];r.bindRenderbuffer(r.RENDERBUFFER,It),r.framebufferRenderbuffer(r.FRAMEBUFFER,Tt,r.RENDERBUFFER,It)}}else{const mt=R.texture.mipmaps;if(mt&&mt.length>0?e.bindFramebuffer(r.FRAMEBUFFER,T.__webglFramebuffer[0]):e.bindFramebuffer(r.FRAMEBUFFER,T.__webglFramebuffer),T.__webglDepthbuffer===void 0)T.__webglDepthbuffer=r.createRenderbuffer(),ze(T.__webglDepthbuffer,R,!1);else{const Tt=R.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,It=T.__webglDepthbuffer;r.bindRenderbuffer(r.RENDERBUFFER,It),r.framebufferRenderbuffer(r.FRAMEBUFFER,Tt,r.RENDERBUFFER,It)}}e.bindFramebuffer(r.FRAMEBUFFER,null)}function Ct(R,T,Q){const mt=n.get(R);T!==void 0&&fe(mt.__webglFramebuffer,R,R.texture,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,0),Q!==void 0&&St(R)}function bt(R){const T=R.texture,Q=n.get(R),mt=n.get(T);R.addEventListener("dispose",y);const Tt=R.textures,It=R.isWebGLCubeRenderTarget===!0,Nt=Tt.length>1;if(Nt||(mt.__webglTexture===void 0&&(mt.__webglTexture=r.createTexture()),mt.__version=T.version,a.memory.textures++),It){Q.__webglFramebuffer=[];for(let ht=0;ht<6;ht++)if(T.mipmaps&&T.mipmaps.length>0){Q.__webglFramebuffer[ht]=[];for(let gt=0;gt0){Q.__webglFramebuffer=[];for(let ht=0;ht0&&se(R)===!1){Q.__webglMultisampledFramebuffer=r.createFramebuffer(),Q.__webglColorRenderbuffer=[],e.bindFramebuffer(r.FRAMEBUFFER,Q.__webglMultisampledFramebuffer);for(let ht=0;ht0)for(let gt=0;gt0)for(let gt=0;gt0){if(se(R)===!1){const T=R.textures,Q=R.width,mt=R.height;let Tt=r.COLOR_BUFFER_BIT;const It=R.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,Nt=n.get(R),ht=T.length>1;if(ht)for(let Yt=0;Yt0?e.bindFramebuffer(r.DRAW_FRAMEBUFFER,Nt.__webglFramebuffer[0]):e.bindFramebuffer(r.DRAW_FRAMEBUFFER,Nt.__webglFramebuffer);for(let Yt=0;Yt0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&T.__useRenderToTexture!==!1}function ve(R){const T=a.render.frame;h.get(R)!==T&&(h.set(R,T),R.update())}function Rt(R,T){const Q=R.colorSpace,mt=R.format,Tt=R.type;return R.isCompressedTexture===!0||R.isVideoTexture===!0||Q!==Bs&&Q!==Ci&&(Ne.getTransfer(Q)===Ge?(mt!==Ln||Tt!==zn)&&Ft("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):ie("WebGLTextures: Unsupported texture color space:",Q)),T}function He(R){return typeof HTMLImageElement<"u"&&R instanceof HTMLImageElement?(c.width=R.naturalWidth||R.width,c.height=R.naturalHeight||R.height):typeof VideoFrame<"u"&&R instanceof VideoFrame?(c.width=R.displayWidth,c.height=R.displayHeight):(c.width=R.width,c.height=R.height),c}this.allocateTextureUnit=st,this.resetTextureUnits=lt,this.getTextureUnits=ut,this.setTextureUnits=$,this.setTexture2D=wt,this.setTexture2DArray=Et,this.setTexture3D=kt,this.setTextureCube=Zt,this.rebindTextures=Ct,this.setupRenderTarget=bt,this.updateRenderTargetMipmap=Xt,this.updateMultisampleRenderTarget=G,this.setupDepthRenderbuffer=St,this.setupFrameBufferTexture=fe,this.useMultisampledRTT=se,this.isReversedDepthBuffer=function(){return e.buffers.depth.getReversed()}}function Fp(r,t){function e(n,i=Ci){let s;const a=Ne.getTransfer(i);if(n===zn)return r.UNSIGNED_BYTE;if(n===Ra)return r.UNSIGNED_SHORT_4_4_4_4;if(n===Ia)return r.UNSIGNED_SHORT_5_5_5_1;if(n===vc)return r.UNSIGNED_INT_5_9_9_9_REV;if(n===yc)return r.UNSIGNED_INT_10F_11F_11F_REV;if(n===_c)return r.BYTE;if(n===xc)return r.SHORT;if(n===Br)return r.UNSIGNED_SHORT;if(n===Ca)return r.INT;if(n===Kn)return r.UNSIGNED_INT;if(n===Pn)return r.FLOAT;if(n===gi)return r.HALF_FLOAT;if(n===Mc)return r.ALPHA;if(n===Sc)return r.RGB;if(n===Ln)return r.RGBA;if(n===_i)return r.DEPTH_COMPONENT;if(n===Vi)return r.DEPTH_STENCIL;if(n===Pa)return r.RED;if(n===Rs)return r.RED_INTEGER;if(n===Gi)return r.RG;if(n===La)return r.RG_INTEGER;if(n===Da)return r.RGBA_INTEGER;if(n===Is||n===Ps||n===Ls||n===Ds)if(a===Ge)if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(n===Is)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Ps)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Ls)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Ds)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=t.get("WEBGL_compressed_texture_s3tc"),s!==null){if(n===Is)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Ps)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Ls)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Ds)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Ua||n===Na||n===Fa||n===Oa)if(s=t.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(n===Ua)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Na)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Fa)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Oa)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Ba||n===za||n===ka||n===Va||n===Ga||n===Us||n===Ha)if(s=t.get("WEBGL_compressed_texture_etc"),s!==null){if(n===Ba||n===za)return a===Ge?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(n===ka)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(n===Va)return s.COMPRESSED_R11_EAC;if(n===Ga)return s.COMPRESSED_SIGNED_R11_EAC;if(n===Us)return s.COMPRESSED_RG11_EAC;if(n===Ha)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===Wa||n===Xa||n===qa||n===Ya||n===Za||n===$a||n===Ja||n===Ka||n===ja||n===Qa||n===to||n===eo||n===no||n===io)if(s=t.get("WEBGL_compressed_texture_astc"),s!==null){if(n===Wa)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Xa)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===qa)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Ya)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===Za)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===$a)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Ja)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Ka)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===ja)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===Qa)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===to)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===eo)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===no)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===io)return a===Ge?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===ro||n===so||n===ao)if(s=t.get("EXT_texture_compression_bptc"),s!==null){if(n===ro)return a===Ge?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===so)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===ao)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===oo||n===lo||n===Ns||n===co)if(s=t.get("EXT_texture_compression_rgtc"),s!==null){if(n===oo)return s.COMPRESSED_RED_RGTC1_EXT;if(n===lo)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Ns)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===co)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===zr?r.UNSIGNED_INT_24_8:r[n]!==void 0?r[n]:null}return{convert:e}}const aS=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,oS=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`;class lS{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const n=new lh(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=n}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,n=new Qn({vertexShader:aS,fragmentShader:oS,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new pn(new cs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class cS extends ri{constructor(t,e){super();const n=this;let i=null,s=1,a=null,o="local-floor",l=1,c=null,h=null,d=null,u=null,f=null,p=null;const _=typeof XRWebGLBinding<"u",g=new lS,m={},x=e.getContextAttributes();let S=null,b=null;const P=[],E=[],O=new Mt;let y=null;const I=new Tn;I.viewport=new We;const k=new Tn;k.viewport=new We;const z=[I,k],K=new Xf;let lt=null,ut=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(xt){let Ht=P[xt];return Ht===void 0&&(Ht=new So,P[xt]=Ht),Ht.getTargetRaySpace()},this.getControllerGrip=function(xt){let Ht=P[xt];return Ht===void 0&&(Ht=new So,P[xt]=Ht),Ht.getGripSpace()},this.getHand=function(xt){let Ht=P[xt];return Ht===void 0&&(Ht=new So,P[xt]=Ht),Ht.getHandSpace()};function $(xt){const Ht=E.indexOf(xt.inputSource);if(Ht===-1)return;const Pt=P[Ht];Pt!==void 0&&(Pt.update(xt.inputSource,xt.frame,c||a),Pt.dispatchEvent({type:xt.type,data:xt.inputSource}))}function st(){i.removeEventListener("select",$),i.removeEventListener("selectstart",$),i.removeEventListener("selectend",$),i.removeEventListener("squeeze",$),i.removeEventListener("squeezestart",$),i.removeEventListener("squeezeend",$),i.removeEventListener("end",st),i.removeEventListener("inputsourceschange",tt);for(let xt=0;xt=0&&(E[oe]=null,P[oe].disconnect(Pt))}for(let Ht=0;Ht=E.length){E.push(Pt),oe=fe;break}else if(E[fe]===null){E[fe]=Pt,oe=fe;break}if(oe===-1)break}const me=P[oe];me&&me.connect(Pt)}}const wt=new D,Et=new D;function kt(xt,Ht,Pt){wt.setFromMatrixPosition(Ht.matrixWorld),Et.setFromMatrixPosition(Pt.matrixWorld);const oe=wt.distanceTo(Et),me=Ht.projectionMatrix.elements,fe=Pt.projectionMatrix.elements,ze=me[14]/(me[10]-1),_e=me[14]/(me[10]+1),St=(me[9]+1)/me[5],Ct=(me[9]-1)/me[5],bt=(me[8]-1)/me[0],Xt=(fe[8]+1)/fe[0],zt=ze*bt,xe=ze*Xt,G=oe/(-bt+Xt),Te=G*-bt;if(Ht.matrixWorld.decompose(xt.position,xt.quaternion,xt.scale),xt.translateX(Te),xt.translateZ(G),xt.matrixWorld.compose(xt.position,xt.quaternion,xt.scale),xt.matrixWorldInverse.copy(xt.matrixWorld).invert(),me[10]===-1)xt.projectionMatrix.copy(Ht.projectionMatrix),xt.projectionMatrixInverse.copy(Ht.projectionMatrixInverse);else{const se=ze+G,ve=_e+G,Rt=zt-Te,He=xe+(oe-Te),R=St*_e/ve*se,T=Ct*_e/ve*se;xt.projectionMatrix.makePerspective(Rt,He,R,T,se,ve),xt.projectionMatrixInverse.copy(xt.projectionMatrix).invert()}}function Zt(xt,Ht){Ht===null?xt.matrixWorld.copy(xt.matrix):xt.matrixWorld.multiplyMatrices(Ht.matrixWorld,xt.matrix),xt.matrixWorldInverse.copy(xt.matrixWorld).invert()}this.updateCamera=function(xt){if(i===null)return;let Ht=xt.near,Pt=xt.far;g.texture!==null&&(g.depthNear>0&&(Ht=g.depthNear),g.depthFar>0&&(Pt=g.depthFar)),K.near=k.near=I.near=Ht,K.far=k.far=I.far=Pt,(lt!==K.near||ut!==K.far)&&(i.updateRenderState({depthNear:K.near,depthFar:K.far}),lt=K.near,ut=K.far),K.layers.mask=xt.layers.mask|6,I.layers.mask=K.layers.mask&-5,k.layers.mask=K.layers.mask&-3;const oe=xt.parent,me=K.cameras;Zt(K,oe);for(let fe=0;fe0&&(g.alphaTest.value=m.alphaTest);const x=t.get(m),S=x.envMap,b=x.envMapRotation;S&&(g.envMap.value=S,g.envMapRotation.value.setFromMatrix4(hS.makeRotationFromEuler(b)).transpose(),S.isCubeTexture&&S.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(Op),g.reflectivity.value=m.reflectivity,g.ior.value=m.ior,g.refractionRatio.value=m.refractionRatio),m.lightMap&&(g.lightMap.value=m.lightMap,g.lightMapIntensity.value=m.lightMapIntensity,e(m.lightMap,g.lightMapTransform)),m.aoMap&&(g.aoMap.value=m.aoMap,g.aoMapIntensity.value=m.aoMapIntensity,e(m.aoMap,g.aoMapTransform))}function a(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,m.map&&(g.map.value=m.map,e(m.map,g.mapTransform))}function o(g,m){g.dashSize.value=m.dashSize,g.totalSize.value=m.dashSize+m.gapSize,g.scale.value=m.scale}function l(g,m,x,S){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.size.value=m.size*x,g.scale.value=S*.5,m.map&&(g.map.value=m.map,e(m.map,g.uvTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,e(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function c(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.rotation.value=m.rotation,m.map&&(g.map.value=m.map,e(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,e(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function h(g,m){g.specular.value.copy(m.specular),g.shininess.value=Math.max(m.shininess,1e-4)}function d(g,m){m.gradientMap&&(g.gradientMap.value=m.gradientMap)}function u(g,m){g.metalness.value=m.metalness,m.metalnessMap&&(g.metalnessMap.value=m.metalnessMap,e(m.metalnessMap,g.metalnessMapTransform)),g.roughness.value=m.roughness,m.roughnessMap&&(g.roughnessMap.value=m.roughnessMap,e(m.roughnessMap,g.roughnessMapTransform)),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)}function f(g,m,x){g.ior.value=m.ior,m.sheen>0&&(g.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),g.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(g.sheenColorMap.value=m.sheenColorMap,e(m.sheenColorMap,g.sheenColorMapTransform)),m.sheenRoughnessMap&&(g.sheenRoughnessMap.value=m.sheenRoughnessMap,e(m.sheenRoughnessMap,g.sheenRoughnessMapTransform))),m.clearcoat>0&&(g.clearcoat.value=m.clearcoat,g.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(g.clearcoatMap.value=m.clearcoatMap,e(m.clearcoatMap,g.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,e(m.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(g.clearcoatNormalMap.value=m.clearcoatNormalMap,e(m.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===yt&&g.clearcoatNormalScale.value.negate())),m.dispersion>0&&(g.dispersion.value=m.dispersion),m.iridescence>0&&(g.iridescence.value=m.iridescence,g.iridescenceIOR.value=m.iridescenceIOR,g.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(g.iridescenceMap.value=m.iridescenceMap,e(m.iridescenceMap,g.iridescenceMapTransform)),m.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=m.iridescenceThicknessMap,e(m.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),m.transmission>0&&(g.transmission.value=m.transmission,g.transmissionSamplerMap.value=x.texture,g.transmissionSamplerSize.value.set(x.width,x.height),m.transmissionMap&&(g.transmissionMap.value=m.transmissionMap,e(m.transmissionMap,g.transmissionMapTransform)),g.thickness.value=m.thickness,m.thicknessMap&&(g.thicknessMap.value=m.thicknessMap,e(m.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=m.attenuationDistance,g.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(g.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(g.anisotropyMap.value=m.anisotropyMap,e(m.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=m.specularIntensity,g.specularColor.value.copy(m.specularColor),m.specularColorMap&&(g.specularColorMap.value=m.specularColorMap,e(m.specularColorMap,g.specularColorMapTransform)),m.specularIntensityMap&&(g.specularIntensityMap.value=m.specularIntensityMap,e(m.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,m){m.matcap&&(g.matcap.value=m.matcap)}function _(g,m){const x=t.get(m).light;g.referencePosition.value.setFromMatrixPosition(x.matrixWorld),g.nearDistance.value=x.shadow.camera.near,g.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:i}}function dS(r,t,e,n){let i={},s={},a=[];const o=r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS);function l(x,S){const b=S.program;n.uniformBlockBinding(x,b)}function c(x,S){let b=i[x.id];b===void 0&&(p(x),b=h(x),i[x.id]=b,x.addEventListener("dispose",g));const P=S.program;n.updateUBOMapping(x,P);const E=t.render.frame;s[x.id]!==E&&(u(x),s[x.id]=E)}function h(x){const S=d();x.__bindingPointIndex=S;const b=r.createBuffer(),P=x.__size,E=x.usage;return r.bindBuffer(r.UNIFORM_BUFFER,b),r.bufferData(r.UNIFORM_BUFFER,P,E),r.bindBuffer(r.UNIFORM_BUFFER,null),r.bindBufferBase(r.UNIFORM_BUFFER,S,b),b}function d(){for(let x=0;x0&&(b+=P-E),x.__size=b,x.__cache={},this}function _(x){const S={boundary:0,storage:0};return typeof x=="number"||typeof x=="boolean"?(S.boundary=4,S.storage=4):x.isVector2?(S.boundary=8,S.storage=8):x.isVector3||x.isColor?(S.boundary=16,S.storage=12):x.isVector4?(S.boundary=16,S.storage=16):x.isMatrix3?(S.boundary=48,S.storage=48):x.isMatrix4?(S.boundary=64,S.storage=64):x.isTexture?Ft("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(x)?(S.boundary=16,S.storage=x.byteLength):Ft("WebGLRenderer: Unsupported uniform value type.",x),S}function g(x){const S=x.target;S.removeEventListener("dispose",g);const b=a.indexOf(S.__bindingPointIndex);a.splice(b,1),r.deleteBuffer(i[S.id]),delete i[S.id],delete s[S.id]}function m(){for(const x in i)r.deleteBuffer(i[x]);a=[],i={},s={}}return{bind:l,update:c,dispose:m}}const fS=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let bi=null;function pS(){return bi===null&&(bi=new ci(fS,16,16,Gi,gi),bi.name="DFG_LUT",bi.minFilter=tn,bi.magFilter=tn,bi.wrapS=Bn,bi.wrapT=Bn,bi.generateMipmaps=!1,bi.needsUpdate=!0),bi}class mS{constructor(t={}){const{canvas:e=Zu(),context:n=null,depth:i=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:u=!1,outputBufferType:f=zn}=t;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=a;const _=f,g=new Set([Da,La,Rs]),m=new Set([zn,Kn,Br,zr,Ra,Ia]),x=new Uint32Array(4),S=new Int32Array(4),b=new D;let P=null,E=null;const O=[],y=[];let I=null;this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ii,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const k=this;let z=!1,K=null;this._outputColorSpace=kn;let lt=0,ut=0,$=null,st=-1,tt=null;const wt=new We,Et=new We;let kt=null;const Zt=new $t(0);let re=0,Ie=e.width,Be=e.height,be=1,xt=null,Ht=null;const Pt=new We(0,0,Ie,Be),oe=new We(0,0,Ie,Be);let me=!1;const fe=new os;let ze=!1,_e=!1;const St=new ge,Ct=new D,bt=new We,Xt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let zt=!1;function xe(){return $===null?be:1}let G=n;function Te(w,j){return e.getContext(w,j)}try{const w={alpha:!0,depth:i,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${vt}`),e.addEventListener("webglcontextlost",At,!1),e.addEventListener("webglcontextrestored",ce,!1),e.addEventListener("webglcontextcreationerror",Ee,!1),G===null){const j="webgl2";if(G=Te(j,w),G===null)throw Te(j)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(w){throw ie("WebGLRenderer: "+w.message),w}let se,ve,Rt,He,R,T,Q,mt,Tt,It,Nt,ht,gt,Yt,te,Ot,Lt,Ae,Pe,Ve,q,Dt,pt;function Jt(){se=new my(G),se.init(),q=new Fp(G,se),ve=new oy(G,se,t,q),Rt=new rS(G,se),ve.reversedDepthBuffer&&u&&Rt.buffers.depth.setReversed(!0),He=new xy(G),R=new WM,T=new sS(G,se,Rt,R,ve,q,He),Q=new py(k),mt=new nx(G),Dt=new sy(G,mt),Tt=new gy(G,mt,He,Dt),It=new yy(G,Tt,mt,Dt,He),Ae=new vy(G,ve,T),te=new ly(R),Nt=new HM(k,Q,se,ve,Dt,te),ht=new uS(k,R),gt=new qM,Yt=new jM(se),Lt=new ry(k,Q,Rt,It,p,l),Ot=new iS(k,It,ve),pt=new dS(G,He,ve,Rt),Pe=new ay(G,se,He),Ve=new _y(G,se,He),He.programs=Nt.programs,k.capabilities=ve,k.extensions=se,k.properties=R,k.renderLists=gt,k.shadowMap=Ot,k.state=Rt,k.info=He}Jt(),_!==zn&&(I=new Sy(_,e.width,e.height,i,s));const Bt=new cS(k,G);this.xr=Bt,this.getContext=function(){return G},this.getContextAttributes=function(){return G.getContextAttributes()},this.forceContextLoss=function(){const w=se.get("WEBGL_lose_context");w&&w.loseContext()},this.forceContextRestore=function(){const w=se.get("WEBGL_lose_context");w&&w.restoreContext()},this.getPixelRatio=function(){return be},this.setPixelRatio=function(w){w!==void 0&&(be=w,this.setSize(Ie,Be,!1))},this.getSize=function(w){return w.set(Ie,Be)},this.setSize=function(w,j,ot=!0){if(Bt.isPresenting){Ft("WebGLRenderer: Can't change size while VR device is presenting.");return}Ie=w,Be=j,e.width=Math.floor(w*be),e.height=Math.floor(j*be),ot===!0&&(e.style.width=w+"px",e.style.height=j+"px"),I!==null&&I.setSize(e.width,e.height),this.setViewport(0,0,w,j)},this.getDrawingBufferSize=function(w){return w.set(Ie*be,Be*be).floor()},this.setDrawingBufferSize=function(w,j,ot){Ie=w,Be=j,be=ot,e.width=Math.floor(w*ot),e.height=Math.floor(j*ot),this.setViewport(0,0,w,j)},this.setEffects=function(w){if(_===zn){ie("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(w){for(let j=0;j{function qt(){if(it.forEach(function(ee){R.get(ee).currentProgram.isReady()&&it.delete(ee)}),it.size===0){rt(w);return}setTimeout(qt,10)}se.get("KHR_parallel_shader_compile")!==null?qt():setTimeout(qt,10)})};let lu=null;function gS(w){lu&&lu(w)}function Bp(){Dr.stop()}function zp(){Dr.start()}const Dr=new lp;Dr.setAnimationLoop(gS),typeof self<"u"&&Dr.setContext(self),this.setAnimationLoop=function(w){lu=w,Bt.setAnimationLoop(w),w===null?Dr.stop():Dr.start()},Bt.addEventListener("sessionstart",Bp),Bt.addEventListener("sessionend",zp),this.render=function(w,j){if(j!==void 0&&j.isCamera!==!0){ie("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(z===!0)return;K!==null&&K.renderStart(w,j);const ot=Bt.enabled===!0&&Bt.isPresenting===!0,it=I!==null&&($===null||ot)&&I.begin(k,$);if(w.matrixWorldAutoUpdate===!0&&w.updateMatrixWorld(),j.parent===null&&j.matrixWorldAutoUpdate===!0&&j.updateMatrixWorld(),Bt.enabled===!0&&Bt.isPresenting===!0&&(I===null||I.isCompositing()===!1)&&(Bt.cameraAutoUpdate===!0&&Bt.updateCamera(j),j=Bt.getCamera()),w.isScene===!0&&w.onBeforeRender(k,w,j,$),E=Yt.get(w,y.length),E.init(j),E.state.textureUnits=T.getTextureUnits(),y.push(E),St.multiplyMatrices(j.projectionMatrix,j.matrixWorldInverse),fe.setFromProjectionMatrix(St,Xn,j.reversedDepth),_e=this.localClippingEnabled,ze=te.init(this.clippingPlanes,_e),P=gt.get(w,O.length),P.init(),O.push(P),Bt.enabled===!0&&Bt.isPresenting===!0){const ee=k.xr.getDepthSensingMesh();ee!==null&&cu(ee,j,-1/0,k.sortObjects)}cu(w,j,0,k.sortObjects),P.finish(),k.sortObjects===!0&&P.sort(xt,Ht),zt=Bt.enabled===!1||Bt.isPresenting===!1||Bt.hasDepthSensing()===!1,zt&&Lt.addToRenderList(P,w),this.info.render.frame++,ze===!0&&te.beginShadows();const rt=E.state.shadowsArray;if(Ot.render(rt,w,j),ze===!0&&te.endShadows(),this.info.autoReset===!0&&this.info.reset(),(it&&I.hasRenderPass())===!1){const ee=P.opaque,Wt=P.transmissive;if(E.setupLights(),j.isArrayCamera){const ae=j.cameras;if(Wt.length>0)for(let he=0,Ce=ae.length;he0&&Vp(ee,Wt,w,j),zt&&Lt.render(w),kp(P,w,j)}$!==null&&ut===0&&(T.updateMultisampleRenderTarget($),T.updateRenderTargetMipmap($)),it&&I.end(k),w.isScene===!0&&w.onAfterRender(k,w,j),Dt.resetDefaultState(),st=-1,tt=null,y.pop(),y.length>0?(E=y[y.length-1],T.setTextureUnits(E.state.textureUnits),ze===!0&&te.setGlobalState(k.clippingPlanes,E.state.camera)):E=null,O.pop(),O.length>0?P=O[O.length-1]:P=null,K!==null&&K.renderEnd()};function cu(w,j,ot,it){if(w.visible===!1)return;if(w.layers.test(j.layers)){if(w.isGroup)ot=w.renderOrder;else if(w.isLOD)w.autoUpdate===!0&&w.update(j);else if(w.isLightProbeGrid)E.pushLightProbeGrid(w);else if(w.isLight)E.pushLight(w),w.castShadow&&E.pushShadow(w);else if(w.isSprite){if(!w.frustumCulled||fe.intersectsSprite(w)){it&&bt.setFromMatrixPosition(w.matrixWorld).applyMatrix4(St);const ee=It.update(w),Wt=w.material;Wt.visible&&P.push(w,ee,Wt,ot,bt.z,null)}}else if((w.isMesh||w.isLine||w.isPoints)&&(!w.frustumCulled||fe.intersectsObject(w))){const ee=It.update(w),Wt=w.material;if(it&&(w.boundingSphere!==void 0?(w.boundingSphere===null&&w.computeBoundingSphere(),bt.copy(w.boundingSphere.center)):(ee.boundingSphere===null&&ee.computeBoundingSphere(),bt.copy(ee.boundingSphere.center)),bt.applyMatrix4(w.matrixWorld).applyMatrix4(St)),Array.isArray(Wt)){const ae=ee.groups;for(let he=0,Ce=ae.length;he0&&Vl(rt,j,ot),qt.length>0&&Vl(qt,j,ot),ee.length>0&&Vl(ee,j,ot),Rt.buffers.depth.setTest(!0),Rt.buffers.depth.setMask(!0),Rt.buffers.color.setMask(!0),Rt.setPolygonOffset(!1)}function Vp(w,j,ot,it){if((ot.isScene===!0?ot.overrideMaterial:null)!==null)return;if(E.state.transmissionRenderTarget[it.id]===void 0){const ue=se.has("EXT_color_buffer_half_float")||se.has("EXT_color_buffer_float");E.state.transmissionRenderTarget[it.id]=new Yn(1,1,{generateMipmaps:!0,type:ue?gi:zn,minFilter:mi,samples:Math.max(4,ve.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ne.workingColorSpace})}const qt=E.state.transmissionRenderTarget[it.id],ee=it.viewport||wt;qt.setSize(ee.z*k.transmissionResolutionScale,ee.w*k.transmissionResolutionScale);const Wt=k.getRenderTarget(),ae=k.getActiveCubeFace(),he=k.getActiveMipmapLevel();k.setRenderTarget(qt),k.getClearColor(Zt),re=k.getClearAlpha(),re<1&&k.setClearColor(16777215,.5),k.clear(),zt&&Lt.render(ot);const Ce=k.toneMapping;k.toneMapping=ii;const De=it.viewport;if(it.viewport!==void 0&&(it.viewport=void 0),E.setupLightsView(it),ze===!0&&te.setGlobalState(k.clippingPlanes,it),Vl(w,ot,it),T.updateMultisampleRenderTarget(qt),T.updateRenderTargetMipmap(qt),se.has("WEBGL_multisampled_render_to_texture")===!1){let ue=!1;for(let Ye=0,un=j.length;Ye0,it.currentProgram=De,it.uniformsList=null,De}function Hp(w){if(w.uniformsList===null){const j=w.currentProgram.getUniforms();w.uniformsList=Bl.seqWithValue(j.seq,w.uniforms)}return w.uniformsList}function Wp(w,j){const ot=R.get(w);ot.outputColorSpace=j.outputColorSpace,ot.batching=j.batching,ot.batchingColor=j.batchingColor,ot.instancing=j.instancing,ot.instancingColor=j.instancingColor,ot.instancingMorph=j.instancingMorph,ot.skinning=j.skinning,ot.morphTargets=j.morphTargets,ot.morphNormals=j.morphNormals,ot.morphColors=j.morphColors,ot.morphTargetsCount=j.morphTargetsCount,ot.numClippingPlanes=j.numClippingPlanes,ot.numIntersection=j.numClipIntersection,ot.vertexAlphas=j.vertexAlphas,ot.vertexTangents=j.vertexTangents,ot.toneMapping=j.toneMapping}function _S(w,j){if(w.length===0)return null;if(w.length===1)return w[0].texture!==null?w[0]:null;b.setFromMatrixPosition(j.matrixWorld);for(let ot=0,it=w.length;ot0),ue=!!ot.morphAttributes.position,Ye=!!ot.morphAttributes.normal,un=!!ot.morphAttributes.color;let an=ii;it.toneMapped&&($===null||$.isXRRenderTarget===!0)&&(an=k.toneMapping);const Ze=ot.morphAttributes.position||ot.morphAttributes.normal||ot.morphAttributes.color,In=Ze!==void 0?Ze.length:0,jt=R.get(it),Jn=E.state.lights;if(ze===!0&&(_e===!0||w!==tt)){const Ke=w===tt&&it.id===st;te.setState(it,w,Ke)}let ke=!1;it.version===jt.__version?(jt.needsLights&&jt.lightsStateVersion!==Jn.state.version||jt.outputColorSpace!==Wt||rt.isBatchedMesh&&jt.batching===!1||!rt.isBatchedMesh&&jt.batching===!0||rt.isBatchedMesh&&jt.batchingColor===!0&&rt.colorTexture===null||rt.isBatchedMesh&&jt.batchingColor===!1&&rt.colorTexture!==null||rt.isInstancedMesh&&jt.instancing===!1||!rt.isInstancedMesh&&jt.instancing===!0||rt.isSkinnedMesh&&jt.skinning===!1||!rt.isSkinnedMesh&&jt.skinning===!0||rt.isInstancedMesh&&jt.instancingColor===!0&&rt.instanceColor===null||rt.isInstancedMesh&&jt.instancingColor===!1&&rt.instanceColor!==null||rt.isInstancedMesh&&jt.instancingMorph===!0&&rt.morphTexture===null||rt.isInstancedMesh&&jt.instancingMorph===!1&&rt.morphTexture!==null||jt.envMap!==he||it.fog===!0&&jt.fog!==qt||jt.numClippingPlanes!==void 0&&(jt.numClippingPlanes!==te.numPlanes||jt.numIntersection!==te.numIntersection)||jt.vertexAlphas!==Ce||jt.vertexTangents!==De||jt.morphTargets!==ue||jt.morphNormals!==Ye||jt.morphColors!==un||jt.toneMapping!==an||jt.morphTargetsCount!==In||!!jt.lightProbeGrid!=E.state.lightProbeGridArray.length>0)&&(ke=!0):(ke=!0,jt.__version=it.version);let ei=jt.currentProgram;ke===!0&&(ei=Gl(it,j,rt),K&&it.isNodeMaterial&&K.onUpdateProgram(it,ei,jt));let Ai=!1,rr=!1,vs=!1;const $e=ei.getUniforms(),dn=jt.uniforms;if(Rt.useProgram(ei.program)&&(Ai=!0,rr=!0,vs=!0),it.id!==st&&(st=it.id,rr=!0),jt.needsLights){const Ke=_S(E.state.lightProbeGridArray,rt);jt.lightProbeGrid!==Ke&&(jt.lightProbeGrid=Ke,rr=!0)}if(Ai||tt!==w){Rt.buffers.depth.getReversed()&&w.reversedDepth!==!0&&(w._reversedDepth=!0,w.updateProjectionMatrix()),$e.setValue(G,"projectionMatrix",w.projectionMatrix),$e.setValue(G,"viewMatrix",w.matrixWorldInverse);const ar=$e.map.cameraPosition;ar!==void 0&&ar.setValue(G,Ct.setFromMatrixPosition(w.matrixWorld)),ve.logarithmicDepthBuffer&&$e.setValue(G,"logDepthBufFC",2/(Math.log(w.far+1)/Math.LN2)),(it.isMeshPhongMaterial||it.isMeshToonMaterial||it.isMeshLambertMaterial||it.isMeshBasicMaterial||it.isMeshStandardMaterial||it.isShaderMaterial)&&$e.setValue(G,"isOrthographic",w.isOrthographicCamera===!0),tt!==w&&(tt=w,rr=!0,vs=!0)}if(jt.needsLights&&(Jn.state.directionalShadowMap.length>0&&$e.setValue(G,"directionalShadowMap",Jn.state.directionalShadowMap,T),Jn.state.spotShadowMap.length>0&&$e.setValue(G,"spotShadowMap",Jn.state.spotShadowMap,T),Jn.state.pointShadowMap.length>0&&$e.setValue(G,"pointShadowMap",Jn.state.pointShadowMap,T)),rt.isSkinnedMesh){$e.setOptional(G,rt,"bindMatrix"),$e.setOptional(G,rt,"bindMatrixInverse");const Ke=rt.skeleton;Ke&&(Ke.boneTexture===null&&Ke.computeBoneTexture(),$e.setValue(G,"boneTexture",Ke.boneTexture,T))}rt.isBatchedMesh&&($e.setOptional(G,rt,"batchingTexture"),$e.setValue(G,"batchingTexture",rt._matricesTexture,T),$e.setOptional(G,rt,"batchingIdTexture"),$e.setValue(G,"batchingIdTexture",rt._indirectTexture,T),$e.setOptional(G,rt,"batchingColorTexture"),rt._colorsTexture!==null&&$e.setValue(G,"batchingColorTexture",rt._colorsTexture,T));const sr=ot.morphAttributes;if((sr.position!==void 0||sr.normal!==void 0||sr.color!==void 0)&&Ae.update(rt,ot,ei),(rr||jt.receiveShadow!==rt.receiveShadow)&&(jt.receiveShadow=rt.receiveShadow,$e.setValue(G,"receiveShadow",rt.receiveShadow)),(it.isMeshStandardMaterial||it.isMeshLambertMaterial||it.isMeshPhongMaterial)&&it.envMap===null&&j.environment!==null&&(dn.envMapIntensity.value=j.environmentIntensity),dn.dfgLUT!==void 0&&(dn.dfgLUT.value=pS()),rr){if($e.setValue(G,"toneMappingExposure",k.toneMappingExposure),jt.needsLights&&vS(dn,vs),qt&&it.fog===!0&&ht.refreshFogUniforms(dn,qt),ht.refreshMaterialUniforms(dn,it,be,Be,E.state.transmissionRenderTarget[w.id]),jt.needsLights&&jt.lightProbeGrid){const Ke=jt.lightProbeGrid;dn.probesSH.value=Ke.texture,dn.probesMin.value.copy(Ke.boundingBox.min),dn.probesMax.value.copy(Ke.boundingBox.max),dn.probesResolution.value.copy(Ke.resolution)}Bl.upload(G,Hp(jt),dn,T)}if(it.isShaderMaterial&&it.uniformsNeedUpdate===!0&&(Bl.upload(G,Hp(jt),dn,T),it.uniformsNeedUpdate=!1),it.isSpriteMaterial&&$e.setValue(G,"center",rt.center),$e.setValue(G,"modelViewMatrix",rt.modelViewMatrix),$e.setValue(G,"normalMatrix",rt.normalMatrix),$e.setValue(G,"modelMatrix",rt.matrixWorld),it.uniformsGroups!==void 0){const Ke=it.uniformsGroups;for(let ar=0,ys=Ke.length;ar0&&T.useMultisampledRTT(w)===!1?it=R.get(w).__webglMultisampledFramebuffer:Array.isArray(he)?it=he[ot]:it=he,wt.copy(w.viewport),Et.copy(w.scissor),kt=w.scissorTest}else wt.copy(Pt).multiplyScalar(be).floor(),Et.copy(oe).multiplyScalar(be).floor(),kt=me;if(ot!==0&&(it=MS),Rt.bindFramebuffer(G.FRAMEBUFFER,it)&&Rt.drawBuffers(w,it),Rt.viewport(wt),Rt.scissor(Et),Rt.setScissorTest(kt),rt){const Wt=R.get(w.texture);G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_CUBE_MAP_POSITIVE_X+j,Wt.__webglTexture,ot)}else if(qt){const Wt=j;for(let ae=0;ae1&&G.readBuffer(G.COLOR_ATTACHMENT0+Wt),!ve.textureFormatReadable(Ce)){ie("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!ve.textureTypeReadable(De)){ie("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}j>=0&&j<=w.width-it&&ot>=0&&ot<=w.height-rt&&G.readPixels(j,ot,it,rt,q.convert(Ce),q.convert(De),qt)}finally{const he=$!==null?R.get($).__webglFramebuffer:null;Rt.bindFramebuffer(G.FRAMEBUFFER,he)}}},this.readRenderTargetPixelsAsync=async function(w,j,ot,it,rt,qt,ee,Wt=0){if(!(w&&w.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let ae=R.get(w).__webglFramebuffer;if(w.isWebGLCubeRenderTarget&&ee!==void 0&&(ae=ae[ee]),ae)if(j>=0&&j<=w.width-it&&ot>=0&&ot<=w.height-rt){Rt.bindFramebuffer(G.FRAMEBUFFER,ae);const he=w.textures[Wt],Ce=he.format,De=he.type;if(w.textures.length>1&&G.readBuffer(G.COLOR_ATTACHMENT0+Wt),!ve.textureFormatReadable(Ce))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!ve.textureTypeReadable(De))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const ue=G.createBuffer();G.bindBuffer(G.PIXEL_PACK_BUFFER,ue),G.bufferData(G.PIXEL_PACK_BUFFER,qt.byteLength,G.STREAM_READ),G.readPixels(j,ot,it,rt,q.convert(Ce),q.convert(De),0);const Ye=$!==null?R.get($).__webglFramebuffer:null;Rt.bindFramebuffer(G.FRAMEBUFFER,Ye);const un=G.fenceSync(G.SYNC_GPU_COMMANDS_COMPLETE,0);return G.flush(),await Qm(G,un,4),G.bindBuffer(G.PIXEL_PACK_BUFFER,ue),G.getBufferSubData(G.PIXEL_PACK_BUFFER,0,qt),G.deleteBuffer(ue),G.deleteSync(un),qt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(w,j=null,ot=0){const it=Math.pow(2,-ot),rt=Math.floor(w.image.width*it),qt=Math.floor(w.image.height*it),ee=j!==null?j.x:0,Wt=j!==null?j.y:0;T.setTexture2D(w,0),G.copyTexSubImage2D(G.TEXTURE_2D,ot,0,0,ee,Wt,rt,qt),Rt.unbindTexture()};const SS=G.createFramebuffer(),bS=G.createFramebuffer();this.copyTextureToTexture=function(w,j,ot=null,it=null,rt=0,qt=0){let ee,Wt,ae,he,Ce,De,ue,Ye,un;const an=w.isCompressedTexture?w.mipmaps[qt]:w.image;if(ot!==null)ee=ot.max.x-ot.min.x,Wt=ot.max.y-ot.min.y,ae=ot.isBox3?ot.max.z-ot.min.z:1,he=ot.min.x,Ce=ot.min.y,De=ot.isBox3?ot.min.z:0;else{const dn=Math.pow(2,-rt);ee=Math.floor(an.width*dn),Wt=Math.floor(an.height*dn),w.isDataArrayTexture?ae=an.depth:w.isData3DTexture?ae=Math.floor(an.depth*dn):ae=1,he=0,Ce=0,De=0}it!==null?(ue=it.x,Ye=it.y,un=it.z):(ue=0,Ye=0,un=0);const Ze=q.convert(j.format),In=q.convert(j.type);let jt;j.isData3DTexture?(T.setTexture3D(j,0),jt=G.TEXTURE_3D):j.isDataArrayTexture||j.isCompressedArrayTexture?(T.setTexture2DArray(j,0),jt=G.TEXTURE_2D_ARRAY):(T.setTexture2D(j,0),jt=G.TEXTURE_2D),Rt.activeTexture(G.TEXTURE0),Rt.pixelStorei(G.UNPACK_FLIP_Y_WEBGL,j.flipY),Rt.pixelStorei(G.UNPACK_PREMULTIPLY_ALPHA_WEBGL,j.premultiplyAlpha),Rt.pixelStorei(G.UNPACK_ALIGNMENT,j.unpackAlignment);const Jn=Rt.getParameter(G.UNPACK_ROW_LENGTH),ke=Rt.getParameter(G.UNPACK_IMAGE_HEIGHT),ei=Rt.getParameter(G.UNPACK_SKIP_PIXELS),Ai=Rt.getParameter(G.UNPACK_SKIP_ROWS),rr=Rt.getParameter(G.UNPACK_SKIP_IMAGES);Rt.pixelStorei(G.UNPACK_ROW_LENGTH,an.width),Rt.pixelStorei(G.UNPACK_IMAGE_HEIGHT,an.height),Rt.pixelStorei(G.UNPACK_SKIP_PIXELS,he),Rt.pixelStorei(G.UNPACK_SKIP_ROWS,Ce),Rt.pixelStorei(G.UNPACK_SKIP_IMAGES,De);const vs=w.isDataArrayTexture||w.isData3DTexture,$e=j.isDataArrayTexture||j.isData3DTexture;if(w.isDepthTexture){const dn=R.get(w),sr=R.get(j),Ke=R.get(dn.__renderTarget),ar=R.get(sr.__renderTarget);Rt.bindFramebuffer(G.READ_FRAMEBUFFER,Ke.__webglFramebuffer),Rt.bindFramebuffer(G.DRAW_FRAMEBUFFER,ar.__webglFramebuffer);for(let ys=0;ys=0&&J.y*X.y>=0&&J.z*X.z>=0}var Z=function(J,X){X==null&&(X=1),X=Math.max(.01,Math.min(1,X)),this.centerPoint=J,this.faces=J.getOrderedFaces(),this.boundary=[],this.neighborIds=[],this.neighbors=[];for(var H={},dt=0;dt0&&(nt=new at(Ut[L-1],Ut[L],A[L]),Gt.push(nt))}}_t=Gt;var ct={};for(var ft in B){var ne=B[ft].project(J);ct[ne]=ne}B=ct,this.tiles=[],this.tileLookup={};for(var ft in B){var le=new vt(B[ft],H);this.tiles.push(le),this.tileLookup[le.toString()]=le}for(var de in this.tiles){var ye=this;this.tiles[de].neighbors=this.tiles[de].neighborIds.map(function(Le){return ye.tileLookup[Le]})}};return Z.prototype.toJson=function(){return JSON.stringify({radius:this.radius,tiles:this.tiles.map(function(J){return J.toJson()})})},Z.prototype.toObj=function(){for(var J=[],X=[],H=`# vertices +`,dt={},M=0;M=0;B--)this.observers[B](this);return this},ignore:function(M){if(this.observers)for(var B=this.observers,W=B.length;W--;)B[W]===M&&B.splice(W,1);return this},set:function(M,B,W){if(typeof M!="number"&&(W=B,B=M.y,M=M.x),this.x===M&&this.y===B)return this;if(this.x=H.clean(M),this.y=H.clean(B),W!==!1)return this.change()},zero:function(){return this.set(0,0)},clone:function(){return new this.constructor(this.x,this.y)},negate:function(M){return M?new this.constructor(-this.x,-this.y):this.set(-this.x,-this.y)},add:function(M,B){return B?new this.constructor(this.x+M.x,this.y+M.y):(this.x+=M.x,this.y+=M.y,this.change())},subtract:function(M,B){return B?new this.constructor(this.x-M.x,this.y-M.y):(this.x-=M.x,this.y-=M.y,this.change())},multiply:function(M,B){var W,_t;return typeof M!="number"?(W=M.x,_t=M.y):W=_t=M,B?new this.constructor(this.x*W,this.y*_t):this.set(this.x*W,this.y*_t)},rotate:function(M,B,W){var _t=this.x,yt=this.y,Gt=Math.cos(M),et=Math.sin(M),Ut,A;return B=B?-1:1,Ut=Gt*_t-B*et*yt,A=B*et*_t+Gt*yt,W?new this.constructor(Ut,A):this.set(Ut,A)},length:function(){var M=this.x,B=this.y;return Math.sqrt(M*M+B*B)},lengthSquared:function(){var M=this.x,B=this.y;return M*M+B*B},distance:function(M){var B=this.x-M.x,W=this.y-M.y;return Math.sqrt(B*B+W*W)},normalize:function(M){var B=this.length(),W=Byt?W:yt,Ut=_t>Gt?_t:Gt;return B?new this.constructor(et,Ut):this.set(et,Ut)},clamp:function(M,B,W){var _t=this.min(B,!0).max(M);return W?_t:this.set(_t.x,_t.y)},lerp:function(M,B){return this.add(M.subtract(this,!0).multiply(B),!0)},skew:function(){return new this.constructor(-this.y,this.x)},dot:function(M){return H.clean(this.x*M.x+M.y*this.y)},perpDot:function(M){return H.clean(this.x*M.y-this.y*M.x)},angleTo:function(M){return Math.atan2(this.perpDot(M),this.dot(M))},divide:function(M,B){var W,_t;if(typeof M!="number"?(W=M.x,_t=M.y):W=_t=M,W===0||_t===0)throw new Error("division by zero");if(isNaN(W)||isNaN(_t))throw new Error("NaN detected");return B?new this.constructor(this.x/W,this.y/_t):this.set(this.x/W,this.y/_t)},isPointOnLine:function(M,B){return(M.y-this.y)*(M.x-B.x)===(M.y-B.y)*(M.x-this.x)},toArray:function(){return[this.x,this.y]},fromArray:function(M){return this.set(M[0],M[1])},toJSON:function(){return{x:this.x,y:this.y}},toString:function(){return"("+this.x+", "+this.y+")"},constructor:H},H.fromArray=function(M,B){return new(B||H)(M[0],M[1])},H.precision=Z||8;var dt=Math.pow(10,H.precision);return H.clean=Y||function(M){if(isNaN(M))throw new Error("NaN detected");if(!isFinite(M))throw new Error("Infinity detected");return Math.round(M)===M?M:Math.round(M*dt)/dt},H.inject=at,Y||(H.fast=at(function(M){return M}),vt.exports=H),H})()})($l)),$l.exports}var Jl,vu;function yu(){if(vu)return Jl;vu=1;var vt={fnName:function(Y){var Z=Y.toString();return Z=Z.substr(9),Z=Z.substr(0,Z.indexOf("(")),Z},thrower:function(Y,Z,J){var X=Y;throw J&&(X+="_"+J),Z&&(X+=" - "),Z&&J&&(X+=J+": "),Z&&(X+=Z),new Error(X)},getIdsOfObjects:function(Y){var Z=[];for(var J in Y)Z.push(Y[J].id_);return Z},compare:function(Y,Z){return Y-Z},arrayDiffs:function(Y,Z){var J=0,X=0,H=[],dt=[];for(Y.sort(this.compare),Z.sort(this.compare);J0?!1:(this.children_.push(new vt(this.leftTop_,this.rad_,Y++,this),new vt(this.topMid_,this.rad_,Y++,this),new vt(this.leftMid_,this.rad_,Y++,this),new vt(this.center_,this.rad_,Y++,this)),Y)},looseChildren:function(){this.children_=[]},addObjects:function(Y){var Z;for(Z in Y)this.addObject(Z,Y[Z])},addObject:function(Y,Z){this.objectCount_++,this.objects_[Y]=Z},removeObjects:function(Y,Z){var J;Y||(Y=[]);for(J in this.objects_)Y.push({obj:this.objects_[J],quadrant:this}),delete this.objects_[J];return this.objectCount_=0,(!Z||Z===1)&&this.parent_&&this.parent_.removeObjects(Y,1),(!Z||Z===-1)&&this.children_.forEach(function(X){X.removeObjects(Y,-1)}),Y},removeObject:function(Y){var Z=this.objects_[Y];return this.objectCount_--,delete this.objects_[Y],Z},getObjectCountForLimit:function(){var Y,Z,J={};for(Z in this.objects_)J[Z]=!0;for(Y=0;Ythis.rad_.x+Z||J.y>this.rad_.y+Z?!1:J.x<=this.rad_.x||J.y<=this.rad_.y?!0:(cornerDistSq=Math.pow(J.x-this.rad_.x,2)+Math.pow(J.y-this.rad_.y,2),cornerDistSq<=Math.pow(Z,2))},hasChildren:function(){return this.getChildCount()!==0},getChildCount:function(Y){var Z=this.children_.length;return Y&&this.children_.forEach(function(J){Z+=J.getChildCount(Y)}),Z},getChildren:function(Y,Z){return Z||(Z=[]),Z.push.apply(Z,this.children_),Y&&this.children_.forEach(function(J){J.getChildren(Y,Z)}),Z},getObjectsUp:function(Y){var Z;if(!Y.quadrants[this.id_]){Y.quadrants[this.id_]=!0;for(Z in this.objects_)Y.objects[Z]=this.objects_[Z];this.parent_&&this.parent_.getObjectsUp(Y)}},getObjectsDown:function(Y){var Z;if(!Y.quadrants[this.id_]){Y.quadrants[this.id_]=!0;for(Z in this.objects_)Y.objects[Z]=this.objects_[Z];for(Z=0;ZC[yt.p].distance(L[yt.p])},removeQuadrantParentQuadrants:function(C,L){C.parent_&&L[C.parent_.id_]&&(delete L[C.parent_.id_],et.removeQuadrantParentQuadrants(C.parent_,L))},getSubtreeTopQuadrant:function F(C,L){return!C.parent_||!L[C.parent_.id_]?C:F(C.parent_,L)},removeQuadrantChildtree:function(C,L){var nt,ct=C.getChildren();for(nt=0;ntW.quadrantObjectsLimit_)){for(C.refactoring_=!0,L=0;L=0;B--)this.observers[B](this,M);return this},ignore:function(M){if(this.observers)if(!M)this.observers=[];else for(var B=this.observers,W=B.length;W--;)B[W]===M&&B.splice(W,1);return this},set:function(M,B,W){if(typeof M!="number"&&(W=B,B=M.y,M=M.x),this.x===M&&this.y===B)return this;var _t=null;if(W!==!1&&this.observers&&this.observers.length&&(_t=this.clone()),this.x=H.clean(M),this.y=H.clean(B),W!==!1)return this.change(_t)},zero:function(){return this.set(0,0)},clone:function(){return new this.constructor(this.x,this.y)},negate:function(M){return M?new this.constructor(-this.x,-this.y):this.set(-this.x,-this.y)},add:function(M,B,W){return typeof M!="number"&&(W=B,X(M)?(B=M[1],M=M[0]):(B=M.y,M=M.x)),M+=this.x,B+=this.y,W?new this.constructor(M,B):this.set(M,B)},subtract:function(M,B,W){return typeof M!="number"&&(W=B,X(M)?(B=M[1],M=M[0]):(B=M.y,M=M.x)),M=this.x-M,B=this.y-B,W?new this.constructor(M,B):this.set(M,B)},multiply:function(M,B,W){return typeof M!="number"?(W=B,X(M)?(B=M[1],M=M[0]):(B=M.y,M=M.x)):typeof B!="number"&&(W=B,B=M),M*=this.x,B*=this.y,W?new this.constructor(M,B):this.set(M,B)},rotate:function(M,B,W){var _t=this.x,yt=this.y,Gt=Math.cos(M),et=Math.sin(M),Ut,A;return B=B?-1:1,Ut=Gt*_t-B*et*yt,A=B*et*_t+Gt*yt,W?new this.constructor(Ut,A):this.set(Ut,A)},length:function(){var M=this.x,B=this.y;return Math.sqrt(M*M+B*B)},lengthSquared:function(){var M=this.x,B=this.y;return M*M+B*B},distance:function(M){var B=this.x-M.x,W=this.y-M.y;return Math.sqrt(B*B+W*W)},normalize:function(M){var B=this.length(),W=Byt?W:yt,Ut=_t>Gt?_t:Gt;return B?new this.constructor(et,Ut):this.set(et,Ut)},clamp:function(M,B,W){var _t=this.min(B,!0).max(M);return W?_t:this.set(_t.x,_t.y)},lerp:function(M,B,W){return this.add(M.subtract(this,!0).multiply(B),W)},skew:function(M){return M?new this.constructor(-this.y,this.x):this.set(-this.y,this.x)},dot:function(M){return H.clean(this.x*M.x+M.y*this.y)},perpDot:function(M){return H.clean(this.x*M.y-this.y*M.x)},angleTo:function(M){return Math.atan2(this.perpDot(M),this.dot(M))},divide:function(M,B,W){if(typeof M!="number"?(W=B,X(M)?(B=M[1],M=M[0]):(B=M.y,M=M.x)):typeof B!="number"&&(W=B,B=M),M===0||B===0)throw new Error("division by zero");if(isNaN(M)||isNaN(B))throw new Error("NaN detected");return W?new this.constructor(this.x/M,this.y/B):this.set(this.x/M,this.y/B)},isPointOnLine:function(M,B){return(M.y-this.y)*(M.x-B.x)===(M.y-B.y)*(M.x-this.x)},toArray:function(){return[this.x,this.y]},fromArray:function(M){return this.set(M[0],M[1])},toJSON:function(){return{x:this.x,y:this.y}},toString:function(){return"("+this.x+", "+this.y+")"},constructor:H},H.fromArray=function(M,B){return new(B||H)(M[0],M[1])},H.precision=Z||8;var dt=Math.pow(10,H.precision);return H.clean=Y||function(M){if(isNaN(M))throw new Error("NaN detected");if(!isFinite(M))throw new Error("Infinity detected");return Math.round(M)===M?M:Math.round(M*dt)/dt},H.inject=at,Y||(H.fast=at(function(M){return M}),vt.exports=H),H})()})(tc)),tc.exports}var ec,Au;function Ms(){if(Au)return ec;Au=1;var vt={renderToCanvas:function(at,Y,Z){var J=document.createElement("canvas");return J.width=at,J.height=Y,Z(J.getContext("2d")),J},mapPoint:function(at,Y,Z){Z||(Z=500);var J=(90-at)*Math.PI/180,X=(180-Y)*Math.PI/180,H=Z*Math.sin(J)*Math.cos(X),dt=Z*Math.cos(J),M=Z*Math.sin(J)*Math.sin(X);return{x:H,y:dt,z:M}},hexToRgb:function(at){var Y=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;at=at.replace(Y,function(J,X,H,dt){return X+X+H+H+dt+dt});var Z=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(at);return Z?{r:parseInt(Z[1],16),g:parseInt(Z[2],16),b:parseInt(Z[3],16)}:null},createLabel:function(at,Y,Z,J,X){var H=document.createElement("canvas"),dt=H.getContext("2d");dt.font=Y+"pt "+J;var M=dt.measureText(at).width;return H.width=M,H.height=Y+10,H.width%2&&H.width++,H.height%2&&H.height++,X&&(H.height+=30),dt.font=Y+"pt "+J,dt.textAlign="center",dt.textBaseline="middle",dt.strokeStyle="black",dt.miterLimit=2,dt.lineJoin="circle",dt.lineWidth=6,dt.strokeText(at,H.width/2,H.height/2),dt.lineWidth=2,dt.fillStyle=Z,dt.fillText(at,H.width/2,H.height/2),X&&(dt.strokeStyle=X,dt.lineWidth=4,dt.beginPath(),dt.moveTo(0,H.height-10),dt.lineTo(H.width-1,H.height-10),dt.stroke()),H}};return ec=vt,ec}var nc,wu;function tm(){if(wu)return nc;wu=1;var vt=Ur(),at=Hl(),Y=Ms(),Z=function(X){var H=20,dt=20;return Y.renderToCanvas(H,dt,function(M){M.fillStyle=X,M.beginPath(),M.arc(H/2,dt/2,H/4,0,2*Math.PI),M.fill()})},J=function(X,H,dt,M,B,W,_t){var yt={lineColor:"#8FD8D8",lineWidth:1,topColor:"#8FD8D8",smokeColor:"#FFF",labelColor:"#FFF",font:"Inconsolata",showLabel:dt.length>0,showTop:dt.length>0,showSmoke:dt.length>0},Gt,et,Ut,A,F,C,L;if(this.lat=X,this.lon=H,this.text=dt,this.altitude=M,this.scene=B,this.smokeProvider=W,this.dateCreated=Date.now(),_t)for(var nt in yt)_t[nt]!=null&&(yt[nt]=_t[nt]);this.opts=yt,this.topVisible=yt.showTop,this.smokeVisible=yt.showSmoke,this.labelVisible=yt.showLabel,Gt=new vt.LineBasicMaterial({color:yt.lineColor,linewidth:yt.lineWidth}),L=Y.mapPoint(X,H),this.lineGeometry=new vt.BufferGeometry,this._linePosAttr=new vt.BufferAttribute(new Float32Array([L.x,L.y,L.z,L.x,L.y,L.z]),3),this.lineGeometry.setAttribute("position",this._linePosAttr),this.line=new vt.Line(this.lineGeometry,Gt),et=Y.createLabel(dt,18,yt.labelColor,yt.font),Ut=new vt.Texture(et),Ut.needsUpdate=!0,A=new vt.SpriteMaterial({map:Ut,opacity:0,depthTest:!0,fog:!0}),this.labelSprite=new vt.Sprite(A),this.labelSprite.position.set(L.x*M*1.1,L.y*M+(L.y<0?-15:30),L.z*M*1.1),this.labelSprite.scale.set(et.width,et.height),F=new vt.Texture(Z(yt.topColor)),F.needsUpdate=!0,C=new vt.SpriteMaterial({map:F,depthTest:!0,fog:!0,opacity:0}),this.topSprite=new vt.Sprite(C),this.topSprite.scale.set(20,20),this.topSprite.position.set(L.x*M,L.y*M,L.z*M),this.smokeVisible&&(this.smokeId=W.setFire(X,H,M));var ct=this;(yt.showTop||yt.showLabel)&&new at.Tween({opacity:0},!0).to({opacity:1},500).onUpdate(function(ft){ct.topVisible?C.opacity=ft.opacity:C.opacity=0,ct.labelVisible?A.opacity=ft.opacity:A.opacity=0}).delay(1e3).start(),new at.Tween(L,!0).to({x:L.x*M,y:L.y*M,z:L.z*M},1500).easing(at.Easing.Elastic.Out).onUpdate(function(ft){ct._linePosAttr.setXYZ(1,ft.x,ft.y,ft.z),ct._linePosAttr.needsUpdate=!0}).start(),this.scene.add(this.labelSprite),this.scene.add(this.line),this.scene.add(this.topSprite)};return J.prototype.toString=function(){return""+this.lat+"_"+this.lon},J.prototype.changeAltitude=function(X){var H=Y.mapPoint(this.lat,this.lon),dt=this;new at.Tween({altitude:this.altitude},!0).to({altitude:X},1500).easing(at.Easing.Elastic.Out).onUpdate(function(M){dt.smokeVisible&&dt.smokeProvider.changeAltitude(M.altitude,dt.smokeId),dt.topVisible&&dt.topSprite.position.set(H.x*M.altitude,H.y*M.altitude,H.z*M.altitude),dt.labelVisible&&dt.labelSprite.position.set(H.x*M.altitude*1.1,H.y*M.altitude+(H.y<0?-15:30),H.z*M.altitude*1.1),dt._linePosAttr.setXYZ(1,H.x*M.altitude,H.y*M.altitude,H.z*M.altitude),dt._linePosAttr.needsUpdate=!0}).onComplete(function(){dt.altitude=X}).start()},J.prototype.hideTop=function(){this.topVisible&&(this.topSprite.material.opacity=0,this.topVisible=!1)},J.prototype.showTop=function(){this.topVisible||(this.topSprite.material.opacity=1,this.topVisible=!0)},J.prototype.hideLabel=function(){this.labelVisible&&(this.labelSprite.material.opacity=0,this.labelVisible=!1)},J.prototype.showLabel=function(){this.labelVisible||(this.labelSprite.material.opacity=1,this.labelVisible=!0)},J.prototype.hideSmoke=function(){this.smokeVisible&&(this.smokeProvider.extinguish(this.smokeId),this.smokeVisible=!1)},J.prototype.showSmoke=function(){this.smokeVisible||(this.smokeId=this.smokeProvider.setFire(this.lat,this.lon,this.altitude),this.smokeVisible=!0)},J.prototype.age=function(){return Date.now()-this.dateCreated},J.prototype.remove=function(){this.scene.remove(this.labelSprite),this.scene.remove(this.line),this.scene.remove(this.topSprite),this.smokeVisible&&this.smokeProvider.extinguish(this.smokeId)},nc=J,nc}var ic,Eu;function em(){if(Eu)return ic;Eu=1;var vt=Ur(),at=Hl(),Y=Ms(),Z=function(X){var H=30,dt=30,M,B;return M=Y.renderToCanvas(H,dt,function(W){W.fillStyle=X,W.strokeStyle=X,W.lineWidth=3,W.beginPath(),W.arc(H/2,dt/2,H/3,0,2*Math.PI),W.stroke(),W.beginPath(),W.arc(H/2,dt/2,H/5,0,2*Math.PI),W.fill()}),B=new vt.Texture(M),B.needsUpdate=!0,B},J=function(X,H,dt,M,B,W,_t){var yt={lineColor:"#FFCC00",lineWidth:1,markerColor:"#FFCC00",labelColor:"#FFF",font:"Inconsolata",fontSize:20,drawTime:2e3,lineSegments:150},Gt,et,Ut,A,F;if(this.lat=parseFloat(X),this.lon=parseFloat(H),this.text=dt,this.altitude=parseFloat(M),this.scene=W,this.previous=B,this.next=[],this.previous&&this.previous.next.push(this),_t)for(var C in yt)_t[C]!=null&&(yt[C]=_t[C]);this.opts=yt,Gt=Y.mapPoint(X,H),B&&Y.mapPoint(B.lat,B.lon),W._encom_markerTexture||(W._encom_markerTexture=Z(this.opts.markerColor)),et=new vt.SpriteMaterial({map:W._encom_markerTexture,opacity:.7,depthTest:!0,fog:!0}),this.marker=new vt.Sprite(et),this.marker.scale.set(0,0),this.marker.position.set(Gt.x*M,Gt.y*M,Gt.z*M),Ut=Y.createLabel(dt.toUpperCase(),this.opts.fontSize,this.opts.labelColor,this.opts.font,this.opts.markerColor),A=new vt.Texture(Ut),A.needsUpdate=!0,F=new vt.SpriteMaterial({map:A,opacity:0,depthTest:!0,fog:!0}),this.labelSprite=new vt.Sprite(F),this.labelSprite.position.set(Gt.x*M*1.1,Gt.y*M*1.05+(Gt.y<0?-15:30),Gt.z*M*1.1),this.labelSprite.scale.set(Ut.width,Ut.height),new at.Tween({opacity:0},!0).to({opacity:1},500).onUpdate(function(mn){F.opacity=mn.opacity}).start();var L=this;if(new at.Tween({x:0,y:0},!0).to({x:50,y:50},2e3).easing(at.Easing.Elastic.Out).onUpdate(function(mn){L.marker.scale.set(mn.x,mn.y)}).delay(this.previous?L.opts.drawTime:0).start(),this.previous){var nt,ct,ft,ne,le,de=[],ye=[],Le,Kt,je;nt=new vt.LineBasicMaterial({color:this.opts.lineColor,transparent:!0,linewidth:3,opacity:.5}),ct=new vt.LineBasicMaterial({color:this.opts.lineColor,linewidth:1,transparent:!0,opacity:.5}),ft=(X-B.lat)/L.opts.lineSegments,ne=(H-B.lon)/L.opts.lineSegments,le=Y.mapPoint(B.lat,B.lon),de=[],ye=[];for(var Je=L.opts.lineSegments+1,Qe=new Float32Array(Je*3),on=new Float32Array(Je*3),Ue=0;Ue=mn.index&&(L._splinePosAttr.setXYZ(fi,Le.x*1.2,Le.y*1.2,Le.z*1.2),L._splineDottedPosAttr.setXYZ(fi,Kt.x*1.19,Kt.y*1.19,Kt.z*1.19));L._splinePosAttr.needsUpdate=!0,L._splineDottedPosAttr.needsUpdate=!0,de.length>0&&setTimeout(je,L.opts.drawTime/L.opts.lineSegments)},je(),L.lineSpline=new vt.Line(L.geometrySpline,nt),L.lineDotted=new vt.Line(L.geometrySplineDotted,ct),this.scene.add(L.lineSpline),this.scene.add(L.lineDotted)}this.scene.add(this.marker),this.scene.add(this.labelSprite)};return J.prototype.remove=function(){for(var X=0,H=this,dt=function(B){for(var W=0;Wthis.tileDisplayDuration;)if(this.shutDownFlag&&this.currentTile>=X)this.done=!0,this.shutDownCb();else{this.currentDisplayTime-=this.tileDisplayDuration,this.currentTile++,this.currentTile==X&&!this.shutDownFlag&&(this.currentTile=dt);var B=this.currentTile%this.tilesHorizontal;Y.offset.x=B/this.tilesHorizontal;var W=Math.floor(this.currentTile/this.tilesHorizontal);Y.offset.y=1-W/this.tilesVertical-1/this.tilesVertical}},this.shutDown=function(M){_this.shutDownFlag=!0,_this.shutDownCb=M}};return rc=at,rc}var sc,Ru;function im(){if(Ru)return sc;Ru=1;var vt=nm(),at=Ur(),Y=Ms(),Z=function(X,H,dt,M,B,W,_t,yt){var Gt=X/dt,et=Math.floor((X-M)/B),Ut=H-25,A=Ut/(X-M),F=0,C=0,L=0,nt=Y.hexToRgb(W);return Y.renderToCanvas(X*H/dt,H*dt,function(ct){for(var ft=0;ft=Gt&&(F=0,C+=H,L++);var ne=F+25,le=C+Math.floor(H/2);ct.lineWidth=2,ct.strokeStyle=yt;var de=Math.PI/16,ye=-Math.PI+Math.PI/4,Le=8,Kt=Math.floor(X-2*(X-M)/B)+1;ft=X)ct.arc(ne,le,Le,Je*Math.PI/2+ye+de,Je*Math.PI/2+ye+Math.PI/2-2*de);else if(ft>M&&ft=je&&ft=Kt&&ft<(X-Kt)/2+Kt){var Qe=(X-Kt)/2,on=Math.PI/2,Ue=ft-Kt,yn=on/Qe,Mn=Je*(Math.PI/2)+Math.PI/4+de+yn*Ue;ct.arc(ne,le,Le,Mn,Mn+Math.PI/2-2*de)}else ct.arc(ne,le,Le,Je*Math.PI/2+ye+de,Je*Math.PI/2+ye+Math.PI/2-2*de);ct.stroke()}for(var mn,ni=0;ni0&&mn*A0?-1:1,this.mesh.lon=H,this.mesh.position.set(Gt.x,Gt.y,Gt.z),this.mesh.rotation.z=-1*(X/90)*Math.PI/2,this.mesh.rotation.y=H/180*Math.PI,M.add(this.mesh)};return J.prototype.changeAltitude=function(X){var H=Y.mapPoint(this.lat,this.lon);H.x*=X,H.y*=X,H.z*=X,this.altitude=X,this.mesh.position.set(H.x,H.y,H.z)},J.prototype.changeCanvas=function(X,H,dt,M){numFrames=50,pixels=100,rows=10,waveStart=Math.floor(numFrames/8),X?this.opts.numWaves=X:X=this.opts.numWaves,H?this.opts.waveColor=H:H=this.opts.waveColor,dt?this.opts.coreColor=dt:dt=this.opts.coreColor,M?this.opts.shieldColor=M:M=this.opts.shieldColor,this.canvas=Z(numFrames,pixels,rows,waveStart,X,H,dt,M),this.texture=new at.Texture(this.canvas),this.texture.needsUpdate=!0,repeatAt=Math.floor(numFrames-2*(numFrames-waveStart)/X)+1,this.animator=new vt(this.texture,rows,numFrames/rows,numFrames,80,repeatAt),this.material.map=this.texture},J.prototype.tick=function(X,H,dt){this.mesh.lookAt(X),this.mesh.rotateZ(this.mesh.tiltDirection*Math.PI/2),this.mesh.rotateZ(Math.sin(H+this.mesh.lon/180*Math.PI)*this.mesh.tiltMultiplier*this.mesh.tiltDirection*-1),this.animator&&this.animator.update(dt)},J.prototype.remove=function(){this.scene.remove(this.mesh);for(var X=0;X 0.0 && active > 0.0) {"," dt = mod(dt,1500.0);"," }"," float opacity = 1.0 - dt/ 1500.0;"," if (dt == 0.0 || active == 0.0){"," opacity = 0.0;"," }"," vec3 newPos = getPos(myStartLat, myStartLon - ( dt / 50.0));"," vColor = vec4( color, opacity );"," vec4 mvPosition = modelViewMatrix * vec4( newPos, 1.0 );"," gl_PointSize = 2.5 - (dt / 1500.0);"," gl_Position = projectionMatrix * mvPosition;","}"].join(` +`),Y=["varying vec4 vColor;","void main()","{"," gl_FragColor = vColor;"," float depth = gl_FragCoord.z / gl_FragCoord.w;"," float fogFactor = smoothstep(1500.0, 1800.0, depth );"," vec3 fogColor = vec3(0.0);"," gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w), fogFactor );","}"].join(` +`),Z=function(J,X){var H={smokeCount:5e3,smokePerPin:30,smokePerSecond:20};if(X)for(var dt in H)X[dt]!==void 0&&(H[dt]=X[dt]);this.opts=H;var M=H.smokeCount;this._myStartTime=new Float32Array(M),this._myStartLat=new Float32Array(M),this._myStartLon=new Float32Array(M),this._altitude=new Float32Array(M),this._active=new Float32Array(M);var B=new vt.BufferGeometry;B.setAttribute("position",new vt.BufferAttribute(new Float32Array(M*3),3)),B.setAttribute("myStartTime",new vt.BufferAttribute(this._myStartTime,1)),B.setAttribute("myStartLat",new vt.BufferAttribute(this._myStartLat,1)),B.setAttribute("myStartLon",new vt.BufferAttribute(this._myStartLon,1)),B.setAttribute("altitude",new vt.BufferAttribute(this._altitude,1)),B.setAttribute("active",new vt.BufferAttribute(this._active,1)),this._geometry=B,this.uniforms={currentTime:{type:"f",value:0},color:{type:"c",value:new vt.Color("#aaa")}};var W=new vt.ShaderMaterial({uniforms:this.uniforms,vertexShader:at,fragmentShader:Y,transparent:!0});this.smokeIndex=0,this.totalRunTime=0,J.add(new vt.Points(B,W))};return Z.prototype.setFire=function(J,X,H){for(var dt=this.smokeIndex,M=0;M0&&this.firstRunTime+(et=this.data.pop()).when=Date.now()&&this.data.push(et)}},_t=function(){this.hexGrid&&this.scene.remove(this.hexGrid);var et=["#define PI 3.141592653589793238462643","#define DISTANCE 500.0","#define INTRODURATION "+(parseFloat(this.introLinesDuration)+1e-5),"#define INTROALTITUDE "+(parseFloat(this.introLinesAltitude)+1e-5),"attribute float lng;","uniform float currentTime;","varying vec4 vColor;","","void main()","{"," vec3 newPos = position;"," float opacityVal = 0.0;"," float introStart = INTRODURATION * ((180.0 + lng)/360.0);"," if(currentTime > introStart){"," opacityVal = 1.0;"," }"," if(currentTime > introStart && currentTime < introStart + INTRODURATION / 8.0){"," newPos = position * INTROALTITUDE;"," opacityVal = .3;"," }"," if(currentTime > introStart + INTRODURATION / 8.0 && currentTime < introStart + INTRODURATION / 8.0 + 200.0){"," newPos = position * (1.0 + ((INTROALTITUDE-1.0) * (1.0-(currentTime - introStart-(INTRODURATION/8.0))/200.0)));"," }"," vColor = vec4( color, opacityVal );"," gl_Position = projectionMatrix * modelViewMatrix * vec4(newPos, 1.0);","}"].join(` +`),Ut=["varying vec4 vColor;","void main()","{"," gl_FragColor = vColor;"," float depth = gl_FragCoord.z / gl_FragCoord.w;"," float fogFactor = smoothstep("+parseInt(this.cameraDistance)+".0,"+parseInt(this.cameraDistance+300)+".0, depth );"," vec3 fogColor = vec3(0.0);"," gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}"].join(` +`);this.pointUniforms={currentTime:{type:"f",value:0}};var A=new at.ShaderMaterial({uniforms:this.pointUniforms,vertexShader:et,fragmentShader:Ut,transparent:!0,vertexColors:!0,side:at.DoubleSide}),F=this.tiles.length*4,C=new at.BufferGeometry;C.setAttribute("position",new at.BufferAttribute(new Float32Array(F*9),3)),C.setAttribute("color",new at.BufferAttribute(new Float32Array(F*9),3)),C.setAttribute("lng",new at.BufferAttribute(new Float32Array(F*3),1));var L=C.attributes.lng.array,nt={};new at.Color(this.baseColor).getHSL(nt);for(var ct=[],ft=0;ft<10;ft++){var ne=new at.Color;ne.setHSL((nt.h+(ft-5)*.02+1)%1,nt.s,Math.min(1,nt.l+Math.random()/3)),ct.push(ne)}for(var le=C.attributes.position.array,de=C.attributes.color.array,ye=function(on,Ue,yn,Mn,mn,ni,fi,ba,Ta,Nr,Ss,zi,Sn){var wi=on*3,en=wi*3;L[wi]=zi,L[wi+1]=zi,L[wi+2]=zi,le[en]=Ue,le[en+1]=yn,le[en+2]=Mn,le[en+3]=mn,le[en+4]=ni,le[en+5]=fi,le[en+6]=ba,le[en+7]=Ta,le[en+8]=Nr,de[en]=Sn.r,de[en+1]=Sn.g,de[en+2]=Sn.b,de[en+3]=Sn.r,de[en+4]=Sn.g,de[en+5]=Sn.b,de[en+6]=Sn.r,de[en+7]=Sn.g,de[en+8]=Sn.b},Le=0;Le5&&ye(je+3,Kt.b[0].x,Kt.b[0].y,Kt.b[0].z,Kt.b[5].x,Kt.b[5].y,Kt.b[5].z,Kt.b[4].x,Kt.b[4].y,Kt.b[4].z,Kt.lat,Kt.lon,Qe)}C.computeBoundingSphere(),this.hexGrid=new at.Mesh(C,A),this.scene.add(this.hexGrid)},yt=function(){for(var et=new at.LineBasicMaterial({color:this.introLinesColor,transparent:!0,linewidth:2,opacity:.5}),Ut=0;Ut0;)Ut.scene.remove(Ut.scene.children[0]);typeof et=="function"&&et()},1e3)},Gt.prototype.addPin=function(et,Ut,A){et=parseFloat(et),Ut=parseFloat(Ut);var F={lineColor:this.pinColor,topColor:this.pinColor,font:this.font},C=1.2;(typeof A!="string"||A.length===0)&&(C-=.05+Math.random()*.05);var L=new J(et,Ut,A,C,this.scene,this.smokeProvider,F);this.pins.push(L);var nt=B(et,Ut);if(L.pos_=new Z(parseInt(nt.x),parseInt(nt.y)),A.length>0?L.rad_=nt.rad:L.rad_=1,this.quadtree.addObject(L),A.length>0){var ct=this.quadtree.getCollisionsForObject(L),ft=0,ne=0,le=[];for(var de in ct)ct[de].text.length>0&&(ft++,ct[de].age()>5e3?le.push(ct[de]):ne++);if(ft>0&&ne==0)for(var de=0;de0&&(L.hideLabel(),L.hideSmoke(),L.hideTop(),L.changeAltitude(Math.random()*.05+1.1))}if(this.pins.length>this.maxPins){var ye=this.pins.shift();this.quadtree.removeObject(ye),ye.remove()}return L},Gt.prototype.addMarker=function(et,Ut,A,F){var C,L={markerColor:this.markerColor,lineColor:this.markerColor,font:this.font};return typeof F=="boolean"&&F?C=new X(et,Ut,A,1.2,this.markers[this.markers.length-1],this.scene,L):typeof F=="object"?C=new X(et,Ut,A,1.2,F,this.scene,L):C=new X(et,Ut,A,1.2,null,this.scene,L),this.markers.push(C),this.markers.length>this.maxMarkers&&this.markers.shift().remove(),C},Gt.prototype.addSatellite=function(et,Ut,A,F,C,L){F||(F={}),F.coreColor==null&&(F.coreColor=this.satelliteColor);var nt=new H(et,Ut,A,this.scene,F,C,L);return this.satellites[nt.toString()]||(this.satellites[nt.toString()]=nt),nt.onRemove((function(){delete this.satellites[nt.toString()]}).bind(this)),nt},Gt.prototype.addConstellation=function(et,Ut){for(var A,F=[],C=0;Cthis.maxPins;){var Ut=this.pins.shift();this.quadtree.removeObject(Ut),Ut.remove()}},Gt.prototype.setMaxMarkers=function(et){for(this.maxMarkers=et;this.markers.length>this.maxMarkers;)this.markers.shift().remove()},Gt.prototype.setBaseColor=function(et){this.baseColor=et,_t.call(this)},Gt.prototype.setMarkerColor=function(et){this.markerColor=et,this.scene._encom_markerTexture=null},Gt.prototype.setPinColor=function(et){this.pinColor=et},Gt.prototype.setScale=function(et){this.scale=et,this.cameraDistance=1700/et,this.scene&&this.scene.fog&&(this.scene.fog.near=this.cameraDistance,this.scene.fog.far=this.cameraDistance+300,_t.call(this),this.camera.far=this.cameraDistance+300,this.camera.updateProjectionMatrix())},Gt.prototype.tick=function(){if(this.camera){this.firstRunTime||(this.firstRunTime=Date.now()),W.call(this),vt.update(),this.lastRenderDate||(this.lastRenderDate=new Date),this.firstRenderDate||(this.firstRenderDate=new Date),this.totalRunTime=new Date-this.firstRenderDate;var et=new Date-this.lastRenderDate;this.lastRenderDate=new Date;var Ut=2*Math.PI/(this.dayLength/et);this.cameraAngle+=Ut,this.active||(this.cameraDistance+=1e3*et/1e3),this.camera.position.x=this.cameraDistance*Math.cos(this.cameraAngle)*Math.cos(this.viewAngle),this.camera.position.y=Math.sin(this.viewAngle)*this.cameraDistance,this.camera.position.z=this.cameraDistance*Math.sin(this.cameraAngle)*Math.cos(this.viewAngle);for(var A in this.satellites)this.satellites[A].tick(this.camera.position,this.cameraAngle,et);for(var A=0;Athis.totalRunTime?(this.totalRunTime/this.introLinesDuration<.1&&(this.introLines.children[0].material.opacity=this.totalRunTime/this.introLinesDuration*10-.2),this.totalRunTime/this.introLinesDuration>.8?this.introLines.children[0].material.opacity=Math.max(1-this.totalRunTime/this.introLinesDuration,0)*5:this.introLines.children[0].material.opacity=1,this.introLines.rotateY(2*Math.PI/(this.introLinesDuration/et))):this.introLines&&(this.scene.remove(this.introLines),delete[this.introLines]),this.pointUniforms.currentTime.value=this.totalRunTime,this.smokeProvider.tick(this.totalRunTime),this.camera.lookAt(this.scene.position),this.renderer.render(this.scene,this.camera)}},oc=Gt,oc}var Lu;function am(){return Lu||(Lu=1,window.ENCOM=window.ENCOM||{},window.ENCOM.Globe=sm()),hu}var om=am();return qp(om)})(); diff --git a/index.html b/index.html index db3793d..aae5eee 100644 --- a/index.html +++ b/index.html @@ -341,11 +341,7 @@ var docHeight = $(document).height(); - WebFontConfig = { - google: { - families: ['Inconsolata'] - }, - active: function(){ + (function startGlobe(){ /* don't start the globe until the font has been loaded */ $("#options").css({ "visibility": "visible", @@ -376,20 +372,7 @@ createGlobe(); }); - } - }; - - /* Webgl stuff */ - - - /* web font stuff*/ - var wf = document.createElement('script'); - wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + - '://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js'; - wf.type = 'text/javascript'; - wf.async = 'true'; - var s = document.getElementsByTagName('script')[0]; - s.parentNode.insertBefore(wf, s); + })(); }); diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..789828c --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1213 @@ +{ + "name": "encom-globe", + "version": "0.5.4", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "encom-globe", + "version": "0.5.4", + "license": "MIT", + "dependencies": { + "@tweenjs/tween.js": "^25.0.0", + "hexasphere.js": "*", + "quadtree2": "~0.5.3", + "three": "^0.184.0", + "vec2": "~1.5.0" + }, + "devDependencies": { + "minimist": "^1.2.8", + "pngjs": "^7.0.0", + "vite": "^6.3.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.2.tgz", + "integrity": "sha512-dnlp69efPPg6Uaw2dVqzWRfAWRnYVb1XJ8CyyhIbZeaq4CA5/mLeZ1IEt9QqQxmbdvagjLIm2ZL8BxXv5lH4Yw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.2.tgz", + "integrity": "sha512-OqZTwDRDchGRHHm/hwLOL7uVPB9aUvI0am/eQuWMNyFHf5PSEQmyEeYYheA0EPPKUO/l0uigCp+iaTjoLjVoHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.2.tgz", + "integrity": "sha512-UwRE7CGpvSVEQS8gUMBe1uADWjNnVgP3Iusyda1nSRwNDCsRjnGc7w6El6WLQsXmZTbLZx9cecegumcitNfpmA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.2.tgz", + "integrity": "sha512-gjEtURKLCC5VXm1I+2i1u9OhxFsKAQJKTVB8WvDAHF+oZlq0GTVFOlTlO1q3AlCTE/DF32c16ESvfgqR7343/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.2.tgz", + "integrity": "sha512-Bcl6CYDeAgE70cqZaMojOi/eK63h5Me97ZqAQoh77VPjMysA/4ORQBRGo3rRy45x4MzVlU9uZxs8Uwy7ZaKnBw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.2.tgz", + "integrity": "sha512-LU+TPda3mAE2QB0/Hp5VyeKJivpC6+tlOXd1VMoXV/YFMvk/MNk5iXeBfB4MQGRWyOYVJ01625vjkr0Az98OJQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.2.tgz", + "integrity": "sha512-2QxQrM+KQ7DAW4o22j+XZ6RKdxjLD7BOWTP0Bv0tmjdyhXSsr2Ul1oJDQqh9Zf5qOwTuTc7Ek83mOFaKnodPjg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.2.tgz", + "integrity": "sha512-TbziEu2DVsTEOPif2mKWkMeDMLoYjx95oESa9fkQQK7r/Orta0gnkcDpzwufEcAO2BLBsD7mZkXGFqEdMRRwfw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.2.tgz", + "integrity": "sha512-bO/rVDiDUuM2YfuCUwZ1t1cP+/yqjqz+Xf2VtkdppefuOFS2OSeAfgafaHNkFn0t02hEyXngZkxtGqXcXwO8Rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.2.tgz", + "integrity": "sha512-hr26p7e93Rl0Za+JwW7EAnwAvKkehh12BU1Llm9Ykiibg4uIr2rbpxG9WCf56GuvidlTG9KiiQT/TXT1yAWxTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.2.tgz", + "integrity": "sha512-pOjB/uSIyDt+ow3k/RcLvUAOGpysT2phDn7TTUB3n75SlIgZzM6NKAqlErPhoFU+npgY3/n+2HYIQVbF70P9/A==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.2.tgz", + "integrity": "sha512-2/w+q8jszv9Ww1c+6uJT3OwqhdmGP2/4T17cu8WuwyUuuaCDDJ2ojdyYwZzCxx0GcsZBhzi3HmH+J5pZNXnd+Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.2.tgz", + "integrity": "sha512-11+aL5vKheYgczxtPVVRhdptAM2H7fcDR5Gw4/bTcteuZBlH4oP9f5s9zYO9aGZvoGeBpqXI/9TZZihZ609wKw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.2.tgz", + "integrity": "sha512-i16fokAGK46IVZuV8LIIwMdtqhin9hfYkCh8pf8iC3QU3LpwL+1FSFGej+O7l3E/AoknL6Dclh2oTdnRMpTzFQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.2.tgz", + "integrity": "sha512-49FkKS6RGQoriDSK/6E2GkAsAuU5kETFCh7pG4yD/ylj9rKhTmO3elsnmBvRD4PgJPds5W2PkhC82aVwmUcJ7A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.2.tgz", + "integrity": "sha512-mjYNkHPfGpUR00DuM1ZZIgs64Hpf4bWcz9Z41+4Q+pgDx73UwWdAYyf6EG/lRFldmdHHzgrYyge5akFUW0D3mQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.2.tgz", + "integrity": "sha512-ALyvJz965BQk8E9Al/JDKKDLH2kfKFLTGMlgkAbbYtZuJt9LU8DW3ZoDMCtQpXAltZxwBHevXz5u+gf0yA0YoA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.2.tgz", + "integrity": "sha512-UQjrkIdWrKI626Du8lCQ6MJp/6V1LAo2bOK9OTu4mSn8GGXIkPXk/Vsp4bLHCd9Z9Iz2OTEaokUE90VweJgIYQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.2.tgz", + "integrity": "sha512-bTsRGj6VlSdn/XD4CGyzMnzaBs9bsRxy79eTqTCBsA8TMIEky7qg48aPkvJvFe1HyzQ5oMZdg7AnVlWQSKLTnw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.2.tgz", + "integrity": "sha512-6d4Z3534xitaA1FcMWP7mQPq5zGwBmGbhphh2DwaA1aNIXUu3KTOfwrWpbwI4/Gr0uANo7NTtaykFyO2hPuFLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.2.tgz", + "integrity": "sha512-NetAg5iO2uN7eB8zE5qrZ3CSil+7IJt4WDFLcC75Ymywq1VZVD6qJ6EvNLjZ3rEm6gB7XW5JdT60c6MN35Z85Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.2.tgz", + "integrity": "sha512-NCYhOotpgWZ5kdxCZsv6Iudx0wX8980Q/oW4pNFNihpBKsDbEA1zpkfxJGC0yugsUuyDZ7gL37dbzwhR0VI7pQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.2.tgz", + "integrity": "sha512-RXsaOqXxfoUBQoOgvmmijVxJnW2IGB0eoMO7F8FAjaj0UTywUO/luSqimWBJn04WNgUkeNhh7fs7pESXajWmkg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.2.tgz", + "integrity": "sha512-qdAzEULD+/hzObedtmV6iBpdL5TIbKVztGiK7O3/KYSf+HIzU257+MX1EXJcyIiDbMAqmbwaufcYPvyRryeZtA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.2.tgz", + "integrity": "sha512-Nd/SgG27WoA9e+/TdK74KnHz852TLa94ovOYySo/yMPuTmpckK/jIF2jSwS3g7ELSKXK13/cVdmg1Z/DaCWKxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tweenjs/tween.js": { + "version": "25.0.0", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz", + "integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==", + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/hexasphere.js": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/hexasphere.js/-/hexasphere.js-0.2.2.tgz", + "integrity": "sha512-QpUuIjcSYxT82++b8P13tMeCVquKM3O7c4CIUANguUd6+aJy98fZ/tYOZ+wgWDtlNED26dl4HWUZDLfS4M0VOg==", + "license": "MIT" + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pngjs": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz", + "integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.19.0" + } + }, + "node_modules/postcss": { + "version": "8.5.10", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.10.tgz", + "integrity": "sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/quadtree2": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/quadtree2/-/quadtree2-0.5.4.tgz", + "integrity": "sha512-91mM5tFdSwXZw6K450rn9sJ1AESe465sPVxhEy/9i4syNckUF5YqCp06/ulogVkD/TdM9E4sP0YjlDbCuccnwA==", + "license": "MIT", + "dependencies": { + "vec2": "1.4.0" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/quadtree2/node_modules/vec2": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/vec2/-/vec2-1.4.0.tgz", + "integrity": "sha512-CWbYQOUuAZ2iNjgMwGRqCGIWyMGHzq/mt1g6DAABXgVYn+OmFk3krFPY6SnY8bYtg37QbcXR62osDAKukLNpHQ==" + }, + "node_modules/rollup": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.2.tgz", + "integrity": "sha512-J9qZyW++QK/09NyN/zeO0dG/1GdGfyp9lV8ajHnRVLfo/uFsbji5mHnDgn/qYdUHyCkM2N+8VyspgZclfAh0eQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.60.2", + "@rollup/rollup-android-arm64": "4.60.2", + "@rollup/rollup-darwin-arm64": "4.60.2", + "@rollup/rollup-darwin-x64": "4.60.2", + "@rollup/rollup-freebsd-arm64": "4.60.2", + "@rollup/rollup-freebsd-x64": "4.60.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.60.2", + "@rollup/rollup-linux-arm-musleabihf": "4.60.2", + "@rollup/rollup-linux-arm64-gnu": "4.60.2", + "@rollup/rollup-linux-arm64-musl": "4.60.2", + "@rollup/rollup-linux-loong64-gnu": "4.60.2", + "@rollup/rollup-linux-loong64-musl": "4.60.2", + "@rollup/rollup-linux-ppc64-gnu": "4.60.2", + "@rollup/rollup-linux-ppc64-musl": "4.60.2", + "@rollup/rollup-linux-riscv64-gnu": "4.60.2", + "@rollup/rollup-linux-riscv64-musl": "4.60.2", + "@rollup/rollup-linux-s390x-gnu": "4.60.2", + "@rollup/rollup-linux-x64-gnu": "4.60.2", + "@rollup/rollup-linux-x64-musl": "4.60.2", + "@rollup/rollup-openbsd-x64": "4.60.2", + "@rollup/rollup-openharmony-arm64": "4.60.2", + "@rollup/rollup-win32-arm64-msvc": "4.60.2", + "@rollup/rollup-win32-ia32-msvc": "4.60.2", + "@rollup/rollup-win32-x64-gnu": "4.60.2", + "@rollup/rollup-win32-x64-msvc": "4.60.2", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/three": { + "version": "0.184.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.184.0.tgz", + "integrity": "sha512-wtTRjG92pM5eUg/KuUnHsqSAlPM296brTOcLgMRqEeylYTh/CdtvKUvCyyCQTzFuStieWxvZb8mVTMvdPyUpxg==", + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.16", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", + "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/vec2": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/vec2/-/vec2-1.5.0.tgz", + "integrity": "sha512-nm0BnIvyav5jp6iZNRJ5CMLauEB/PKXax8pBCAZSowuWrF5lCKNjq/Mh2wICyrpOfuU48nWX+urNQWQbpTF3eQ==" + }, + "node_modules/vite": { + "version": "6.4.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.2.tgz", + "integrity": "sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json index 5b7faa2..019466d 100644 --- a/package.json +++ b/package.json @@ -4,16 +4,14 @@ "description": "encom-globe", "main": "src/Globe.js", "devDependencies": { - "minimist": "0.0.8", - "grunt": "~0.4.2", - "grunt-contrib-watch": "~0.5.3", - "grunt-shell": "~0.6.4", - "browserify": "~3.41.0", - "grunt-browserify": "~2.0.7", - "pngjs": "~0.4.0", - "grunt-contrib-uglify": "~0.4.0" + "minimist": "^1.2.8", + "pngjs": "^7.0.0", + "vite": "^6.3.2" }, "scripts": { + "build": "vite build && vite build --config vite.min.config.js", + "dev": "vite build --watch", + "buildgrid": "node bin/buildgrid -r 500 -o grid.js -m resources/equirectangle_projection.png", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { @@ -26,8 +24,7 @@ "hexasphere.js": "*", "quadtree2": "~0.5.3", "vec2": "~1.5.0", - "three": "~0.66.2", - "pusher.color": "~0.2.4", - "tween.js": "~0.13.0" + "three": "^0.184.0", + "@tweenjs/tween.js": "^25.0.0" } } diff --git a/src/Globe.js b/src/Globe.js index 325dd52..7721d60 100644 --- a/src/Globe.js +++ b/src/Globe.js @@ -1,4 +1,4 @@ -var TWEEN = require('tween.js'), +var TWEEN = require('@tweenjs/tween.js'), THREE = require('three'), Hexasphere = require('hexasphere.js'), Quadtree2 = require('quadtree2'), @@ -7,7 +7,6 @@ var TWEEN = require('tween.js'), Marker = require('./Marker'), Satellite = require('./Satellite'), SmokeProvider = require('./SmokeProvider'), - pusherColor = require('pusher.color'), utils = require('./utils'); var latLonToXYZ = function(width, height, lat,lon){ @@ -30,11 +29,12 @@ var addInitialData = function(){ if(this.data.length == 0){ return; } + var next; while(this.data.length > 0 && this.firstRunTime + (next = this.data.pop()).when < Date.now()){ this.addPin(next.lat, next.lng, next.label); } - if(this.firstRunTime + next.when >= Date.now()){ + if(next && this.firstRunTime + next.when >= Date.now()){ this.data.push(next); } }; @@ -87,21 +87,16 @@ var createParticles = function(){ "}" ].join("\n"); - var pointAttributes = { - lng: {type: 'f', value: null} - }; - this.pointUniforms = { currentTime: { type: 'f', value: 0.0} } var pointMaterial = new THREE.ShaderMaterial( { uniforms: this.pointUniforms, - attributes: pointAttributes, vertexShader: pointVertexShader, fragmentShader: pointFragmentShader, transparent: true, - vertexColors: THREE.VertexColors, + vertexColors: true, side: THREE.DoubleSide }); @@ -109,33 +104,23 @@ var createParticles = function(){ var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'index', Uint16Array, triangles * 3, 1 ); - geometry.addAttribute( 'position', Float32Array, triangles * 3, 3 ); - geometry.addAttribute( 'normal', Float32Array, triangles * 3, 3 ); - geometry.addAttribute( 'color', Float32Array, triangles * 3, 3 ); - geometry.addAttribute( 'lng', Float32Array, triangles * 3, 1 ); + geometry.setAttribute( 'position', new THREE.BufferAttribute( new Float32Array( triangles * 9 ), 3 ) ); + geometry.setAttribute( 'color', new THREE.BufferAttribute( new Float32Array( triangles * 9 ), 3 ) ); + geometry.setAttribute( 'lng', new THREE.BufferAttribute( new Float32Array( triangles * 3 ), 1 ) ); var lng_values = geometry.attributes.lng.array; - var baseColorSet = pusherColor(this.baseColor).hueSet(); + var baseHsl = {}; + new THREE.Color(this.baseColor).getHSL(baseHsl); var myColors = []; - for(var i = 0; i< baseColorSet.length; i++){ - myColors.push(baseColorSet[i].shade(Math.random()/3.0)); - } - - // break geometry into - // chunks of 21,845 triangles (3 unique vertices per triangle) - // for indices to fit into 16 bit integer number - // floor(2^16 / 3) = 21845 - - var chunkSize = 21845; - - var indices = geometry.attributes.index.array; - - for ( var i = 0; i < indices.length; i ++ ) { - - indices[ i ] = i % ( 3 * chunkSize ); - + for(var ci = 0; ci < 10; ci++){ + var c = new THREE.Color(); + c.setHSL( + (baseHsl.h + (ci - 5) * 0.02 + 1) % 1, + baseHsl.s, + Math.min(1, baseHsl.l + Math.random() / 3.0) + ); + myColors.push(c); } var positions = geometry.attributes.position.array; @@ -148,8 +133,6 @@ var createParticles = function(){ var addTriangle = function(k, ax, ay, az, bx, by, bz, cx, cy, cz, lat, lng, color){ var p = k * 3; var i = p * 3; - var colorIndex = Math.floor(Math.random()*myColors.length); - var colorRGB = myColors[colorIndex].rgb(); lng_values[p] = lng; lng_values[p+1] = lng; @@ -186,10 +169,7 @@ var createParticles = function(){ var k = i * 4; var colorIndex = Math.floor(Math.random()*myColors.length); - var colorRGB = myColors[colorIndex].rgb(); - var color = new THREE.Color(); - - color.setRGB(colorRGB[0]/255.0, colorRGB[1]/255.0, colorRGB[2]/255.0); + var color = myColors[colorIndex]; addTriangle(k, t.b[0].x, t.b[0].y, t.b[0].z, t.b[1].x, t.b[1].y, t.b[1].z, t.b[2].x, t.b[2].y, t.b[2].z, t.lat, t.lon, color); addTriangle(k+1, t.b[0].x, t.b[0].y, t.b[0].z, t.b[2].x, t.b[2].y, t.b[2].z, t.b[3].x, t.b[3].y, t.b[3].z, t.lat, t.lon, color); @@ -201,22 +181,6 @@ var createParticles = function(){ } - geometry.offsets = []; - - var offsets = triangles / chunkSize; - - for ( var i = 0; i < offsets; i ++ ) { - - var offset = { - start: i * chunkSize * 3, - index: i * chunkSize * 3, - count: Math.min( triangles - ( i * chunkSize ), chunkSize ) * 3 - }; - - geometry.offsets.push( offset ); - - } - geometry.computeBoundingSphere(); this.hexGrid = new THREE.Mesh( geometry, pointMaterial ); @@ -225,7 +189,6 @@ var createParticles = function(){ }; var createIntroLines = function(){ - var sPoint; var introLinesMaterial = new THREE.LineBasicMaterial({ color: this.introLinesColor, transparent: true, @@ -234,8 +197,6 @@ var createIntroLines = function(){ }); for(var i = 0; i= nextSpot.index){ - currentVert.set(currentPoint.x*1.2, currentPoint.y*1.2, currentPoint.z*1.2); - currentVert2.set(currentPoint2.x*1.19, currentPoint2.y*1.19, currentPoint2.z*1.19); + _this._splinePosAttr.setXYZ(x, currentPoint.x*1.2, currentPoint.y*1.2, currentPoint.z*1.2); + _this._splineDottedPosAttr.setXYZ(x, currentPoint2.x*1.19, currentPoint2.y*1.19, currentPoint2.z*1.19); } - _this.geometrySpline.verticesNeedUpdate = true; - _this.geometrySplineDotted.verticesNeedUpdate = true; } + _this._splinePosAttr.needsUpdate = true; + _this._splineDottedPosAttr.needsUpdate = true; + if(pointList.length > 0){ setTimeout(update,_this.opts.drawTime/_this.opts.lineSegments); } - }; update(); - this.scene.add(new THREE.Line(_this.geometrySpline, materialSpline)); - this.scene.add(new THREE.Line(_this.geometrySplineDotted, materialSplineDotted, THREE.LinePieces)); + _this.lineSpline = new THREE.Line(_this.geometrySpline, materialSpline); + _this.lineDotted = new THREE.Line(_this.geometrySplineDotted, materialSplineDotted); + this.scene.add(_this.lineSpline); + this.scene.add(_this.lineDotted); } this.scene.add(this.marker); @@ -236,28 +231,33 @@ Marker.prototype.remove = function(){ var _this = this; var update = function(ref){ - - for(var i = 0; i< x; i++){ - ref.geometrySpline.vertices[i].set(ref.geometrySpline.vertices[i+1]); - ref.geometrySplineDotted.vertices[i].set(ref.geometrySplineDotted.vertices[i+1]); - ref.geometrySpline.verticesNeedUpdate = true; - ref.geometrySplineDotted.verticesNeedUpdate = true; + for(var i = 0; i < x; i++){ + ref._splinePosAttr.setXYZ(i, + ref._splinePosAttr.getX(i+1), + ref._splinePosAttr.getY(i+1), + ref._splinePosAttr.getZ(i+1)); + ref._splineDottedPosAttr.setXYZ(i, + ref._splineDottedPosAttr.getX(i+1), + ref._splineDottedPosAttr.getY(i+1), + ref._splineDottedPosAttr.getZ(i+1)); + ref._splinePosAttr.needsUpdate = true; + ref._splineDottedPosAttr.needsUpdate = true; } x++; - if(x < ref.geometrySpline.vertices.length){ - setTimeout(function(){update(ref)}, _this.opts.drawTime/_this.opts.lineSegments) + if(x < ref._splinePosAttr.count){ + setTimeout(function(){ update(ref); }, _this.opts.drawTime/_this.opts.lineSegments); } else { - _this.scene.remove(ref.geometrySpline); - _this.scene.remove(ref.geometrySplineDotted); + _this.scene.remove(ref.lineSpline); + _this.scene.remove(ref.lineDotted); } - } + }; for(var j = 0; j< _this.next.length; j++){ (function(k){ update(_this.next[k]); })(j); - } + } _this.scene.remove(_this.marker); _this.scene.remove(_this.labelSprite); diff --git a/src/Pin.js b/src/Pin.js index 57cfbd8..4cb680c 100644 --- a/src/Pin.js +++ b/src/Pin.js @@ -1,5 +1,5 @@ var THREE = require('three'), - TWEEN = require('tween.js'), + TWEEN = require('@tweenjs/tween.js'), utils = require('./utils'); @@ -64,7 +64,6 @@ var Pin = function(lat, lon, text, altitude, scene, smokeProvider, _opts){ /* the line */ - this.lineGeometry = new THREE.Geometry(); lineMaterial = new THREE.LineBasicMaterial({ color: opts.lineColor, linewidth: opts.lineWidth @@ -72,8 +71,10 @@ var Pin = function(lat, lon, text, altitude, scene, smokeProvider, _opts){ point = utils.mapPoint(lat,lon); - this.lineGeometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)); - this.lineGeometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)); + this.lineGeometry = new THREE.BufferGeometry(); + this._linePosAttr = new THREE.BufferAttribute( + new Float32Array([point.x, point.y, point.z, point.x, point.y, point.z]), 3); + this.lineGeometry.setAttribute('position', this._linePosAttr); this.line = new THREE.Line(this.lineGeometry, lineMaterial); /* the label */ @@ -84,14 +85,13 @@ var Pin = function(lat, lon, text, altitude, scene, smokeProvider, _opts){ labelMaterial = new THREE.SpriteMaterial({ map : labelTexture, - useScreenCoordinates: false, opacity:0, depthTest: true, fog: true }); this.labelSprite = new THREE.Sprite(labelMaterial); - this.labelSprite.position = {x: point.x*altitude*1.1, y: point.y*altitude + (point.y < 0 ? -15 : 30), z: point.z*altitude*1.1}; + this.labelSprite.position.set(point.x*altitude*1.1, point.y*altitude + (point.y < 0 ? -15 : 30), point.z*altitude*1.1); this.labelSprite.scale.set(labelCanvas.width, labelCanvas.height); /* the top */ @@ -113,16 +113,16 @@ var Pin = function(lat, lon, text, altitude, scene, smokeProvider, _opts){ /* intro animations */ if(opts.showTop || opts.showLabel){ - new TWEEN.Tween( {opacity: 0}) + new TWEEN.Tween( {opacity: 0}, true) .to( {opacity: 1}, 500 ) - .onUpdate(function(){ + .onUpdate(function(o){ if(_this.topVisible){ - topMaterial.opacity = this.opacity; + topMaterial.opacity = o.opacity; } else { topMaterial.opacity = 0; } if(_this.labelVisible){ - labelMaterial.opacity = this.opacity; + labelMaterial.opacity = o.opacity; } else { labelMaterial.opacity = 0; } @@ -131,14 +131,12 @@ var Pin = function(lat, lon, text, altitude, scene, smokeProvider, _opts){ } - new TWEEN.Tween(point) + new TWEEN.Tween(point, true) .to( {x: point.x*altitude, y: point.y*altitude, z: point.z*altitude}, 1500 ) .easing( TWEEN.Easing.Elastic.Out ) - .onUpdate(function(){ - _this.lineGeometry.vertices[1].x = this.x; - _this.lineGeometry.vertices[1].y = this.y; - _this.lineGeometry.vertices[1].z = this.z; - _this.lineGeometry.verticesNeedUpdate = true; + .onUpdate(function(o){ + _this._linePosAttr.setXYZ(1, o.x, o.y, o.z); + _this._linePosAttr.needsUpdate = true; }).start(); /* add to scene */ @@ -157,23 +155,21 @@ Pin.prototype.changeAltitude = function(altitude){ var point = utils.mapPoint(this.lat, this.lon); var _this = this; // arghhhh - new TWEEN.Tween({altitude: this.altitude}) + new TWEEN.Tween({altitude: this.altitude}, true) .to( {altitude: altitude}, 1500 ) .easing( TWEEN.Easing.Elastic.Out ) - .onUpdate(function(){ + .onUpdate(function(o){ if(_this.smokeVisible){ - _this.smokeProvider.changeAltitude(this.altitude, _this.smokeId); + _this.smokeProvider.changeAltitude(o.altitude, _this.smokeId); } if(_this.topVisible){ - _this.topSprite.position.set(point.x * this.altitude, point.y * this.altitude, point.z * this.altitude); + _this.topSprite.position.set(point.x * o.altitude, point.y * o.altitude, point.z * o.altitude); } if(_this.labelVisible){ - _this.labelSprite.position = {x: point.x*this.altitude*1.1, y: point.y*this.altitude + (point.y < 0 ? -15 : 30), z: point.z*this.altitude*1.1}; + _this.labelSprite.position.set(point.x*o.altitude*1.1, point.y*o.altitude + (point.y < 0 ? -15 : 30), point.z*o.altitude*1.1); } - _this.lineGeometry.vertices[1].x = point.x * this.altitude; - _this.lineGeometry.vertices[1].y = point.y * this.altitude; - _this.lineGeometry.vertices[1].z = point.z * this.altitude; - _this.lineGeometry.verticesNeedUpdate = true; + _this._linePosAttr.setXYZ(1, point.x * o.altitude, point.y * o.altitude, point.z * o.altitude); + _this._linePosAttr.needsUpdate = true; }) .onComplete(function(){ diff --git a/src/SmokeProvider.js b/src/SmokeProvider.js index 0bc53c0..e97e6b7 100644 --- a/src/SmokeProvider.js +++ b/src/SmokeProvider.js @@ -40,7 +40,7 @@ var vertexShader = [ " opacity = 0.0;", " }", " vec3 newPos = getPos(myStartLat, myStartLon - ( dt / 50.0));", - " vColor = vec4( color, opacity );", // set color associated to vertex; use later in fragment shader. + " vColor = vec4( color, opacity );", " vec4 mvPosition = modelViewMatrix * vec4( newPos, 1.0 );", " gl_PointSize = 2.5 - (dt / 1500.0);", " gl_Position = projectionMatrix * mvPosition;", @@ -48,26 +48,24 @@ var vertexShader = [ ].join("\n"); var fragmentShader = [ - "varying vec4 vColor;", - "void main()", + "varying vec4 vColor;", + "void main()", "{", - " gl_FragColor = vColor;", + " gl_FragColor = vColor;", " float depth = gl_FragCoord.z / gl_FragCoord.w;", " float fogFactor = smoothstep(1500.0, 1800.0, depth );", " vec3 fogColor = vec3(0.0);", " gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w), fogFactor );", - "}" ].join("\n"); var SmokeProvider = function(scene, _opts){ - /* options that can be passed in */ var opts = { smokeCount: 5000, smokePerPin: 30, smokePerSecond: 20 - } + }; if(_opts){ for(var i in opts){ @@ -78,96 +76,80 @@ var SmokeProvider = function(scene, _opts){ } this.opts = opts; - this.geometry = new THREE.Geometry(); - this.attributes = { - myStartTime: {type: 'f', value: []}, - myStartLat: {type: 'f', value: []}, - myStartLon: {type: 'f', value: []}, - altitude: {type: 'f', value: []}, - active: {type: 'f', value: []} - }; + + var count = opts.smokeCount; + + this._myStartTime = new Float32Array(count); + this._myStartLat = new Float32Array(count); + this._myStartLon = new Float32Array(count); + this._altitude = new Float32Array(count); + this._active = new Float32Array(count); + + var geometry = new THREE.BufferGeometry(); + geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count * 3), 3)); + geometry.setAttribute('myStartTime', new THREE.BufferAttribute(this._myStartTime, 1)); + geometry.setAttribute('myStartLat', new THREE.BufferAttribute(this._myStartLat, 1)); + geometry.setAttribute('myStartLon', new THREE.BufferAttribute(this._myStartLon, 1)); + geometry.setAttribute('altitude', new THREE.BufferAttribute(this._altitude, 1)); + geometry.setAttribute('active', new THREE.BufferAttribute(this._active, 1)); + + this._geometry = geometry; this.uniforms = { - currentTime: { type: 'f', value: 0.0}, - color: { type: 'c', value: new THREE.Color("#aaa")}, - } + currentTime: { type: 'f', value: 0.0 }, + color: { type: 'c', value: new THREE.Color("#aaa") } + }; - var material = new THREE.ShaderMaterial( { + var material = new THREE.ShaderMaterial({ uniforms: this.uniforms, - attributes: this.attributes, vertexShader: vertexShader, fragmentShader: fragmentShader, transparent: true }); - for(var i = 0; i< opts.smokeCount; i++){ - var vertex = new THREE.Vector3(); - vertex.set(0,0,0); - this.geometry.vertices.push( vertex ); - this.attributes.myStartTime.value[i] = 0.0; - this.attributes.myStartLat.value[i] = 0.0; - this.attributes.myStartLon.value[i] = 0.0; - this.attributes.altitude.value[i] = 0.0; - this.attributes.active.value[i] = 0.0; - } - - this.attributes.myStartTime.needsUpdate = true; - this.attributes.myStartLat.needsUpdate = true; - this.attributes.myStartLon.needsUpdate = true; - this.attributes.altitude.needsUpdate = true; - this.attributes.active.needsUpdate = true; - this.smokeIndex = 0; this.totalRunTime = 0; - scene.add( new THREE.ParticleSystem( this.geometry, material)); - + scene.add(new THREE.Points(geometry, material)); }; SmokeProvider.prototype.setFire = function(lat, lon, altitude){ - var point = utils.mapPoint(lat, lon); - - /* add the smoke */ var startSmokeIndex = this.smokeIndex; - for(var i = 0; i< this.opts.smokePerPin; i++){ - this.geometry.vertices[this.smokeIndex].set(point.x * altitude, point.y * altitude, point.z * altitude); - this.geometry.verticesNeedUpdate = true; - this.attributes.myStartTime.value[this.smokeIndex] = this.totalRunTime + (1000*i/this.opts.smokePerSecond + 1500); - this.attributes.myStartLat.value[this.smokeIndex] = lat; - this.attributes.myStartLon.value[this.smokeIndex] = lon; - this.attributes.altitude.value[this.smokeIndex] = altitude; - this.attributes.active.value[this.smokeIndex] = 1.0; - - this.attributes.myStartTime.needsUpdate = true; - this.attributes.myStartLat.needsUpdate = true; - this.attributes.myStartLon.needsUpdate = true; - this.attributes.altitude.needsUpdate = true; - this.attributes.active.needsUpdate = true; + for(var i = 0; i < this.opts.smokePerPin; i++){ + var si = this.smokeIndex; + this._myStartTime[si] = this.totalRunTime + (1000*i/this.opts.smokePerSecond + 1500); + this._myStartLat[si] = lat; + this._myStartLon[si] = lon; + this._altitude[si] = altitude; + this._active[si] = 1.0; this.smokeIndex++; - this.smokeIndex = this.smokeIndex % this.geometry.vertices.length; + this.smokeIndex = this.smokeIndex % this.opts.smokeCount; } + this._geometry.getAttribute('myStartTime').needsUpdate = true; + this._geometry.getAttribute('myStartLat').needsUpdate = true; + this._geometry.getAttribute('myStartLon').needsUpdate = true; + this._geometry.getAttribute('altitude').needsUpdate = true; + this._geometry.getAttribute('active').needsUpdate = true; return startSmokeIndex; - }; SmokeProvider.prototype.extinguish = function(index){ - for(var i = 0; i< this.opts.smokePerPin; i++){ - this.attributes.active.value[(i + index) % this.opts.smokeCount] = 0.0; - this.attributes.active.needsUpdate = true; + for(var i = 0; i < this.opts.smokePerPin; i++){ + this._active[(i + index) % this.opts.smokeCount] = 0.0; } + this._geometry.getAttribute('active').needsUpdate = true; }; SmokeProvider.prototype.changeAltitude = function(altitude, index){ - for(var i = 0; i< this.opts.smokePerPin; i++){ - this.attributes.altitude.value[(i + index) % this.opts.smokeCount] = altitude; - this.attributes.altitude.needsUpdate = true; + for(var i = 0; i < this.opts.smokePerPin; i++){ + this._altitude[(i + index) % this.opts.smokeCount] = altitude; } - + this._geometry.getAttribute('altitude').needsUpdate = true; }; SmokeProvider.prototype.tick = function(totalRunTime){ @@ -175,4 +157,4 @@ SmokeProvider.prototype.tick = function(totalRunTime){ this.uniforms.currentTime.value = this.totalRunTime; }; -module.exports = SmokeProvider; +module.exports = SmokeProvider; diff --git a/vite.config.js b/vite.config.js new file mode 100644 index 0000000..930602c --- /dev/null +++ b/vite.config.js @@ -0,0 +1,24 @@ +import { defineConfig } from 'vite' + +export default defineConfig({ + build: { + lib: { + entry: './browserify.js', + name: '_encomBundle', + formats: ['iife'], + fileName: () => 'encom-globe.js', + }, + outDir: 'build', + emptyOutDir: false, + minify: false, + commonjsOptions: { + include: [/.*/], + transformMixedEsModules: true, + }, + rollupOptions: { + output: { + strict: false, + }, + }, + }, +}) diff --git a/vite.min.config.js b/vite.min.config.js new file mode 100644 index 0000000..ab81163 --- /dev/null +++ b/vite.min.config.js @@ -0,0 +1,24 @@ +import { defineConfig } from 'vite' + +export default defineConfig({ + build: { + lib: { + entry: './browserify.js', + name: '_encomBundle', + formats: ['iife'], + fileName: () => 'encom-globe.min.js', + }, + outDir: 'build', + emptyOutDir: false, + minify: 'esbuild', + commonjsOptions: { + include: [/.*/], + transformMixedEsModules: true, + }, + rollupOptions: { + output: { + strict: false, + }, + }, + }, +})